grammar.js 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752
  1. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  2. function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
  3. import { codeFrameFromSource } from "@webassemblyjs/helper-code-frame";
  4. import * as t from "@webassemblyjs/ast";
  5. import { parse32I } from "./number-literals";
  6. import { parseString } from "./string-literals";
  7. import { tokens, keywords } from "./tokenizer";
  8. function hasPlugin(name) {
  9. if (name !== "wast") throw new Error("unknow plugin");
  10. return true;
  11. }
  12. function isKeyword(token, id) {
  13. return token.type === tokens.keyword && token.value === id;
  14. }
  15. function tokenToString(token) {
  16. if (token.type === "keyword") {
  17. return "keyword (".concat(token.value, ")");
  18. }
  19. return token.type;
  20. }
  21. function identifierFromToken(token) {
  22. var _token$loc = token.loc,
  23. end = _token$loc.end,
  24. start = _token$loc.start;
  25. return t.withLoc(t.identifier(token.value), end, start);
  26. }
  27. export function parse(tokensList, source) {
  28. var current = 0;
  29. var getUniqueName = t.getUniqueNameGenerator();
  30. var state = {
  31. registredExportedElements: []
  32. }; // But this time we're going to use recursion instead of a `while` loop. So we
  33. // define a `walk` function.
  34. function walk() {
  35. var token = tokensList[current];
  36. function eatToken() {
  37. token = tokensList[++current];
  38. }
  39. function getEndLoc() {
  40. var currentToken = token;
  41. if (typeof currentToken === "undefined") {
  42. var lastToken = tokensList[tokensList.length - 1];
  43. currentToken = lastToken;
  44. }
  45. return currentToken.loc.end;
  46. }
  47. function getStartLoc() {
  48. return token.loc.start;
  49. }
  50. function eatTokenOfType(type) {
  51. if (token.type !== type) {
  52. throw new Error("\n" + codeFrameFromSource(source, token.loc) + "Assertion error: expected token of type " + type + ", given " + tokenToString(token));
  53. }
  54. eatToken();
  55. }
  56. function parseExportIndex(token) {
  57. if (token.type === tokens.identifier) {
  58. var index = identifierFromToken(token);
  59. eatToken();
  60. return index;
  61. } else if (token.type === tokens.number) {
  62. var _index = t.numberLiteralFromRaw(token.value);
  63. eatToken();
  64. return _index;
  65. } else {
  66. throw function () {
  67. return new Error("\n" + codeFrameFromSource(source, token.loc) + "\n" + "unknown export index" + ", given " + tokenToString(token));
  68. }();
  69. }
  70. }
  71. function lookaheadAndCheck() {
  72. var len = arguments.length;
  73. for (var i = 0; i < len; i++) {
  74. var tokenAhead = tokensList[current + i];
  75. var expectedToken = i < 0 || arguments.length <= i ? undefined : arguments[i];
  76. if (tokenAhead.type === "keyword") {
  77. if (isKeyword(tokenAhead, expectedToken) === false) {
  78. return false;
  79. }
  80. } else if (expectedToken !== tokenAhead.type) {
  81. return false;
  82. }
  83. }
  84. return true;
  85. } // TODO(sven): there is probably a better way to do this
  86. // can refactor it if it get out of hands
  87. function maybeIgnoreComment() {
  88. if (typeof token === "undefined") {
  89. // Ignore
  90. return;
  91. }
  92. while (token.type === tokens.comment) {
  93. eatToken();
  94. if (typeof token === "undefined") {
  95. // Hit the end
  96. break;
  97. }
  98. }
  99. }
  100. /**
  101. * Parses a memory instruction
  102. *
  103. * WAST:
  104. *
  105. * memory: ( memory <name>? <memory_sig> )
  106. * ( memory <name>? ( export <string> ) <...> )
  107. * ( memory <name>? ( import <string> <string> ) <memory_sig> )
  108. * ( memory <name>? ( export <string> )* ( data <string>* )
  109. * memory_sig: <nat> <nat>?
  110. *
  111. */
  112. function parseMemory() {
  113. var id = t.identifier(getUniqueName("memory"));
  114. var limits = t.limit(0);
  115. if (token.type === tokens.string || token.type === tokens.identifier) {
  116. id = t.identifier(token.value);
  117. eatToken();
  118. } else {
  119. id = t.withRaw(id, ""); // preserve anonymous
  120. }
  121. /**
  122. * Maybe data
  123. */
  124. if (lookaheadAndCheck(tokens.openParen, keywords.data)) {
  125. eatToken(); // (
  126. eatToken(); // data
  127. // TODO(sven): do something with the data collected here
  128. var stringInitializer = token.value;
  129. eatTokenOfType(tokens.string); // Update limits accordingly
  130. limits = t.limit(stringInitializer.length);
  131. eatTokenOfType(tokens.closeParen);
  132. }
  133. /**
  134. * Maybe export
  135. */
  136. if (lookaheadAndCheck(tokens.openParen, keywords.export)) {
  137. eatToken(); // (
  138. eatToken(); // export
  139. if (token.type !== tokens.string) {
  140. throw function () {
  141. return new Error("\n" + codeFrameFromSource(source, token.loc) + "\n" + "Expected string in export" + ", given " + tokenToString(token));
  142. }();
  143. }
  144. var _name = token.value;
  145. eatToken();
  146. state.registredExportedElements.push({
  147. exportType: "Memory",
  148. name: _name,
  149. id: id
  150. });
  151. eatTokenOfType(tokens.closeParen);
  152. }
  153. /**
  154. * Memory signature
  155. */
  156. if (token.type === tokens.number) {
  157. limits = t.limit(parse32I(token.value));
  158. eatToken();
  159. if (token.type === tokens.number) {
  160. limits.max = parse32I(token.value);
  161. eatToken();
  162. }
  163. }
  164. return t.memory(limits, id);
  165. }
  166. /**
  167. * Parses a data section
  168. * https://webassembly.github.io/spec/core/text/modules.html#data-segments
  169. *
  170. * WAST:
  171. *
  172. * data: ( data <index>? <offset> <string> )
  173. */
  174. function parseData() {
  175. // optional memory index
  176. var memidx = 0;
  177. if (token.type === tokens.number) {
  178. memidx = token.value;
  179. eatTokenOfType(tokens.number); // .
  180. }
  181. eatTokenOfType(tokens.openParen);
  182. var offset;
  183. if (token.type === tokens.valtype) {
  184. eatTokenOfType(tokens.valtype); // i32
  185. eatTokenOfType(tokens.dot); // .
  186. if (token.value !== "const") {
  187. throw new Error("constant expression required");
  188. }
  189. eatTokenOfType(tokens.name); // const
  190. var numberLiteral = t.numberLiteralFromRaw(token.value, "i32");
  191. offset = t.objectInstruction("const", "i32", [numberLiteral]);
  192. eatToken();
  193. eatTokenOfType(tokens.closeParen);
  194. } else {
  195. eatTokenOfType(tokens.name); // get_global
  196. var _numberLiteral = t.numberLiteralFromRaw(token.value, "i32");
  197. offset = t.instruction("get_global", [_numberLiteral]);
  198. eatToken();
  199. eatTokenOfType(tokens.closeParen);
  200. }
  201. var byteArray = parseString(token.value);
  202. eatToken(); // "string"
  203. return t.data(t.memIndexLiteral(memidx), offset, t.byteArray(byteArray));
  204. }
  205. /**
  206. * Parses a table instruction
  207. *
  208. * WAST:
  209. *
  210. * table: ( table <name>? <table_type> )
  211. * ( table <name>? ( export <string> ) <...> )
  212. * ( table <name>? ( import <string> <string> ) <table_type> )
  213. * ( table <name>? ( export <string> )* <elem_type> ( elem <var>* ) )
  214. *
  215. * table_type: <nat> <nat>? <elem_type>
  216. * elem_type: anyfunc
  217. *
  218. * elem: ( elem <var>? (offset <instr>* ) <var>* )
  219. * ( elem <var>? <expr> <var>* )
  220. */
  221. function parseTable() {
  222. var name = t.identifier(getUniqueName("table"));
  223. var limit = t.limit(0);
  224. var elemIndices = [];
  225. var elemType = "anyfunc";
  226. if (token.type === tokens.string || token.type === tokens.identifier) {
  227. name = identifierFromToken(token);
  228. eatToken();
  229. } else {
  230. name = t.withRaw(name, ""); // preserve anonymous
  231. }
  232. while (token.type !== tokens.closeParen) {
  233. /**
  234. * Maybe export
  235. */
  236. if (lookaheadAndCheck(tokens.openParen, keywords.elem)) {
  237. eatToken(); // (
  238. eatToken(); // elem
  239. while (token.type === tokens.identifier) {
  240. elemIndices.push(t.identifier(token.value));
  241. eatToken();
  242. }
  243. eatTokenOfType(tokens.closeParen);
  244. } else if (lookaheadAndCheck(tokens.openParen, keywords.export)) {
  245. eatToken(); // (
  246. eatToken(); // export
  247. if (token.type !== tokens.string) {
  248. throw function () {
  249. return new Error("\n" + codeFrameFromSource(source, token.loc) + "\n" + "Expected string in export" + ", given " + tokenToString(token));
  250. }();
  251. }
  252. var exportName = token.value;
  253. eatToken();
  254. state.registredExportedElements.push({
  255. exportType: "Table",
  256. name: exportName,
  257. id: name
  258. });
  259. eatTokenOfType(tokens.closeParen);
  260. } else if (isKeyword(token, keywords.anyfunc)) {
  261. // It's the default value, we can ignore it
  262. eatToken(); // anyfunc
  263. } else if (token.type === tokens.number) {
  264. /**
  265. * Table type
  266. */
  267. var min = parseInt(token.value);
  268. eatToken();
  269. if (token.type === tokens.number) {
  270. var max = parseInt(token.value);
  271. eatToken();
  272. limit = t.limit(min, max);
  273. } else {
  274. limit = t.limit(min);
  275. }
  276. eatToken();
  277. } else {
  278. throw function () {
  279. return new Error("\n" + codeFrameFromSource(source, token.loc) + "\n" + "Unexpected token" + ", given " + tokenToString(token));
  280. }();
  281. }
  282. }
  283. if (elemIndices.length > 0) {
  284. return t.table(elemType, limit, name, elemIndices);
  285. } else {
  286. return t.table(elemType, limit, name);
  287. }
  288. }
  289. /**
  290. * Parses an import statement
  291. *
  292. * WAST:
  293. *
  294. * import: ( import <string> <string> <imkind> )
  295. * imkind: ( func <name>? <func_sig> )
  296. * ( global <name>? <global_sig> )
  297. * ( table <name>? <table_sig> )
  298. * ( memory <name>? <memory_sig> )
  299. *
  300. * global_sig: <type> | ( mut <type> )
  301. */
  302. function parseImport() {
  303. if (token.type !== tokens.string) {
  304. throw new Error("Expected a string, " + token.type + " given.");
  305. }
  306. var moduleName = token.value;
  307. eatToken();
  308. if (token.type !== tokens.string) {
  309. throw new Error("Expected a string, " + token.type + " given.");
  310. }
  311. var name = token.value;
  312. eatToken();
  313. eatTokenOfType(tokens.openParen);
  314. var descr;
  315. if (isKeyword(token, keywords.func)) {
  316. eatToken(); // keyword
  317. var fnParams = [];
  318. var fnResult = [];
  319. var fnName = t.identifier(getUniqueName("func"));
  320. if (token.type === tokens.identifier) {
  321. fnName = identifierFromToken(token);
  322. eatToken();
  323. }
  324. while (token.type === tokens.openParen) {
  325. eatToken();
  326. if (lookaheadAndCheck(keywords.param) === true) {
  327. eatToken();
  328. fnParams.push.apply(fnParams, _toConsumableArray(parseFuncParam()));
  329. } else if (lookaheadAndCheck(keywords.result) === true) {
  330. eatToken();
  331. fnResult.push.apply(fnResult, _toConsumableArray(parseFuncResult()));
  332. } else {
  333. throw function () {
  334. return new Error("\n" + codeFrameFromSource(source, token.loc) + "\n" + "Unexpected token in import of type" + ", given " + tokenToString(token));
  335. }();
  336. }
  337. eatTokenOfType(tokens.closeParen);
  338. }
  339. if (typeof fnName === "undefined") {
  340. throw new Error("Imported function must have a name");
  341. }
  342. descr = t.funcImportDescr(fnName, t.signature(fnParams, fnResult));
  343. } else if (isKeyword(token, keywords.global)) {
  344. eatToken(); // keyword
  345. if (token.type === tokens.openParen) {
  346. eatToken(); // (
  347. eatTokenOfType(tokens.keyword); // mut keyword
  348. var valtype = token.value;
  349. eatToken();
  350. descr = t.globalType(valtype, "var");
  351. eatTokenOfType(tokens.closeParen);
  352. } else {
  353. var _valtype = token.value;
  354. eatTokenOfType(tokens.valtype);
  355. descr = t.globalType(_valtype, "const");
  356. }
  357. } else if (isKeyword(token, keywords.memory) === true) {
  358. eatToken(); // Keyword
  359. descr = parseMemory();
  360. } else if (isKeyword(token, keywords.table) === true) {
  361. eatToken(); // Keyword
  362. descr = parseTable();
  363. } else {
  364. throw new Error("Unsupported import type: " + tokenToString(token));
  365. }
  366. eatTokenOfType(tokens.closeParen);
  367. return t.moduleImport(moduleName, name, descr);
  368. }
  369. /**
  370. * Parses a block instruction
  371. *
  372. * WAST:
  373. *
  374. * expr: ( block <name>? <block_sig> <instr>* )
  375. * instr: block <name>? <block_sig> <instr>* end <name>?
  376. * block_sig : ( result <type>* )*
  377. *
  378. */
  379. function parseBlock() {
  380. var label = t.identifier(getUniqueName("block"));
  381. var blockResult = null;
  382. var instr = [];
  383. if (token.type === tokens.identifier) {
  384. label = identifierFromToken(token);
  385. eatToken();
  386. } else {
  387. label = t.withRaw(label, ""); // preserve anonymous
  388. }
  389. while (token.type === tokens.openParen) {
  390. eatToken();
  391. if (lookaheadAndCheck(keywords.result) === true) {
  392. eatToken();
  393. blockResult = token.value;
  394. eatToken();
  395. } else if (lookaheadAndCheck(tokens.name) === true || lookaheadAndCheck(tokens.valtype) === true || token.type === "keyword" // is any keyword
  396. ) {
  397. // Instruction
  398. instr.push(parseFuncInstr());
  399. } else {
  400. throw function () {
  401. return new Error("\n" + codeFrameFromSource(source, token.loc) + "\n" + "Unexpected token in block body of type" + ", given " + tokenToString(token));
  402. }();
  403. }
  404. maybeIgnoreComment();
  405. eatTokenOfType(tokens.closeParen);
  406. }
  407. return t.blockInstruction(label, instr, blockResult);
  408. }
  409. /**
  410. * Parses a if instruction
  411. *
  412. * WAST:
  413. *
  414. * expr:
  415. * ( if <name>? <block_sig> ( then <instr>* ) ( else <instr>* )? )
  416. * ( if <name>? <block_sig> <expr>+ ( then <instr>* ) ( else <instr>* )? )
  417. *
  418. * instr:
  419. * if <name>? <block_sig> <instr>* end <name>?
  420. * if <name>? <block_sig> <instr>* else <name>? <instr>* end <name>?
  421. *
  422. * block_sig : ( result <type>* )*
  423. *
  424. */
  425. function parseIf() {
  426. var blockResult = null;
  427. var label = t.identifier(getUniqueName("if"));
  428. var testInstrs = [];
  429. var consequent = [];
  430. var alternate = [];
  431. if (token.type === tokens.identifier) {
  432. label = identifierFromToken(token);
  433. eatToken();
  434. } else {
  435. label = t.withRaw(label, ""); // preserve anonymous
  436. }
  437. while (token.type === tokens.openParen) {
  438. eatToken(); // (
  439. /**
  440. * Block signature
  441. */
  442. if (isKeyword(token, keywords.result) === true) {
  443. eatToken();
  444. blockResult = token.value;
  445. eatTokenOfType(tokens.valtype);
  446. eatTokenOfType(tokens.closeParen);
  447. continue;
  448. }
  449. /**
  450. * Then
  451. */
  452. if (isKeyword(token, keywords.then) === true) {
  453. eatToken(); // then
  454. while (token.type === tokens.openParen) {
  455. eatToken(); // Instruction
  456. if (lookaheadAndCheck(tokens.name) === true || lookaheadAndCheck(tokens.valtype) === true || token.type === "keyword" // is any keyword
  457. ) {
  458. consequent.push(parseFuncInstr());
  459. } else {
  460. throw function () {
  461. return new Error("\n" + codeFrameFromSource(source, token.loc) + "\n" + "Unexpected token in consequent body of type" + ", given " + tokenToString(token));
  462. }();
  463. }
  464. eatTokenOfType(tokens.closeParen);
  465. }
  466. eatTokenOfType(tokens.closeParen);
  467. continue;
  468. }
  469. /**
  470. * Alternate
  471. */
  472. if (isKeyword(token, keywords.else)) {
  473. eatToken(); // else
  474. while (token.type === tokens.openParen) {
  475. eatToken(); // Instruction
  476. if (lookaheadAndCheck(tokens.name) === true || lookaheadAndCheck(tokens.valtype) === true || token.type === "keyword" // is any keyword
  477. ) {
  478. alternate.push(parseFuncInstr());
  479. } else {
  480. throw function () {
  481. return new Error("\n" + codeFrameFromSource(source, token.loc) + "\n" + "Unexpected token in alternate body of type" + ", given " + tokenToString(token));
  482. }();
  483. }
  484. eatTokenOfType(tokens.closeParen);
  485. }
  486. eatTokenOfType(tokens.closeParen);
  487. continue;
  488. }
  489. /**
  490. * Test instruction
  491. */
  492. if (lookaheadAndCheck(tokens.name) === true || lookaheadAndCheck(tokens.valtype) === true || token.type === "keyword" // is any keyword
  493. ) {
  494. testInstrs.push(parseFuncInstr());
  495. eatTokenOfType(tokens.closeParen);
  496. continue;
  497. }
  498. throw function () {
  499. return new Error("\n" + codeFrameFromSource(source, token.loc) + "\n" + "Unexpected token in if body" + ", given " + tokenToString(token));
  500. }();
  501. }
  502. return t.ifInstruction(label, testInstrs, blockResult, consequent, alternate);
  503. }
  504. /**
  505. * Parses a loop instruction
  506. *
  507. * WAT:
  508. *
  509. * blockinstr :: 'loop' I:label rt:resulttype (in:instr*) 'end' id?
  510. *
  511. * WAST:
  512. *
  513. * instr :: loop <name>? <block_sig> <instr>* end <name>?
  514. * expr :: ( loop <name>? <block_sig> <instr>* )
  515. * block_sig :: ( result <type>* )*
  516. *
  517. */
  518. function parseLoop() {
  519. var label = t.identifier(getUniqueName("loop"));
  520. var blockResult;
  521. var instr = [];
  522. if (token.type === tokens.identifier) {
  523. label = identifierFromToken(token);
  524. eatToken();
  525. } else {
  526. label = t.withRaw(label, ""); // preserve anonymous
  527. }
  528. while (token.type === tokens.openParen) {
  529. eatToken();
  530. if (lookaheadAndCheck(keywords.result) === true) {
  531. eatToken();
  532. blockResult = token.value;
  533. eatToken();
  534. } else if (lookaheadAndCheck(tokens.name) === true || lookaheadAndCheck(tokens.valtype) === true || token.type === "keyword" // is any keyword
  535. ) {
  536. // Instruction
  537. instr.push(parseFuncInstr());
  538. } else {
  539. throw function () {
  540. return new Error("\n" + codeFrameFromSource(source, token.loc) + "\n" + "Unexpected token in loop body" + ", given " + tokenToString(token));
  541. }();
  542. }
  543. eatTokenOfType(tokens.closeParen);
  544. }
  545. return t.loopInstruction(label, blockResult, instr);
  546. }
  547. function parseCallIndirect() {
  548. var typeRef;
  549. var params = [];
  550. var results = [];
  551. var instrs = [];
  552. while (token.type !== tokens.closeParen) {
  553. if (lookaheadAndCheck(tokens.openParen, keywords.type)) {
  554. eatToken(); // (
  555. eatToken(); // type
  556. typeRef = parseTypeReference();
  557. } else if (lookaheadAndCheck(tokens.openParen, keywords.param)) {
  558. eatToken(); // (
  559. eatToken(); // param
  560. /**
  561. * Params can be empty:
  562. * (params)`
  563. */
  564. if (token.type !== tokens.closeParen) {
  565. params.push.apply(params, _toConsumableArray(parseFuncParam()));
  566. }
  567. } else if (lookaheadAndCheck(tokens.openParen, keywords.result)) {
  568. eatToken(); // (
  569. eatToken(); // result
  570. /**
  571. * Results can be empty:
  572. * (result)`
  573. */
  574. if (token.type !== tokens.closeParen) {
  575. results.push.apply(results, _toConsumableArray(parseFuncResult()));
  576. }
  577. } else {
  578. eatTokenOfType(tokens.openParen);
  579. instrs.push(parseFuncInstr());
  580. }
  581. eatTokenOfType(tokens.closeParen);
  582. }
  583. return t.callIndirectInstruction(typeRef !== undefined ? typeRef : t.signature(params, results), instrs);
  584. }
  585. /**
  586. * Parses an export instruction
  587. *
  588. * WAT:
  589. *
  590. * export: ( export <string> <exkind> )
  591. * exkind: ( func <var> )
  592. * ( global <var> )
  593. * ( table <var> )
  594. * ( memory <var> )
  595. * var: <nat> | <name>
  596. *
  597. */
  598. function parseExport() {
  599. if (token.type !== tokens.string) {
  600. throw new Error("Expected string after export, got: " + token.type);
  601. }
  602. var name = token.value;
  603. eatToken();
  604. var moduleExportDescr = parseModuleExportDescr();
  605. return t.moduleExport(name, moduleExportDescr);
  606. }
  607. function parseModuleExportDescr() {
  608. var startLoc = getStartLoc();
  609. var type = "";
  610. var index;
  611. eatTokenOfType(tokens.openParen);
  612. while (token.type !== tokens.closeParen) {
  613. if (isKeyword(token, keywords.func)) {
  614. type = "Func";
  615. eatToken();
  616. index = parseExportIndex(token);
  617. } else if (isKeyword(token, keywords.table)) {
  618. type = "Table";
  619. eatToken();
  620. index = parseExportIndex(token);
  621. } else if (isKeyword(token, keywords.global)) {
  622. type = "Global";
  623. eatToken();
  624. index = parseExportIndex(token);
  625. } else if (isKeyword(token, keywords.memory)) {
  626. type = "Memory";
  627. eatToken();
  628. index = parseExportIndex(token);
  629. }
  630. eatToken();
  631. }
  632. if (type === "") {
  633. throw new Error("Unknown export type");
  634. }
  635. if (index === undefined) {
  636. throw new Error("Exported function must have a name");
  637. }
  638. var node = t.moduleExportDescr(type, index);
  639. var endLoc = getEndLoc();
  640. eatTokenOfType(tokens.closeParen);
  641. return t.withLoc(node, endLoc, startLoc);
  642. }
  643. function parseModule() {
  644. var name = null;
  645. var isBinary = false;
  646. var isQuote = false;
  647. var moduleFields = [];
  648. if (token.type === tokens.identifier) {
  649. name = token.value;
  650. eatToken();
  651. }
  652. if (hasPlugin("wast") && token.type === tokens.name && token.value === "binary") {
  653. eatToken();
  654. isBinary = true;
  655. }
  656. if (hasPlugin("wast") && token.type === tokens.name && token.value === "quote") {
  657. eatToken();
  658. isQuote = true;
  659. }
  660. if (isBinary === true) {
  661. var blob = [];
  662. while (token.type === tokens.string) {
  663. blob.push(token.value);
  664. eatToken();
  665. maybeIgnoreComment();
  666. }
  667. eatTokenOfType(tokens.closeParen);
  668. return t.binaryModule(name, blob);
  669. }
  670. if (isQuote === true) {
  671. var string = [];
  672. while (token.type === tokens.string) {
  673. string.push(token.value);
  674. eatToken();
  675. }
  676. eatTokenOfType(tokens.closeParen);
  677. return t.quoteModule(name, string);
  678. }
  679. while (token.type !== tokens.closeParen) {
  680. moduleFields.push(walk());
  681. if (state.registredExportedElements.length > 0) {
  682. state.registredExportedElements.forEach(function (decl) {
  683. moduleFields.push(t.moduleExport(decl.name, t.moduleExportDescr(decl.exportType, decl.id)));
  684. });
  685. state.registredExportedElements = [];
  686. }
  687. token = tokensList[current];
  688. }
  689. eatTokenOfType(tokens.closeParen);
  690. return t.module(name, moduleFields);
  691. }
  692. /**
  693. * Parses the arguments of an instruction
  694. */
  695. function parseFuncInstrArguments(signature) {
  696. var args = [];
  697. var namedArgs = {};
  698. var signaturePtr = 0;
  699. while (token.type === tokens.name || isKeyword(token, keywords.offset)) {
  700. var key = token.value;
  701. eatToken();
  702. eatTokenOfType(tokens.equal);
  703. var value = void 0;
  704. if (token.type === tokens.number) {
  705. value = t.numberLiteralFromRaw(token.value);
  706. } else {
  707. throw new Error("Unexpected type for argument: " + token.type);
  708. }
  709. namedArgs[key] = value;
  710. eatToken();
  711. } // $FlowIgnore
  712. var signatureLength = signature.vector ? Infinity : signature.length;
  713. while (token.type !== tokens.closeParen && ( // $FlowIgnore
  714. token.type === tokens.openParen || signaturePtr < signatureLength)) {
  715. if (token.type === tokens.identifier) {
  716. args.push(t.identifier(token.value));
  717. eatToken();
  718. } else if (token.type === tokens.valtype) {
  719. // Handle locals
  720. args.push(t.valtypeLiteral(token.value));
  721. eatToken();
  722. } else if (token.type === tokens.string) {
  723. args.push(t.stringLiteral(token.value));
  724. eatToken();
  725. } else if (token.type === tokens.number) {
  726. args.push( // TODO(sven): refactor the type signature handling
  727. // https://github.com/xtuc/webassemblyjs/pull/129 is a good start
  728. t.numberLiteralFromRaw(token.value, // $FlowIgnore
  729. signature[signaturePtr] || "f64")); // $FlowIgnore
  730. if (!signature.vector) {
  731. ++signaturePtr;
  732. }
  733. eatToken();
  734. } else if (token.type === tokens.openParen) {
  735. /**
  736. * Maybe some nested instructions
  737. */
  738. eatToken(); // Instruction
  739. if (lookaheadAndCheck(tokens.name) === true || lookaheadAndCheck(tokens.valtype) === true || token.type === "keyword" // is any keyword
  740. ) {
  741. // $FlowIgnore
  742. args.push(parseFuncInstr());
  743. } else {
  744. throw function () {
  745. return new Error("\n" + codeFrameFromSource(source, token.loc) + "\n" + "Unexpected token in nested instruction" + ", given " + tokenToString(token));
  746. }();
  747. }
  748. if (token.type === tokens.closeParen) {
  749. eatToken();
  750. }
  751. } else {
  752. throw function () {
  753. return new Error("\n" + codeFrameFromSource(source, token.loc) + "\n" + "Unexpected token in instruction argument" + ", given " + tokenToString(token));
  754. }();
  755. }
  756. }
  757. return {
  758. args: args,
  759. namedArgs: namedArgs
  760. };
  761. }
  762. /**
  763. * Parses an instruction
  764. *
  765. * WAT:
  766. *
  767. * instr :: plaininst
  768. * blockinstr
  769. *
  770. * blockinstr :: 'block' I:label rt:resulttype (in:instr*) 'end' id?
  771. * 'loop' I:label rt:resulttype (in:instr*) 'end' id?
  772. * 'if' I:label rt:resulttype (in:instr*) 'else' id? (in2:intr*) 'end' id?
  773. *
  774. * plaininst :: 'unreachable'
  775. * 'nop'
  776. * 'br' l:labelidx
  777. * 'br_if' l:labelidx
  778. * 'br_table' l*:vec(labelidx) ln:labelidx
  779. * 'return'
  780. * 'call' x:funcidx
  781. * 'call_indirect' x, I:typeuse
  782. *
  783. * WAST:
  784. *
  785. * instr:
  786. * <expr>
  787. * <op>
  788. * block <name>? <block_sig> <instr>* end <name>?
  789. * loop <name>? <block_sig> <instr>* end <name>?
  790. * if <name>? <block_sig> <instr>* end <name>?
  791. * if <name>? <block_sig> <instr>* else <name>? <instr>* end <name>?
  792. *
  793. * expr:
  794. * ( <op> )
  795. * ( <op> <expr>+ )
  796. * ( block <name>? <block_sig> <instr>* )
  797. * ( loop <name>? <block_sig> <instr>* )
  798. * ( if <name>? <block_sig> ( then <instr>* ) ( else <instr>* )? )
  799. * ( if <name>? <block_sig> <expr>+ ( then <instr>* ) ( else <instr>* )? )
  800. *
  801. * op:
  802. * unreachable
  803. * nop
  804. * br <var>
  805. * br_if <var>
  806. * br_table <var>+
  807. * return
  808. * call <var>
  809. * call_indirect <func_sig>
  810. * drop
  811. * select
  812. * get_local <var>
  813. * set_local <var>
  814. * tee_local <var>
  815. * get_global <var>
  816. * set_global <var>
  817. * <type>.load((8|16|32)_<sign>)? <offset>? <align>?
  818. * <type>.store(8|16|32)? <offset>? <align>?
  819. * current_memory
  820. * grow_memory
  821. * <type>.const <value>
  822. * <type>.<unop>
  823. * <type>.<binop>
  824. * <type>.<testop>
  825. * <type>.<relop>
  826. * <type>.<cvtop>/<type>
  827. *
  828. * func_type: ( type <var> )? <param>* <result>*
  829. */
  830. function parseFuncInstr() {
  831. var startLoc = getStartLoc();
  832. maybeIgnoreComment();
  833. /**
  834. * A simple instruction
  835. */
  836. if (token.type === tokens.name || token.type === tokens.valtype) {
  837. var _name2 = token.value;
  838. var object;
  839. eatToken();
  840. if (token.type === tokens.dot) {
  841. object = _name2;
  842. eatToken();
  843. if (token.type !== tokens.name) {
  844. throw new TypeError("Unknown token: " + token.type + ", name expected");
  845. }
  846. _name2 = token.value;
  847. eatToken();
  848. }
  849. if (token.type === tokens.closeParen) {
  850. var _endLoc = token.loc.end;
  851. if (typeof object === "undefined") {
  852. return t.withLoc(t.instruction(_name2), _endLoc, startLoc);
  853. } else {
  854. return t.withLoc(t.objectInstruction(_name2, object, []), _endLoc, startLoc);
  855. }
  856. }
  857. var signature = t.signatureForOpcode(object || "", _name2);
  858. var _parseFuncInstrArgume = parseFuncInstrArguments(signature),
  859. _args = _parseFuncInstrArgume.args,
  860. _namedArgs = _parseFuncInstrArgume.namedArgs;
  861. var endLoc = token.loc.end;
  862. if (typeof object === "undefined") {
  863. return t.withLoc(t.instruction(_name2, _args, _namedArgs), endLoc, startLoc);
  864. } else {
  865. return t.withLoc(t.objectInstruction(_name2, object, _args, _namedArgs), endLoc, startLoc);
  866. }
  867. } else if (isKeyword(token, keywords.loop)) {
  868. /**
  869. * Else a instruction with a keyword (loop or block)
  870. */
  871. eatToken(); // keyword
  872. return parseLoop();
  873. } else if (isKeyword(token, keywords.block)) {
  874. eatToken(); // keyword
  875. return parseBlock();
  876. } else if (isKeyword(token, keywords.call_indirect)) {
  877. eatToken(); // keyword
  878. return parseCallIndirect();
  879. } else if (isKeyword(token, keywords.call)) {
  880. eatToken(); // keyword
  881. var index;
  882. if (token.type === tokens.identifier) {
  883. index = identifierFromToken(token);
  884. eatToken();
  885. } else if (token.type === tokens.number) {
  886. index = t.indexLiteral(token.value);
  887. eatToken();
  888. }
  889. var instrArgs = []; // Nested instruction
  890. while (token.type === tokens.openParen) {
  891. eatToken();
  892. instrArgs.push(parseFuncInstr());
  893. eatTokenOfType(tokens.closeParen);
  894. }
  895. if (typeof index === "undefined") {
  896. throw new Error("Missing argument in call instruciton");
  897. }
  898. if (instrArgs.length > 0) {
  899. return t.callInstruction(index, instrArgs);
  900. } else {
  901. return t.callInstruction(index);
  902. }
  903. } else if (isKeyword(token, keywords.if)) {
  904. eatToken(); // Keyword
  905. return parseIf();
  906. } else if (isKeyword(token, keywords.module) && hasPlugin("wast")) {
  907. eatToken(); // In WAST you can have a module as an instruction's argument
  908. // we will cast it into a instruction to not break the flow
  909. // $FlowIgnore
  910. var module = parseModule();
  911. return module;
  912. } else {
  913. throw function () {
  914. return new Error("\n" + codeFrameFromSource(source, token.loc) + "\n" + "Unexpected instruction in function body" + ", given " + tokenToString(token));
  915. }();
  916. }
  917. }
  918. /*
  919. * Parses a function
  920. *
  921. * WAT:
  922. *
  923. * functype :: ( 'func' t1:vec(param) t2:vec(result) )
  924. * param :: ( 'param' id? t:valtype )
  925. * result :: ( 'result' t:valtype )
  926. *
  927. * WAST:
  928. *
  929. * func :: ( func <name>? <func_sig> <local>* <instr>* )
  930. * ( func <name>? ( export <string> ) <...> )
  931. * ( func <name>? ( import <string> <string> ) <func_sig> )
  932. * func_sig :: ( type <var> )? <param>* <result>*
  933. * param :: ( param <type>* ) | ( param <name> <type> )
  934. * result :: ( result <type>* )
  935. * local :: ( local <type>* ) | ( local <name> <type> )
  936. *
  937. */
  938. function parseFunc() {
  939. var fnName = t.identifier(getUniqueName("func"));
  940. var typeRef;
  941. var fnBody = [];
  942. var fnParams = [];
  943. var fnResult = []; // name
  944. if (token.type === tokens.identifier) {
  945. fnName = identifierFromToken(token);
  946. eatToken();
  947. } else {
  948. fnName = t.withRaw(fnName, ""); // preserve anonymous
  949. }
  950. maybeIgnoreComment();
  951. while (token.type === tokens.openParen || token.type === tokens.name || token.type === tokens.valtype) {
  952. // Instructions without parens
  953. if (token.type === tokens.name || token.type === tokens.valtype) {
  954. fnBody.push(parseFuncInstr());
  955. continue;
  956. }
  957. eatToken();
  958. if (lookaheadAndCheck(keywords.param) === true) {
  959. eatToken();
  960. fnParams.push.apply(fnParams, _toConsumableArray(parseFuncParam()));
  961. } else if (lookaheadAndCheck(keywords.result) === true) {
  962. eatToken();
  963. fnResult.push.apply(fnResult, _toConsumableArray(parseFuncResult()));
  964. } else if (lookaheadAndCheck(keywords.export) === true) {
  965. eatToken();
  966. parseFuncExport(fnName);
  967. } else if (lookaheadAndCheck(keywords.type) === true) {
  968. eatToken();
  969. typeRef = parseTypeReference();
  970. } else if (lookaheadAndCheck(tokens.name) === true || lookaheadAndCheck(tokens.valtype) === true || token.type === "keyword" // is any keyword
  971. ) {
  972. // Instruction
  973. fnBody.push(parseFuncInstr());
  974. } else {
  975. throw function () {
  976. return new Error("\n" + codeFrameFromSource(source, token.loc) + "\n" + "Unexpected token in func body" + ", given " + tokenToString(token));
  977. }();
  978. }
  979. eatTokenOfType(tokens.closeParen);
  980. }
  981. return t.func(fnName, typeRef !== undefined ? typeRef : t.signature(fnParams, fnResult), fnBody);
  982. }
  983. /**
  984. * Parses shorthand export in func
  985. *
  986. * export :: ( export <string> )
  987. */
  988. function parseFuncExport(funcId) {
  989. if (token.type !== tokens.string) {
  990. throw function () {
  991. return new Error("\n" + codeFrameFromSource(source, token.loc) + "\n" + "Function export expected a string" + ", given " + tokenToString(token));
  992. }();
  993. }
  994. var name = token.value;
  995. eatToken();
  996. /**
  997. * Func export shorthand, we trait it as a syntaxic sugar.
  998. * A export ModuleField will be added later.
  999. *
  1000. * We give the anonymous function a generated name and export it.
  1001. */
  1002. var id = t.identifier(funcId.value);
  1003. state.registredExportedElements.push({
  1004. exportType: "Func",
  1005. name: name,
  1006. id: id
  1007. });
  1008. }
  1009. /**
  1010. * Parses a type instruction
  1011. *
  1012. * WAST:
  1013. *
  1014. * typedef: ( type <name>? ( func <param>* <result>* ) )
  1015. */
  1016. function parseType() {
  1017. var id;
  1018. var params = [];
  1019. var result = [];
  1020. if (token.type === tokens.identifier) {
  1021. id = identifierFromToken(token);
  1022. eatToken();
  1023. }
  1024. if (lookaheadAndCheck(tokens.openParen, keywords.func)) {
  1025. eatToken(); // (
  1026. eatToken(); // func
  1027. if (token.type === tokens.closeParen) {
  1028. eatToken(); // function with an empty signature, we can abort here
  1029. return t.typeInstruction(id, t.signature([], []));
  1030. }
  1031. if (lookaheadAndCheck(tokens.openParen, keywords.param)) {
  1032. eatToken(); // (
  1033. eatToken(); // param
  1034. params = parseFuncParam();
  1035. eatTokenOfType(tokens.closeParen);
  1036. }
  1037. if (lookaheadAndCheck(tokens.openParen, keywords.result)) {
  1038. eatToken(); // (
  1039. eatToken(); // result
  1040. result = parseFuncResult();
  1041. eatTokenOfType(tokens.closeParen);
  1042. }
  1043. eatTokenOfType(tokens.closeParen);
  1044. }
  1045. return t.typeInstruction(id, t.signature(params, result));
  1046. }
  1047. /**
  1048. * Parses a function result
  1049. *
  1050. * WAST:
  1051. *
  1052. * result :: ( result <type>* )
  1053. */
  1054. function parseFuncResult() {
  1055. var results = [];
  1056. while (token.type !== tokens.closeParen) {
  1057. if (token.type !== tokens.valtype) {
  1058. throw function () {
  1059. return new Error("\n" + codeFrameFromSource(source, token.loc) + "\n" + "Unexpected token in func result" + ", given " + tokenToString(token));
  1060. }();
  1061. }
  1062. var valtype = token.value;
  1063. eatToken();
  1064. results.push(valtype);
  1065. }
  1066. return results;
  1067. }
  1068. /**
  1069. * Parses a type reference
  1070. *
  1071. */
  1072. function parseTypeReference() {
  1073. var ref;
  1074. if (token.type === tokens.identifier) {
  1075. ref = identifierFromToken(token);
  1076. eatToken();
  1077. } else if (token.type === tokens.number) {
  1078. ref = t.numberLiteralFromRaw(token.value);
  1079. eatToken();
  1080. }
  1081. return ref;
  1082. }
  1083. /**
  1084. * Parses a global instruction
  1085. *
  1086. * WAST:
  1087. *
  1088. * global: ( global <name>? <global_sig> <instr>* )
  1089. * ( global <name>? ( export <string> ) <...> )
  1090. * ( global <name>? ( import <string> <string> ) <global_sig> )
  1091. *
  1092. * global_sig: <type> | ( mut <type> )
  1093. *
  1094. */
  1095. function parseGlobal() {
  1096. var name = t.identifier(getUniqueName("global"));
  1097. var type; // Keep informations in case of a shorthand import
  1098. var importing = null;
  1099. maybeIgnoreComment();
  1100. if (token.type === tokens.identifier) {
  1101. name = identifierFromToken(token);
  1102. eatToken();
  1103. } else {
  1104. name = t.withRaw(name, ""); // preserve anonymous
  1105. }
  1106. /**
  1107. * maybe export
  1108. */
  1109. if (lookaheadAndCheck(tokens.openParen, keywords.export)) {
  1110. eatToken(); // (
  1111. eatToken(); // export
  1112. var exportName = token.value;
  1113. eatTokenOfType(tokens.string);
  1114. state.registredExportedElements.push({
  1115. exportType: "Global",
  1116. name: exportName,
  1117. id: name
  1118. });
  1119. eatTokenOfType(tokens.closeParen);
  1120. }
  1121. /**
  1122. * maybe import
  1123. */
  1124. if (lookaheadAndCheck(tokens.openParen, keywords.import)) {
  1125. eatToken(); // (
  1126. eatToken(); // import
  1127. var moduleName = token.value;
  1128. eatTokenOfType(tokens.string);
  1129. var _name3 = token.value;
  1130. eatTokenOfType(tokens.string);
  1131. importing = {
  1132. module: moduleName,
  1133. name: _name3,
  1134. descr: undefined
  1135. };
  1136. eatTokenOfType(tokens.closeParen);
  1137. }
  1138. /**
  1139. * global_sig
  1140. */
  1141. if (token.type === tokens.valtype) {
  1142. type = t.globalType(token.value, "const");
  1143. eatToken();
  1144. } else if (token.type === tokens.openParen) {
  1145. eatToken(); // (
  1146. if (isKeyword(token, keywords.mut) === false) {
  1147. throw function () {
  1148. return new Error("\n" + codeFrameFromSource(source, token.loc) + "\n" + "Unsupported global type, expected mut" + ", given " + tokenToString(token));
  1149. }();
  1150. }
  1151. eatToken(); // mut
  1152. type = t.globalType(token.value, "var");
  1153. eatToken();
  1154. eatTokenOfType(tokens.closeParen);
  1155. }
  1156. if (type === undefined) {
  1157. throw function () {
  1158. return new Error("\n" + codeFrameFromSource(source, token.loc) + "\n" + "Could not determine global type" + ", given " + tokenToString(token));
  1159. }();
  1160. }
  1161. maybeIgnoreComment();
  1162. var init = [];
  1163. if (importing != null) {
  1164. importing.descr = type;
  1165. init.push(t.moduleImport(importing.module, importing.name, importing.descr));
  1166. }
  1167. /**
  1168. * instr*
  1169. */
  1170. while (token.type === tokens.openParen) {
  1171. eatToken();
  1172. init.push(parseFuncInstr());
  1173. eatTokenOfType(tokens.closeParen);
  1174. }
  1175. return t.global(type, init, name);
  1176. }
  1177. /**
  1178. * Parses a function param
  1179. *
  1180. * WAST:
  1181. *
  1182. * param :: ( param <type>* ) | ( param <name> <type> )
  1183. */
  1184. function parseFuncParam() {
  1185. var params = [];
  1186. var id;
  1187. var valtype;
  1188. if (token.type === tokens.identifier) {
  1189. id = token.value;
  1190. eatToken();
  1191. }
  1192. if (token.type === tokens.valtype) {
  1193. valtype = token.value;
  1194. eatToken();
  1195. params.push({
  1196. id: id,
  1197. valtype: valtype
  1198. });
  1199. /**
  1200. * Shorthand notation for multiple anonymous parameters
  1201. * @see https://webassembly.github.io/spec/core/text/types.html#function-types
  1202. * @see https://github.com/xtuc/webassemblyjs/issues/6
  1203. */
  1204. if (id === undefined) {
  1205. while (token.type === tokens.valtype) {
  1206. valtype = token.value;
  1207. eatToken();
  1208. params.push({
  1209. id: undefined,
  1210. valtype: valtype
  1211. });
  1212. }
  1213. }
  1214. } else {// ignore
  1215. }
  1216. return params;
  1217. }
  1218. /**
  1219. * Parses an element segments instruction
  1220. *
  1221. * WAST:
  1222. *
  1223. * elem: ( elem <var>? (offset <instr>* ) <var>* )
  1224. * ( elem <var>? <expr> <var>* )
  1225. *
  1226. * var: <nat> | <name>
  1227. */
  1228. function parseElem() {
  1229. var tableIndex = t.indexLiteral(0);
  1230. var offset = [];
  1231. var funcs = [];
  1232. if (token.type === tokens.identifier) {
  1233. tableIndex = identifierFromToken(token);
  1234. eatToken();
  1235. }
  1236. if (token.type === tokens.number) {
  1237. tableIndex = t.indexLiteral(token.value);
  1238. eatToken();
  1239. }
  1240. while (token.type !== tokens.closeParen) {
  1241. if (lookaheadAndCheck(tokens.openParen, keywords.offset)) {
  1242. eatToken(); // (
  1243. eatToken(); // offset
  1244. while (token.type !== tokens.closeParen) {
  1245. eatTokenOfType(tokens.openParen);
  1246. offset.push(parseFuncInstr());
  1247. eatTokenOfType(tokens.closeParen);
  1248. }
  1249. eatTokenOfType(tokens.closeParen);
  1250. } else if (token.type === tokens.identifier) {
  1251. funcs.push(t.identifier(token.value));
  1252. eatToken();
  1253. } else if (token.type === tokens.number) {
  1254. funcs.push(t.indexLiteral(token.value));
  1255. eatToken();
  1256. } else if (token.type === tokens.openParen) {
  1257. eatToken(); // (
  1258. offset.push(parseFuncInstr());
  1259. eatTokenOfType(tokens.closeParen);
  1260. } else {
  1261. throw function () {
  1262. return new Error("\n" + codeFrameFromSource(source, token.loc) + "\n" + "Unsupported token in elem" + ", given " + tokenToString(token));
  1263. }();
  1264. }
  1265. }
  1266. return t.elem(tableIndex, offset, funcs);
  1267. }
  1268. /**
  1269. * Parses the start instruction in a module
  1270. *
  1271. * WAST:
  1272. *
  1273. * start: ( start <var> )
  1274. * var: <nat> | <name>
  1275. *
  1276. * WAT:
  1277. * start ::= ‘(’ ‘start’ x:funcidx ‘)’
  1278. */
  1279. function parseStart() {
  1280. if (token.type === tokens.identifier) {
  1281. var index = identifierFromToken(token);
  1282. eatToken();
  1283. return t.start(index);
  1284. }
  1285. if (token.type === tokens.number) {
  1286. var _index2 = t.indexLiteral(token.value);
  1287. eatToken();
  1288. return t.start(_index2);
  1289. }
  1290. throw new Error("Unknown start, token: " + tokenToString(token));
  1291. }
  1292. if (token.type === tokens.openParen) {
  1293. eatToken();
  1294. var startLoc = getStartLoc();
  1295. if (isKeyword(token, keywords.export)) {
  1296. eatToken();
  1297. var node = parseExport();
  1298. var _endLoc2 = getEndLoc();
  1299. return t.withLoc(node, _endLoc2, startLoc);
  1300. }
  1301. if (isKeyword(token, keywords.loop)) {
  1302. eatToken();
  1303. var _node = parseLoop();
  1304. var _endLoc3 = getEndLoc();
  1305. return t.withLoc(_node, _endLoc3, startLoc);
  1306. }
  1307. if (isKeyword(token, keywords.func)) {
  1308. eatToken();
  1309. var _node2 = parseFunc();
  1310. var _endLoc4 = getEndLoc();
  1311. maybeIgnoreComment();
  1312. eatTokenOfType(tokens.closeParen);
  1313. return t.withLoc(_node2, _endLoc4, startLoc);
  1314. }
  1315. if (isKeyword(token, keywords.module)) {
  1316. eatToken();
  1317. var _node3 = parseModule();
  1318. var _endLoc5 = getEndLoc();
  1319. return t.withLoc(_node3, _endLoc5, startLoc);
  1320. }
  1321. if (isKeyword(token, keywords.import)) {
  1322. eatToken();
  1323. var _node4 = parseImport();
  1324. var _endLoc6 = getEndLoc();
  1325. eatTokenOfType(tokens.closeParen);
  1326. return t.withLoc(_node4, _endLoc6, startLoc);
  1327. }
  1328. if (isKeyword(token, keywords.block)) {
  1329. eatToken();
  1330. var _node5 = parseBlock();
  1331. var _endLoc7 = getEndLoc();
  1332. eatTokenOfType(tokens.closeParen);
  1333. return t.withLoc(_node5, _endLoc7, startLoc);
  1334. }
  1335. if (isKeyword(token, keywords.memory)) {
  1336. eatToken();
  1337. var _node6 = parseMemory();
  1338. var _endLoc8 = getEndLoc();
  1339. eatTokenOfType(tokens.closeParen);
  1340. return t.withLoc(_node6, _endLoc8, startLoc);
  1341. }
  1342. if (isKeyword(token, keywords.data)) {
  1343. eatToken();
  1344. var _node7 = parseData();
  1345. var _endLoc9 = getEndLoc();
  1346. eatTokenOfType(tokens.closeParen);
  1347. return t.withLoc(_node7, _endLoc9, startLoc);
  1348. }
  1349. if (isKeyword(token, keywords.table)) {
  1350. eatToken();
  1351. var _node8 = parseTable();
  1352. var _endLoc10 = getEndLoc();
  1353. eatTokenOfType(tokens.closeParen);
  1354. return t.withLoc(_node8, _endLoc10, startLoc);
  1355. }
  1356. if (isKeyword(token, keywords.global)) {
  1357. eatToken();
  1358. var _node9 = parseGlobal();
  1359. var _endLoc11 = getEndLoc();
  1360. eatTokenOfType(tokens.closeParen);
  1361. return t.withLoc(_node9, _endLoc11, startLoc);
  1362. }
  1363. if (isKeyword(token, keywords.type)) {
  1364. eatToken();
  1365. var _node10 = parseType();
  1366. var _endLoc12 = getEndLoc();
  1367. eatTokenOfType(tokens.closeParen);
  1368. return t.withLoc(_node10, _endLoc12, startLoc);
  1369. }
  1370. if (isKeyword(token, keywords.start)) {
  1371. eatToken();
  1372. var _node11 = parseStart();
  1373. var _endLoc13 = getEndLoc();
  1374. eatTokenOfType(tokens.closeParen);
  1375. return t.withLoc(_node11, _endLoc13, startLoc);
  1376. }
  1377. if (isKeyword(token, keywords.elem)) {
  1378. eatToken();
  1379. var _node12 = parseElem();
  1380. var _endLoc14 = getEndLoc();
  1381. eatTokenOfType(tokens.closeParen);
  1382. return t.withLoc(_node12, _endLoc14, startLoc);
  1383. }
  1384. var instruction = parseFuncInstr();
  1385. var endLoc = getEndLoc();
  1386. maybeIgnoreComment();
  1387. if (_typeof(instruction) === "object") {
  1388. if (typeof token !== "undefined") {
  1389. eatTokenOfType(tokens.closeParen);
  1390. }
  1391. return t.withLoc(instruction, endLoc, startLoc);
  1392. }
  1393. }
  1394. if (token.type === tokens.comment) {
  1395. var _startLoc = getStartLoc();
  1396. var builder = token.opts.type === "leading" ? t.leadingComment : t.blockComment;
  1397. var _node13 = builder(token.value);
  1398. eatToken(); // comment
  1399. var _endLoc15 = getEndLoc();
  1400. return t.withLoc(_node13, _endLoc15, _startLoc);
  1401. }
  1402. throw function () {
  1403. return new Error("\n" + codeFrameFromSource(source, token.loc) + "\n" + "Unknown token" + ", given " + tokenToString(token));
  1404. }();
  1405. }
  1406. var body = [];
  1407. while (current < tokensList.length) {
  1408. body.push(walk());
  1409. }
  1410. return t.program(body);
  1411. }