index.cjs 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. // FIXME profile adding a per-Tree TreeNode cache, validating it by
  4. // parent pointer
  5. /// The default maximum length of a `TreeBuffer` node.
  6. const DefaultBufferLength = 1024;
  7. let nextPropID = 0;
  8. class Range {
  9. constructor(from, to) {
  10. this.from = from;
  11. this.to = to;
  12. }
  13. }
  14. /// Each [node type](#common.NodeType) or [individual tree](#common.Tree)
  15. /// can have metadata associated with it in props. Instances of this
  16. /// class represent prop names.
  17. class NodeProp {
  18. /// Create a new node prop type.
  19. constructor(config = {}) {
  20. this.id = nextPropID++;
  21. this.perNode = !!config.perNode;
  22. this.deserialize = config.deserialize || (() => {
  23. throw new Error("This node type doesn't define a deserialize function");
  24. });
  25. }
  26. /// This is meant to be used with
  27. /// [`NodeSet.extend`](#common.NodeSet.extend) or
  28. /// [`LRParser.configure`](#lr.ParserConfig.props) to compute
  29. /// prop values for each node type in the set. Takes a [match
  30. /// object](#common.NodeType^match) or function that returns undefined
  31. /// if the node type doesn't get this prop, and the prop's value if
  32. /// it does.
  33. add(match) {
  34. if (this.perNode)
  35. throw new RangeError("Can't add per-node props to node types");
  36. if (typeof match != "function")
  37. match = NodeType.match(match);
  38. return (type) => {
  39. let result = match(type);
  40. return result === undefined ? null : [this, result];
  41. };
  42. }
  43. }
  44. /// Prop that is used to describe matching delimiters. For opening
  45. /// delimiters, this holds an array of node names (written as a
  46. /// space-separated string when declaring this prop in a grammar)
  47. /// for the node types of closing delimiters that match it.
  48. NodeProp.closedBy = new NodeProp({ deserialize: str => str.split(" ") });
  49. /// The inverse of [`closedBy`](#common.NodeProp^closedBy). This is
  50. /// attached to closing delimiters, holding an array of node names
  51. /// of types of matching opening delimiters.
  52. NodeProp.openedBy = new NodeProp({ deserialize: str => str.split(" ") });
  53. /// Used to assign node types to groups (for example, all node
  54. /// types that represent an expression could be tagged with an
  55. /// `"Expression"` group).
  56. NodeProp.group = new NodeProp({ deserialize: str => str.split(" ") });
  57. /// The hash of the [context](#lr.ContextTracker.constructor)
  58. /// that the node was parsed in, if any. Used to limit reuse of
  59. /// contextual nodes.
  60. NodeProp.contextHash = new NodeProp({ perNode: true });
  61. /// The distance beyond the end of the node that the tokenizer
  62. /// looked ahead for any of the tokens inside the node. (The LR
  63. /// parser only stores this when it is larger than 25, for
  64. /// efficiency reasons.)
  65. NodeProp.lookAhead = new NodeProp({ perNode: true });
  66. /// This per-node prop is used to replace a given node, or part of a
  67. /// node, with another tree. This is useful to include trees from
  68. /// different languages in mixed-language parsers.
  69. NodeProp.mounted = new NodeProp({ perNode: true });
  70. /// A mounted tree, which can be [stored](#common.NodeProp^mounted) on
  71. /// a tree node to indicate that parts of its content are
  72. /// represented by another tree.
  73. class MountedTree {
  74. constructor(
  75. /// The inner tree.
  76. tree,
  77. /// If this is null, this tree replaces the entire node (it will
  78. /// be included in the regular iteration instead of its host
  79. /// node). If not, only the given ranges are considered to be
  80. /// covered by this tree. This is used for trees that are mixed in
  81. /// a way that isn't strictly hierarchical. Such mounted trees are
  82. /// only entered by [`resolveInner`](#common.Tree.resolveInner)
  83. /// and [`enter`](#common.SyntaxNode.enter).
  84. overlay,
  85. /// The parser used to create this subtree.
  86. parser) {
  87. this.tree = tree;
  88. this.overlay = overlay;
  89. this.parser = parser;
  90. }
  91. }
  92. const noProps = Object.create(null);
  93. /// Each node in a syntax tree has a node type associated with it.
  94. class NodeType {
  95. /// @internal
  96. constructor(
  97. /// The name of the node type. Not necessarily unique, but if the
  98. /// grammar was written properly, different node types with the
  99. /// same name within a node set should play the same semantic
  100. /// role.
  101. name,
  102. /// @internal
  103. props,
  104. /// The id of this node in its set. Corresponds to the term ids
  105. /// used in the parser.
  106. id,
  107. /// @internal
  108. flags = 0) {
  109. this.name = name;
  110. this.props = props;
  111. this.id = id;
  112. this.flags = flags;
  113. }
  114. /// Define a node type.
  115. static define(spec) {
  116. let props = spec.props && spec.props.length ? Object.create(null) : noProps;
  117. let flags = (spec.top ? 1 /* Top */ : 0) | (spec.skipped ? 2 /* Skipped */ : 0) |
  118. (spec.error ? 4 /* Error */ : 0) | (spec.name == null ? 8 /* Anonymous */ : 0);
  119. let type = new NodeType(spec.name || "", props, spec.id, flags);
  120. if (spec.props)
  121. for (let src of spec.props) {
  122. if (!Array.isArray(src))
  123. src = src(type);
  124. if (src) {
  125. if (src[0].perNode)
  126. throw new RangeError("Can't store a per-node prop on a node type");
  127. props[src[0].id] = src[1];
  128. }
  129. }
  130. return type;
  131. }
  132. /// Retrieves a node prop for this type. Will return `undefined` if
  133. /// the prop isn't present on this node.
  134. prop(prop) { return this.props[prop.id]; }
  135. /// True when this is the top node of a grammar.
  136. get isTop() { return (this.flags & 1 /* Top */) > 0; }
  137. /// True when this node is produced by a skip rule.
  138. get isSkipped() { return (this.flags & 2 /* Skipped */) > 0; }
  139. /// Indicates whether this is an error node.
  140. get isError() { return (this.flags & 4 /* Error */) > 0; }
  141. /// When true, this node type doesn't correspond to a user-declared
  142. /// named node, for example because it is used to cache repetition.
  143. get isAnonymous() { return (this.flags & 8 /* Anonymous */) > 0; }
  144. /// Returns true when this node's name or one of its
  145. /// [groups](#common.NodeProp^group) matches the given string.
  146. is(name) {
  147. if (typeof name == 'string') {
  148. if (this.name == name)
  149. return true;
  150. let group = this.prop(NodeProp.group);
  151. return group ? group.indexOf(name) > -1 : false;
  152. }
  153. return this.id == name;
  154. }
  155. /// Create a function from node types to arbitrary values by
  156. /// specifying an object whose property names are node or
  157. /// [group](#common.NodeProp^group) names. Often useful with
  158. /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple
  159. /// names, separated by spaces, in a single property name to map
  160. /// multiple node names to a single value.
  161. static match(map) {
  162. let direct = Object.create(null);
  163. for (let prop in map)
  164. for (let name of prop.split(" "))
  165. direct[name] = map[prop];
  166. return (node) => {
  167. for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) {
  168. let found = direct[i < 0 ? node.name : groups[i]];
  169. if (found)
  170. return found;
  171. }
  172. };
  173. }
  174. }
  175. /// An empty dummy node type to use when no actual type is available.
  176. NodeType.none = new NodeType("", Object.create(null), 0, 8 /* Anonymous */);
  177. /// A node set holds a collection of node types. It is used to
  178. /// compactly represent trees by storing their type ids, rather than a
  179. /// full pointer to the type object, in a numeric array. Each parser
  180. /// [has](#lr.LRParser.nodeSet) a node set, and [tree
  181. /// buffers](#common.TreeBuffer) can only store collections of nodes
  182. /// from the same set. A set can have a maximum of 2**16 (65536) node
  183. /// types in it, so that the ids fit into 16-bit typed array slots.
  184. class NodeSet {
  185. /// Create a set with the given types. The `id` property of each
  186. /// type should correspond to its position within the array.
  187. constructor(
  188. /// The node types in this set, by id.
  189. types) {
  190. this.types = types;
  191. for (let i = 0; i < types.length; i++)
  192. if (types[i].id != i)
  193. throw new RangeError("Node type ids should correspond to array positions when creating a node set");
  194. }
  195. /// Create a copy of this set with some node properties added. The
  196. /// arguments to this method can be created with
  197. /// [`NodeProp.add`](#common.NodeProp.add).
  198. extend(...props) {
  199. let newTypes = [];
  200. for (let type of this.types) {
  201. let newProps = null;
  202. for (let source of props) {
  203. let add = source(type);
  204. if (add) {
  205. if (!newProps)
  206. newProps = Object.assign({}, type.props);
  207. newProps[add[0].id] = add[1];
  208. }
  209. }
  210. newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type);
  211. }
  212. return new NodeSet(newTypes);
  213. }
  214. }
  215. const CachedNode = new WeakMap(), CachedInnerNode = new WeakMap();
  216. /// Options that control iteration. Can be combined with the `|`
  217. /// operator to enable multiple ones.
  218. exports.IterMode = void 0;
  219. (function (IterMode) {
  220. /// When enabled, iteration will only visit [`Tree`](#common.Tree)
  221. /// objects, not nodes packed into
  222. /// [`TreeBuffer`](#common.TreeBuffer)s.
  223. IterMode[IterMode["ExcludeBuffers"] = 1] = "ExcludeBuffers";
  224. /// Enable this to make iteration include anonymous nodes (such as
  225. /// the nodes that wrap repeated grammar constructs into a balanced
  226. /// tree).
  227. IterMode[IterMode["IncludeAnonymous"] = 2] = "IncludeAnonymous";
  228. /// By default, regular [mounted](#common.NodeProp^mounted) nodes
  229. /// replace their base node in iteration. Enable this to ignore them
  230. /// instead.
  231. IterMode[IterMode["IgnoreMounts"] = 4] = "IgnoreMounts";
  232. /// This option only applies in
  233. /// [`enter`](#common.SyntaxNode.enter)-style methods. It tells the
  234. /// library to not enter mounted overlays if one covers the given
  235. /// position.
  236. IterMode[IterMode["IgnoreOverlays"] = 8] = "IgnoreOverlays";
  237. })(exports.IterMode || (exports.IterMode = {}));
  238. /// A piece of syntax tree. There are two ways to approach these
  239. /// trees: the way they are actually stored in memory, and the
  240. /// convenient way.
  241. ///
  242. /// Syntax trees are stored as a tree of `Tree` and `TreeBuffer`
  243. /// objects. By packing detail information into `TreeBuffer` leaf
  244. /// nodes, the representation is made a lot more memory-efficient.
  245. ///
  246. /// However, when you want to actually work with tree nodes, this
  247. /// representation is very awkward, so most client code will want to
  248. /// use the [`TreeCursor`](#common.TreeCursor) or
  249. /// [`SyntaxNode`](#common.SyntaxNode) interface instead, which provides
  250. /// a view on some part of this data structure, and can be used to
  251. /// move around to adjacent nodes.
  252. class Tree {
  253. /// Construct a new tree. See also [`Tree.build`](#common.Tree^build).
  254. constructor(
  255. /// The type of the top node.
  256. type,
  257. /// This node's child nodes.
  258. children,
  259. /// The positions (offsets relative to the start of this tree) of
  260. /// the children.
  261. positions,
  262. /// The total length of this tree
  263. length,
  264. /// Per-node [node props](#common.NodeProp) to associate with this node.
  265. props) {
  266. this.type = type;
  267. this.children = children;
  268. this.positions = positions;
  269. this.length = length;
  270. /// @internal
  271. this.props = null;
  272. if (props && props.length) {
  273. this.props = Object.create(null);
  274. for (let [prop, value] of props)
  275. this.props[typeof prop == "number" ? prop : prop.id] = value;
  276. }
  277. }
  278. /// @internal
  279. toString() {
  280. let mounted = this.prop(NodeProp.mounted);
  281. if (mounted && !mounted.overlay)
  282. return mounted.tree.toString();
  283. let children = "";
  284. for (let ch of this.children) {
  285. let str = ch.toString();
  286. if (str) {
  287. if (children)
  288. children += ",";
  289. children += str;
  290. }
  291. }
  292. return !this.type.name ? children :
  293. (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) +
  294. (children.length ? "(" + children + ")" : "");
  295. }
  296. /// Get a [tree cursor](#common.TreeCursor) positioned at the top of
  297. /// the tree. Mode can be used to [control](#common.IterMode) which
  298. /// nodes the cursor visits.
  299. cursor(mode = 0) {
  300. return new TreeCursor(this.topNode, mode);
  301. }
  302. /// Get a [tree cursor](#common.TreeCursor) pointing into this tree
  303. /// at the given position and side (see
  304. /// [`moveTo`](#common.TreeCursor.moveTo).
  305. cursorAt(pos, side = 0, mode = 0) {
  306. let scope = CachedNode.get(this) || this.topNode;
  307. let cursor = new TreeCursor(scope);
  308. cursor.moveTo(pos, side);
  309. CachedNode.set(this, cursor._tree);
  310. return cursor;
  311. }
  312. /// Get a [syntax node](#common.SyntaxNode) object for the top of the
  313. /// tree.
  314. get topNode() {
  315. return new TreeNode(this, 0, 0, null);
  316. }
  317. /// Get the [syntax node](#common.SyntaxNode) at the given position.
  318. /// If `side` is -1, this will move into nodes that end at the
  319. /// position. If 1, it'll move into nodes that start at the
  320. /// position. With 0, it'll only enter nodes that cover the position
  321. /// from both sides.
  322. resolve(pos, side = 0) {
  323. let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false);
  324. CachedNode.set(this, node);
  325. return node;
  326. }
  327. /// Like [`resolve`](#common.Tree.resolve), but will enter
  328. /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
  329. /// pointing into the innermost overlaid tree at the given position
  330. /// (with parent links going through all parent structure, including
  331. /// the host trees).
  332. resolveInner(pos, side = 0) {
  333. let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true);
  334. CachedInnerNode.set(this, node);
  335. return node;
  336. }
  337. /// Iterate over the tree and its children, calling `enter` for any
  338. /// node that touches the `from`/`to` region (if given) before
  339. /// running over such a node's children, and `leave` (if given) when
  340. /// leaving the node. When `enter` returns `false`, that node will
  341. /// not have its children iterated over (or `leave` called).
  342. iterate(spec) {
  343. let { enter, leave, from = 0, to = this.length } = spec;
  344. for (let c = this.cursor((spec.mode || 0) | exports.IterMode.IncludeAnonymous);;) {
  345. let entered = false;
  346. if (c.from <= to && c.to >= from && (c.type.isAnonymous || enter(c) !== false)) {
  347. if (c.firstChild())
  348. continue;
  349. entered = true;
  350. }
  351. for (;;) {
  352. if (entered && leave && !c.type.isAnonymous)
  353. leave(c);
  354. if (c.nextSibling())
  355. break;
  356. if (!c.parent())
  357. return;
  358. entered = true;
  359. }
  360. }
  361. }
  362. /// Get the value of the given [node prop](#common.NodeProp) for this
  363. /// node. Works with both per-node and per-type props.
  364. prop(prop) {
  365. return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : undefined;
  366. }
  367. /// Returns the node's [per-node props](#common.NodeProp.perNode) in a
  368. /// format that can be passed to the [`Tree`](#common.Tree)
  369. /// constructor.
  370. get propValues() {
  371. let result = [];
  372. if (this.props)
  373. for (let id in this.props)
  374. result.push([+id, this.props[id]]);
  375. return result;
  376. }
  377. /// Balance the direct children of this tree, producing a copy of
  378. /// which may have children grouped into subtrees with type
  379. /// [`NodeType.none`](#common.NodeType^none).
  380. balance(config = {}) {
  381. return this.children.length <= 8 /* BranchFactor */ ? this :
  382. balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree(this.type, children, positions, length, this.propValues), config.makeTree || ((children, positions, length) => new Tree(NodeType.none, children, positions, length)));
  383. }
  384. /// Build a tree from a postfix-ordered buffer of node information,
  385. /// or a cursor over such a buffer.
  386. static build(data) { return buildTree(data); }
  387. }
  388. /// The empty tree
  389. Tree.empty = new Tree(NodeType.none, [], [], 0);
  390. class FlatBufferCursor {
  391. constructor(buffer, index) {
  392. this.buffer = buffer;
  393. this.index = index;
  394. }
  395. get id() { return this.buffer[this.index - 4]; }
  396. get start() { return this.buffer[this.index - 3]; }
  397. get end() { return this.buffer[this.index - 2]; }
  398. get size() { return this.buffer[this.index - 1]; }
  399. get pos() { return this.index; }
  400. next() { this.index -= 4; }
  401. fork() { return new FlatBufferCursor(this.buffer, this.index); }
  402. }
  403. /// Tree buffers contain (type, start, end, endIndex) quads for each
  404. /// node. In such a buffer, nodes are stored in prefix order (parents
  405. /// before children, with the endIndex of the parent indicating which
  406. /// children belong to it).
  407. class TreeBuffer {
  408. /// Create a tree buffer.
  409. constructor(
  410. /// The buffer's content.
  411. buffer,
  412. /// The total length of the group of nodes in the buffer.
  413. length,
  414. /// The node set used in this buffer.
  415. set) {
  416. this.buffer = buffer;
  417. this.length = length;
  418. this.set = set;
  419. }
  420. /// @internal
  421. get type() { return NodeType.none; }
  422. /// @internal
  423. toString() {
  424. let result = [];
  425. for (let index = 0; index < this.buffer.length;) {
  426. result.push(this.childString(index));
  427. index = this.buffer[index + 3];
  428. }
  429. return result.join(",");
  430. }
  431. /// @internal
  432. childString(index) {
  433. let id = this.buffer[index], endIndex = this.buffer[index + 3];
  434. let type = this.set.types[id], result = type.name;
  435. if (/\W/.test(result) && !type.isError)
  436. result = JSON.stringify(result);
  437. index += 4;
  438. if (endIndex == index)
  439. return result;
  440. let children = [];
  441. while (index < endIndex) {
  442. children.push(this.childString(index));
  443. index = this.buffer[index + 3];
  444. }
  445. return result + "(" + children.join(",") + ")";
  446. }
  447. /// @internal
  448. findChild(startIndex, endIndex, dir, pos, side) {
  449. let { buffer } = this, pick = -1;
  450. for (let i = startIndex; i != endIndex; i = buffer[i + 3]) {
  451. if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) {
  452. pick = i;
  453. if (dir > 0)
  454. break;
  455. }
  456. }
  457. return pick;
  458. }
  459. /// @internal
  460. slice(startI, endI, from, to) {
  461. let b = this.buffer;
  462. let copy = new Uint16Array(endI - startI);
  463. for (let i = startI, j = 0; i < endI;) {
  464. copy[j++] = b[i++];
  465. copy[j++] = b[i++] - from;
  466. copy[j++] = b[i++] - from;
  467. copy[j++] = b[i++] - startI;
  468. }
  469. return new TreeBuffer(copy, to - from, this.set);
  470. }
  471. }
  472. function checkSide(side, pos, from, to) {
  473. switch (side) {
  474. case -2 /* Before */: return from < pos;
  475. case -1 /* AtOrBefore */: return to >= pos && from < pos;
  476. case 0 /* Around */: return from < pos && to > pos;
  477. case 1 /* AtOrAfter */: return from <= pos && to > pos;
  478. case 2 /* After */: return to > pos;
  479. case 4 /* DontCare */: return true;
  480. }
  481. }
  482. function enterUnfinishedNodesBefore(node, pos) {
  483. let scan = node.childBefore(pos);
  484. while (scan) {
  485. let last = scan.lastChild;
  486. if (!last || last.to != scan.to)
  487. break;
  488. if (last.type.isError && last.from == last.to) {
  489. node = scan;
  490. scan = last.prevSibling;
  491. }
  492. else {
  493. scan = last;
  494. }
  495. }
  496. return node;
  497. }
  498. function resolveNode(node, pos, side, overlays) {
  499. var _a;
  500. // Move up to a node that actually holds the position, if possible
  501. while (node.from == node.to ||
  502. (side < 1 ? node.from >= pos : node.from > pos) ||
  503. (side > -1 ? node.to <= pos : node.to < pos)) {
  504. let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent;
  505. if (!parent)
  506. return node;
  507. node = parent;
  508. }
  509. let mode = overlays ? 0 : exports.IterMode.IgnoreOverlays;
  510. // Must go up out of overlays when those do not overlap with pos
  511. if (overlays)
  512. for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) {
  513. if (scan instanceof TreeNode && scan.index < 0 && ((_a = parent.enter(pos, side, mode)) === null || _a === void 0 ? void 0 : _a.from) != scan.from)
  514. node = parent;
  515. }
  516. for (;;) {
  517. let inner = node.enter(pos, side, mode);
  518. if (!inner)
  519. return node;
  520. node = inner;
  521. }
  522. }
  523. class TreeNode {
  524. constructor(_tree, from,
  525. // Index in parent node, set to -1 if the node is not a direct child of _parent.node (overlay)
  526. index, _parent) {
  527. this._tree = _tree;
  528. this.from = from;
  529. this.index = index;
  530. this._parent = _parent;
  531. }
  532. get type() { return this._tree.type; }
  533. get name() { return this._tree.type.name; }
  534. get to() { return this.from + this._tree.length; }
  535. nextChild(i, dir, pos, side, mode = 0) {
  536. for (let parent = this;;) {
  537. for (let { children, positions } = parent._tree, e = dir > 0 ? children.length : -1; i != e; i += dir) {
  538. let next = children[i], start = positions[i] + parent.from;
  539. if (!checkSide(side, pos, start, start + next.length))
  540. continue;
  541. if (next instanceof TreeBuffer) {
  542. if (mode & exports.IterMode.ExcludeBuffers)
  543. continue;
  544. let index = next.findChild(0, next.buffer.length, dir, pos - start, side);
  545. if (index > -1)
  546. return new BufferNode(new BufferContext(parent, next, i, start), null, index);
  547. }
  548. else if ((mode & exports.IterMode.IncludeAnonymous) || (!next.type.isAnonymous || hasChild(next))) {
  549. let mounted;
  550. if (!(mode & exports.IterMode.IgnoreMounts) &&
  551. next.props && (mounted = next.prop(NodeProp.mounted)) && !mounted.overlay)
  552. return new TreeNode(mounted.tree, start, i, parent);
  553. let inner = new TreeNode(next, start, i, parent);
  554. return (mode & exports.IterMode.IncludeAnonymous) || !inner.type.isAnonymous ? inner
  555. : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side);
  556. }
  557. }
  558. if ((mode & exports.IterMode.IncludeAnonymous) || !parent.type.isAnonymous)
  559. return null;
  560. if (parent.index >= 0)
  561. i = parent.index + dir;
  562. else
  563. i = dir < 0 ? -1 : parent._parent._tree.children.length;
  564. parent = parent._parent;
  565. if (!parent)
  566. return null;
  567. }
  568. }
  569. get firstChild() { return this.nextChild(0, 1, 0, 4 /* DontCare */); }
  570. get lastChild() { return this.nextChild(this._tree.children.length - 1, -1, 0, 4 /* DontCare */); }
  571. childAfter(pos) { return this.nextChild(0, 1, pos, 2 /* After */); }
  572. childBefore(pos) { return this.nextChild(this._tree.children.length - 1, -1, pos, -2 /* Before */); }
  573. enter(pos, side, mode = 0) {
  574. let mounted;
  575. if (!(mode & exports.IterMode.IgnoreOverlays) && (mounted = this._tree.prop(NodeProp.mounted)) && mounted.overlay) {
  576. let rPos = pos - this.from;
  577. for (let { from, to } of mounted.overlay) {
  578. if ((side > 0 ? from <= rPos : from < rPos) &&
  579. (side < 0 ? to >= rPos : to > rPos))
  580. return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this);
  581. }
  582. }
  583. return this.nextChild(0, 1, pos, side, mode);
  584. }
  585. nextSignificantParent() {
  586. let val = this;
  587. while (val.type.isAnonymous && val._parent)
  588. val = val._parent;
  589. return val;
  590. }
  591. get parent() {
  592. return this._parent ? this._parent.nextSignificantParent() : null;
  593. }
  594. get nextSibling() {
  595. return this._parent && this.index >= 0 ? this._parent.nextChild(this.index + 1, 1, 0, 4 /* DontCare */) : null;
  596. }
  597. get prevSibling() {
  598. return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4 /* DontCare */) : null;
  599. }
  600. cursor(mode = 0) { return new TreeCursor(this, mode); }
  601. get tree() { return this._tree; }
  602. toTree() { return this._tree; }
  603. resolve(pos, side = 0) {
  604. return resolveNode(this, pos, side, false);
  605. }
  606. resolveInner(pos, side = 0) {
  607. return resolveNode(this, pos, side, true);
  608. }
  609. enterUnfinishedNodesBefore(pos) { return enterUnfinishedNodesBefore(this, pos); }
  610. getChild(type, before = null, after = null) {
  611. let r = getChildren(this, type, before, after);
  612. return r.length ? r[0] : null;
  613. }
  614. getChildren(type, before = null, after = null) {
  615. return getChildren(this, type, before, after);
  616. }
  617. /// @internal
  618. toString() { return this._tree.toString(); }
  619. get node() { return this; }
  620. matchContext(context) { return matchNodeContext(this, context); }
  621. }
  622. function getChildren(node, type, before, after) {
  623. let cur = node.cursor(), result = [];
  624. if (!cur.firstChild())
  625. return result;
  626. if (before != null)
  627. while (!cur.type.is(before))
  628. if (!cur.nextSibling())
  629. return result;
  630. for (;;) {
  631. if (after != null && cur.type.is(after))
  632. return result;
  633. if (cur.type.is(type))
  634. result.push(cur.node);
  635. if (!cur.nextSibling())
  636. return after == null ? result : [];
  637. }
  638. }
  639. function matchNodeContext(node, context, i = context.length - 1) {
  640. for (let p = node.parent; i >= 0; p = p.parent) {
  641. if (!p)
  642. return false;
  643. if (!p.type.isAnonymous) {
  644. if (context[i] && context[i] != p.name)
  645. return false;
  646. i--;
  647. }
  648. }
  649. return true;
  650. }
  651. class BufferContext {
  652. constructor(parent, buffer, index, start) {
  653. this.parent = parent;
  654. this.buffer = buffer;
  655. this.index = index;
  656. this.start = start;
  657. }
  658. }
  659. class BufferNode {
  660. constructor(context, _parent, index) {
  661. this.context = context;
  662. this._parent = _parent;
  663. this.index = index;
  664. this.type = context.buffer.set.types[context.buffer.buffer[index]];
  665. }
  666. get name() { return this.type.name; }
  667. get from() { return this.context.start + this.context.buffer.buffer[this.index + 1]; }
  668. get to() { return this.context.start + this.context.buffer.buffer[this.index + 2]; }
  669. child(dir, pos, side) {
  670. let { buffer } = this.context;
  671. let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side);
  672. return index < 0 ? null : new BufferNode(this.context, this, index);
  673. }
  674. get firstChild() { return this.child(1, 0, 4 /* DontCare */); }
  675. get lastChild() { return this.child(-1, 0, 4 /* DontCare */); }
  676. childAfter(pos) { return this.child(1, pos, 2 /* After */); }
  677. childBefore(pos) { return this.child(-1, pos, -2 /* Before */); }
  678. enter(pos, side, mode = 0) {
  679. if (mode & exports.IterMode.ExcludeBuffers)
  680. return null;
  681. let { buffer } = this.context;
  682. let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side);
  683. return index < 0 ? null : new BufferNode(this.context, this, index);
  684. }
  685. get parent() {
  686. return this._parent || this.context.parent.nextSignificantParent();
  687. }
  688. externalSibling(dir) {
  689. return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4 /* DontCare */);
  690. }
  691. get nextSibling() {
  692. let { buffer } = this.context;
  693. let after = buffer.buffer[this.index + 3];
  694. if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length))
  695. return new BufferNode(this.context, this._parent, after);
  696. return this.externalSibling(1);
  697. }
  698. get prevSibling() {
  699. let { buffer } = this.context;
  700. let parentStart = this._parent ? this._parent.index + 4 : 0;
  701. if (this.index == parentStart)
  702. return this.externalSibling(-1);
  703. return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4 /* DontCare */));
  704. }
  705. cursor(mode = 0) { return new TreeCursor(this, mode); }
  706. get tree() { return null; }
  707. toTree() {
  708. let children = [], positions = [];
  709. let { buffer } = this.context;
  710. let startI = this.index + 4, endI = buffer.buffer[this.index + 3];
  711. if (endI > startI) {
  712. let from = buffer.buffer[this.index + 1], to = buffer.buffer[this.index + 2];
  713. children.push(buffer.slice(startI, endI, from, to));
  714. positions.push(0);
  715. }
  716. return new Tree(this.type, children, positions, this.to - this.from);
  717. }
  718. resolve(pos, side = 0) {
  719. return resolveNode(this, pos, side, false);
  720. }
  721. resolveInner(pos, side = 0) {
  722. return resolveNode(this, pos, side, true);
  723. }
  724. enterUnfinishedNodesBefore(pos) { return enterUnfinishedNodesBefore(this, pos); }
  725. /// @internal
  726. toString() { return this.context.buffer.childString(this.index); }
  727. getChild(type, before = null, after = null) {
  728. let r = getChildren(this, type, before, after);
  729. return r.length ? r[0] : null;
  730. }
  731. getChildren(type, before = null, after = null) {
  732. return getChildren(this, type, before, after);
  733. }
  734. get node() { return this; }
  735. matchContext(context) { return matchNodeContext(this, context); }
  736. }
  737. /// A tree cursor object focuses on a given node in a syntax tree, and
  738. /// allows you to move to adjacent nodes.
  739. class TreeCursor {
  740. /// @internal
  741. constructor(node,
  742. /// @internal
  743. mode = 0) {
  744. this.mode = mode;
  745. /// @internal
  746. this.buffer = null;
  747. this.stack = [];
  748. /// @internal
  749. this.index = 0;
  750. this.bufferNode = null;
  751. if (node instanceof TreeNode) {
  752. this.yieldNode(node);
  753. }
  754. else {
  755. this._tree = node.context.parent;
  756. this.buffer = node.context;
  757. for (let n = node._parent; n; n = n._parent)
  758. this.stack.unshift(n.index);
  759. this.bufferNode = node;
  760. this.yieldBuf(node.index);
  761. }
  762. }
  763. /// Shorthand for `.type.name`.
  764. get name() { return this.type.name; }
  765. yieldNode(node) {
  766. if (!node)
  767. return false;
  768. this._tree = node;
  769. this.type = node.type;
  770. this.from = node.from;
  771. this.to = node.to;
  772. return true;
  773. }
  774. yieldBuf(index, type) {
  775. this.index = index;
  776. let { start, buffer } = this.buffer;
  777. this.type = type || buffer.set.types[buffer.buffer[index]];
  778. this.from = start + buffer.buffer[index + 1];
  779. this.to = start + buffer.buffer[index + 2];
  780. return true;
  781. }
  782. yield(node) {
  783. if (!node)
  784. return false;
  785. if (node instanceof TreeNode) {
  786. this.buffer = null;
  787. return this.yieldNode(node);
  788. }
  789. this.buffer = node.context;
  790. return this.yieldBuf(node.index, node.type);
  791. }
  792. /// @internal
  793. toString() {
  794. return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();
  795. }
  796. /// @internal
  797. enterChild(dir, pos, side) {
  798. if (!this.buffer)
  799. return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode));
  800. let { buffer } = this.buffer;
  801. let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side);
  802. if (index < 0)
  803. return false;
  804. this.stack.push(this.index);
  805. return this.yieldBuf(index);
  806. }
  807. /// Move the cursor to this node's first child. When this returns
  808. /// false, the node has no child, and the cursor has not been moved.
  809. firstChild() { return this.enterChild(1, 0, 4 /* DontCare */); }
  810. /// Move the cursor to this node's last child.
  811. lastChild() { return this.enterChild(-1, 0, 4 /* DontCare */); }
  812. /// Move the cursor to the first child that ends after `pos`.
  813. childAfter(pos) { return this.enterChild(1, pos, 2 /* After */); }
  814. /// Move to the last child that starts before `pos`.
  815. childBefore(pos) { return this.enterChild(-1, pos, -2 /* Before */); }
  816. /// Move the cursor to the child around `pos`. If side is -1 the
  817. /// child may end at that position, when 1 it may start there. This
  818. /// will also enter [overlaid](#common.MountedTree.overlay)
  819. /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is
  820. /// set to false.
  821. enter(pos, side, mode = this.mode) {
  822. if (!this.buffer)
  823. return this.yield(this._tree.enter(pos, side, mode));
  824. return mode & exports.IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side);
  825. }
  826. /// Move to the node's parent node, if this isn't the top node.
  827. parent() {
  828. if (!this.buffer)
  829. return this.yieldNode((this.mode & exports.IterMode.IncludeAnonymous) ? this._tree._parent : this._tree.parent);
  830. if (this.stack.length)
  831. return this.yieldBuf(this.stack.pop());
  832. let parent = (this.mode & exports.IterMode.IncludeAnonymous) ? this.buffer.parent : this.buffer.parent.nextSignificantParent();
  833. this.buffer = null;
  834. return this.yieldNode(parent);
  835. }
  836. /// @internal
  837. sibling(dir) {
  838. if (!this.buffer)
  839. return !this._tree._parent ? false
  840. : this.yield(this._tree.index < 0 ? null
  841. : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4 /* DontCare */, this.mode));
  842. let { buffer } = this.buffer, d = this.stack.length - 1;
  843. if (dir < 0) {
  844. let parentStart = d < 0 ? 0 : this.stack[d] + 4;
  845. if (this.index != parentStart)
  846. return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4 /* DontCare */));
  847. }
  848. else {
  849. let after = buffer.buffer[this.index + 3];
  850. if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3]))
  851. return this.yieldBuf(after);
  852. }
  853. return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4 /* DontCare */, this.mode)) : false;
  854. }
  855. /// Move to this node's next sibling, if any.
  856. nextSibling() { return this.sibling(1); }
  857. /// Move to this node's previous sibling, if any.
  858. prevSibling() { return this.sibling(-1); }
  859. atLastNode(dir) {
  860. let index, parent, { buffer } = this;
  861. if (buffer) {
  862. if (dir > 0) {
  863. if (this.index < buffer.buffer.buffer.length)
  864. return false;
  865. }
  866. else {
  867. for (let i = 0; i < this.index; i++)
  868. if (buffer.buffer.buffer[i + 3] < this.index)
  869. return false;
  870. }
  871. ({ index, parent } = buffer);
  872. }
  873. else {
  874. ({ index, _parent: parent } = this._tree);
  875. }
  876. for (; parent; { index, _parent: parent } = parent) {
  877. if (index > -1)
  878. for (let i = index + dir, e = dir < 0 ? -1 : parent._tree.children.length; i != e; i += dir) {
  879. let child = parent._tree.children[i];
  880. if ((this.mode & exports.IterMode.IncludeAnonymous) ||
  881. child instanceof TreeBuffer ||
  882. !child.type.isAnonymous ||
  883. hasChild(child))
  884. return false;
  885. }
  886. }
  887. return true;
  888. }
  889. move(dir, enter) {
  890. if (enter && this.enterChild(dir, 0, 4 /* DontCare */))
  891. return true;
  892. for (;;) {
  893. if (this.sibling(dir))
  894. return true;
  895. if (this.atLastNode(dir) || !this.parent())
  896. return false;
  897. }
  898. }
  899. /// Move to the next node in a
  900. /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR))
  901. /// traversal, going from a node to its first child or, if the
  902. /// current node is empty or `enter` is false, its next sibling or
  903. /// the next sibling of the first parent node that has one.
  904. next(enter = true) { return this.move(1, enter); }
  905. /// Move to the next node in a last-to-first pre-order traveral. A
  906. /// node is followed by its last child or, if it has none, its
  907. /// previous sibling or the previous sibling of the first parent
  908. /// node that has one.
  909. prev(enter = true) { return this.move(-1, enter); }
  910. /// Move the cursor to the innermost node that covers `pos`. If
  911. /// `side` is -1, it will enter nodes that end at `pos`. If it is 1,
  912. /// it will enter nodes that start at `pos`.
  913. moveTo(pos, side = 0) {
  914. // Move up to a node that actually holds the position, if possible
  915. while (this.from == this.to ||
  916. (side < 1 ? this.from >= pos : this.from > pos) ||
  917. (side > -1 ? this.to <= pos : this.to < pos))
  918. if (!this.parent())
  919. break;
  920. // Then scan down into child nodes as far as possible
  921. while (this.enterChild(1, pos, side)) { }
  922. return this;
  923. }
  924. /// Get a [syntax node](#common.SyntaxNode) at the cursor's current
  925. /// position.
  926. get node() {
  927. if (!this.buffer)
  928. return this._tree;
  929. let cache = this.bufferNode, result = null, depth = 0;
  930. if (cache && cache.context == this.buffer) {
  931. scan: for (let index = this.index, d = this.stack.length; d >= 0;) {
  932. for (let c = cache; c; c = c._parent)
  933. if (c.index == index) {
  934. if (index == this.index)
  935. return c;
  936. result = c;
  937. depth = d + 1;
  938. break scan;
  939. }
  940. index = this.stack[--d];
  941. }
  942. }
  943. for (let i = depth; i < this.stack.length; i++)
  944. result = new BufferNode(this.buffer, result, this.stack[i]);
  945. return this.bufferNode = new BufferNode(this.buffer, result, this.index);
  946. }
  947. /// Get the [tree](#common.Tree) that represents the current node, if
  948. /// any. Will return null when the node is in a [tree
  949. /// buffer](#common.TreeBuffer).
  950. get tree() {
  951. return this.buffer ? null : this._tree._tree;
  952. }
  953. /// Iterate over the current node and all its descendants, calling
  954. /// `enter` when entering a node and `leave`, if given, when leaving
  955. /// one. When `enter` returns `false`, any children of that node are
  956. /// skipped, and `leave` isn't called for it.
  957. iterate(enter, leave) {
  958. for (let depth = 0;;) {
  959. let mustLeave = false;
  960. if (this.type.isAnonymous || enter(this) !== false) {
  961. if (this.firstChild()) {
  962. depth++;
  963. continue;
  964. }
  965. if (!this.type.isAnonymous)
  966. mustLeave = true;
  967. }
  968. for (;;) {
  969. if (mustLeave && leave)
  970. leave(this);
  971. mustLeave = this.type.isAnonymous;
  972. if (this.nextSibling())
  973. break;
  974. if (!depth)
  975. return;
  976. this.parent();
  977. depth--;
  978. mustLeave = true;
  979. }
  980. }
  981. }
  982. /// Test whether the current node matches a given context—a sequence
  983. /// of direct parent node names. Empty strings in the context array
  984. /// are treated as wildcards.
  985. matchContext(context) {
  986. if (!this.buffer)
  987. return matchNodeContext(this.node, context);
  988. let { buffer } = this.buffer, { types } = buffer.set;
  989. for (let i = context.length - 1, d = this.stack.length - 1; i >= 0; d--) {
  990. if (d < 0)
  991. return matchNodeContext(this.node, context, i);
  992. let type = types[buffer.buffer[this.stack[d]]];
  993. if (!type.isAnonymous) {
  994. if (context[i] && context[i] != type.name)
  995. return false;
  996. i--;
  997. }
  998. }
  999. return true;
  1000. }
  1001. }
  1002. function hasChild(tree) {
  1003. return tree.children.some(ch => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch));
  1004. }
  1005. function buildTree(data) {
  1006. var _a;
  1007. let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data;
  1008. let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;
  1009. let types = nodeSet.types;
  1010. let contextHash = 0, lookAhead = 0;
  1011. function takeNode(parentStart, minPos, children, positions, inRepeat) {
  1012. let { id, start, end, size } = cursor;
  1013. let lookAheadAtStart = lookAhead;
  1014. while (size < 0) {
  1015. cursor.next();
  1016. if (size == -1 /* Reuse */) {
  1017. let node = reused[id];
  1018. children.push(node);
  1019. positions.push(start - parentStart);
  1020. return;
  1021. }
  1022. else if (size == -3 /* ContextChange */) { // Context change
  1023. contextHash = id;
  1024. return;
  1025. }
  1026. else if (size == -4 /* LookAhead */) {
  1027. lookAhead = id;
  1028. return;
  1029. }
  1030. else {
  1031. throw new RangeError(`Unrecognized record size: ${size}`);
  1032. }
  1033. }
  1034. let type = types[id], node, buffer;
  1035. let startPos = start - parentStart;
  1036. if (end - start <= maxBufferLength && (buffer = findBufferSize(cursor.pos - minPos, inRepeat))) {
  1037. // Small enough for a buffer, and no reused nodes inside
  1038. let data = new Uint16Array(buffer.size - buffer.skip);
  1039. let endPos = cursor.pos - buffer.size, index = data.length;
  1040. while (cursor.pos > endPos)
  1041. index = copyToBuffer(buffer.start, data, index);
  1042. node = new TreeBuffer(data, end - buffer.start, nodeSet);
  1043. startPos = buffer.start - parentStart;
  1044. }
  1045. else { // Make it a node
  1046. let endPos = cursor.pos - size;
  1047. cursor.next();
  1048. let localChildren = [], localPositions = [];
  1049. let localInRepeat = id >= minRepeatType ? id : -1;
  1050. let lastGroup = 0, lastEnd = end;
  1051. while (cursor.pos > endPos) {
  1052. if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) {
  1053. if (cursor.end <= lastEnd - maxBufferLength) {
  1054. makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart);
  1055. lastGroup = localChildren.length;
  1056. lastEnd = cursor.end;
  1057. }
  1058. cursor.next();
  1059. }
  1060. else {
  1061. takeNode(start, endPos, localChildren, localPositions, localInRepeat);
  1062. }
  1063. }
  1064. if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length)
  1065. makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart);
  1066. localChildren.reverse();
  1067. localPositions.reverse();
  1068. if (localInRepeat > -1 && lastGroup > 0) {
  1069. let make = makeBalanced(type);
  1070. node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make);
  1071. }
  1072. else {
  1073. node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end);
  1074. }
  1075. }
  1076. children.push(node);
  1077. positions.push(startPos);
  1078. }
  1079. function makeBalanced(type) {
  1080. return (children, positions, length) => {
  1081. let lookAhead = 0, lastI = children.length - 1, last, lookAheadProp;
  1082. if (lastI >= 0 && (last = children[lastI]) instanceof Tree) {
  1083. if (!lastI && last.type == type && last.length == length)
  1084. return last;
  1085. if (lookAheadProp = last.prop(NodeProp.lookAhead))
  1086. lookAhead = positions[lastI] + last.length + lookAheadProp;
  1087. }
  1088. return makeTree(type, children, positions, length, lookAhead);
  1089. };
  1090. }
  1091. function makeRepeatLeaf(children, positions, base, i, from, to, type, lookAhead) {
  1092. let localChildren = [], localPositions = [];
  1093. while (children.length > i) {
  1094. localChildren.push(children.pop());
  1095. localPositions.push(positions.pop() + base - from);
  1096. }
  1097. children.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead - to));
  1098. positions.push(from - base);
  1099. }
  1100. function makeTree(type, children, positions, length, lookAhead = 0, props) {
  1101. if (contextHash) {
  1102. let pair = [NodeProp.contextHash, contextHash];
  1103. props = props ? [pair].concat(props) : [pair];
  1104. }
  1105. if (lookAhead > 25) {
  1106. let pair = [NodeProp.lookAhead, lookAhead];
  1107. props = props ? [pair].concat(props) : [pair];
  1108. }
  1109. return new Tree(type, children, positions, length, props);
  1110. }
  1111. function findBufferSize(maxSize, inRepeat) {
  1112. // Scan through the buffer to find previous siblings that fit
  1113. // together in a TreeBuffer, and don't contain any reused nodes
  1114. // (which can't be stored in a buffer).
  1115. // If `inRepeat` is > -1, ignore node boundaries of that type for
  1116. // nesting, but make sure the end falls either at the start
  1117. // (`maxSize`) or before such a node.
  1118. let fork = cursor.fork();
  1119. let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength;
  1120. let result = { size: 0, start: 0, skip: 0 };
  1121. scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos;) {
  1122. let nodeSize = fork.size;
  1123. // Pretend nested repeat nodes of the same type don't exist
  1124. if (fork.id == inRepeat && nodeSize >= 0) {
  1125. // Except that we store the current state as a valid return
  1126. // value.
  1127. result.size = size;
  1128. result.start = start;
  1129. result.skip = skip;
  1130. skip += 4;
  1131. size += 4;
  1132. fork.next();
  1133. continue;
  1134. }
  1135. let startPos = fork.pos - nodeSize;
  1136. if (nodeSize < 0 || startPos < minPos || fork.start < minStart)
  1137. break;
  1138. let localSkipped = fork.id >= minRepeatType ? 4 : 0;
  1139. let nodeStart = fork.start;
  1140. fork.next();
  1141. while (fork.pos > startPos) {
  1142. if (fork.size < 0) {
  1143. if (fork.size == -3 /* ContextChange */)
  1144. localSkipped += 4;
  1145. else
  1146. break scan;
  1147. }
  1148. else if (fork.id >= minRepeatType) {
  1149. localSkipped += 4;
  1150. }
  1151. fork.next();
  1152. }
  1153. start = nodeStart;
  1154. size += nodeSize;
  1155. skip += localSkipped;
  1156. }
  1157. if (inRepeat < 0 || size == maxSize) {
  1158. result.size = size;
  1159. result.start = start;
  1160. result.skip = skip;
  1161. }
  1162. return result.size > 4 ? result : undefined;
  1163. }
  1164. function copyToBuffer(bufferStart, buffer, index) {
  1165. let { id, start, end, size } = cursor;
  1166. cursor.next();
  1167. if (size >= 0 && id < minRepeatType) {
  1168. let startIndex = index;
  1169. if (size > 4) {
  1170. let endPos = cursor.pos - (size - 4);
  1171. while (cursor.pos > endPos)
  1172. index = copyToBuffer(bufferStart, buffer, index);
  1173. }
  1174. buffer[--index] = startIndex;
  1175. buffer[--index] = end - bufferStart;
  1176. buffer[--index] = start - bufferStart;
  1177. buffer[--index] = id;
  1178. }
  1179. else if (size == -3 /* ContextChange */) {
  1180. contextHash = id;
  1181. }
  1182. else if (size == -4 /* LookAhead */) {
  1183. lookAhead = id;
  1184. }
  1185. return index;
  1186. }
  1187. let children = [], positions = [];
  1188. while (cursor.pos > 0)
  1189. takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1);
  1190. let length = (_a = data.length) !== null && _a !== void 0 ? _a : (children.length ? positions[0] + children[0].length : 0);
  1191. return new Tree(types[data.topID], children.reverse(), positions.reverse(), length);
  1192. }
  1193. const nodeSizeCache = new WeakMap;
  1194. function nodeSize(balanceType, node) {
  1195. if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType)
  1196. return 1;
  1197. let size = nodeSizeCache.get(node);
  1198. if (size == null) {
  1199. size = 1;
  1200. for (let child of node.children) {
  1201. if (child.type != balanceType || !(child instanceof Tree)) {
  1202. size = 1;
  1203. break;
  1204. }
  1205. size += nodeSize(balanceType, child);
  1206. }
  1207. nodeSizeCache.set(node, size);
  1208. }
  1209. return size;
  1210. }
  1211. function balanceRange(
  1212. // The type the balanced tree's inner nodes.
  1213. balanceType,
  1214. // The direct children and their positions
  1215. children, positions,
  1216. // The index range in children/positions to use
  1217. from, to,
  1218. // The start position of the nodes, relative to their parent.
  1219. start,
  1220. // Length of the outer node
  1221. length,
  1222. // Function to build the top node of the balanced tree
  1223. mkTop,
  1224. // Function to build internal nodes for the balanced tree
  1225. mkTree) {
  1226. let total = 0;
  1227. for (let i = from; i < to; i++)
  1228. total += nodeSize(balanceType, children[i]);
  1229. let maxChild = Math.ceil((total * 1.5) / 8 /* BranchFactor */);
  1230. let localChildren = [], localPositions = [];
  1231. function divide(children, positions, from, to, offset) {
  1232. for (let i = from; i < to;) {
  1233. let groupFrom = i, groupStart = positions[i], groupSize = nodeSize(balanceType, children[i]);
  1234. i++;
  1235. for (; i < to; i++) {
  1236. let nextSize = nodeSize(balanceType, children[i]);
  1237. if (groupSize + nextSize >= maxChild)
  1238. break;
  1239. groupSize += nextSize;
  1240. }
  1241. if (i == groupFrom + 1) {
  1242. if (groupSize > maxChild) {
  1243. let only = children[groupFrom]; // Only trees can have a size > 1
  1244. divide(only.children, only.positions, 0, only.children.length, positions[groupFrom] + offset);
  1245. continue;
  1246. }
  1247. localChildren.push(children[groupFrom]);
  1248. }
  1249. else {
  1250. let length = positions[i - 1] + children[i - 1].length - groupStart;
  1251. localChildren.push(balanceRange(balanceType, children, positions, groupFrom, i, groupStart, length, null, mkTree));
  1252. }
  1253. localPositions.push(groupStart + offset - start);
  1254. }
  1255. }
  1256. divide(children, positions, from, to, 0);
  1257. return (mkTop || mkTree)(localChildren, localPositions, length);
  1258. }
  1259. /// Provides a way to associate values with pieces of trees. As long
  1260. /// as that part of the tree is reused, the associated values can be
  1261. /// retrieved from an updated tree.
  1262. class NodeWeakMap {
  1263. constructor() {
  1264. this.map = new WeakMap();
  1265. }
  1266. setBuffer(buffer, index, value) {
  1267. let inner = this.map.get(buffer);
  1268. if (!inner)
  1269. this.map.set(buffer, inner = new Map);
  1270. inner.set(index, value);
  1271. }
  1272. getBuffer(buffer, index) {
  1273. let inner = this.map.get(buffer);
  1274. return inner && inner.get(index);
  1275. }
  1276. /// Set the value for this syntax node.
  1277. set(node, value) {
  1278. if (node instanceof BufferNode)
  1279. this.setBuffer(node.context.buffer, node.index, value);
  1280. else if (node instanceof TreeNode)
  1281. this.map.set(node.tree, value);
  1282. }
  1283. /// Retrieve value for this syntax node, if it exists in the map.
  1284. get(node) {
  1285. return node instanceof BufferNode ? this.getBuffer(node.context.buffer, node.index)
  1286. : node instanceof TreeNode ? this.map.get(node.tree) : undefined;
  1287. }
  1288. /// Set the value for the node that a cursor currently points to.
  1289. cursorSet(cursor, value) {
  1290. if (cursor.buffer)
  1291. this.setBuffer(cursor.buffer.buffer, cursor.index, value);
  1292. else
  1293. this.map.set(cursor.tree, value);
  1294. }
  1295. /// Retrieve the value for the node that a cursor currently points
  1296. /// to.
  1297. cursorGet(cursor) {
  1298. return cursor.buffer ? this.getBuffer(cursor.buffer.buffer, cursor.index) : this.map.get(cursor.tree);
  1299. }
  1300. }
  1301. /// Tree fragments are used during [incremental
  1302. /// parsing](#common.Parser.startParse) to track parts of old trees
  1303. /// that can be reused in a new parse. An array of fragments is used
  1304. /// to track regions of an old tree whose nodes might be reused in new
  1305. /// parses. Use the static
  1306. /// [`applyChanges`](#common.TreeFragment^applyChanges) method to
  1307. /// update fragments for document changes.
  1308. class TreeFragment {
  1309. /// Construct a tree fragment. You'll usually want to use
  1310. /// [`addTree`](#common.TreeFragment^addTree) and
  1311. /// [`applyChanges`](#common.TreeFragment^applyChanges) instead of
  1312. /// calling this directly.
  1313. constructor(
  1314. /// The start of the unchanged range pointed to by this fragment.
  1315. /// This refers to an offset in the _updated_ document (as opposed
  1316. /// to the original tree).
  1317. from,
  1318. /// The end of the unchanged range.
  1319. to,
  1320. /// The tree that this fragment is based on.
  1321. tree,
  1322. /// The offset between the fragment's tree and the document that
  1323. /// this fragment can be used against. Add this when going from
  1324. /// document to tree positions, subtract it to go from tree to
  1325. /// document positions.
  1326. offset, openStart = false, openEnd = false) {
  1327. this.from = from;
  1328. this.to = to;
  1329. this.tree = tree;
  1330. this.offset = offset;
  1331. this.open = (openStart ? 1 /* Start */ : 0) | (openEnd ? 2 /* End */ : 0);
  1332. }
  1333. /// Whether the start of the fragment represents the start of a
  1334. /// parse, or the end of a change. (In the second case, it may not
  1335. /// be safe to reuse some nodes at the start, depending on the
  1336. /// parsing algorithm.)
  1337. get openStart() { return (this.open & 1 /* Start */) > 0; }
  1338. /// Whether the end of the fragment represents the end of a
  1339. /// full-document parse, or the start of a change.
  1340. get openEnd() { return (this.open & 2 /* End */) > 0; }
  1341. /// Create a set of fragments from a freshly parsed tree, or update
  1342. /// an existing set of fragments by replacing the ones that overlap
  1343. /// with a tree with content from the new tree. When `partial` is
  1344. /// true, the parse is treated as incomplete, and the resulting
  1345. /// fragment has [`openEnd`](#common.TreeFragment.openEnd) set to
  1346. /// true.
  1347. static addTree(tree, fragments = [], partial = false) {
  1348. let result = [new TreeFragment(0, tree.length, tree, 0, false, partial)];
  1349. for (let f of fragments)
  1350. if (f.to > tree.length)
  1351. result.push(f);
  1352. return result;
  1353. }
  1354. /// Apply a set of edits to an array of fragments, removing or
  1355. /// splitting fragments as necessary to remove edited ranges, and
  1356. /// adjusting offsets for fragments that moved.
  1357. static applyChanges(fragments, changes, minGap = 128) {
  1358. if (!changes.length)
  1359. return fragments;
  1360. let result = [];
  1361. let fI = 1, nextF = fragments.length ? fragments[0] : null;
  1362. for (let cI = 0, pos = 0, off = 0;; cI++) {
  1363. let nextC = cI < changes.length ? changes[cI] : null;
  1364. let nextPos = nextC ? nextC.fromA : 1e9;
  1365. if (nextPos - pos >= minGap)
  1366. while (nextF && nextF.from < nextPos) {
  1367. let cut = nextF;
  1368. if (pos >= cut.from || nextPos <= cut.to || off) {
  1369. let fFrom = Math.max(cut.from, pos) - off, fTo = Math.min(cut.to, nextPos) - off;
  1370. cut = fFrom >= fTo ? null : new TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, cI > 0, !!nextC);
  1371. }
  1372. if (cut)
  1373. result.push(cut);
  1374. if (nextF.to > nextPos)
  1375. break;
  1376. nextF = fI < fragments.length ? fragments[fI++] : null;
  1377. }
  1378. if (!nextC)
  1379. break;
  1380. pos = nextC.toA;
  1381. off = nextC.toA - nextC.toB;
  1382. }
  1383. return result;
  1384. }
  1385. }
  1386. /// A superclass that parsers should extend.
  1387. class Parser {
  1388. /// Start a parse, returning a [partial parse](#common.PartialParse)
  1389. /// object. [`fragments`](#common.TreeFragment) can be passed in to
  1390. /// make the parse incremental.
  1391. ///
  1392. /// By default, the entire input is parsed. You can pass `ranges`,
  1393. /// which should be a sorted array of non-empty, non-overlapping
  1394. /// ranges, to parse only those ranges. The tree returned in that
  1395. /// case will start at `ranges[0].from`.
  1396. startParse(input, fragments, ranges) {
  1397. if (typeof input == "string")
  1398. input = new StringInput(input);
  1399. ranges = !ranges ? [new Range(0, input.length)] : ranges.length ? ranges.map(r => new Range(r.from, r.to)) : [new Range(0, 0)];
  1400. return this.createParse(input, fragments || [], ranges);
  1401. }
  1402. /// Run a full parse, returning the resulting tree.
  1403. parse(input, fragments, ranges) {
  1404. let parse = this.startParse(input, fragments, ranges);
  1405. for (;;) {
  1406. let done = parse.advance();
  1407. if (done)
  1408. return done;
  1409. }
  1410. }
  1411. }
  1412. class StringInput {
  1413. constructor(string) {
  1414. this.string = string;
  1415. }
  1416. get length() { return this.string.length; }
  1417. chunk(from) { return this.string.slice(from); }
  1418. get lineChunks() { return false; }
  1419. read(from, to) { return this.string.slice(from, to); }
  1420. }
  1421. /// Create a parse wrapper that, after the inner parse completes,
  1422. /// scans its tree for mixed language regions with the `nest`
  1423. /// function, runs the resulting [inner parses](#common.NestedParse),
  1424. /// and then [mounts](#common.NodeProp^mounted) their results onto the
  1425. /// tree.
  1426. function parseMixed(nest) {
  1427. return (parse, input, fragments, ranges) => new MixedParse(parse, nest, input, fragments, ranges);
  1428. }
  1429. class InnerParse {
  1430. constructor(parser, parse, overlay, target, ranges) {
  1431. this.parser = parser;
  1432. this.parse = parse;
  1433. this.overlay = overlay;
  1434. this.target = target;
  1435. this.ranges = ranges;
  1436. }
  1437. }
  1438. class ActiveOverlay {
  1439. constructor(parser, predicate, mounts, index, start, target, prev) {
  1440. this.parser = parser;
  1441. this.predicate = predicate;
  1442. this.mounts = mounts;
  1443. this.index = index;
  1444. this.start = start;
  1445. this.target = target;
  1446. this.prev = prev;
  1447. this.depth = 0;
  1448. this.ranges = [];
  1449. }
  1450. }
  1451. const stoppedInner = new NodeProp({ perNode: true });
  1452. class MixedParse {
  1453. constructor(base, nest, input, fragments, ranges) {
  1454. this.nest = nest;
  1455. this.input = input;
  1456. this.fragments = fragments;
  1457. this.ranges = ranges;
  1458. this.inner = [];
  1459. this.innerDone = 0;
  1460. this.baseTree = null;
  1461. this.stoppedAt = null;
  1462. this.baseParse = base;
  1463. }
  1464. advance() {
  1465. if (this.baseParse) {
  1466. let done = this.baseParse.advance();
  1467. if (!done)
  1468. return null;
  1469. this.baseParse = null;
  1470. this.baseTree = done;
  1471. this.startInner();
  1472. if (this.stoppedAt != null)
  1473. for (let inner of this.inner)
  1474. inner.parse.stopAt(this.stoppedAt);
  1475. }
  1476. if (this.innerDone == this.inner.length) {
  1477. let result = this.baseTree;
  1478. if (this.stoppedAt != null)
  1479. result = new Tree(result.type, result.children, result.positions, result.length, result.propValues.concat([[stoppedInner, this.stoppedAt]]));
  1480. return result;
  1481. }
  1482. let inner = this.inner[this.innerDone], done = inner.parse.advance();
  1483. if (done) {
  1484. this.innerDone++;
  1485. // This is a somewhat dodgy but super helpful hack where we
  1486. // patch up nodes created by the inner parse (and thus
  1487. // presumably not aliased anywhere else) to hold the information
  1488. // about the inner parse.
  1489. let props = Object.assign(Object.create(null), inner.target.props);
  1490. props[NodeProp.mounted.id] = new MountedTree(done, inner.overlay, inner.parser);
  1491. inner.target.props = props;
  1492. }
  1493. return null;
  1494. }
  1495. get parsedPos() {
  1496. if (this.baseParse)
  1497. return 0;
  1498. let pos = this.input.length;
  1499. for (let i = this.innerDone; i < this.inner.length; i++) {
  1500. if (this.inner[i].ranges[0].from < pos)
  1501. pos = Math.min(pos, this.inner[i].parse.parsedPos);
  1502. }
  1503. return pos;
  1504. }
  1505. stopAt(pos) {
  1506. this.stoppedAt = pos;
  1507. if (this.baseParse)
  1508. this.baseParse.stopAt(pos);
  1509. else
  1510. for (let i = this.innerDone; i < this.inner.length; i++)
  1511. this.inner[i].parse.stopAt(pos);
  1512. }
  1513. startInner() {
  1514. let fragmentCursor = new FragmentCursor(this.fragments);
  1515. let overlay = null;
  1516. let covered = null;
  1517. let cursor = new TreeCursor(new TreeNode(this.baseTree, this.ranges[0].from, 0, null), exports.IterMode.IncludeAnonymous | exports.IterMode.IgnoreMounts);
  1518. scan: for (let nest, isCovered; this.stoppedAt == null || cursor.from < this.stoppedAt;) {
  1519. let enter = true, range;
  1520. if (fragmentCursor.hasNode(cursor)) {
  1521. if (overlay) {
  1522. let match = overlay.mounts.find(m => m.frag.from <= cursor.from && m.frag.to >= cursor.to && m.mount.overlay);
  1523. if (match)
  1524. for (let r of match.mount.overlay) {
  1525. let from = r.from + match.pos, to = r.to + match.pos;
  1526. if (from >= cursor.from && to <= cursor.to && !overlay.ranges.some(r => r.from < to && r.to > from))
  1527. overlay.ranges.push({ from, to });
  1528. }
  1529. }
  1530. enter = false;
  1531. }
  1532. else if (covered && (isCovered = checkCover(covered.ranges, cursor.from, cursor.to))) {
  1533. enter = isCovered != 2 /* Full */;
  1534. }
  1535. else if (!cursor.type.isAnonymous && cursor.from < cursor.to && (nest = this.nest(cursor, this.input))) {
  1536. if (!cursor.tree)
  1537. materialize(cursor);
  1538. let oldMounts = fragmentCursor.findMounts(cursor.from, nest.parser);
  1539. if (typeof nest.overlay == "function") {
  1540. overlay = new ActiveOverlay(nest.parser, nest.overlay, oldMounts, this.inner.length, cursor.from, cursor.tree, overlay);
  1541. }
  1542. else {
  1543. let ranges = punchRanges(this.ranges, nest.overlay || [new Range(cursor.from, cursor.to)]);
  1544. if (ranges.length)
  1545. this.inner.push(new InnerParse(nest.parser, nest.parser.startParse(this.input, enterFragments(oldMounts, ranges), ranges), nest.overlay ? nest.overlay.map(r => new Range(r.from - cursor.from, r.to - cursor.from)) : null, cursor.tree, ranges));
  1546. if (!nest.overlay)
  1547. enter = false;
  1548. else if (ranges.length)
  1549. covered = { ranges, depth: 0, prev: covered };
  1550. }
  1551. }
  1552. else if (overlay && (range = overlay.predicate(cursor))) {
  1553. if (range === true)
  1554. range = new Range(cursor.from, cursor.to);
  1555. if (range.from < range.to)
  1556. overlay.ranges.push(range);
  1557. }
  1558. if (enter && cursor.firstChild()) {
  1559. if (overlay)
  1560. overlay.depth++;
  1561. if (covered)
  1562. covered.depth++;
  1563. }
  1564. else {
  1565. for (;;) {
  1566. if (cursor.nextSibling())
  1567. break;
  1568. if (!cursor.parent())
  1569. break scan;
  1570. if (overlay && !--overlay.depth) {
  1571. let ranges = punchRanges(this.ranges, overlay.ranges);
  1572. if (ranges.length)
  1573. this.inner.splice(overlay.index, 0, new InnerParse(overlay.parser, overlay.parser.startParse(this.input, enterFragments(overlay.mounts, ranges), ranges), overlay.ranges.map(r => new Range(r.from - overlay.start, r.to - overlay.start)), overlay.target, ranges));
  1574. overlay = overlay.prev;
  1575. }
  1576. if (covered && !--covered.depth)
  1577. covered = covered.prev;
  1578. }
  1579. }
  1580. }
  1581. }
  1582. }
  1583. function checkCover(covered, from, to) {
  1584. for (let range of covered) {
  1585. if (range.from >= to)
  1586. break;
  1587. if (range.to > from)
  1588. return range.from <= from && range.to >= to ? 2 /* Full */ : 1 /* Partial */;
  1589. }
  1590. return 0 /* None */;
  1591. }
  1592. // Take a piece of buffer and convert it into a stand-alone
  1593. // TreeBuffer.
  1594. function sliceBuf(buf, startI, endI, nodes, positions, off) {
  1595. if (startI < endI) {
  1596. let from = buf.buffer[startI + 1], to = buf.buffer[endI - 2];
  1597. nodes.push(buf.slice(startI, endI, from, to));
  1598. positions.push(from - off);
  1599. }
  1600. }
  1601. // This function takes a node that's in a buffer, and converts it, and
  1602. // its parent buffer nodes, into a Tree. This is again acting on the
  1603. // assumption that the trees and buffers have been constructed by the
  1604. // parse that was ran via the mix parser, and thus aren't shared with
  1605. // any other code, making violations of the immutability safe.
  1606. function materialize(cursor) {
  1607. let { node } = cursor, depth = 0;
  1608. // Scan up to the nearest tree
  1609. do {
  1610. cursor.parent();
  1611. depth++;
  1612. } while (!cursor.tree);
  1613. // Find the index of the buffer in that tree
  1614. let i = 0, base = cursor.tree, off = 0;
  1615. for (;; i++) {
  1616. off = base.positions[i] + cursor.from;
  1617. if (off <= node.from && off + base.children[i].length >= node.to)
  1618. break;
  1619. }
  1620. let buf = base.children[i], b = buf.buffer;
  1621. // Split a level in the buffer, putting the nodes before and after
  1622. // the child that contains `node` into new buffers.
  1623. function split(startI, endI, type, innerOffset, length) {
  1624. let i = startI;
  1625. while (b[i + 2] + off <= node.from)
  1626. i = b[i + 3];
  1627. let children = [], positions = [];
  1628. sliceBuf(buf, startI, i, children, positions, innerOffset);
  1629. let from = b[i + 1], to = b[i + 2];
  1630. let isTarget = from + off == node.from && to + off == node.to && b[i] == node.type.id;
  1631. children.push(isTarget ? node.toTree() : split(i + 4, b[i + 3], buf.set.types[b[i]], from, to - from));
  1632. positions.push(from - innerOffset);
  1633. sliceBuf(buf, b[i + 3], endI, children, positions, innerOffset);
  1634. return new Tree(type, children, positions, length);
  1635. }
  1636. base.children[i] = split(0, b.length, NodeType.none, 0, buf.length);
  1637. // Move the cursor back to the target node
  1638. for (let d = 0; d <= depth; d++)
  1639. cursor.childAfter(node.from);
  1640. }
  1641. class StructureCursor {
  1642. constructor(root, offset) {
  1643. this.offset = offset;
  1644. this.done = false;
  1645. this.cursor = root.cursor(exports.IterMode.IncludeAnonymous | exports.IterMode.IgnoreMounts);
  1646. }
  1647. // Move to the first node (in pre-order) that starts at or after `pos`.
  1648. moveTo(pos) {
  1649. let { cursor } = this, p = pos - this.offset;
  1650. while (!this.done && cursor.from < p) {
  1651. if (cursor.to >= pos && cursor.enter(p, 1, exports.IterMode.IgnoreOverlays | exports.IterMode.ExcludeBuffers)) ;
  1652. else if (!cursor.next(false))
  1653. this.done = true;
  1654. }
  1655. }
  1656. hasNode(cursor) {
  1657. this.moveTo(cursor.from);
  1658. if (!this.done && this.cursor.from + this.offset == cursor.from && this.cursor.tree) {
  1659. for (let tree = this.cursor.tree;;) {
  1660. if (tree == cursor.tree)
  1661. return true;
  1662. if (tree.children.length && tree.positions[0] == 0 && tree.children[0] instanceof Tree)
  1663. tree = tree.children[0];
  1664. else
  1665. break;
  1666. }
  1667. }
  1668. return false;
  1669. }
  1670. }
  1671. class FragmentCursor {
  1672. constructor(fragments) {
  1673. var _a;
  1674. this.fragments = fragments;
  1675. this.curTo = 0;
  1676. this.fragI = 0;
  1677. if (fragments.length) {
  1678. let first = this.curFrag = fragments[0];
  1679. this.curTo = (_a = first.tree.prop(stoppedInner)) !== null && _a !== void 0 ? _a : first.to;
  1680. this.inner = new StructureCursor(first.tree, -first.offset);
  1681. }
  1682. else {
  1683. this.curFrag = this.inner = null;
  1684. }
  1685. }
  1686. hasNode(node) {
  1687. while (this.curFrag && node.from >= this.curTo)
  1688. this.nextFrag();
  1689. return this.curFrag && this.curFrag.from <= node.from && this.curTo >= node.to && this.inner.hasNode(node);
  1690. }
  1691. nextFrag() {
  1692. var _a;
  1693. this.fragI++;
  1694. if (this.fragI == this.fragments.length) {
  1695. this.curFrag = this.inner = null;
  1696. }
  1697. else {
  1698. let frag = this.curFrag = this.fragments[this.fragI];
  1699. this.curTo = (_a = frag.tree.prop(stoppedInner)) !== null && _a !== void 0 ? _a : frag.to;
  1700. this.inner = new StructureCursor(frag.tree, -frag.offset);
  1701. }
  1702. }
  1703. findMounts(pos, parser) {
  1704. var _a;
  1705. let result = [];
  1706. if (this.inner) {
  1707. this.inner.cursor.moveTo(pos, 1);
  1708. for (let pos = this.inner.cursor.node; pos; pos = pos.parent) {
  1709. let mount = (_a = pos.tree) === null || _a === void 0 ? void 0 : _a.prop(NodeProp.mounted);
  1710. if (mount && mount.parser == parser) {
  1711. for (let i = this.fragI; i < this.fragments.length; i++) {
  1712. let frag = this.fragments[i];
  1713. if (frag.from >= pos.to)
  1714. break;
  1715. if (frag.tree == this.curFrag.tree)
  1716. result.push({
  1717. frag,
  1718. pos: pos.from - frag.offset,
  1719. mount
  1720. });
  1721. }
  1722. }
  1723. }
  1724. }
  1725. return result;
  1726. }
  1727. }
  1728. function punchRanges(outer, ranges) {
  1729. let copy = null, current = ranges;
  1730. for (let i = 1, j = 0; i < outer.length; i++) {
  1731. let gapFrom = outer[i - 1].to, gapTo = outer[i].from;
  1732. for (; j < current.length; j++) {
  1733. let r = current[j];
  1734. if (r.from >= gapTo)
  1735. break;
  1736. if (r.to <= gapFrom)
  1737. continue;
  1738. if (!copy)
  1739. current = copy = ranges.slice();
  1740. if (r.from < gapFrom) {
  1741. copy[j] = new Range(r.from, gapFrom);
  1742. if (r.to > gapTo)
  1743. copy.splice(j + 1, 0, new Range(gapTo, r.to));
  1744. }
  1745. else if (r.to > gapTo) {
  1746. copy[j--] = new Range(gapTo, r.to);
  1747. }
  1748. else {
  1749. copy.splice(j--, 1);
  1750. }
  1751. }
  1752. }
  1753. return current;
  1754. }
  1755. function findCoverChanges(a, b, from, to) {
  1756. let iA = 0, iB = 0, inA = false, inB = false, pos = -1e9;
  1757. let result = [];
  1758. for (;;) {
  1759. let nextA = iA == a.length ? 1e9 : inA ? a[iA].to : a[iA].from;
  1760. let nextB = iB == b.length ? 1e9 : inB ? b[iB].to : b[iB].from;
  1761. if (inA != inB) {
  1762. let start = Math.max(pos, from), end = Math.min(nextA, nextB, to);
  1763. if (start < end)
  1764. result.push(new Range(start, end));
  1765. }
  1766. pos = Math.min(nextA, nextB);
  1767. if (pos == 1e9)
  1768. break;
  1769. if (nextA == pos) {
  1770. if (!inA)
  1771. inA = true;
  1772. else {
  1773. inA = false;
  1774. iA++;
  1775. }
  1776. }
  1777. if (nextB == pos) {
  1778. if (!inB)
  1779. inB = true;
  1780. else {
  1781. inB = false;
  1782. iB++;
  1783. }
  1784. }
  1785. }
  1786. return result;
  1787. }
  1788. // Given a number of fragments for the outer tree, and a set of ranges
  1789. // to parse, find fragments for inner trees mounted around those
  1790. // ranges, if any.
  1791. function enterFragments(mounts, ranges) {
  1792. let result = [];
  1793. for (let { pos, mount, frag } of mounts) {
  1794. let startPos = pos + (mount.overlay ? mount.overlay[0].from : 0), endPos = startPos + mount.tree.length;
  1795. let from = Math.max(frag.from, startPos), to = Math.min(frag.to, endPos);
  1796. if (mount.overlay) {
  1797. let overlay = mount.overlay.map(r => new Range(r.from + pos, r.to + pos));
  1798. let changes = findCoverChanges(ranges, overlay, from, to);
  1799. for (let i = 0, pos = from;; i++) {
  1800. let last = i == changes.length, end = last ? to : changes[i].from;
  1801. if (end > pos)
  1802. result.push(new TreeFragment(pos, end, mount.tree, -startPos, frag.from >= pos, frag.to <= end));
  1803. if (last)
  1804. break;
  1805. pos = changes[i].to;
  1806. }
  1807. }
  1808. else {
  1809. result.push(new TreeFragment(from, to, mount.tree, -startPos, frag.from >= startPos, frag.to <= endPos));
  1810. }
  1811. }
  1812. return result;
  1813. }
  1814. exports.DefaultBufferLength = DefaultBufferLength;
  1815. exports.MountedTree = MountedTree;
  1816. exports.NodeProp = NodeProp;
  1817. exports.NodeSet = NodeSet;
  1818. exports.NodeType = NodeType;
  1819. exports.NodeWeakMap = NodeWeakMap;
  1820. exports.Parser = Parser;
  1821. exports.Tree = Tree;
  1822. exports.TreeBuffer = TreeBuffer;
  1823. exports.TreeCursor = TreeCursor;
  1824. exports.TreeFragment = TreeFragment;
  1825. exports.parseMixed = parseMixed;