index.es.js 74 KB

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