@bpmn-io/properties-panel 0.19.0 → 0.20.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1,4 +1,4 @@
1
- import { useContext, useRef, useEffect, useMemo, useState, useCallback } from '../preact/hooks';
1
+ import { useContext, useRef, useEffect, useMemo, useState, useCallback, useLayoutEffect } from '../preact/hooks';
2
2
  import { isFunction, isArray, get, assign, set, sortBy, find as find$1, isNumber, debounce } from 'min-dash';
3
3
  import classnames from 'classnames';
4
4
  import { forwardRef } from '../preact/compat';
@@ -10,7 +10,7 @@ var ArrowIcon = function ArrowIcon(props) {
10
10
  return jsx("svg", { ...props,
11
11
  children: jsx("path", {
12
12
  fillRule: "evenodd",
13
- d: "m11.657 8-4.95 4.95a1 1 0 0 1-1.414-1.414L8.828 8 5.293 4.464A1 1 0 1 1 6.707 3.05L11.657 8z"
13
+ d: "m11.657 8-4.95 4.95a1 1 0 0 1-1.414-1.414L8.828 8 5.293 4.464A1 1 0 1 1 6.707 3.05L11.657 8Z"
14
14
  })
15
15
  });
16
16
  };
@@ -25,7 +25,7 @@ var CreateIcon = function CreateIcon(props) {
25
25
  return jsx("svg", { ...props,
26
26
  children: jsx("path", {
27
27
  fillRule: "evenodd",
28
- d: "M9 13V9h4a1 1 0 0 0 0-2H9V3a1 1 0 1 0-2 0v4H3a1 1 0 1 0 0 2h4v4a1 1 0 0 0 2 0z"
28
+ d: "M9 13V9h4a1 1 0 0 0 0-2H9V3a1 1 0 1 0-2 0v4H3a1 1 0 1 0 0 2h4v4a1 1 0 0 0 2 0Z"
29
29
  })
30
30
  });
31
31
  };
@@ -40,7 +40,7 @@ var DeleteIcon = function DeleteIcon(props) {
40
40
  return jsx("svg", { ...props,
41
41
  children: jsx("path", {
42
42
  fillRule: "evenodd",
43
- d: "M12 6v7c0 1.1-.4 1.55-1.5 1.55h-5C4.4 14.55 4 14.1 4 13V6h8zm-1.5 1.5h-5v4.3c0 .66.5 1.2 1.111 1.2H9.39c.611 0 1.111-.54 1.111-1.2V7.5zM13 3h-2l-1-1H6L5 3H3v1.5h10V3z"
43
+ d: "M12 6v7c0 1.1-.4 1.55-1.5 1.55h-5C4.4 14.55 4 14.1 4 13V6h8Zm-1.5 1.5h-5v4.3c0 .66.5 1.2 1.111 1.2H9.39c.611 0 1.111-.54 1.111-1.2V7.5ZM13 3h-2l-1-1H6L5 3H3v1.5h10V3Z"
44
44
  })
45
45
  });
46
46
  };
@@ -56,7 +56,7 @@ var ExternalLinkIcon = function ExternalLinkIcon(props) {
56
56
  children: jsx("path", {
57
57
  fillRule: "evenodd",
58
58
  clipRule: "evenodd",
59
- d: "M12.637 12.637v-4.72h1.362v4.721c0 .36-.137.676-.411.95-.275.275-.591.412-.95.412H3.362c-.38 0-.703-.132-.967-.396A1.315 1.315 0 0 1 2 12.638V3.362c0-.38.132-.703.396-.967S2.982 2 3.363 2h4.553v1.363H3.363v9.274h9.274zM14 2H9.28l-.001 1.362h2.408L5.065 9.984l.95.95 6.622-6.622v2.409H14V2z",
59
+ d: "M12.637 12.637v-4.72h1.362v4.721c0 .36-.137.676-.411.95-.275.275-.591.412-.95.412H3.362c-.38 0-.703-.132-.967-.396A1.315 1.315 0 0 1 2 12.638V3.362c0-.38.132-.703.396-.967S2.982 2 3.363 2h4.553v1.363H3.363v9.274h9.274ZM14 2H9.28l-.001 1.362h2.408L5.065 9.984l.95.95 6.622-6.622v2.409H14V2Z",
60
60
  fill: "#818798"
61
61
  })
62
62
  });
@@ -72,15 +72,15 @@ ExternalLinkIcon.defaultProps = {
72
72
  var FeelRequiredIcon = function FeelRequiredIcon(props) {
73
73
  return jsxs("svg", { ...props,
74
74
  children: [jsx("path", {
75
- d: "M5.8 7.06V5.95h4.307v1.11H5.8zm0 3.071v-1.11h4.307v1.11H5.8z",
75
+ d: "M5.8 7.06V5.95h4.307v1.11H5.8Zm0 3.071v-1.11h4.307v1.11H5.8Z",
76
76
  fill: "currentColor"
77
77
  }), jsx("path", {
78
78
  fillRule: "evenodd",
79
79
  clipRule: "evenodd",
80
- d: "M8 3.268A4.732 4.732 0 1 0 12.732 8H14a6 6 0 1 1-6-6v1.268z",
80
+ d: "M8 3.268A4.732 4.732 0 1 0 12.732 8H14a6 6 0 1 1-6-6v1.268Z",
81
81
  fill: "currentColor"
82
82
  }), jsx("path", {
83
- d: "m11.28 6.072-.832-.56 1.016-1.224L10 3.848l.312-.912 1.392.584L11.632 2h1.032l-.072 1.52 1.392-.584.312.912-1.464.44 1.008 1.224-.832.552-.864-1.296-.864 1.304z",
83
+ d: "m11.28 6.072-.832-.56 1.016-1.224L10 3.848l.312-.912 1.392.584L11.632 2h1.032l-.072 1.52 1.392-.584.312.912-1.464.44 1.008 1.224-.832.552-.864-1.296-.864 1.304Z",
84
84
  fill: "currentColor"
85
85
  })]
86
86
  });
@@ -95,12 +95,12 @@ FeelRequiredIcon.defaultProps = {
95
95
  var FeelOptionalIcon = function FeelOptionalIcon(props) {
96
96
  return jsxs("svg", { ...props,
97
97
  children: [jsx("path", {
98
- d: "M5.845 7.04V5.93h4.307v1.11H5.845zm0 3.07V9h4.307v1.11H5.845z",
98
+ d: "M5.845 7.04V5.93h4.307v1.11H5.845Zm0 3.07V9h4.307v1.11H5.845Z",
99
99
  fill: "currentColor"
100
100
  }), jsx("path", {
101
101
  fillRule: "evenodd",
102
102
  clipRule: "evenodd",
103
- d: "M3.286 8a4.714 4.714 0 1 0 9.428 0 4.714 4.714 0 0 0-9.428 0zM8 2a6 6 0 1 0 0 12A6 6 0 0 0 8 2z",
103
+ d: "M3.286 8a4.714 4.714 0 1 0 9.428 0 4.714 4.714 0 0 0-9.428 0ZM8 2a6 6 0 1 0 0 12A6 6 0 0 0 8 2Z",
104
104
  fill: "currentColor"
105
105
  })]
106
106
  });
@@ -425,7 +425,7 @@ function useShowEntryEvent(id) {
425
425
  }
426
426
  }
427
427
  }, [id]);
428
- useEffect(() => {
428
+ useLayoutEffect(() => {
429
429
  if (focus.current && ref.current) {
430
430
  if (isFunction(ref.current.focus)) {
431
431
  ref.current.focus();
@@ -4083,476 +4083,7 @@ direction `dir`. Only the `brackets` and `maxScanDistance`
4083
4083
  properties are used from `config`, if given. Returns null if no
4084
4084
  bracket was found at `pos`, or a match result otherwise.
4085
4085
  */function matchBrackets(state,pos,dir,config={}){let maxScanDistance=config.maxScanDistance||DefaultScanDist,brackets=config.brackets||DefaultBrackets;let tree=syntaxTree(state),node=tree.resolveInner(pos,dir);for(let cur=node;cur;cur=cur.parent){let matches=matchingNodes(cur.type,dir,brackets);if(matches&&cur.from<cur.to)return matchMarkedBrackets(state,pos,dir,cur,matches,brackets);}return matchPlainBrackets(state,pos,dir,tree,node.type,maxScanDistance,brackets);}function matchMarkedBrackets(_state,_pos,dir,token,matching,brackets){let parent=token.parent,firstToken={from:token.from,to:token.to};let depth=0,cursor=parent===null||parent===void 0?void 0:parent.cursor();if(cursor&&(dir<0?cursor.childBefore(token.from):cursor.childAfter(token.to)))do{if(dir<0?cursor.to<=token.from:cursor.from>=token.to){if(depth==0&&matching.indexOf(cursor.type.name)>-1&&cursor.from<cursor.to){return {start:firstToken,end:{from:cursor.from,to:cursor.to},matched:true};}else if(matchingNodes(cursor.type,dir,brackets)){depth++;}else if(matchingNodes(cursor.type,-dir,brackets)){depth--;if(depth==0)return {start:firstToken,end:cursor.from==cursor.to?undefined:{from:cursor.from,to:cursor.to},matched:false};}}}while(dir<0?cursor.prevSibling():cursor.nextSibling());return {start:firstToken,matched:false};}function matchPlainBrackets(state,pos,dir,tree,tokenType,maxScanDistance,brackets){let startCh=dir<0?state.sliceDoc(pos-1,pos):state.sliceDoc(pos,pos+1);let bracket=brackets.indexOf(startCh);if(bracket<0||bracket%2==0!=dir>0)return null;let startToken={from:dir<0?pos-1:pos,to:dir>0?pos+1:pos};let iter=state.doc.iterRange(pos,dir>0?state.doc.length:0),depth=0;for(let distance=0;!iter.next().done&&distance<=maxScanDistance;){let text=iter.value;if(dir<0)distance+=text.length;let basePos=pos+distance*dir;for(let pos=dir>0?0:text.length-1,end=dir>0?text.length:-1;pos!=end;pos+=dir){let found=brackets.indexOf(text[pos]);if(found<0||tree.resolve(basePos+pos,1).type!=tokenType)continue;if(found%2==0==dir>0){depth++;}else if(depth==1){// Closing
4086
- return {start:startToken,end:{from:basePos+pos,to:basePos+pos+1},matched:found>>1==bracket>>1};}else {depth--;}}if(dir>0)distance+=text.length;}return iter.done?{start:startToken,matched:false}:null;}const noTokens=/*@__PURE__*/Object.create(null);const typeArray=[NodeType$1.none];const warned=[];const defaultTable=/*@__PURE__*/Object.create(null);for(let[legacyName,name]of [["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","typeName"],["attribute","propertyName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])defaultTable[legacyName]=/*@__PURE__*/createTokenType(noTokens,name);function warnForPart(part,msg){if(warned.indexOf(part)>-1)return;warned.push(part);console.warn(msg);}function createTokenType(extra,tagStr){let tag=null;for(let part of tagStr.split(".")){let value=extra[part]||tags[part];if(!value){warnForPart(part,`Unknown highlighting tag ${part}`);}else if(typeof value=="function"){if(!tag)warnForPart(part,`Modifier ${part} used at start of tag`);else tag=value(tag);}else {if(tag)warnForPart(part,`Tag ${part} used as modifier`);else tag=value;}}if(!tag)return 0;let name=tagStr.replace(/ /g,"_"),type=NodeType$1.define({id:typeArray.length,name,props:[styleTags({[name]:tag})]});typeArray.push(type);return type.id;}// FIXME profile adding a per-Tree TreeNode cache, validating it by
4087
- // parent pointer
4088
- /// The default maximum length of a `TreeBuffer` node (1024).
4089
- const DefaultBufferLength=1024;let nextPropID=0;class Range{constructor(from,to){this.from=from;this.to=to;}}/// Each [node type](#common.NodeType) or [individual tree](#common.Tree)
4090
- /// can have metadata associated with it in props. Instances of this
4091
- /// class represent prop names.
4092
- class NodeProp{/// Create a new node prop type.
4093
- constructor(config={}){this.id=nextPropID++;this.perNode=!!config.perNode;this.deserialize=config.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function");});}/// This is meant to be used with
4094
- /// [`NodeSet.extend`](#common.NodeSet.extend) or
4095
- /// [`LRParser.configure`](#lr.ParserConfig.props) to compute
4096
- /// prop values for each node type in the set. Takes a [match
4097
- /// object](#common.NodeType^match) or function that returns undefined
4098
- /// if the node type doesn't get this prop, and the prop's value if
4099
- /// it does.
4100
- add(match){if(this.perNode)throw new RangeError("Can't add per-node props to node types");if(typeof match!="function")match=NodeType.match(match);return type=>{let result=match(type);return result===undefined?null:[this,result];};}}/// Prop that is used to describe matching delimiters. For opening
4101
- /// delimiters, this holds an array of node names (written as a
4102
- /// space-separated string when declaring this prop in a grammar)
4103
- /// for the node types of closing delimiters that match it.
4104
- NodeProp.closedBy=new NodeProp({deserialize:str=>str.split(" ")});/// The inverse of [`closedBy`](#common.NodeProp^closedBy). This is
4105
- /// attached to closing delimiters, holding an array of node names
4106
- /// of types of matching opening delimiters.
4107
- NodeProp.openedBy=new NodeProp({deserialize:str=>str.split(" ")});/// Used to assign node types to groups (for example, all node
4108
- /// types that represent an expression could be tagged with an
4109
- /// `"Expression"` group).
4110
- NodeProp.group=new NodeProp({deserialize:str=>str.split(" ")});/// The hash of the [context](#lr.ContextTracker.constructor)
4111
- /// that the node was parsed in, if any. Used to limit reuse of
4112
- /// contextual nodes.
4113
- NodeProp.contextHash=new NodeProp({perNode:true});/// The distance beyond the end of the node that the tokenizer
4114
- /// looked ahead for any of the tokens inside the node. (The LR
4115
- /// parser only stores this when it is larger than 25, for
4116
- /// efficiency reasons.)
4117
- NodeProp.lookAhead=new NodeProp({perNode:true});/// This per-node prop is used to replace a given node, or part of a
4118
- /// node, with another tree. This is useful to include trees from
4119
- /// different languages.
4120
- NodeProp.mounted=new NodeProp({perNode:true});const noProps=Object.create(null);/// Each node in a syntax tree has a node type associated with it.
4121
- class NodeType{/// @internal
4122
- constructor(/// The name of the node type. Not necessarily unique, but if the
4123
- /// grammar was written properly, different node types with the
4124
- /// same name within a node set should play the same semantic
4125
- /// role.
4126
- name,/// @internal
4127
- props,/// The id of this node in its set. Corresponds to the term ids
4128
- /// used in the parser.
4129
- id,/// @internal
4130
- flags=0){this.name=name;this.props=props;this.id=id;this.flags=flags;}static define(spec){let props=spec.props&&spec.props.length?Object.create(null):noProps;let flags=(spec.top?1/* Top */:0)|(spec.skipped?2/* Skipped */:0)|(spec.error?4/* Error */:0)|(spec.name==null?8/* Anonymous */:0);let type=new NodeType(spec.name||"",props,spec.id,flags);if(spec.props)for(let src of spec.props){if(!Array.isArray(src))src=src(type);if(src){if(src[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");props[src[0].id]=src[1];}}return type;}/// Retrieves a node prop for this type. Will return `undefined` if
4131
- /// the prop isn't present on this node.
4132
- prop(prop){return this.props[prop.id];}/// True when this is the top node of a grammar.
4133
- get isTop(){return (this.flags&1/* Top */)>0;}/// True when this node is produced by a skip rule.
4134
- get isSkipped(){return (this.flags&2/* Skipped */)>0;}/// Indicates whether this is an error node.
4135
- get isError(){return (this.flags&4/* Error */)>0;}/// When true, this node type doesn't correspond to a user-declared
4136
- /// named node, for example because it is used to cache repetition.
4137
- get isAnonymous(){return (this.flags&8/* Anonymous */)>0;}/// Returns true when this node's name or one of its
4138
- /// [groups](#common.NodeProp^group) matches the given string.
4139
- is(name){if(typeof name=='string'){if(this.name==name)return true;let group=this.prop(NodeProp.group);return group?group.indexOf(name)>-1:false;}return this.id==name;}/// Create a function from node types to arbitrary values by
4140
- /// specifying an object whose property names are node or
4141
- /// [group](#common.NodeProp^group) names. Often useful with
4142
- /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple
4143
- /// names, separated by spaces, in a single property name to map
4144
- /// multiple node names to a single value.
4145
- static match(map){let direct=Object.create(null);for(let prop in map)for(let name of prop.split(" "))direct[name]=map[prop];return node=>{for(let groups=node.prop(NodeProp.group),i=-1;i<(groups?groups.length:0);i++){let found=direct[i<0?node.name:groups[i]];if(found)return found;}};}}/// An empty dummy node type to use when no actual type is available.
4146
- NodeType.none=new NodeType("",Object.create(null),0,8/* Anonymous */);/// A node set holds a collection of node types. It is used to
4147
- /// compactly represent trees by storing their type ids, rather than a
4148
- /// full pointer to the type object, in a numeric array. Each parser
4149
- /// [has](#lr.LRParser.nodeSet) a node set, and [tree
4150
- /// buffers](#common.TreeBuffer) can only store collections of nodes
4151
- /// from the same set. A set can have a maximum of 2**16 (65536) node
4152
- /// types in it, so that the ids fit into 16-bit typed array slots.
4153
- class NodeSet{/// Create a set with the given types. The `id` property of each
4154
- /// type should correspond to its position within the array.
4155
- constructor(/// The node types in this set, by id.
4156
- types){this.types=types;for(let i=0;i<types.length;i++)if(types[i].id!=i)throw new RangeError("Node type ids should correspond to array positions when creating a node set");}/// Create a copy of this set with some node properties added. The
4157
- /// arguments to this method should be created with
4158
- /// [`NodeProp.add`](#common.NodeProp.add).
4159
- extend(...props){let newTypes=[];for(let type of this.types){let newProps=null;for(let source of props){let add=source(type);if(add){if(!newProps)newProps=Object.assign({},type.props);newProps[add[0].id]=add[1];}}newTypes.push(newProps?new NodeType(type.name,newProps,type.id,type.flags):type);}return new NodeSet(newTypes);}}const CachedNode=new WeakMap(),CachedInnerNode=new WeakMap();/// Options that control iteration. Can be combined with the `|`
4160
- /// operator to enable multiple ones.
4161
- var IterMode;(function(IterMode){/// When enabled, iteration will only visit [`Tree`](#common.Tree)
4162
- /// objects, not nodes packed into
4163
- /// [`TreeBuffer`](#common.TreeBuffer)s.
4164
- IterMode[IterMode["ExcludeBuffers"]=1]="ExcludeBuffers";/// Enable this to make iteration include anonymous nodes (such as
4165
- /// the nodes that wrap repeated grammar constructs into a balanced
4166
- /// tree).
4167
- IterMode[IterMode["IncludeAnonymous"]=2]="IncludeAnonymous";/// By default, regular [mounted](#common.NodeProp^mounted) nodes
4168
- /// replace their base node in iteration. Enable this to ignore them
4169
- /// instead.
4170
- IterMode[IterMode["IgnoreMounts"]=4]="IgnoreMounts";/// This option only applies in
4171
- /// [`enter`](#common.SyntaxNode.enter)-style methods. It tells the
4172
- /// library to not enter mounted overlays if one covers the given
4173
- /// position.
4174
- IterMode[IterMode["IgnoreOverlays"]=8]="IgnoreOverlays";})(IterMode||(IterMode={}));/// A piece of syntax tree. There are two ways to approach these
4175
- /// trees: the way they are actually stored in memory, and the
4176
- /// convenient way.
4177
- ///
4178
- /// Syntax trees are stored as a tree of `Tree` and `TreeBuffer`
4179
- /// objects. By packing detail information into `TreeBuffer` leaf
4180
- /// nodes, the representation is made a lot more memory-efficient.
4181
- ///
4182
- /// However, when you want to actually work with tree nodes, this
4183
- /// representation is very awkward, so most client code will want to
4184
- /// use the [`TreeCursor`](#common.TreeCursor) or
4185
- /// [`SyntaxNode`](#common.SyntaxNode) interface instead, which provides
4186
- /// a view on some part of this data structure, and can be used to
4187
- /// move around to adjacent nodes.
4188
- class Tree{/// Construct a new tree. See also [`Tree.build`](#common.Tree^build).
4189
- constructor(/// The type of the top node.
4190
- type,/// This node's child nodes.
4191
- children,/// The positions (offsets relative to the start of this tree) of
4192
- /// the children.
4193
- positions,/// The total length of this tree
4194
- length,/// Per-node [node props](#common.NodeProp) to associate with this node.
4195
- props){this.type=type;this.children=children;this.positions=positions;this.length=length;/// @internal
4196
- this.props=null;if(props&&props.length){this.props=Object.create(null);for(let[prop,value]of props)this.props[typeof prop=="number"?prop:prop.id]=value;}}/// @internal
4197
- toString(){let mounted=this.prop(NodeProp.mounted);if(mounted&&!mounted.overlay)return mounted.tree.toString();let children="";for(let ch of this.children){let str=ch.toString();if(str){if(children)children+=",";children+=str;}}return !this.type.name?children:(/\W/.test(this.type.name)&&!this.type.isError?JSON.stringify(this.type.name):this.type.name)+(children.length?"("+children+")":"");}/// Get a [tree cursor](#common.TreeCursor) positioned at the top of
4198
- /// the tree. Mode can be used to [control](#common.IterMode) which
4199
- /// nodes the cursor visits.
4200
- cursor(mode=0){return new TreeCursor(this.topNode,mode);}/// Get a [tree cursor](#common.TreeCursor) pointing into this tree
4201
- /// at the given position and side (see
4202
- /// [`moveTo`](#common.TreeCursor.moveTo).
4203
- cursorAt(pos,side=0,mode=0){let scope=CachedNode.get(this)||this.topNode;let cursor=new TreeCursor(scope);cursor.moveTo(pos,side);CachedNode.set(this,cursor._tree);return cursor;}/// Get a [syntax node](#common.SyntaxNode) object for the top of the
4204
- /// tree.
4205
- get topNode(){return new TreeNode(this,0,0,null);}/// Get the [syntax node](#common.SyntaxNode) at the given position.
4206
- /// If `side` is -1, this will move into nodes that end at the
4207
- /// position. If 1, it'll move into nodes that start at the
4208
- /// position. With 0, it'll only enter nodes that cover the position
4209
- /// from both sides.
4210
- resolve(pos,side=0){let node=resolveNode(CachedNode.get(this)||this.topNode,pos,side,false);CachedNode.set(this,node);return node;}/// Like [`resolve`](#common.Tree.resolve), but will enter
4211
- /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
4212
- /// pointing into the innermost overlaid tree at the given position
4213
- /// (with parent links going through all parent structure, including
4214
- /// the host trees).
4215
- resolveInner(pos,side=0){let node=resolveNode(CachedInnerNode.get(this)||this.topNode,pos,side,true);CachedInnerNode.set(this,node);return node;}/// Iterate over the tree and its children, calling `enter` for any
4216
- /// node that touches the `from`/`to` region (if given) before
4217
- /// running over such a node's children, and `leave` (if given) when
4218
- /// leaving the node. When `enter` returns `false`, that node will
4219
- /// not have its children iterated over (or `leave` called).
4220
- iterate(spec){let{enter,leave,from=0,to=this.length}=spec;for(let c=this.cursor((spec.mode||0)|IterMode.IncludeAnonymous);;){let entered=false;if(c.from<=to&&c.to>=from&&(c.type.isAnonymous||enter(c)!==false)){if(c.firstChild())continue;entered=true;}for(;;){if(entered&&leave&&!c.type.isAnonymous)leave(c);if(c.nextSibling())break;if(!c.parent())return;entered=true;}}}/// Get the value of the given [node prop](#common.NodeProp) for this
4221
- /// node. Works with both per-node and per-type props.
4222
- prop(prop){return !prop.perNode?this.type.prop(prop):this.props?this.props[prop.id]:undefined;}/// Returns the node's [per-node props](#common.NodeProp.perNode) in a
4223
- /// format that can be passed to the [`Tree`](#common.Tree)
4224
- /// constructor.
4225
- get propValues(){let result=[];if(this.props)for(let id in this.props)result.push([+id,this.props[id]]);return result;}/// Balance the direct children of this tree, producing a copy of
4226
- /// which may have children grouped into subtrees with type
4227
- /// [`NodeType.none`](#common.NodeType^none).
4228
- balance(config={}){return this.children.length<=8/* BranchFactor */?this: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)));}/// Build a tree from a postfix-ordered buffer of node information,
4229
- /// or a cursor over such a buffer.
4230
- static build(data){return buildTree(data);}}/// The empty tree
4231
- Tree.empty=new Tree(NodeType.none,[],[],0);class FlatBufferCursor{constructor(buffer,index){this.buffer=buffer;this.index=index;}get id(){return this.buffer[this.index-4];}get start(){return this.buffer[this.index-3];}get end(){return this.buffer[this.index-2];}get size(){return this.buffer[this.index-1];}get pos(){return this.index;}next(){this.index-=4;}fork(){return new FlatBufferCursor(this.buffer,this.index);}}/// Tree buffers contain (type, start, end, endIndex) quads for each
4232
- /// node. In such a buffer, nodes are stored in prefix order (parents
4233
- /// before children, with the endIndex of the parent indicating which
4234
- /// children belong to it)
4235
- class TreeBuffer{/// Create a tree buffer.
4236
- constructor(/// The buffer's content.
4237
- buffer,/// The total length of the group of nodes in the buffer.
4238
- length,/// The node set used in this buffer.
4239
- set){this.buffer=buffer;this.length=length;this.set=set;}/// @internal
4240
- get type(){return NodeType.none;}/// @internal
4241
- toString(){let result=[];for(let index=0;index<this.buffer.length;){result.push(this.childString(index));index=this.buffer[index+3];}return result.join(",");}/// @internal
4242
- childString(index){let id=this.buffer[index],endIndex=this.buffer[index+3];let type=this.set.types[id],result=type.name;if(/\W/.test(result)&&!type.isError)result=JSON.stringify(result);index+=4;if(endIndex==index)return result;let children=[];while(index<endIndex){children.push(this.childString(index));index=this.buffer[index+3];}return result+"("+children.join(",")+")";}/// @internal
4243
- findChild(startIndex,endIndex,dir,pos,side){let{buffer}=this,pick=-1;for(let i=startIndex;i!=endIndex;i=buffer[i+3]){if(checkSide(side,pos,buffer[i+1],buffer[i+2])){pick=i;if(dir>0)break;}}return pick;}/// @internal
4244
- slice(startI,endI,from,to){let b=this.buffer;let copy=new Uint16Array(endI-startI);for(let i=startI,j=0;i<endI;){copy[j++]=b[i++];copy[j++]=b[i++]-from;copy[j++]=b[i++]-from;copy[j++]=b[i++]-startI;}return new TreeBuffer(copy,to-from,this.set);}}function checkSide(side,pos,from,to){switch(side){case-2/* Before */:return from<pos;case-1/* AtOrBefore */:return to>=pos&&from<pos;case 0/* Around */:return from<pos&&to>pos;case 1/* AtOrAfter */:return from<=pos&&to>pos;case 2/* After */:return to>pos;case 4/* DontCare */:return true;}}function enterUnfinishedNodesBefore(node,pos){let scan=node.childBefore(pos);while(scan){let last=scan.lastChild;if(!last||last.to!=scan.to)break;if(last.type.isError&&last.from==last.to){node=scan;scan=last.prevSibling;}else {scan=last;}}return node;}function resolveNode(node,pos,side,overlays){var _a;// Move up to a node that actually holds the position, if possible
4245
- while(node.from==node.to||(side<1?node.from>=pos:node.from>pos)||(side>-1?node.to<=pos:node.to<pos)){let parent=!overlays&&node instanceof TreeNode&&node.index<0?null:node.parent;if(!parent)return node;node=parent;}let mode=overlays?0:IterMode.IgnoreOverlays;// Must go up out of overlays when those do not overlap with pos
4246
- if(overlays)for(let scan=node,parent=scan.parent;parent;scan=parent,parent=scan.parent){if(scan instanceof TreeNode&&scan.index<0&&((_a=parent.enter(pos,side,mode))===null||_a===void 0?void 0:_a.from)!=scan.from)node=parent;}for(;;){let inner=node.enter(pos,side,mode);if(!inner)return node;node=inner;}}class TreeNode{constructor(_tree,from,// Index in parent node, set to -1 if the node is not a direct child of _parent.node (overlay)
4247
- index,_parent){this._tree=_tree;this.from=from;this.index=index;this._parent=_parent;}get type(){return this._tree.type;}get name(){return this._tree.type.name;}get to(){return this.from+this._tree.length;}nextChild(i,dir,pos,side,mode=0){for(let parent=this;;){for(let{children,positions}=parent._tree,e=dir>0?children.length:-1;i!=e;i+=dir){let next=children[i],start=positions[i]+parent.from;if(!checkSide(side,pos,start,start+next.length))continue;if(next instanceof TreeBuffer){if(mode&IterMode.ExcludeBuffers)continue;let index=next.findChild(0,next.buffer.length,dir,pos-start,side);if(index>-1)return new BufferNode(new BufferContext(parent,next,i,start),null,index);}else if(mode&IterMode.IncludeAnonymous||!next.type.isAnonymous||hasChild(next)){let mounted;if(!(mode&IterMode.IgnoreMounts)&&next.props&&(mounted=next.prop(NodeProp.mounted))&&!mounted.overlay)return new TreeNode(mounted.tree,start,i,parent);let inner=new TreeNode(next,start,i,parent);return mode&IterMode.IncludeAnonymous||!inner.type.isAnonymous?inner:inner.nextChild(dir<0?next.children.length-1:0,dir,pos,side);}}if(mode&IterMode.IncludeAnonymous||!parent.type.isAnonymous)return null;if(parent.index>=0)i=parent.index+dir;else i=dir<0?-1:parent._parent._tree.children.length;parent=parent._parent;if(!parent)return null;}}get firstChild(){return this.nextChild(0,1,0,4/* DontCare */);}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4/* DontCare */);}childAfter(pos){return this.nextChild(0,1,pos,2/* After */);}childBefore(pos){return this.nextChild(this._tree.children.length-1,-1,pos,-2/* Before */);}enter(pos,side,mode=0){let mounted;if(!(mode&IterMode.IgnoreOverlays)&&(mounted=this._tree.prop(NodeProp.mounted))&&mounted.overlay){let rPos=pos-this.from;for(let{from,to}of mounted.overlay){if((side>0?from<=rPos:from<rPos)&&(side<0?to>=rPos:to>rPos))return new TreeNode(mounted.tree,mounted.overlay[0].from+this.from,-1,this);}}return this.nextChild(0,1,pos,side,mode);}nextSignificantParent(){let val=this;while(val.type.isAnonymous&&val._parent)val=val._parent;return val;}get parent(){return this._parent?this._parent.nextSignificantParent():null;}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4/* DontCare */):null;}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4/* DontCare */):null;}cursor(mode=0){return new TreeCursor(this,mode);}get tree(){return this._tree;}toTree(){return this._tree;}resolve(pos,side=0){return resolveNode(this,pos,side,false);}resolveInner(pos,side=0){return resolveNode(this,pos,side,true);}enterUnfinishedNodesBefore(pos){return enterUnfinishedNodesBefore(this,pos);}getChild(type,before=null,after=null){let r=getChildren(this,type,before,after);return r.length?r[0]:null;}getChildren(type,before=null,after=null){return getChildren(this,type,before,after);}/// @internal
4248
- toString(){return this._tree.toString();}get node(){return this;}matchContext(context){return matchNodeContext(this,context);}}function getChildren(node,type,before,after){let cur=node.cursor(),result=[];if(!cur.firstChild())return result;if(before!=null)while(!cur.type.is(before))if(!cur.nextSibling())return result;for(;;){if(after!=null&&cur.type.is(after))return result;if(cur.type.is(type))result.push(cur.node);if(!cur.nextSibling())return after==null?result:[];}}function matchNodeContext(node,context,i=context.length-1){for(let p=node.parent;i>=0;p=p.parent){if(!p)return false;if(!p.type.isAnonymous){if(context[i]&&context[i]!=p.name)return false;i--;}}return true;}class BufferContext{constructor(parent,buffer,index,start){this.parent=parent;this.buffer=buffer;this.index=index;this.start=start;}}class BufferNode{constructor(context,_parent,index){this.context=context;this._parent=_parent;this.index=index;this.type=context.buffer.set.types[context.buffer.buffer[index]];}get name(){return this.type.name;}get from(){return this.context.start+this.context.buffer.buffer[this.index+1];}get to(){return this.context.start+this.context.buffer.buffer[this.index+2];}child(dir,pos,side){let{buffer}=this.context;let index=buffer.findChild(this.index+4,buffer.buffer[this.index+3],dir,pos-this.context.start,side);return index<0?null:new BufferNode(this.context,this,index);}get firstChild(){return this.child(1,0,4/* DontCare */);}get lastChild(){return this.child(-1,0,4/* DontCare */);}childAfter(pos){return this.child(1,pos,2/* After */);}childBefore(pos){return this.child(-1,pos,-2/* Before */);}enter(pos,side,mode=0){if(mode&IterMode.ExcludeBuffers)return null;let{buffer}=this.context;let index=buffer.findChild(this.index+4,buffer.buffer[this.index+3],side>0?1:-1,pos-this.context.start,side);return index<0?null:new BufferNode(this.context,this,index);}get parent(){return this._parent||this.context.parent.nextSignificantParent();}externalSibling(dir){return this._parent?null:this.context.parent.nextChild(this.context.index+dir,dir,0,4/* DontCare */);}get nextSibling(){let{buffer}=this.context;let after=buffer.buffer[this.index+3];if(after<(this._parent?buffer.buffer[this._parent.index+3]:buffer.buffer.length))return new BufferNode(this.context,this._parent,after);return this.externalSibling(1);}get prevSibling(){let{buffer}=this.context;let parentStart=this._parent?this._parent.index+4:0;if(this.index==parentStart)return this.externalSibling(-1);return new BufferNode(this.context,this._parent,buffer.findChild(parentStart,this.index,-1,0,4/* DontCare */));}cursor(mode=0){return new TreeCursor(this,mode);}get tree(){return null;}toTree(){let children=[],positions=[];let{buffer}=this.context;let startI=this.index+4,endI=buffer.buffer[this.index+3];if(endI>startI){let from=buffer.buffer[this.index+1],to=buffer.buffer[this.index+2];children.push(buffer.slice(startI,endI,from,to));positions.push(0);}return new Tree(this.type,children,positions,this.to-this.from);}resolve(pos,side=0){return resolveNode(this,pos,side,false);}resolveInner(pos,side=0){return resolveNode(this,pos,side,true);}enterUnfinishedNodesBefore(pos){return enterUnfinishedNodesBefore(this,pos);}/// @internal
4249
- toString(){return this.context.buffer.childString(this.index);}getChild(type,before=null,after=null){let r=getChildren(this,type,before,after);return r.length?r[0]:null;}getChildren(type,before=null,after=null){return getChildren(this,type,before,after);}get node(){return this;}matchContext(context){return matchNodeContext(this,context);}}/// A tree cursor object focuses on a given node in a syntax tree, and
4250
- /// allows you to move to adjacent nodes.
4251
- class TreeCursor{/// @internal
4252
- constructor(node,/// @internal
4253
- mode=0){this.mode=mode;/// @internal
4254
- this.buffer=null;this.stack=[];/// @internal
4255
- this.index=0;this.bufferNode=null;if(node instanceof TreeNode){this.yieldNode(node);}else {this._tree=node.context.parent;this.buffer=node.context;for(let n=node._parent;n;n=n._parent)this.stack.unshift(n.index);this.bufferNode=node;this.yieldBuf(node.index);}}/// Shorthand for `.type.name`.
4256
- get name(){return this.type.name;}yieldNode(node){if(!node)return false;this._tree=node;this.type=node.type;this.from=node.from;this.to=node.to;return true;}yieldBuf(index,type){this.index=index;let{start,buffer}=this.buffer;this.type=type||buffer.set.types[buffer.buffer[index]];this.from=start+buffer.buffer[index+1];this.to=start+buffer.buffer[index+2];return true;}yield(node){if(!node)return false;if(node instanceof TreeNode){this.buffer=null;return this.yieldNode(node);}this.buffer=node.context;return this.yieldBuf(node.index,node.type);}/// @internal
4257
- toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString();}/// @internal
4258
- enterChild(dir,pos,side){if(!this.buffer)return this.yield(this._tree.nextChild(dir<0?this._tree._tree.children.length-1:0,dir,pos,side,this.mode));let{buffer}=this.buffer;let index=buffer.findChild(this.index+4,buffer.buffer[this.index+3],dir,pos-this.buffer.start,side);if(index<0)return false;this.stack.push(this.index);return this.yieldBuf(index);}/// Move the cursor to this node's first child. When this returns
4259
- /// false, the node has no child, and the cursor has not been moved.
4260
- firstChild(){return this.enterChild(1,0,4/* DontCare */);}/// Move the cursor to this node's last child.
4261
- lastChild(){return this.enterChild(-1,0,4/* DontCare */);}/// Move the cursor to the first child that ends after `pos`.
4262
- childAfter(pos){return this.enterChild(1,pos,2/* After */);}/// Move to the last child that starts before `pos`.
4263
- childBefore(pos){return this.enterChild(-1,pos,-2/* Before */);}/// Move the cursor to the child around `pos`. If side is -1 the
4264
- /// child may end at that position, when 1 it may start there. This
4265
- /// will also enter [overlaid](#common.MountedTree.overlay)
4266
- /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is
4267
- /// set to false.
4268
- enter(pos,side,mode=this.mode){if(!this.buffer)return this.yield(this._tree.enter(pos,side,mode));return mode&IterMode.ExcludeBuffers?false:this.enterChild(1,pos,side);}/// Move to the node's parent node, if this isn't the top node.
4269
- parent(){if(!this.buffer)return this.yieldNode(this.mode&IterMode.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let parent=this.mode&IterMode.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();this.buffer=null;return this.yieldNode(parent);}/// @internal
4270
- sibling(dir){if(!this.buffer)return !this._tree._parent?false:this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+dir,dir,0,4/* DontCare */,this.mode));let{buffer}=this.buffer,d=this.stack.length-1;if(dir<0){let parentStart=d<0?0:this.stack[d]+4;if(this.index!=parentStart)return this.yieldBuf(buffer.findChild(parentStart,this.index,-1,0,4/* DontCare */));}else {let after=buffer.buffer[this.index+3];if(after<(d<0?buffer.buffer.length:buffer.buffer[this.stack[d]+3]))return this.yieldBuf(after);}return d<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+dir,dir,0,4/* DontCare */,this.mode)):false;}/// Move to this node's next sibling, if any.
4271
- nextSibling(){return this.sibling(1);}/// Move to this node's previous sibling, if any.
4272
- prevSibling(){return this.sibling(-1);}atLastNode(dir){let index,parent,{buffer}=this;if(buffer){if(dir>0){if(this.index<buffer.buffer.buffer.length)return false;}else {for(let i=0;i<this.index;i++)if(buffer.buffer.buffer[i+3]<this.index)return false;}({index,parent}=buffer);}else {({index,_parent:parent}=this._tree);}for(;parent;({index,_parent:parent}=parent)){if(index>-1)for(let i=index+dir,e=dir<0?-1:parent._tree.children.length;i!=e;i+=dir){let child=parent._tree.children[i];if(this.mode&IterMode.IncludeAnonymous||child instanceof TreeBuffer||!child.type.isAnonymous||hasChild(child))return false;}}return true;}move(dir,enter){if(enter&&this.enterChild(dir,0,4/* DontCare */))return true;for(;;){if(this.sibling(dir))return true;if(this.atLastNode(dir)||!this.parent())return false;}}/// Move to the next node in a
4273
- /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR))
4274
- /// traversal, going from a node to its first child or, if the
4275
- /// current node is empty or `enter` is false, its next sibling or
4276
- /// the next sibling of the first parent node that has one.
4277
- next(enter=true){return this.move(1,enter);}/// Move to the next node in a last-to-first pre-order traveral. A
4278
- /// node is followed by its last child or, if it has none, its
4279
- /// previous sibling or the previous sibling of the first parent
4280
- /// node that has one.
4281
- prev(enter=true){return this.move(-1,enter);}/// Move the cursor to the innermost node that covers `pos`. If
4282
- /// `side` is -1, it will enter nodes that end at `pos`. If it is 1,
4283
- /// it will enter nodes that start at `pos`.
4284
- moveTo(pos,side=0){// Move up to a node that actually holds the position, if possible
4285
- while(this.from==this.to||(side<1?this.from>=pos:this.from>pos)||(side>-1?this.to<=pos:this.to<pos))if(!this.parent())break;// Then scan down into child nodes as far as possible
4286
- while(this.enterChild(1,pos,side)){}return this;}/// Get a [syntax node](#common.SyntaxNode) at the cursor's current
4287
- /// position.
4288
- get node(){if(!this.buffer)return this._tree;let cache=this.bufferNode,result=null,depth=0;if(cache&&cache.context==this.buffer){scan:for(let index=this.index,d=this.stack.length;d>=0;){for(let c=cache;c;c=c._parent)if(c.index==index){if(index==this.index)return c;result=c;depth=d+1;break scan;}index=this.stack[--d];}}for(let i=depth;i<this.stack.length;i++)result=new BufferNode(this.buffer,result,this.stack[i]);return this.bufferNode=new BufferNode(this.buffer,result,this.index);}/// Get the [tree](#common.Tree) that represents the current node, if
4289
- /// any. Will return null when the node is in a [tree
4290
- /// buffer](#common.TreeBuffer).
4291
- get tree(){return this.buffer?null:this._tree._tree;}/// Iterate over the current node and all its descendants, calling
4292
- /// `enter` when entering a node and `leave`, if given, when leaving
4293
- /// one. When `enter` returns `false`, any children of that node are
4294
- /// skipped, and `leave` isn't called for it.
4295
- iterate(enter,leave){for(let depth=0;;){let mustLeave=false;if(this.type.isAnonymous||enter(this)!==false){if(this.firstChild()){depth++;continue;}if(!this.type.isAnonymous)mustLeave=true;}for(;;){if(mustLeave&&leave)leave(this);mustLeave=this.type.isAnonymous;if(this.nextSibling())break;if(!depth)return;this.parent();depth--;mustLeave=true;}}}/// Test whether the current node matches a given context—a sequence
4296
- /// of direct parent node names. Empty strings in the context array
4297
- /// are treated as wildcards.
4298
- matchContext(context){if(!this.buffer)return matchNodeContext(this.node,context);let{buffer}=this.buffer,{types}=buffer.set;for(let i=context.length-1,d=this.stack.length-1;i>=0;d--){if(d<0)return matchNodeContext(this.node,context,i);let type=types[buffer.buffer[this.stack[d]]];if(!type.isAnonymous){if(context[i]&&context[i]!=type.name)return false;i--;}}return true;}}function hasChild(tree){return tree.children.some(ch=>ch instanceof TreeBuffer||!ch.type.isAnonymous||hasChild(ch));}function buildTree(data){var _a;let{buffer,nodeSet,maxBufferLength=DefaultBufferLength,reused=[],minRepeatType=nodeSet.types.length}=data;let cursor=Array.isArray(buffer)?new FlatBufferCursor(buffer,buffer.length):buffer;let types=nodeSet.types;let contextHash=0,lookAhead=0;function takeNode(parentStart,minPos,children,positions,inRepeat){let{id,start,end,size}=cursor;let lookAheadAtStart=lookAhead;while(size<0){cursor.next();if(size==-1/* Reuse */){let node=reused[id];children.push(node);positions.push(start-parentStart);return;}else if(size==-3/* ContextChange */){// Context change
4299
- contextHash=id;return;}else if(size==-4/* LookAhead */){lookAhead=id;return;}else {throw new RangeError(`Unrecognized record size: ${size}`);}}let type=types[id],node,buffer;let startPos=start-parentStart;if(end-start<=maxBufferLength&&(buffer=findBufferSize(cursor.pos-minPos,inRepeat))){// Small enough for a buffer, and no reused nodes inside
4300
- let data=new Uint16Array(buffer.size-buffer.skip);let endPos=cursor.pos-buffer.size,index=data.length;while(cursor.pos>endPos)index=copyToBuffer(buffer.start,data,index);node=new TreeBuffer(data,end-buffer.start,nodeSet);startPos=buffer.start-parentStart;}else {// Make it a node
4301
- let endPos=cursor.pos-size;cursor.next();let localChildren=[],localPositions=[];let localInRepeat=id>=minRepeatType?id:-1;let lastGroup=0,lastEnd=end;while(cursor.pos>endPos){if(localInRepeat>=0&&cursor.id==localInRepeat&&cursor.size>=0){if(cursor.end<=lastEnd-maxBufferLength){makeRepeatLeaf(localChildren,localPositions,start,lastGroup,cursor.end,lastEnd,localInRepeat,lookAheadAtStart);lastGroup=localChildren.length;lastEnd=cursor.end;}cursor.next();}else {takeNode(start,endPos,localChildren,localPositions,localInRepeat);}}if(localInRepeat>=0&&lastGroup>0&&lastGroup<localChildren.length)makeRepeatLeaf(localChildren,localPositions,start,lastGroup,start,lastEnd,localInRepeat,lookAheadAtStart);localChildren.reverse();localPositions.reverse();if(localInRepeat>-1&&lastGroup>0){let make=makeBalanced(type);node=balanceRange(type,localChildren,localPositions,0,localChildren.length,0,end-start,make,make);}else {node=makeTree(type,localChildren,localPositions,end-start,lookAheadAtStart-end);}}children.push(node);positions.push(startPos);}function makeBalanced(type){return (children,positions,length)=>{let lookAhead=0,lastI=children.length-1,last,lookAheadProp;if(lastI>=0&&(last=children[lastI])instanceof Tree){if(!lastI&&last.type==type&&last.length==length)return last;if(lookAheadProp=last.prop(NodeProp.lookAhead))lookAhead=positions[lastI]+last.length+lookAheadProp;}return makeTree(type,children,positions,length,lookAhead);};}function makeRepeatLeaf(children,positions,base,i,from,to,type,lookAhead){let localChildren=[],localPositions=[];while(children.length>i){localChildren.push(children.pop());localPositions.push(positions.pop()+base-from);}children.push(makeTree(nodeSet.types[type],localChildren,localPositions,to-from,lookAhead-to));positions.push(from-base);}function makeTree(type,children,positions,length,lookAhead=0,props){if(contextHash){let pair=[NodeProp.contextHash,contextHash];props=props?[pair].concat(props):[pair];}if(lookAhead>25){let pair=[NodeProp.lookAhead,lookAhead];props=props?[pair].concat(props):[pair];}return new Tree(type,children,positions,length,props);}function findBufferSize(maxSize,inRepeat){// Scan through the buffer to find previous siblings that fit
4302
- // together in a TreeBuffer, and don't contain any reused nodes
4303
- // (which can't be stored in a buffer).
4304
- // If `inRepeat` is > -1, ignore node boundaries of that type for
4305
- // nesting, but make sure the end falls either at the start
4306
- // (`maxSize`) or before such a node.
4307
- let fork=cursor.fork();let size=0,start=0,skip=0,minStart=fork.end-maxBufferLength;let result={size:0,start:0,skip:0};scan:for(let minPos=fork.pos-maxSize;fork.pos>minPos;){let nodeSize=fork.size;// Pretend nested repeat nodes of the same type don't exist
4308
- if(fork.id==inRepeat&&nodeSize>=0){// Except that we store the current state as a valid return
4309
- // value.
4310
- result.size=size;result.start=start;result.skip=skip;skip+=4;size+=4;fork.next();continue;}let startPos=fork.pos-nodeSize;if(nodeSize<0||startPos<minPos||fork.start<minStart)break;let localSkipped=fork.id>=minRepeatType?4:0;let nodeStart=fork.start;fork.next();while(fork.pos>startPos){if(fork.size<0){if(fork.size==-3/* ContextChange */)localSkipped+=4;else break scan;}else if(fork.id>=minRepeatType){localSkipped+=4;}fork.next();}start=nodeStart;size+=nodeSize;skip+=localSkipped;}if(inRepeat<0||size==maxSize){result.size=size;result.start=start;result.skip=skip;}return result.size>4?result:undefined;}function copyToBuffer(bufferStart,buffer,index){let{id,start,end,size}=cursor;cursor.next();if(size>=0&&id<minRepeatType){let startIndex=index;if(size>4){let endPos=cursor.pos-(size-4);while(cursor.pos>endPos)index=copyToBuffer(bufferStart,buffer,index);}buffer[--index]=startIndex;buffer[--index]=end-bufferStart;buffer[--index]=start-bufferStart;buffer[--index]=id;}else if(size==-3/* ContextChange */){contextHash=id;}else if(size==-4/* LookAhead */){lookAhead=id;}return index;}let children=[],positions=[];while(cursor.pos>0)takeNode(data.start||0,data.bufferStart||0,children,positions,-1);let length=(_a=data.length)!==null&&_a!==void 0?_a:children.length?positions[0]+children[0].length:0;return new Tree(types[data.topID],children.reverse(),positions.reverse(),length);}const nodeSizeCache=new WeakMap();function nodeSize(balanceType,node){if(!balanceType.isAnonymous||node instanceof TreeBuffer||node.type!=balanceType)return 1;let size=nodeSizeCache.get(node);if(size==null){size=1;for(let child of node.children){if(child.type!=balanceType||!(child instanceof Tree)){size=1;break;}size+=nodeSize(balanceType,child);}nodeSizeCache.set(node,size);}return size;}function balanceRange(// The type the balanced tree's inner nodes.
4311
- balanceType,// The direct children and their positions
4312
- children,positions,// The index range in children/positions to use
4313
- from,to,// The start position of the nodes, relative to their parent.
4314
- start,// Length of the outer node
4315
- length,// Function to build the top node of the balanced tree
4316
- mkTop,// Function to build internal nodes for the balanced tree
4317
- mkTree){let total=0;for(let i=from;i<to;i++)total+=nodeSize(balanceType,children[i]);let maxChild=Math.ceil(total*1.5/8/* BranchFactor */);let localChildren=[],localPositions=[];function divide(children,positions,from,to,offset){for(let i=from;i<to;){let groupFrom=i,groupStart=positions[i],groupSize=nodeSize(balanceType,children[i]);i++;for(;i<to;i++){let nextSize=nodeSize(balanceType,children[i]);if(groupSize+nextSize>=maxChild)break;groupSize+=nextSize;}if(i==groupFrom+1){if(groupSize>maxChild){let only=children[groupFrom];// Only trees can have a size > 1
4318
- divide(only.children,only.positions,0,only.children.length,positions[groupFrom]+offset);continue;}localChildren.push(children[groupFrom]);}else {let length=positions[i-1]+children[i-1].length-groupStart;localChildren.push(balanceRange(balanceType,children,positions,groupFrom,i,groupStart,length,null,mkTree));}localPositions.push(groupStart+offset-start);}}divide(children,positions,from,to,0);return (mkTop||mkTree)(localChildren,localPositions,length);}/// A superclass that parsers should extend.
4319
- class Parser{/// Start a parse, returning a [partial parse](#common.PartialParse)
4320
- /// object. [`fragments`](#common.TreeFragment) can be passed in to
4321
- /// make the parse incremental.
4322
- ///
4323
- /// By default, the entire input is parsed. You can pass `ranges`,
4324
- /// which should be a sorted array of non-empty, non-overlapping
4325
- /// ranges, to parse only those ranges. The tree returned in that
4326
- /// case will start at `ranges[0].from`.
4327
- startParse(input,fragments,ranges){if(typeof input=="string")input=new StringInput(input);ranges=!ranges?[new Range(0,input.length)]:ranges.length?ranges.map(r=>new Range(r.from,r.to)):[new Range(0,0)];return this.createParse(input,fragments||[],ranges);}/// Run a full parse, returning the resulting tree.
4328
- parse(input,fragments,ranges){let parse=this.startParse(input,fragments,ranges);for(;;){let done=parse.advance();if(done)return done;}}}class StringInput{constructor(string){this.string=string;}get length(){return this.string.length;}chunk(from){return this.string.slice(from);}get lineChunks(){return false;}read(from,to){return this.string.slice(from,to);}}new NodeProp({perNode:true});/// A parse stack. These are used internally by the parser to track
4329
- /// parsing progress. They also provide some properties and methods
4330
- /// that external code such as a tokenizer can use to get information
4331
- /// about the parse state.
4332
- class Stack{/// @internal
4333
- constructor(/// The parse that this stack is part of @internal
4334
- p,/// Holds state, input pos, buffer index triplets for all but the
4335
- /// top state @internal
4336
- stack,/// The current parse state @internal
4337
- state,// The position at which the next reduce should take place. This
4338
- // can be less than `this.pos` when skipped expressions have been
4339
- // added to the stack (which should be moved outside of the next
4340
- // reduction)
4341
- /// @internal
4342
- reducePos,/// The input position up to which this stack has parsed.
4343
- pos,/// The dynamic score of the stack, including dynamic precedence
4344
- /// and error-recovery penalties
4345
- /// @internal
4346
- score,// The output buffer. Holds (type, start, end, size) quads
4347
- // representing nodes created by the parser, where `size` is
4348
- // amount of buffer array entries covered by this node.
4349
- /// @internal
4350
- buffer,// The base offset of the buffer. When stacks are split, the split
4351
- // instance shared the buffer history with its parent up to
4352
- // `bufferBase`, which is the absolute offset (including the
4353
- // offset of previous splits) into the buffer at which this stack
4354
- // starts writing.
4355
- /// @internal
4356
- bufferBase,/// @internal
4357
- curContext,/// @internal
4358
- lookAhead=0,// A parent stack from which this was split off, if any. This is
4359
- // set up so that it always points to a stack that has some
4360
- // additional buffer content, never to a stack with an equal
4361
- // `bufferBase`.
4362
- /// @internal
4363
- parent){this.p=p;this.stack=stack;this.state=state;this.reducePos=reducePos;this.pos=pos;this.score=score;this.buffer=buffer;this.bufferBase=bufferBase;this.curContext=curContext;this.lookAhead=lookAhead;this.parent=parent;}/// @internal
4364
- toString(){return `[${this.stack.filter((_,i)=>i%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`;}// Start an empty stack
4365
- /// @internal
4366
- static start(p,state,pos=0){let cx=p.parser.context;return new Stack(p,[],state,pos,pos,0,[],0,cx?new StackContext(cx,cx.start):null,0,null);}/// The stack's current [context](#lr.ContextTracker) value, if
4367
- /// any. Its type will depend on the context tracker's type
4368
- /// parameter, or it will be `null` if there is no context
4369
- /// tracker.
4370
- get context(){return this.curContext?this.curContext.context:null;}// Push a state onto the stack, tracking its start position as well
4371
- // as the buffer base at that point.
4372
- /// @internal
4373
- pushState(state,start){this.stack.push(this.state,start,this.bufferBase+this.buffer.length);this.state=state;}// Apply a reduce action
4374
- /// @internal
4375
- reduce(action){let depth=action>>19/* ReduceDepthShift */,type=action&65535/* ValueMask */;let{parser}=this.p;let dPrec=parser.dynamicPrecedence(type);if(dPrec)this.score+=dPrec;if(depth==0){this.pushState(parser.getGoto(this.state,type,true),this.reducePos);// Zero-depth reductions are a special case—they add stuff to
4376
- // the stack without popping anything off.
4377
- if(type<parser.minRepeatTerm)this.storeNode(type,this.reducePos,this.reducePos,4,true);this.reduceContext(type,this.reducePos);return;}// Find the base index into `this.stack`, content after which will
4378
- // be dropped. Note that with `StayFlag` reductions we need to
4379
- // consume two extra frames (the dummy parent node for the skipped
4380
- // expression and the state that we'll be staying in, which should
4381
- // be moved to `this.state`).
4382
- let base=this.stack.length-(depth-1)*3-(action&262144/* StayFlag */?6:0);let start=this.stack[base-2];let bufferBase=this.stack[base-1],count=this.bufferBase+this.buffer.length-bufferBase;// Store normal terms or `R -> R R` repeat reductions
4383
- if(type<parser.minRepeatTerm||action&131072/* RepeatFlag */){let pos=parser.stateFlag(this.state,1/* Skipped */)?this.pos:this.reducePos;this.storeNode(type,start,pos,count+4,true);}if(action&262144/* StayFlag */){this.state=this.stack[base];}else {let baseStateID=this.stack[base-3];this.state=parser.getGoto(baseStateID,type,true);}while(this.stack.length>base)this.stack.pop();this.reduceContext(type,start);}// Shift a value into the buffer
4384
- /// @internal
4385
- storeNode(term,start,end,size=4,isReduce=false){if(term==0/* Err */&&(!this.stack.length||this.stack[this.stack.length-1]<this.buffer.length+this.bufferBase)){// Try to omit/merge adjacent error nodes
4386
- let cur=this,top=this.buffer.length;if(top==0&&cur.parent){top=cur.bufferBase-cur.parent.bufferBase;cur=cur.parent;}if(top>0&&cur.buffer[top-4]==0/* Err */&&cur.buffer[top-1]>-1){if(start==end)return;if(cur.buffer[top-2]>=start){cur.buffer[top-2]=end;return;}}}if(!isReduce||this.pos==end){// Simple case, just append
4387
- this.buffer.push(term,start,end,size);}else {// There may be skipped nodes that have to be moved forward
4388
- let index=this.buffer.length;if(index>0&&this.buffer[index-4]!=0/* Err */)while(index>0&&this.buffer[index-2]>end){// Move this record forward
4389
- this.buffer[index]=this.buffer[index-4];this.buffer[index+1]=this.buffer[index-3];this.buffer[index+2]=this.buffer[index-2];this.buffer[index+3]=this.buffer[index-1];index-=4;if(size>4)size-=4;}this.buffer[index]=term;this.buffer[index+1]=start;this.buffer[index+2]=end;this.buffer[index+3]=size;}}// Apply a shift action
4390
- /// @internal
4391
- shift(action,next,nextEnd){let start=this.pos;if(action&131072/* GotoFlag */){this.pushState(action&65535/* ValueMask */,this.pos);}else if((action&262144/* StayFlag */)==0){// Regular shift
4392
- let nextState=action,{parser}=this.p;if(nextEnd>this.pos||next<=parser.maxNode){this.pos=nextEnd;if(!parser.stateFlag(nextState,1/* Skipped */))this.reducePos=nextEnd;}this.pushState(nextState,start);this.shiftContext(next,start);if(next<=parser.maxNode)this.buffer.push(next,start,nextEnd,4);}else {// Shift-and-stay, which means this is a skipped token
4393
- this.pos=nextEnd;this.shiftContext(next,start);if(next<=this.p.parser.maxNode)this.buffer.push(next,start,nextEnd,4);}}// Apply an action
4394
- /// @internal
4395
- apply(action,next,nextEnd){if(action&65536/* ReduceFlag */)this.reduce(action);else this.shift(action,next,nextEnd);}// Add a prebuilt (reused) node into the buffer.
4396
- /// @internal
4397
- useNode(value,next){let index=this.p.reused.length-1;if(index<0||this.p.reused[index]!=value){this.p.reused.push(value);index++;}let start=this.pos;this.reducePos=this.pos=start+value.length;this.pushState(next,start);this.buffer.push(index,start,this.reducePos,-1/* size == -1 means this is a reused value */);if(this.curContext)this.updateContext(this.curContext.tracker.reuse(this.curContext.context,value,this,this.p.stream.reset(this.pos-value.length)));}// Split the stack. Due to the buffer sharing and the fact
4398
- // that `this.stack` tends to stay quite shallow, this isn't very
4399
- // expensive.
4400
- /// @internal
4401
- split(){let parent=this;let off=parent.buffer.length;// Because the top of the buffer (after this.pos) may be mutated
4402
- // to reorder reductions and skipped tokens, and shared buffers
4403
- // should be immutable, this copies any outstanding skipped tokens
4404
- // to the new buffer, and puts the base pointer before them.
4405
- while(off>0&&parent.buffer[off-2]>parent.reducePos)off-=4;let buffer=parent.buffer.slice(off),base=parent.bufferBase+off;// Make sure parent points to an actual parent with content, if there is such a parent.
4406
- while(parent&&base==parent.bufferBase)parent=parent.parent;return new Stack(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,buffer,base,this.curContext,this.lookAhead,parent);}// Try to recover from an error by 'deleting' (ignoring) one token.
4407
- /// @internal
4408
- recoverByDelete(next,nextEnd){let isNode=next<=this.p.parser.maxNode;if(isNode)this.storeNode(next,this.pos,nextEnd,4);this.storeNode(0/* Err */,this.pos,nextEnd,isNode?8:4);this.pos=this.reducePos=nextEnd;this.score-=190/* Delete */;}/// Check if the given term would be able to be shifted (optionally
4409
- /// after some reductions) on this stack. This can be useful for
4410
- /// external tokenizers that want to make sure they only provide a
4411
- /// given token when it applies.
4412
- canShift(term){for(let sim=new SimulatedStack(this);;){let action=this.p.parser.stateSlot(sim.state,4/* DefaultReduce */)||this.p.parser.hasAction(sim.state,term);if((action&65536/* ReduceFlag */)==0)return true;if(action==0)return false;sim.reduce(action);}}// Apply up to Recover.MaxNext recovery actions that conceptually
4413
- // inserts some missing token or rule.
4414
- /// @internal
4415
- recoverByInsert(next){if(this.stack.length>=300/* MaxInsertStackDepth */)return [];let nextStates=this.p.parser.nextStates(this.state);if(nextStates.length>4/* MaxNext */<<1||this.stack.length>=120/* DampenInsertStackDepth */){let best=[];for(let i=0,s;i<nextStates.length;i+=2){if((s=nextStates[i+1])!=this.state&&this.p.parser.hasAction(s,next))best.push(nextStates[i],s);}if(this.stack.length<120/* DampenInsertStackDepth */)for(let i=0;best.length<4/* MaxNext */<<1&&i<nextStates.length;i+=2){let s=nextStates[i+1];if(!best.some((v,i)=>i&1&&v==s))best.push(nextStates[i],s);}nextStates=best;}let result=[];for(let i=0;i<nextStates.length&&result.length<4/* MaxNext */;i+=2){let s=nextStates[i+1];if(s==this.state)continue;let stack=this.split();stack.pushState(s,this.pos);stack.storeNode(0/* Err */,stack.pos,stack.pos,4,true);stack.shiftContext(nextStates[i],this.pos);stack.score-=200/* Insert */;result.push(stack);}return result;}// Force a reduce, if possible. Return false if that can't
4416
- // be done.
4417
- /// @internal
4418
- forceReduce(){let reduce=this.p.parser.stateSlot(this.state,5/* ForcedReduce */);if((reduce&65536/* ReduceFlag */)==0)return false;let{parser}=this.p;if(!parser.validAction(this.state,reduce)){let depth=reduce>>19/* ReduceDepthShift */,term=reduce&65535/* ValueMask */;let target=this.stack.length-depth*3;if(target<0||parser.getGoto(this.stack[target],term,false)<0)return false;this.storeNode(0/* Err */,this.reducePos,this.reducePos,4,true);this.score-=100/* Reduce */;}this.reducePos=this.pos;this.reduce(reduce);return true;}/// @internal
4419
- forceAll(){while(!this.p.parser.stateFlag(this.state,2/* Accepting */)){if(!this.forceReduce()){this.storeNode(0/* Err */,this.pos,this.pos,4,true);break;}}return this;}/// Check whether this state has no further actions (assumed to be a direct descendant of the
4420
- /// top state, since any other states must be able to continue
4421
- /// somehow). @internal
4422
- get deadEnd(){if(this.stack.length!=3)return false;let{parser}=this.p;return parser.data[parser.stateSlot(this.state,1/* Actions */)]==65535/* End */&&!parser.stateSlot(this.state,4/* DefaultReduce */);}/// Restart the stack (put it back in its start state). Only safe
4423
- /// when this.stack.length == 3 (state is directly below the top
4424
- /// state). @internal
4425
- restart(){this.state=this.stack[0];this.stack.length=0;}/// @internal
4426
- sameState(other){if(this.state!=other.state||this.stack.length!=other.stack.length)return false;for(let i=0;i<this.stack.length;i+=3)if(this.stack[i]!=other.stack[i])return false;return true;}/// Get the parser used by this stack.
4427
- get parser(){return this.p.parser;}/// Test whether a given dialect (by numeric ID, as exported from
4428
- /// the terms file) is enabled.
4429
- dialectEnabled(dialectID){return this.p.parser.dialect.flags[dialectID];}shiftContext(term,start){if(this.curContext)this.updateContext(this.curContext.tracker.shift(this.curContext.context,term,this,this.p.stream.reset(start)));}reduceContext(term,start){if(this.curContext)this.updateContext(this.curContext.tracker.reduce(this.curContext.context,term,this,this.p.stream.reset(start)));}/// @internal
4430
- emitContext(){let last=this.buffer.length-1;if(last<0||this.buffer[last]!=-3)this.buffer.push(this.curContext.hash,this.reducePos,this.reducePos,-3);}/// @internal
4431
- emitLookAhead(){let last=this.buffer.length-1;if(last<0||this.buffer[last]!=-4)this.buffer.push(this.lookAhead,this.reducePos,this.reducePos,-4);}updateContext(context){if(context!=this.curContext.context){let newCx=new StackContext(this.curContext.tracker,context);if(newCx.hash!=this.curContext.hash)this.emitContext();this.curContext=newCx;}}/// @internal
4432
- setLookAhead(lookAhead){if(lookAhead>this.lookAhead){this.emitLookAhead();this.lookAhead=lookAhead;}}/// @internal
4433
- close(){if(this.curContext&&this.curContext.tracker.strict)this.emitContext();if(this.lookAhead>0)this.emitLookAhead();}}class StackContext{constructor(tracker,context){this.tracker=tracker;this.context=context;this.hash=tracker.strict?tracker.hash(context):0;}}var Recover;(function(Recover){Recover[Recover["Insert"]=200]="Insert";Recover[Recover["Delete"]=190]="Delete";Recover[Recover["Reduce"]=100]="Reduce";Recover[Recover["MaxNext"]=4]="MaxNext";Recover[Recover["MaxInsertStackDepth"]=300]="MaxInsertStackDepth";Recover[Recover["DampenInsertStackDepth"]=120]="DampenInsertStackDepth";})(Recover||(Recover={}));// Used to cheaply run some reductions to scan ahead without mutating
4434
- // an entire stack
4435
- class SimulatedStack{constructor(start){this.start=start;this.state=start.state;this.stack=start.stack;this.base=this.stack.length;}reduce(action){let term=action&65535/* ValueMask */,depth=action>>19/* ReduceDepthShift */;if(depth==0){if(this.stack==this.start.stack)this.stack=this.stack.slice();this.stack.push(this.state,0,0);this.base+=3;}else {this.base-=(depth-1)*3;}let goto=this.start.p.parser.getGoto(this.stack[this.base-3],term,true);this.state=goto;}}// This is given to `Tree.build` to build a buffer, and encapsulates
4436
- // the parent-stack-walking necessary to read the nodes.
4437
- class StackBufferCursor{constructor(stack,pos,index){this.stack=stack;this.pos=pos;this.index=index;this.buffer=stack.buffer;if(this.index==0)this.maybeNext();}static create(stack,pos=stack.bufferBase+stack.buffer.length){return new StackBufferCursor(stack,pos,pos-stack.bufferBase);}maybeNext(){let next=this.stack.parent;if(next!=null){this.index=this.stack.bufferBase-next.bufferBase;this.stack=next;this.buffer=next.buffer;}}get id(){return this.buffer[this.index-4];}get start(){return this.buffer[this.index-3];}get end(){return this.buffer[this.index-2];}get size(){return this.buffer[this.index-1];}next(){this.index-=4;this.pos-=4;if(this.index==0)this.maybeNext();}fork(){return new StackBufferCursor(this.stack,this.pos,this.index);}}class CachedToken{constructor(){this.start=-1;this.value=-1;this.end=-1;this.extended=-1;this.lookAhead=0;this.mask=0;this.context=0;}}const nullToken=new CachedToken();/// [Tokenizers](#lr.ExternalTokenizer) interact with the input
4438
- /// through this interface. It presents the input as a stream of
4439
- /// characters, tracking lookahead and hiding the complexity of
4440
- /// [ranges](#common.Parser.parse^ranges) from tokenizer code.
4441
- class InputStream{/// @internal
4442
- constructor(/// @internal
4443
- input,/// @internal
4444
- ranges){this.input=input;this.ranges=ranges;/// @internal
4445
- this.chunk="";/// @internal
4446
- this.chunkOff=0;/// Backup chunk
4447
- this.chunk2="";this.chunk2Pos=0;/// The character code of the next code unit in the input, or -1
4448
- /// when the stream is at the end of the input.
4449
- this.next=-1;/// @internal
4450
- this.token=nullToken;this.rangeIndex=0;this.pos=this.chunkPos=ranges[0].from;this.range=ranges[0];this.end=ranges[ranges.length-1].to;this.readNext();}resolveOffset(offset,assoc){let range=this.range,index=this.rangeIndex;let pos=this.pos+offset;while(pos<range.from){if(!index)return null;let next=this.ranges[--index];pos-=range.from-next.to;range=next;}while(assoc<0?pos>range.to:pos>=range.to){if(index==this.ranges.length-1)return null;let next=this.ranges[++index];pos+=next.from-range.to;range=next;}return pos;}/// Look at a code unit near the stream position. `.peek(0)` equals
4451
- /// `.next`, `.peek(-1)` gives you the previous character, and so
4452
- /// on.
4453
- ///
4454
- /// Note that looking around during tokenizing creates dependencies
4455
- /// on potentially far-away content, which may reduce the
4456
- /// effectiveness incremental parsing—when looking forward—or even
4457
- /// cause invalid reparses when looking backward more than 25 code
4458
- /// units, since the library does not track lookbehind.
4459
- peek(offset){let idx=this.chunkOff+offset,pos,result;if(idx>=0&&idx<this.chunk.length){pos=this.pos+offset;result=this.chunk.charCodeAt(idx);}else {let resolved=this.resolveOffset(offset,1);if(resolved==null)return -1;pos=resolved;if(pos>=this.chunk2Pos&&pos<this.chunk2Pos+this.chunk2.length){result=this.chunk2.charCodeAt(pos-this.chunk2Pos);}else {let i=this.rangeIndex,range=this.range;while(range.to<=pos)range=this.ranges[++i];this.chunk2=this.input.chunk(this.chunk2Pos=pos);if(pos+this.chunk2.length>range.to)this.chunk2=this.chunk2.slice(0,range.to-pos);result=this.chunk2.charCodeAt(0);}}if(pos>=this.token.lookAhead)this.token.lookAhead=pos+1;return result;}/// Accept a token. By default, the end of the token is set to the
4460
- /// current stream position, but you can pass an offset (relative to
4461
- /// the stream position) to change that.
4462
- acceptToken(token,endOffset=0){let end=endOffset?this.resolveOffset(endOffset,-1):this.pos;if(end==null||end<this.token.start)throw new RangeError("Token end out of bounds");this.token.value=token;this.token.end=end;}getChunk(){if(this.pos>=this.chunk2Pos&&this.pos<this.chunk2Pos+this.chunk2.length){let{chunk,chunkPos}=this;this.chunk=this.chunk2;this.chunkPos=this.chunk2Pos;this.chunk2=chunk;this.chunk2Pos=chunkPos;this.chunkOff=this.pos-this.chunkPos;}else {this.chunk2=this.chunk;this.chunk2Pos=this.chunkPos;let nextChunk=this.input.chunk(this.pos);let end=this.pos+nextChunk.length;this.chunk=end>this.range.to?nextChunk.slice(0,this.range.to-this.pos):nextChunk;this.chunkPos=this.pos;this.chunkOff=0;}}readNext(){if(this.chunkOff>=this.chunk.length){this.getChunk();if(this.chunkOff==this.chunk.length)return this.next=-1;}return this.next=this.chunk.charCodeAt(this.chunkOff);}/// Move the stream forward N (defaults to 1) code units. Returns
4463
- /// the new value of [`next`](#lr.InputStream.next).
4464
- advance(n=1){this.chunkOff+=n;while(this.pos+n>=this.range.to){if(this.rangeIndex==this.ranges.length-1)return this.setDone();n-=this.range.to-this.pos;this.range=this.ranges[++this.rangeIndex];this.pos=this.range.from;}this.pos+=n;if(this.pos>=this.token.lookAhead)this.token.lookAhead=this.pos+1;return this.readNext();}setDone(){this.pos=this.chunkPos=this.end;this.range=this.ranges[this.rangeIndex=this.ranges.length-1];this.chunk="";return this.next=-1;}/// @internal
4465
- reset(pos,token){if(token){this.token=token;token.start=pos;token.lookAhead=pos+1;token.value=token.extended=-1;}else {this.token=nullToken;}if(this.pos!=pos){this.pos=pos;if(pos==this.end){this.setDone();return this;}while(pos<this.range.from)this.range=this.ranges[--this.rangeIndex];while(pos>=this.range.to)this.range=this.ranges[++this.rangeIndex];if(pos>=this.chunkPos&&pos<this.chunkPos+this.chunk.length){this.chunkOff=pos-this.chunkPos;}else {this.chunk="";this.chunkOff=0;}this.readNext();}return this;}/// @internal
4466
- read(from,to){if(from>=this.chunkPos&&to<=this.chunkPos+this.chunk.length)return this.chunk.slice(from-this.chunkPos,to-this.chunkPos);if(from>=this.chunk2Pos&&to<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(from-this.chunk2Pos,to-this.chunk2Pos);if(from>=this.range.from&&to<=this.range.to)return this.input.read(from,to);let result="";for(let r of this.ranges){if(r.from>=to)break;if(r.to>from)result+=this.input.read(Math.max(r.from,from),Math.min(r.to,to));}return result;}}/// @internal
4467
- class TokenGroup{constructor(data,id){this.data=data;this.id=id;}token(input,stack){readToken(this.data,input,stack,this.id);}}TokenGroup.prototype.contextual=TokenGroup.prototype.fallback=TokenGroup.prototype.extend=false;// Tokenizer data is stored a big uint16 array containing, for each
4468
- // state:
4469
- //
4470
- // - A group bitmask, indicating what token groups are reachable from
4471
- // this state, so that paths that can only lead to tokens not in
4472
- // any of the current groups can be cut off early.
4473
- //
4474
- // - The position of the end of the state's sequence of accepting
4475
- // tokens
4476
- //
4477
- // - The number of outgoing edges for the state
4478
- //
4479
- // - The accepting tokens, as (token id, group mask) pairs
4480
- //
4481
- // - The outgoing edges, as (start character, end character, state
4482
- // index) triples, with end character being exclusive
4483
- //
4484
- // This function interprets that data, running through a stream as
4485
- // long as new states with the a matching group mask can be reached,
4486
- // and updating `token` when it matches a token.
4487
- function readToken(data,input,stack,group){let state=0,groupMask=1<<group,{parser}=stack.p,{dialect}=parser;scan:for(;;){if((groupMask&data[state])==0)break;let accEnd=data[state+1];// Check whether this state can lead to a token in the current group
4488
- // Accept tokens in this state, possibly overwriting
4489
- // lower-precedence / shorter tokens
4490
- for(let i=state+3;i<accEnd;i+=2)if((data[i+1]&groupMask)>0){let term=data[i];if(dialect.allows(term)&&(input.token.value==-1||input.token.value==term||parser.overrides(term,input.token.value))){input.acceptToken(term);break;}}// Do a binary search on the state's edges
4491
- for(let next=input.next,low=0,high=data[state+2];low<high;){let mid=low+high>>1;let index=accEnd+mid+(mid<<1);let from=data[index],to=data[index+1];if(next<from)high=mid;else if(next>=to)low=mid+1;else {state=data[index+2];input.advance();continue scan;}}break;}}// See lezer-generator/src/encode.ts for comments about the encoding
4492
- // used here
4493
- function decodeArray(input,Type=Uint16Array){if(typeof input!="string")return input;let array=null;for(let pos=0,out=0;pos<input.length;){let value=0;for(;;){let next=input.charCodeAt(pos++),stop=false;if(next==126/* BigValCode */){value=65535/* BigVal */;break;}if(next>=92/* Gap2 */)next--;if(next>=34/* Gap1 */)next--;let digit=next-32/* Start */;if(digit>=46/* Base */){digit-=46/* Base */;stop=true;}value+=digit;if(stop)break;value*=46/* Base */;}if(array)array[out++]=value;else array=new Type(value);}return array;}// Environment variable used to control console output
4494
- const verbose=typeof process!="undefined"&&process.env&&/\bparse\b/.test(process.env.LOG);let stackIDs=null;var Safety;(function(Safety){Safety[Safety["Margin"]=25]="Margin";})(Safety||(Safety={}));function cutAt(tree,pos,side){let cursor=tree.cursor(IterMode.IncludeAnonymous);cursor.moveTo(pos);for(;;){if(!(side<0?cursor.childBefore(pos):cursor.childAfter(pos)))for(;;){if((side<0?cursor.to<pos:cursor.from>pos)&&!cursor.type.isError)return side<0?Math.max(0,Math.min(cursor.to-1,pos-25/* Margin */)):Math.min(tree.length,Math.max(cursor.from+1,pos+25/* Margin */));if(side<0?cursor.prevSibling():cursor.nextSibling())break;if(!cursor.parent())return side<0?0:tree.length;}}}class FragmentCursor{constructor(fragments,nodeSet){this.fragments=fragments;this.nodeSet=nodeSet;this.i=0;this.fragment=null;this.safeFrom=-1;this.safeTo=-1;this.trees=[];this.start=[];this.index=[];this.nextFragment();}nextFragment(){let fr=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(fr){this.safeFrom=fr.openStart?cutAt(fr.tree,fr.from+fr.offset,1)-fr.offset:fr.from;this.safeTo=fr.openEnd?cutAt(fr.tree,fr.to+fr.offset,-1)-fr.offset:fr.to;while(this.trees.length){this.trees.pop();this.start.pop();this.index.pop();}this.trees.push(fr.tree);this.start.push(-fr.offset);this.index.push(0);this.nextStart=this.safeFrom;}else {this.nextStart=1e9;}}// `pos` must be >= any previously given `pos` for this cursor
4495
- nodeAt(pos){if(pos<this.nextStart)return null;while(this.fragment&&this.safeTo<=pos)this.nextFragment();if(!this.fragment)return null;for(;;){let last=this.trees.length-1;if(last<0){// End of tree
4496
- this.nextFragment();return null;}let top=this.trees[last],index=this.index[last];if(index==top.children.length){this.trees.pop();this.start.pop();this.index.pop();continue;}let next=top.children[index];let start=this.start[last]+top.positions[index];if(start>pos){this.nextStart=start;return null;}if(next instanceof Tree){if(start==pos){if(start<this.safeFrom)return null;let end=start+next.length;if(end<=this.safeTo){let lookAhead=next.prop(NodeProp.lookAhead);if(!lookAhead||end+lookAhead<this.fragment.to)return next;}}this.index[last]++;if(start+next.length>=Math.max(this.safeFrom,pos)){// Enter this node
4497
- this.trees.push(next);this.start.push(start);this.index.push(0);}}else {this.index[last]++;this.nextStart=start+next.length;}}}}class TokenCache{constructor(parser,stream){this.stream=stream;this.tokens=[];this.mainToken=null;this.actions=[];this.tokens=parser.tokenizers.map(_=>new CachedToken());}getActions(stack){let actionIndex=0;let main=null;let{parser}=stack.p,{tokenizers}=parser;let mask=parser.stateSlot(stack.state,3/* TokenizerMask */);let context=stack.curContext?stack.curContext.hash:0;let lookAhead=0;for(let i=0;i<tokenizers.length;i++){if((1<<i&mask)==0)continue;let tokenizer=tokenizers[i],token=this.tokens[i];if(main&&!tokenizer.fallback)continue;if(tokenizer.contextual||token.start!=stack.pos||token.mask!=mask||token.context!=context){this.updateCachedToken(token,tokenizer,stack);token.mask=mask;token.context=context;}if(token.lookAhead>token.end+25/* Margin */)lookAhead=Math.max(token.lookAhead,lookAhead);if(token.value!=0/* Err */){let startIndex=actionIndex;if(token.extended>-1)actionIndex=this.addActions(stack,token.extended,token.end,actionIndex);actionIndex=this.addActions(stack,token.value,token.end,actionIndex);if(!tokenizer.extend){main=token;if(actionIndex>startIndex)break;}}}while(this.actions.length>actionIndex)this.actions.pop();if(lookAhead)stack.setLookAhead(lookAhead);if(!main&&stack.pos==this.stream.end){main=new CachedToken();main.value=stack.p.parser.eofTerm;main.start=main.end=stack.pos;actionIndex=this.addActions(stack,main.value,main.end,actionIndex);}this.mainToken=main;return this.actions;}getMainToken(stack){if(this.mainToken)return this.mainToken;let main=new CachedToken(),{pos,p}=stack;main.start=pos;main.end=Math.min(pos+1,p.stream.end);main.value=pos==p.stream.end?p.parser.eofTerm:0/* Err */;return main;}updateCachedToken(token,tokenizer,stack){tokenizer.token(this.stream.reset(stack.pos,token),stack);if(token.value>-1){let{parser}=stack.p;for(let i=0;i<parser.specialized.length;i++)if(parser.specialized[i]==token.value){let result=parser.specializers[i](this.stream.read(token.start,token.end),stack);if(result>=0&&stack.p.parser.dialect.allows(result>>1)){if((result&1)==0/* Specialize */)token.value=result>>1;else token.extended=result>>1;break;}}}else {token.value=0/* Err */;token.end=Math.min(stack.p.stream.end,stack.pos+1);}}putAction(action,token,end,index){// Don't add duplicate actions
4498
- for(let i=0;i<index;i+=3)if(this.actions[i]==action)return index;this.actions[index++]=action;this.actions[index++]=token;this.actions[index++]=end;return index;}addActions(stack,token,end,index){let{state}=stack,{parser}=stack.p,{data}=parser;for(let set=0;set<2;set++){for(let i=parser.stateSlot(state,set?2/* Skip */:1/* Actions */);;i+=3){if(data[i]==65535/* End */){if(data[i+1]==1/* Next */){i=pair(data,i+2);}else {if(index==0&&data[i+1]==2/* Other */)index=this.putAction(pair(data,i+2),token,end,index);break;}}if(data[i]==token)index=this.putAction(pair(data,i+1),token,end,index);}}return index;}}var Rec;(function(Rec){Rec[Rec["Distance"]=5]="Distance";Rec[Rec["MaxRemainingPerStep"]=3]="MaxRemainingPerStep";// When two stacks have been running independently long enough to
4499
- // add this many elements to their buffers, prune one.
4500
- Rec[Rec["MinBufferLengthPrune"]=500]="MinBufferLengthPrune";Rec[Rec["ForceReduceLimit"]=10]="ForceReduceLimit";// Once a stack reaches this depth (in .stack.length) force-reduce
4501
- // it back to CutTo to avoid creating trees that overflow the stack
4502
- // on recursive traversal.
4503
- Rec[Rec["CutDepth"]=15000]="CutDepth";Rec[Rec["CutTo"]=9000]="CutTo";})(Rec||(Rec={}));class Parse{constructor(parser,input,fragments,ranges){this.parser=parser;this.input=input;this.ranges=ranges;this.recovering=0;this.nextStackID=0x2654;// ♔, ♕, ♖, ♗, ♘, ♙, ♠, ♡, ♢, ♣, ♤, ♥, ♦, ♧
4504
- this.minStackPos=0;this.reused=[];this.stoppedAt=null;this.stream=new InputStream(input,ranges);this.tokens=new TokenCache(parser,this.stream);this.topTerm=parser.top[1];let{from}=ranges[0];this.stacks=[Stack.start(this,parser.top[0],from)];this.fragments=fragments.length&&this.stream.end-from>parser.bufferLength*4?new FragmentCursor(fragments,parser.nodeSet):null;}get parsedPos(){return this.minStackPos;}// Move the parser forward. This will process all parse stacks at
4505
- // `this.pos` and try to advance them to a further position. If no
4506
- // stack for such a position is found, it'll start error-recovery.
4507
- //
4508
- // When the parse is finished, this will return a syntax tree. When
4509
- // not, it returns `null`.
4510
- advance(){let stacks=this.stacks,pos=this.minStackPos;// This will hold stacks beyond `pos`.
4511
- let newStacks=this.stacks=[];let stopped,stoppedTokens;// Keep advancing any stacks at `pos` until they either move
4512
- // forward or can't be advanced. Gather stacks that can't be
4513
- // advanced further in `stopped`.
4514
- for(let i=0;i<stacks.length;i++){let stack=stacks[i];for(;;){this.tokens.mainToken=null;if(stack.pos>pos){newStacks.push(stack);}else if(this.advanceStack(stack,newStacks,stacks)){continue;}else {if(!stopped){stopped=[];stoppedTokens=[];}stopped.push(stack);let tok=this.tokens.getMainToken(stack);stoppedTokens.push(tok.value,tok.end);}break;}}if(!newStacks.length){let finished=stopped&&findFinished(stopped);if(finished)return this.stackToTree(finished);if(this.parser.strict){if(verbose&&stopped)console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none"));throw new SyntaxError("No parse at "+pos);}if(!this.recovering)this.recovering=5/* Distance */;}if(this.recovering&&stopped){let finished=this.stoppedAt!=null&&stopped[0].pos>this.stoppedAt?stopped[0]:this.runRecovery(stopped,stoppedTokens,newStacks);if(finished)return this.stackToTree(finished.forceAll());}if(this.recovering){let maxRemaining=this.recovering==1?1:this.recovering*3/* MaxRemainingPerStep */;if(newStacks.length>maxRemaining){newStacks.sort((a,b)=>b.score-a.score);while(newStacks.length>maxRemaining)newStacks.pop();}if(newStacks.some(s=>s.reducePos>pos))this.recovering--;}else if(newStacks.length>1){// Prune stacks that are in the same state, or that have been
4515
- // running without splitting for a while, to avoid getting stuck
4516
- // with multiple successful stacks running endlessly on.
4517
- outer:for(let i=0;i<newStacks.length-1;i++){let stack=newStacks[i];for(let j=i+1;j<newStacks.length;j++){let other=newStacks[j];if(stack.sameState(other)||stack.buffer.length>500/* MinBufferLengthPrune */&&other.buffer.length>500/* MinBufferLengthPrune */){if((stack.score-other.score||stack.buffer.length-other.buffer.length)>0){newStacks.splice(j--,1);}else {newStacks.splice(i--,1);continue outer;}}}}}this.minStackPos=newStacks[0].pos;for(let i=1;i<newStacks.length;i++)if(newStacks[i].pos<this.minStackPos)this.minStackPos=newStacks[i].pos;return null;}stopAt(pos){if(this.stoppedAt!=null&&this.stoppedAt<pos)throw new RangeError("Can't move stoppedAt forward");this.stoppedAt=pos;}// Returns an updated version of the given stack, or null if the
4518
- // stack can't advance normally. When `split` and `stacks` are
4519
- // given, stacks split off by ambiguous operations will be pushed to
4520
- // `split`, or added to `stacks` if they move `pos` forward.
4521
- advanceStack(stack,stacks,split){let start=stack.pos,{parser}=this;let base=verbose?this.stackID(stack)+" -> ":"";if(this.stoppedAt!=null&&start>this.stoppedAt)return stack.forceReduce()?stack:null;if(this.fragments){let strictCx=stack.curContext&&stack.curContext.tracker.strict,cxHash=strictCx?stack.curContext.hash:0;for(let cached=this.fragments.nodeAt(start);cached;){let match=this.parser.nodeSet.types[cached.type.id]==cached.type?parser.getGoto(stack.state,cached.type.id):-1;if(match>-1&&cached.length&&(!strictCx||(cached.prop(NodeProp.contextHash)||0)==cxHash)){stack.useNode(cached,match);if(verbose)console.log(base+this.stackID(stack)+` (via reuse of ${parser.getName(cached.type.id)})`);return true;}if(!(cached instanceof Tree)||cached.children.length==0||cached.positions[0]>0)break;let inner=cached.children[0];if(inner instanceof Tree&&cached.positions[0]==0)cached=inner;else break;}}let defaultReduce=parser.stateSlot(stack.state,4/* DefaultReduce */);if(defaultReduce>0){stack.reduce(defaultReduce);if(verbose)console.log(base+this.stackID(stack)+` (via always-reduce ${parser.getName(defaultReduce&65535/* ValueMask */)})`);return true;}if(stack.stack.length>=15000/* CutDepth */){while(stack.stack.length>9000/* CutTo */&&stack.forceReduce()){}}let actions=this.tokens.getActions(stack);for(let i=0;i<actions.length;){let action=actions[i++],term=actions[i++],end=actions[i++];let last=i==actions.length||!split;let localStack=last?stack:stack.split();localStack.apply(action,term,end);if(verbose)console.log(base+this.stackID(localStack)+` (via ${(action&65536/* ReduceFlag */)==0?"shift":`reduce of ${parser.getName(action&65535/* ValueMask */)}`} for ${parser.getName(term)} @ ${start}${localStack==stack?"":", split"})`);if(last)return true;else if(localStack.pos>start)stacks.push(localStack);else split.push(localStack);}return false;}// Advance a given stack forward as far as it will go. Returns the
4522
- // (possibly updated) stack if it got stuck, or null if it moved
4523
- // forward and was given to `pushStackDedup`.
4524
- advanceFully(stack,newStacks){let pos=stack.pos;for(;;){if(!this.advanceStack(stack,null,null))return false;if(stack.pos>pos){pushStackDedup(stack,newStacks);return true;}}}runRecovery(stacks,tokens,newStacks){let finished=null,restarted=false;for(let i=0;i<stacks.length;i++){let stack=stacks[i],token=tokens[i<<1],tokenEnd=tokens[(i<<1)+1];let base=verbose?this.stackID(stack)+" -> ":"";if(stack.deadEnd){if(restarted)continue;restarted=true;stack.restart();if(verbose)console.log(base+this.stackID(stack)+" (restarted)");let done=this.advanceFully(stack,newStacks);if(done)continue;}let force=stack.split(),forceBase=base;for(let j=0;force.forceReduce()&&j<10/* ForceReduceLimit */;j++){if(verbose)console.log(forceBase+this.stackID(force)+" (via force-reduce)");let done=this.advanceFully(force,newStacks);if(done)break;if(verbose)forceBase=this.stackID(force)+" -> ";}for(let insert of stack.recoverByInsert(token)){if(verbose)console.log(base+this.stackID(insert)+" (via recover-insert)");this.advanceFully(insert,newStacks);}if(this.stream.end>stack.pos){if(tokenEnd==stack.pos){tokenEnd++;token=0/* Err */;}stack.recoverByDelete(token,tokenEnd);if(verbose)console.log(base+this.stackID(stack)+` (via recover-delete ${this.parser.getName(token)})`);pushStackDedup(stack,newStacks);}else if(!finished||finished.score<stack.score){finished=stack;}}return finished;}// Convert the stack's buffer to a syntax tree.
4525
- stackToTree(stack){stack.close();return Tree.build({buffer:StackBufferCursor.create(stack),nodeSet:this.parser.nodeSet,topID:this.topTerm,maxBufferLength:this.parser.bufferLength,reused:this.reused,start:this.ranges[0].from,length:stack.pos-this.ranges[0].from,minRepeatType:this.parser.minRepeatTerm});}stackID(stack){let id=(stackIDs||(stackIDs=new WeakMap())).get(stack);if(!id)stackIDs.set(stack,id=String.fromCodePoint(this.nextStackID++));return id+stack;}}function pushStackDedup(stack,newStacks){for(let i=0;i<newStacks.length;i++){let other=newStacks[i];if(other.pos==stack.pos&&other.sameState(stack)){if(newStacks[i].score<stack.score)newStacks[i]=stack;return;}}newStacks.push(stack);}class Dialect{constructor(source,flags,disabled){this.source=source;this.flags=flags;this.disabled=disabled;}allows(term){return !this.disabled||this.disabled[term]==0;}}/// A parser holds the parse tables for a given grammar, as generated
4526
- /// by `lezer-generator`.
4527
- class LRParser extends Parser{/// @internal
4528
- constructor(spec){super();/// @internal
4529
- this.wrappers=[];if(spec.version!=14/* Version */)throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14/* Version */})`);let nodeNames=spec.nodeNames.split(" ");this.minRepeatTerm=nodeNames.length;for(let i=0;i<spec.repeatNodeCount;i++)nodeNames.push("");let topTerms=Object.keys(spec.topRules).map(r=>spec.topRules[r][1]);let nodeProps=[];for(let i=0;i<nodeNames.length;i++)nodeProps.push([]);function setProp(nodeID,prop,value){nodeProps[nodeID].push([prop,prop.deserialize(String(value))]);}if(spec.nodeProps)for(let propSpec of spec.nodeProps){let prop=propSpec[0];if(typeof prop=="string")prop=NodeProp[prop];for(let i=1;i<propSpec.length;){let next=propSpec[i++];if(next>=0){setProp(next,prop,propSpec[i++]);}else {let value=propSpec[i+-next];for(let j=-next;j>0;j--)setProp(propSpec[i++],prop,value);i++;}}}this.nodeSet=new NodeSet(nodeNames.map((name,i)=>NodeType.define({name:i>=this.minRepeatTerm?undefined:name,id:i,props:nodeProps[i],top:topTerms.indexOf(i)>-1,error:i==0,skipped:spec.skippedNodes&&spec.skippedNodes.indexOf(i)>-1})));if(spec.propSources)this.nodeSet=this.nodeSet.extend(...spec.propSources);this.strict=false;this.bufferLength=DefaultBufferLength;let tokenArray=decodeArray(spec.tokenData);this.context=spec.context;this.specialized=new Uint16Array(spec.specialized?spec.specialized.length:0);this.specializers=[];if(spec.specialized)for(let i=0;i<spec.specialized.length;i++){this.specialized[i]=spec.specialized[i].term;this.specializers[i]=spec.specialized[i].get;}this.states=decodeArray(spec.states,Uint32Array);this.data=decodeArray(spec.stateData);this.goto=decodeArray(spec.goto);this.maxTerm=spec.maxTerm;this.tokenizers=spec.tokenizers.map(value=>typeof value=="number"?new TokenGroup(tokenArray,value):value);this.topRules=spec.topRules;this.dialects=spec.dialects||{};this.dynamicPrecedences=spec.dynamicPrecedences||null;this.tokenPrecTable=spec.tokenPrec;this.termNames=spec.termNames||null;this.maxNode=this.nodeSet.types.length-1;this.dialect=this.parseDialect();this.top=this.topRules[Object.keys(this.topRules)[0]];}createParse(input,fragments,ranges){let parse=new Parse(this,input,fragments,ranges);for(let w of this.wrappers)parse=w(parse,input,fragments,ranges);return parse;}/// Get a goto table entry @internal
4530
- getGoto(state,term,loose=false){let table=this.goto;if(term>=table[0])return -1;for(let pos=table[term+1];;){let groupTag=table[pos++],last=groupTag&1;let target=table[pos++];if(last&&loose)return target;for(let end=pos+(groupTag>>1);pos<end;pos++)if(table[pos]==state)return target;if(last)return -1;}}/// Check if this state has an action for a given terminal @internal
4531
- hasAction(state,terminal){let data=this.data;for(let set=0;set<2;set++){for(let i=this.stateSlot(state,set?2/* Skip */:1/* Actions */),next;;i+=3){if((next=data[i])==65535/* End */){if(data[i+1]==1/* Next */)next=data[i=pair(data,i+2)];else if(data[i+1]==2/* Other */)return pair(data,i+2);else break;}if(next==terminal||next==0/* Err */)return pair(data,i+1);}}return 0;}/// @internal
4532
- stateSlot(state,slot){return this.states[state*6/* Size */+slot];}/// @internal
4533
- stateFlag(state,flag){return (this.stateSlot(state,0/* Flags */)&flag)>0;}/// @internal
4534
- validAction(state,action){if(action==this.stateSlot(state,4/* DefaultReduce */))return true;for(let i=this.stateSlot(state,1/* Actions */);;i+=3){if(this.data[i]==65535/* End */){if(this.data[i+1]==1/* Next */)i=pair(this.data,i+2);else return false;}if(action==pair(this.data,i+1))return true;}}/// Get the states that can follow this one through shift actions or
4535
- /// goto jumps. @internal
4536
- nextStates(state){let result=[];for(let i=this.stateSlot(state,1/* Actions */);;i+=3){if(this.data[i]==65535/* End */){if(this.data[i+1]==1/* Next */)i=pair(this.data,i+2);else break;}if((this.data[i+2]&65536/* ReduceFlag */>>16)==0){let value=this.data[i+1];if(!result.some((v,i)=>i&1&&v==value))result.push(this.data[i],value);}}return result;}/// @internal
4537
- overrides(token,prev){let iPrev=findOffset(this.data,this.tokenPrecTable,prev);return iPrev<0||findOffset(this.data,this.tokenPrecTable,token)<iPrev;}/// Configure the parser. Returns a new parser instance that has the
4538
- /// given settings modified. Settings not provided in `config` are
4539
- /// kept from the original parser.
4540
- configure(config){// Hideous reflection-based kludge to make it easy to create a
4541
- // slightly modified copy of a parser.
4542
- let copy=Object.assign(Object.create(LRParser.prototype),this);if(config.props)copy.nodeSet=this.nodeSet.extend(...config.props);if(config.top){let info=this.topRules[config.top];if(!info)throw new RangeError(`Invalid top rule name ${config.top}`);copy.top=info;}if(config.tokenizers)copy.tokenizers=this.tokenizers.map(t=>{let found=config.tokenizers.find(r=>r.from==t);return found?found.to:t;});if(config.contextTracker)copy.context=config.contextTracker;if(config.dialect)copy.dialect=this.parseDialect(config.dialect);if(config.strict!=null)copy.strict=config.strict;if(config.wrap)copy.wrappers=copy.wrappers.concat(config.wrap);if(config.bufferLength!=null)copy.bufferLength=config.bufferLength;return copy;}/// Tells you whether any [parse wrappers](#lr.ParserConfig.wrap)
4543
- /// are registered for this parser.
4544
- hasWrappers(){return this.wrappers.length>0;}/// Returns the name associated with a given term. This will only
4545
- /// work for all terms when the parser was generated with the
4546
- /// `--names` option. By default, only the names of tagged terms are
4547
- /// stored.
4548
- getName(term){return this.termNames?this.termNames[term]:String(term<=this.maxNode&&this.nodeSet.types[term].name||term);}/// The eof term id is always allocated directly after the node
4549
- /// types. @internal
4550
- get eofTerm(){return this.maxNode+1;}/// The type of top node produced by the parser.
4551
- get topNode(){return this.nodeSet.types[this.top[1]];}/// @internal
4552
- dynamicPrecedence(term){let prec=this.dynamicPrecedences;return prec==null?0:prec[term]||0;}/// @internal
4553
- parseDialect(dialect){let values=Object.keys(this.dialects),flags=values.map(()=>false);if(dialect)for(let part of dialect.split(" ")){let id=values.indexOf(part);if(id>=0)flags[id]=true;}let disabled=null;for(let i=0;i<values.length;i++)if(!flags[i]){for(let j=this.dialects[values[i]],id;(id=this.data[j++])!=65535/* End */;)(disabled||(disabled=new Uint8Array(this.maxTerm+1)))[id]=1;}return new Dialect(dialect,flags,disabled);}/// (used by the output of the parser generator) @internal
4554
- static deserialize(spec){return new LRParser(spec);}}function pair(data,off){return data[off]|data[off+1]<<16;}function findOffset(data,start,term){for(let i=start,next;(next=data[i])!=65535/* End */;i++)if(next==term)return i-start;return -1;}function findFinished(stacks){let best=null;for(let stack of stacks){let stopped=stack.p.stoppedAt;if((stack.pos==stack.p.stream.end||stopped!=null&&stack.pos>stopped)&&stack.p.parser.stateFlag(stack.state,2/* Accepting */)&&(!best||best.score<stack.score))best=stack;}return best;}// This file was generated by lezer-generator. You probably shouldn't edit it.
4555
- const spec_identifier={__proto__:null,for:10,in:18,return:23,if:26,then:28,else:30,some:34,every:36,satisfies:43,or:46,and:50,between:58,instance:82,of:85,days:93,time:95,duration:97,years:99,months:101,date:103,list:109,context:115,function:122,string:141,length:143,upper:145,case:147,lower:149,substring:151,before:153,after:155,starts:157,with:159,ends:161,contains:163,insert:165,index:167,distinct:169,values:171,met:173,by:175,overlaps:177,finished:179,started:181,day:183,year:185,week:187,month:189,get:191,value:193,entries:195,start:205,position:207,decimal:209,sep:211,separator:213,grouping:215,null:218,true:344,false:344,"?":232,external:248,method:265,signature:267,not:273};const parser=LRParser.deserialize({version:14,states:"!#UO]QPOOO&hQPOOO'sQPO'#FiO]QPO'#DOO*[QPO'#DOO,zQPO'#DrOOQO'#En'#EnOOQO'#Eo'#EoOOQO'#Ep'#EpO,zQPO'#EqOOQO'#F{'#F{OOQO'#Fz'#FzOOQO'#Es'#EsO-P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(c(`(dQ(e(bQ(g(TQ(j(wQ(o'iR(r({$yeOPRS^_gi!O!R!S!T!U!W!X![!]!^!_#U#W#j#r#u#|#}$O$R$S$`$e%W%e%f%l&c&d&e&f&g&h&i&j&p&q&r&s&t&u&y&{&}'R'^'_'`'b'c'd'e'f'g'h'i'p'q'r'u'x'z'|'}(O(P(Q(R(S(T(Z([(](`(b(d(f(l(m(w({X!vh'](u(yX!{j'a(v(zV}P#W#jR%s%bT%w%c'w$Q!YQT{!a!j!l!y#X#Y#Z#[#^#g#h#i$f$s$u$z$|$}%Q%R%X%[%j%y%z&a&k&l&m&n&o&v&w&x&z&|'O'Q'S'U'V'W'Y'k'l'm'n'o's't'v'y'{(U(V(W(X(Y(^(_(a(c(e(g(j(o(rR!cXR#b!XQ!m_R#c!X$rZOPRSgi!O!R!S!T!U!W!X![!]!^!_#U#W#r#u#|#}$O$R$S$`$e%W%e%f%l&c&d&e&f&g&h&i&j&p&q&r&s&t&u&y&{&}'R'^'_'`'b'c'd'e'f'g'h'i'p'q'r'u'x'z'|'}(O(P(Q(R(S(T(Z([(](`(b(d(f(l(m(w({U!g]`#pV!k^_#jW!h]^_#jQ!n`R$r#pX$Y#T'j(x(|R!rc",nodeNames:"⚠ LineComment BlockComment Expressions ForExpression for InExpressions InExpression Name in IterationContext return IfExpression if then else QuantifiedExpression some every InExpressions InExpression satisfies Disjunction or Conjunction and Comparison CompareOp CompareOp between PositiveUnaryTest ( PositiveUnaryTests ) ArithmeticExpression ArithOp ArithOp ArithOp ArithOp ArithOp InstanceOf instance of Type QualifiedName SpecialType days time duration years months date > ListType list < ContextType context ContextEntryTypes ContextEntryType FunctionType function ArgumentTypes ArgumentType PathExpression ] FilterExpression [ FunctionInvocation SpecialFunctionName string length upper case lower substring before after starts with ends contains insert index distinct values met by overlaps finished started day year week month get value entries NamedParameters NamedParameter ParameterName SpecialParameterName start position decimal sep separator grouping PositionalParameters null NumericLiteral StringLiteral BooleanLiteral DateTimeLiteral DateTimeConstructor VariableName ? SimplePositiveUnaryTest Interval ParenthesizedExpression List FunctionDefinition FormalParameters FormalParameter external FunctionBody } { Context ContextEntry Key SpecialKey method signature UnaryTests Wildcard not",maxTerm:177,nodeProps:[["group",-18,4,12,16,22,24,26,34,40,64,66,68,115,116,117,119,120,121,128,"Expression",-5,109,110,111,112,113,"Expression Literal"],["closedBy",31,")",67,"]",127,"}"],["openedBy",33,"(",65,"[",126,"{"]],skippedNodes:[0,1,2],repeatNodeCount:11,tokenData:"+Y~R|XY#{Y^#{pq#{qr$prs${tu%oxy&yyz'Oz{'T{|'b|}'g}!O'l!O!P'y!P!Q(c!Q![)n![!]*P!]!^*U!^!_*Z!_!`$v!`!a*j!a!b%o!c!}%o!}#O*t#P#Q*y#Q#R']#R#S%o#T#o%o#o#p+O#q#r+T#y#z#{$f$g#{#BY#BZ#{$IS$I_#{$I`$Ib%o$I|$JO#{$JT$JU#{$KV$KW#{$Kh%#t%o&/x&Et%o&FU&FV#{&FV;'S%o;'S;:j&s?&r?Ah%o?BY?Mn%o~$QY$[~X^#{pq#{#y#z#{$f$g#{#BY#BZ#{$IS$I_#{$I|$JO#{$JT$JU#{$KV$KW#{&FU&FV#{~$sP!_!`$v~${Ok~~%QU$q~OY${Zr${rs%ds#O${#O#P%i#P~${~%iO$q~~%lPO~${~%t_$`~tu%o!Q![%o!a!b%o!c!}%o#R#S%o#T#o%o1p4U%o$I`$Ib%o$Je$Jg%o$Kh%#t%o&/x&Et%o&FV;'S%o;'S;:j&s?&r?Ah%o?BY?Mn%o~&vP;=`<%l%o~'OOo~~'TOq~~'YPu~z{']~'bOw~~'gOs~~'lO$c~R'qPtP!`!a'tQ'yO$jQ~(OQ$f~!O!P(U!Q![(Z~(ZO$b~~(`P$p~!Q![(Z~(hQv~z{(n!P!Q)c~(qROz(nz{(z{~(n~(}TOz(nz{(z{!P(n!P!Q)^!Q~(n~)cOQ~~)hQP~OY)cZ~)c~)sQ$p~!O!P)y!Q![)n~)|P!Q![(Z~*UO$h~~*ZO$w~R*bP!XQlP!_!`*eP*jOlPR*qP!UQlP!_!`*e~*yO!e~~+OO!c~~+TO#s~~+YO#r~",tokenizers:[0,1],topRules:{"Expressions":[0,3],"UnaryTests":[1,134]},dynamicPrecedences:{"24":-1,"68":-1,"151":-1},specialized:[{term:154,get:value=>spec_identifier[value]||-1}],tokenPrec:0});const highlightTags=styleTags({VariableName:tags.variableName,NumericLiteral:tags.number,QualifiedName:tags.name,Name:tags.name,BooleanLiteral:tags.bool,StringLiteral:tags.string,LineComment:tags.lineComment,BlockComment:tags.blockComment,'( )':tags.paren,BuiltInFunctionName:tags.function(tags.variableName),BuiltInType:tags.function(tags.variableName),ListType:tags.function(tags.variableName),ContextType:tags.function(tags.variableName),FunctionType:tags.function(tags.variableName),DateAndTime:tags.function(tags.variableName),'DateTimeConstructor!':tags.function(tags.variableName),'for in return null':tags.atom,List:tags.list,Interval:tags.list});const parserWithMetadata=parser.configure({props:[highlightTags]});const FeelLanguage=LRLanguage.define({parser:parserWithMetadata});function language(){return new LanguageSupport(FeelLanguage,[]);}/**
4086
+ return {start:startToken,end:{from:basePos+pos,to:basePos+pos+1},matched:found>>1==bracket>>1};}else {depth--;}}if(dir>0)distance+=text.length;}return iter.done?{start:startToken,matched:false}:null;}const noTokens=/*@__PURE__*/Object.create(null);const typeArray=[NodeType$1.none];const warned=[];const defaultTable=/*@__PURE__*/Object.create(null);for(let[legacyName,name]of [["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","typeName"],["attribute","propertyName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])defaultTable[legacyName]=/*@__PURE__*/createTokenType(noTokens,name);function warnForPart(part,msg){if(warned.indexOf(part)>-1)return;warned.push(part);console.warn(msg);}function createTokenType(extra,tagStr){let tag=null;for(let part of tagStr.split(".")){let value=extra[part]||tags[part];if(!value){warnForPart(part,`Unknown highlighting tag ${part}`);}else if(typeof value=="function"){if(!tag)warnForPart(part,`Modifier ${part} used at start of tag`);else tag=value(tag);}else {if(tag)warnForPart(part,`Tag ${part} used as modifier`);else tag=value;}}if(!tag)return 0;let name=tagStr.replace(/ /g,"_"),type=NodeType$1.define({id:typeArray.length,name,props:[styleTags({[name]:tag})]});typeArray.push(type);return type.id;}/**
4556
4087
  Comment or uncomment the current selection. Will use line comments
4557
4088
  if available, otherwise falling back to block comments.
4558
4089
  */const toggleComment=target=>{let config=getConfig(target.state);return config.line?toggleLineComment(target):config.block?toggleBlockCommentByLine(target):false;};function command(f,option){return ({state,dispatch})=>{if(state.readOnly)return false;let tr=f(option,state);if(!tr)return false;dispatch(state.update(tr));return true;};}/**
@@ -4809,8 +4340,7 @@ this.moveSelection((this.selectedIndex+1)%this.items.length);}else if(event.keyC
4809
4340
  this.moveSelection(0);}else if(event.keyCode==35){// End
4810
4341
  this.moveSelection(this.items.length-1);}else if(event.keyCode==13){// Enter
4811
4342
  this.view.focus();}else if(event.keyCode>=65&&event.keyCode<=90&&this.selectedIndex>=0){// A-Z
4812
- let{diagnostic}=this.items[this.selectedIndex],keys=assignKeys(diagnostic.actions);for(let i=0;i<keys.length;i++)if(keys[i].toUpperCase().charCodeAt(0)==event.keyCode){let found=findDiagnostic(this.view.state.field(lintState).diagnostics,diagnostic);if(found)diagnostic.actions[i].apply(view,found.from,found.to);}}else {return;}event.preventDefault();};let onclick=event=>{for(let i=0;i<this.items.length;i++){if(this.items[i].dom.contains(event.target))this.moveSelection(i);}};this.list=crelt("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown,onclick});this.dom=crelt("div",{class:"cm-panel-lint"},this.list,crelt("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>closeLintPanel(this.view)},"×"));this.update();}get selectedIndex(){let selected=this.view.state.field(lintState).selected;if(!selected)return -1;for(let i=0;i<this.items.length;i++)if(this.items[i].diagnostic==selected.diagnostic)return i;return -1;}update(){let{diagnostics,selected}=this.view.state.field(lintState);let i=0,needsSync=false,newSelectedItem=null;diagnostics.between(0,this.view.state.doc.length,(_start,_end,{spec})=>{let found=-1,item;for(let j=i;j<this.items.length;j++)if(this.items[j].diagnostic==spec.diagnostic){found=j;break;}if(found<0){item=new PanelItem(this.view,spec.diagnostic);this.items.splice(i,0,item);needsSync=true;}else {item=this.items[found];if(found>i){this.items.splice(i,found-i);needsSync=true;}}if(selected&&item.diagnostic==selected.diagnostic){if(!item.dom.hasAttribute("aria-selected")){item.dom.setAttribute("aria-selected","true");newSelectedItem=item;}}else if(item.dom.hasAttribute("aria-selected")){item.dom.removeAttribute("aria-selected");}i++;});while(i<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0)){needsSync=true;this.items.pop();}if(this.items.length==0){this.items.push(new PanelItem(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")}));needsSync=true;}if(newSelectedItem){this.list.setAttribute("aria-activedescendant",newSelectedItem.id);this.view.requestMeasure({key:this,read:()=>({sel:newSelectedItem.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel,panel})=>{if(sel.top<panel.top)this.list.scrollTop-=panel.top-sel.top;else if(sel.bottom>panel.bottom)this.list.scrollTop+=sel.bottom-panel.bottom;}});}else if(this.selectedIndex<0){this.list.removeAttribute("aria-activedescendant");}if(needsSync)this.sync();}sync(){let domPos=this.list.firstChild;function rm(){let prev=domPos;domPos=prev.nextSibling;prev.remove();}for(let item of this.items){if(item.dom.parentNode==this.list){while(domPos!=item.dom)rm();domPos=item.dom.nextSibling;}else {this.list.insertBefore(item.dom,domPos);}}while(domPos)rm();}moveSelection(selectedIndex){if(this.selectedIndex<0)return;let field=this.view.state.field(lintState);let selection=findDiagnostic(field.diagnostics,this.items[selectedIndex].diagnostic);if(!selection)return;this.view.dispatch({selection:{anchor:selection.from,head:selection.to},scrollIntoView:true,effects:movePanelSelection.of(selection)});}static open(view){return new LintPanel(view);}}function svg(content,attrs=`viewBox="0 0 40 40"`){return `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${attrs}>${encodeURIComponent(content)}</svg>')`;}function underline(color){return svg(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${color}" fill="none" stroke-width=".7"/>`,`width="6" height="3"`);}const baseTheme$2=/*@__PURE__*/EditorView.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:/*@__PURE__*/underline("#d11")},".cm-lintRange-warning":{backgroundImage:/*@__PURE__*/underline("orange")},".cm-lintRange-info":{backgroundImage:/*@__PURE__*/underline("#999")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}});const FeelLinter=function(editorView){const messages=[];// don't lint if the Editor is empty
4813
- if(editorView.state.doc.length===0){return messages;}const tree=syntaxTree(editorView.state);tree.iterate({enter:node=>{if(node.type.isError){const error=node.toString();/* The error has the pattern [⚠ || ⚠(NodeType)]. The regex extracts the node type from inside the brackets */const match=/\((.*?)\)/.exec(error);const nodeType=match&&match[1];let message;if(nodeType){message='unexpected '+nodeType;}else {message='expression expected';}messages.push({from:node.from,to:node.to,severity:'error',message:message,source:'syntaxError'});}}});return messages;};var syntaxLinter=linter$1(FeelLinter);var linter=[syntaxLinter];const baseTheme$1=EditorView.theme({'& .cm-content':{padding:'0px'},'& .cm-line':{padding:'0px'},'&.cm-editor.cm-focused':{outline:'none'}});const highlightTheme=EditorView.baseTheme({'& .variableName':{color:'#10f'},'& .number':{color:'#164'},'& .string':{color:'#a11'},'& .function':{color:'#aa3731',fontWeight:'bold'},'& .atom':{color:'#708'}});const syntaxClasses=syntaxHighlighting(HighlightStyle.define([{tag:tags.variableName,class:'variableName'},{tag:tags.name,class:'variableName'},{tag:tags.number,class:'number'},{tag:tags.string,class:'string'},{tag:tags.function(tags.variableName),class:'function'},{tag:tags.atom,class:'atom'}]));var theme=[baseTheme$1,highlightTheme,syntaxClasses];/**
4343
+ let{diagnostic}=this.items[this.selectedIndex],keys=assignKeys(diagnostic.actions);for(let i=0;i<keys.length;i++)if(keys[i].toUpperCase().charCodeAt(0)==event.keyCode){let found=findDiagnostic(this.view.state.field(lintState).diagnostics,diagnostic);if(found)diagnostic.actions[i].apply(view,found.from,found.to);}}else {return;}event.preventDefault();};let onclick=event=>{for(let i=0;i<this.items.length;i++){if(this.items[i].dom.contains(event.target))this.moveSelection(i);}};this.list=crelt("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown,onclick});this.dom=crelt("div",{class:"cm-panel-lint"},this.list,crelt("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>closeLintPanel(this.view)},"×"));this.update();}get selectedIndex(){let selected=this.view.state.field(lintState).selected;if(!selected)return -1;for(let i=0;i<this.items.length;i++)if(this.items[i].diagnostic==selected.diagnostic)return i;return -1;}update(){let{diagnostics,selected}=this.view.state.field(lintState);let i=0,needsSync=false,newSelectedItem=null;diagnostics.between(0,this.view.state.doc.length,(_start,_end,{spec})=>{let found=-1,item;for(let j=i;j<this.items.length;j++)if(this.items[j].diagnostic==spec.diagnostic){found=j;break;}if(found<0){item=new PanelItem(this.view,spec.diagnostic);this.items.splice(i,0,item);needsSync=true;}else {item=this.items[found];if(found>i){this.items.splice(i,found-i);needsSync=true;}}if(selected&&item.diagnostic==selected.diagnostic){if(!item.dom.hasAttribute("aria-selected")){item.dom.setAttribute("aria-selected","true");newSelectedItem=item;}}else if(item.dom.hasAttribute("aria-selected")){item.dom.removeAttribute("aria-selected");}i++;});while(i<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0)){needsSync=true;this.items.pop();}if(this.items.length==0){this.items.push(new PanelItem(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")}));needsSync=true;}if(newSelectedItem){this.list.setAttribute("aria-activedescendant",newSelectedItem.id);this.view.requestMeasure({key:this,read:()=>({sel:newSelectedItem.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel,panel})=>{if(sel.top<panel.top)this.list.scrollTop-=panel.top-sel.top;else if(sel.bottom>panel.bottom)this.list.scrollTop+=sel.bottom-panel.bottom;}});}else if(this.selectedIndex<0){this.list.removeAttribute("aria-activedescendant");}if(needsSync)this.sync();}sync(){let domPos=this.list.firstChild;function rm(){let prev=domPos;domPos=prev.nextSibling;prev.remove();}for(let item of this.items){if(item.dom.parentNode==this.list){while(domPos!=item.dom)rm();domPos=item.dom.nextSibling;}else {this.list.insertBefore(item.dom,domPos);}}while(domPos)rm();}moveSelection(selectedIndex){if(this.selectedIndex<0)return;let field=this.view.state.field(lintState);let selection=findDiagnostic(field.diagnostics,this.items[selectedIndex].diagnostic);if(!selection)return;this.view.dispatch({selection:{anchor:selection.from,head:selection.to},scrollIntoView:true,effects:movePanelSelection.of(selection)});}static open(view){return new LintPanel(view);}}function svg(content,attrs=`viewBox="0 0 40 40"`){return `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${attrs}>${encodeURIComponent(content)}</svg>')`;}function underline(color){return svg(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${color}" fill="none" stroke-width=".7"/>`,`width="6" height="3"`);}const baseTheme$2=/*@__PURE__*/EditorView.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:/*@__PURE__*/underline("#d11")},".cm-lintRange-warning":{backgroundImage:/*@__PURE__*/underline("orange")},".cm-lintRange-info":{backgroundImage:/*@__PURE__*/underline("#999")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}});/**
4814
4344
  An instance of this is passed to completion source functions.
4815
4345
  */class CompletionContext{/**
4816
4346
  Create a new completion context. (Mostly useful for testing
@@ -4859,78 +4389,551 @@ this.any=[];this.precise=[];this.byWord=[];for(let p=0;p<pattern.length;){let ch
4859
4389
  // with the match score, followed by any number of `from, to` pairs
4860
4390
  // indicating the matched parts of `word`.
4861
4391
  //
4862
- // The score is a number that is more negative the worse the match
4863
- // is. See `Penalty` above.
4864
- match(word){if(this.pattern.length==0)return [0];if(word.length<this.pattern.length)return null;let{chars,folded,any,precise,byWord}=this;// For single-character queries, only match when they occur right
4865
- // at the start
4866
- if(chars.length==1){let first=codePointAt(word,0);return first==chars[0]?[0,0,codePointSize(first)]:first==folded[0]?[-200/* CaseFold */,0,codePointSize(first)]:null;}let direct=word.indexOf(this.pattern);if(direct==0)return [0,0,this.pattern.length];let len=chars.length,anyTo=0;if(direct<0){for(let i=0,e=Math.min(word.length,200);i<e&&anyTo<len;){let next=codePointAt(word,i);if(next==chars[anyTo]||next==folded[anyTo])any[anyTo++]=i;i+=codePointSize(next);}// No match, exit immediately
4867
- if(anyTo<len)return null;}// This tracks the extent of the precise (non-folded, not
4868
- // necessarily adjacent) match
4869
- let preciseTo=0;// Tracks whether there is a match that hits only characters that
4870
- // appear to be starting words. `byWordFolded` is set to true when
4871
- // a case folded character is encountered in such a match
4872
- let byWordTo=0,byWordFolded=false;// If we've found a partial adjacent match, these track its state
4873
- let adjacentTo=0,adjacentStart=-1,adjacentEnd=-1;let hasLower=/[a-z]/.test(word),wordAdjacent=true;// Go over the option's text, scanning for the various kinds of matches
4874
- for(let i=0,e=Math.min(word.length,200),prevType=0/* NonWord */;i<e&&byWordTo<len;){let next=codePointAt(word,i);if(direct<0){if(preciseTo<len&&next==chars[preciseTo])precise[preciseTo++]=i;if(adjacentTo<len){if(next==chars[adjacentTo]||next==folded[adjacentTo]){if(adjacentTo==0)adjacentStart=i;adjacentEnd=i+1;adjacentTo++;}else {adjacentTo=0;}}}let ch,type=next<0xff?next>=48&&next<=57||next>=97&&next<=122?2/* Lower */:next>=65&&next<=90?1/* Upper */:0/* NonWord */:(ch=fromCodePoint(next))!=ch.toLowerCase()?1/* Upper */:ch!=ch.toUpperCase()?2/* Lower */:0/* NonWord */;if(!i||type==1/* Upper */&&hasLower||prevType==0/* NonWord */&&type!=0/* NonWord */){if(chars[byWordTo]==next||folded[byWordTo]==next&&(byWordFolded=true))byWord[byWordTo++]=i;else if(byWord.length)wordAdjacent=false;}prevType=type;i+=codePointSize(next);}if(byWordTo==len&&byWord[0]==0&&wordAdjacent)return this.result(-100/* ByWord */+(byWordFolded?-200/* CaseFold */:0),byWord,word);if(adjacentTo==len&&adjacentStart==0)return [-200/* CaseFold */-word.length,0,adjacentEnd];if(direct>-1)return [-700/* NotStart */-word.length,direct,direct+this.pattern.length];if(adjacentTo==len)return [-200/* CaseFold */+-700/* NotStart */-word.length,adjacentStart,adjacentEnd];if(byWordTo==len)return this.result(-100/* ByWord */+(byWordFolded?-200/* CaseFold */:0)+-700/* NotStart */+(wordAdjacent?0:-1100/* Gap */),byWord,word);return chars.length==2?null:this.result((any[0]?-700/* NotStart */:0)+-200/* CaseFold */+-1100/* Gap */,any,word);}result(score,positions,word){let result=[score-word.length],i=1;for(let pos of positions){let to=pos+(this.astral?codePointSize(codePointAt(word,pos)):1);if(i>1&&result[i-1]==pos)result[i-1]=to;else {result[i++]=pos;result[i++]=to;}}return result;}}const completionConfig=/*@__PURE__*/Facet.define({combine(configs){return combineConfig(configs,{activateOnTyping:true,override:null,closeOnBlur:true,maxRenderedOptions:100,defaultKeymap:true,optionClass:()=>"",aboveCursor:false,icons:true,addToOptions:[]},{defaultKeymap:(a,b)=>a&&b,closeOnBlur:(a,b)=>a&&b,icons:(a,b)=>a&&b,optionClass:(a,b)=>c=>joinClass(a(c),b(c)),addToOptions:(a,b)=>a.concat(b)});}});function joinClass(a,b){return a?b?a+" "+b:a:b;}function optionContent(config){let content=config.addToOptions.slice();if(config.icons)content.push({render(completion){let icon=document.createElement("div");icon.classList.add("cm-completionIcon");if(completion.type)icon.classList.add(...completion.type.split(/\s+/g).map(cls=>"cm-completionIcon-"+cls));icon.setAttribute("aria-hidden","true");return icon;},position:20});content.push({render(completion,_s,match){let labelElt=document.createElement("span");labelElt.className="cm-completionLabel";let{label}=completion,off=0;for(let j=1;j<match.length;){let from=match[j++],to=match[j++];if(from>off)labelElt.appendChild(document.createTextNode(label.slice(off,from)));let span=labelElt.appendChild(document.createElement("span"));span.appendChild(document.createTextNode(label.slice(from,to)));span.className="cm-completionMatchedText";off=to;}if(off<label.length)labelElt.appendChild(document.createTextNode(label.slice(off)));return labelElt;},position:50},{render(completion){if(!completion.detail)return null;let detailElt=document.createElement("span");detailElt.className="cm-completionDetail";detailElt.textContent=completion.detail;return detailElt;},position:80});return content.sort((a,b)=>a.position-b.position).map(a=>a.render);}function rangeAroundSelected(total,selected,max){if(total<=max)return {from:0,to:total};if(selected<=total>>1){let off=Math.floor(selected/max);return {from:off*max,to:(off+1)*max};}let off=Math.floor((total-selected)/max);return {from:total-(off+1)*max,to:total-off*max};}class CompletionTooltip{constructor(view,stateField){this.view=view;this.stateField=stateField;this.info=null;this.placeInfo={read:()=>this.measureInfo(),write:pos=>this.positionInfo(pos),key:this};let cState=view.state.field(stateField);let{options,selected}=cState.open;let config=view.state.facet(completionConfig);this.optionContent=optionContent(config);this.optionClass=config.optionClass;this.range=rangeAroundSelected(options.length,selected,config.maxRenderedOptions);this.dom=document.createElement("div");this.dom.className="cm-tooltip-autocomplete";this.dom.addEventListener("mousedown",e=>{for(let dom=e.target,match;dom&&dom!=this.dom;dom=dom.parentNode){if(dom.nodeName=="LI"&&(match=/-(\d+)$/.exec(dom.id))&&+match[1]<options.length){applyCompletion(view,options[+match[1]]);e.preventDefault();return;}}});this.list=this.dom.appendChild(this.createListBox(options,cState.id,this.range));this.list.addEventListener("scroll",()=>{if(this.info)this.view.requestMeasure(this.placeInfo);});}mount(){this.updateSel();}update(update){if(update.state.field(this.stateField)!=update.startState.field(this.stateField))this.updateSel();}positioned(){if(this.info)this.view.requestMeasure(this.placeInfo);}updateSel(){let cState=this.view.state.field(this.stateField),open=cState.open;if(open.selected<this.range.from||open.selected>=this.range.to){this.range=rangeAroundSelected(open.options.length,open.selected,this.view.state.facet(completionConfig).maxRenderedOptions);this.list.remove();this.list=this.dom.appendChild(this.createListBox(open.options,cState.id,this.range));this.list.addEventListener("scroll",()=>{if(this.info)this.view.requestMeasure(this.placeInfo);});}if(this.updateSelectedOption(open.selected)){if(this.info){this.info.remove();this.info=null;}let{completion}=open.options[open.selected];let{info}=completion;if(!info)return;let infoResult=typeof info==='string'?document.createTextNode(info):info(completion);if(!infoResult)return;if('then'in infoResult){infoResult.then(node=>{if(node&&this.view.state.field(this.stateField,false)==cState)this.addInfoPane(node);}).catch(e=>logException(this.view.state,e,"completion info"));}else {this.addInfoPane(infoResult);}}}addInfoPane(content){let dom=this.info=document.createElement("div");dom.className="cm-tooltip cm-completionInfo";dom.appendChild(content);this.dom.appendChild(dom);this.view.requestMeasure(this.placeInfo);}updateSelectedOption(selected){let set=null;for(let opt=this.list.firstChild,i=this.range.from;opt;opt=opt.nextSibling,i++){if(i==selected){if(!opt.hasAttribute("aria-selected")){opt.setAttribute("aria-selected","true");set=opt;}}else {if(opt.hasAttribute("aria-selected"))opt.removeAttribute("aria-selected");}}if(set)scrollIntoView(this.list,set);return set;}measureInfo(){let sel=this.dom.querySelector("[aria-selected]");if(!sel||!this.info)return null;let listRect=this.dom.getBoundingClientRect();let infoRect=this.info.getBoundingClientRect();let selRect=sel.getBoundingClientRect();if(selRect.top>Math.min(innerHeight,listRect.bottom)-10||selRect.bottom<Math.max(0,listRect.top)+10)return null;let top=Math.max(0,Math.min(selRect.top,innerHeight-infoRect.height))-listRect.top;let left=this.view.textDirection==Direction.RTL;let spaceLeft=listRect.left,spaceRight=innerWidth-listRect.right;if(left&&spaceLeft<Math.min(infoRect.width,spaceRight))left=false;else if(!left&&spaceRight<Math.min(infoRect.width,spaceLeft))left=true;return {top,left};}positionInfo(pos){if(this.info){this.info.style.top=(pos?pos.top:-1e6)+"px";if(pos){this.info.classList.toggle("cm-completionInfo-left",pos.left);this.info.classList.toggle("cm-completionInfo-right",!pos.left);}}}createListBox(options,id,range){const ul=document.createElement("ul");ul.id=id;ul.setAttribute("role","listbox");ul.setAttribute("aria-expanded","true");ul.setAttribute("aria-label",this.view.state.phrase("Completions"));for(let i=range.from;i<range.to;i++){let{completion,match}=options[i];const li=ul.appendChild(document.createElement("li"));li.id=id+"-"+i;li.setAttribute("role","option");let cls=this.optionClass(completion);if(cls)li.className=cls;for(let source of this.optionContent){let node=source(completion,this.view.state,match);if(node)li.appendChild(node);}}if(range.from)ul.classList.add("cm-completionListIncompleteTop");if(range.to<options.length)ul.classList.add("cm-completionListIncompleteBottom");return ul;}}// We allocate a new function instance every time the completion
4875
- // changes to force redrawing/repositioning of the tooltip
4876
- function completionTooltip(stateField){return view=>new CompletionTooltip(view,stateField);}function scrollIntoView(container,element){let parent=container.getBoundingClientRect();let self=element.getBoundingClientRect();if(self.top<parent.top)container.scrollTop-=parent.top-self.top;else if(self.bottom>parent.bottom)container.scrollTop+=self.bottom-parent.bottom;}// Used to pick a preferred option when two options with the same
4877
- // label occur in the result.
4878
- function score(option){return (option.boost||0)*100+(option.apply?10:0)+(option.info?5:0)+(option.type?1:0);}function sortOptions(active,state){let options=[],i=0;for(let a of active)if(a.hasResult()){if(a.result.filter===false){let getMatch=a.result.getMatch;for(let option of a.result.options){let match=[1e9-i++];if(getMatch)for(let n of getMatch(option))match.push(n);options.push(new Option(option,a,match));}}else {let matcher=new FuzzyMatcher(state.sliceDoc(a.from,a.to)),match;for(let option of a.result.options)if(match=matcher.match(option.label)){if(option.boost!=null)match[0]+=option.boost;options.push(new Option(option,a,match));}}}let result=[],prev=null;for(let opt of options.sort(cmpOption)){if(!prev||prev.label!=opt.completion.label||prev.detail!=opt.completion.detail||prev.type!=null&&opt.completion.type!=null&&prev.type!=opt.completion.type||prev.apply!=opt.completion.apply)result.push(opt);else if(score(opt.completion)>score(prev))result[result.length-1]=opt;prev=opt.completion;}return result;}class CompletionDialog{constructor(options,attrs,tooltip,timestamp,selected){this.options=options;this.attrs=attrs;this.tooltip=tooltip;this.timestamp=timestamp;this.selected=selected;}setSelected(selected,id){return selected==this.selected||selected>=this.options.length?this:new CompletionDialog(this.options,makeAttrs(id,selected),this.tooltip,this.timestamp,selected);}static build(active,state,id,prev,conf){let options=sortOptions(active,state);if(!options.length)return null;let selected=0;if(prev&&prev.selected){let selectedValue=prev.options[prev.selected].completion;for(let i=0;i<options.length;i++)if(options[i].completion==selectedValue){selected=i;break;}}return new CompletionDialog(options,makeAttrs(id,selected),{pos:active.reduce((a,b)=>b.hasResult()?Math.min(a,b.from):a,1e8),create:completionTooltip(completionState),above:conf.aboveCursor},prev?prev.timestamp:Date.now(),selected);}map(changes){return new CompletionDialog(this.options,this.attrs,Object.assign(Object.assign({},this.tooltip),{pos:changes.mapPos(this.tooltip.pos)}),this.timestamp,this.selected);}}class CompletionState{constructor(active,id,open){this.active=active;this.id=id;this.open=open;}static start(){return new CompletionState(none,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null);}update(tr){let{state}=tr,conf=state.facet(completionConfig);let sources=conf.override||state.languageDataAt("autocomplete",cur(state)).map(asSource);let active=sources.map(source=>{let value=this.active.find(s=>s.source==source)||new ActiveSource(source,this.active.some(a=>a.state!=0/* Inactive */)?1/* Pending */:0/* Inactive */);return value.update(tr,conf);});if(active.length==this.active.length&&active.every((a,i)=>a==this.active[i]))active=this.active;let open=tr.selection||active.some(a=>a.hasResult()&&tr.changes.touchesRange(a.from,a.to))||!sameResults(active,this.active)?CompletionDialog.build(active,state,this.id,this.open,conf):this.open&&tr.docChanged?this.open.map(tr.changes):this.open;if(!open&&active.every(a=>a.state!=1/* Pending */)&&active.some(a=>a.hasResult()))active=active.map(a=>a.hasResult()?new ActiveSource(a.source,0/* Inactive */):a);for(let effect of tr.effects)if(effect.is(setSelectedEffect))open=open&&open.setSelected(effect.value,this.id);return active==this.active&&open==this.open?this:new CompletionState(active,this.id,open);}get tooltip(){return this.open?this.open.tooltip:null;}get attrs(){return this.open?this.open.attrs:baseAttrs;}}function sameResults(a,b){if(a==b)return true;for(let iA=0,iB=0;;){while(iA<a.length&&!a[iA].hasResult)iA++;while(iB<b.length&&!b[iB].hasResult)iB++;let endA=iA==a.length,endB=iB==b.length;if(endA||endB)return endA==endB;if(a[iA++].result!=b[iB++].result)return false;}}const baseAttrs={"aria-autocomplete":"list"};function makeAttrs(id,selected){return {"aria-autocomplete":"list","aria-haspopup":"listbox","aria-activedescendant":id+"-"+selected,"aria-controls":id};}const none=[];function cmpOption(a,b){let dScore=b.match[0]-a.match[0];if(dScore)return dScore;return a.completion.label.localeCompare(b.completion.label);}function getUserEvent(tr){return tr.isUserEvent("input.type")?"input":tr.isUserEvent("delete.backward")?"delete":null;}class ActiveSource{constructor(source,state,explicitPos=-1){this.source=source;this.state=state;this.explicitPos=explicitPos;}hasResult(){return false;}update(tr,conf){let event=getUserEvent(tr),value=this;if(event)value=value.handleUserEvent(tr,event,conf);else if(tr.docChanged)value=value.handleChange(tr);else if(tr.selection&&value.state!=0/* Inactive */)value=new ActiveSource(value.source,0/* Inactive */);for(let effect of tr.effects){if(effect.is(startCompletionEffect))value=new ActiveSource(value.source,1/* Pending */,effect.value?cur(tr.state):-1);else if(effect.is(closeCompletionEffect))value=new ActiveSource(value.source,0/* Inactive */);else if(effect.is(setActiveEffect))for(let active of effect.value)if(active.source==value.source)value=active;}return value;}handleUserEvent(tr,type,conf){return type=="delete"||!conf.activateOnTyping?this.map(tr.changes):new ActiveSource(this.source,1/* Pending */);}handleChange(tr){return tr.changes.touchesRange(cur(tr.startState))?new ActiveSource(this.source,0/* Inactive */):this.map(tr.changes);}map(changes){return changes.empty||this.explicitPos<0?this:new ActiveSource(this.source,this.state,changes.mapPos(this.explicitPos));}}class ActiveResult extends ActiveSource{constructor(source,explicitPos,result,from,to){super(source,2/* Result */,explicitPos);this.result=result;this.from=from;this.to=to;}hasResult(){return true;}handleUserEvent(tr,type,conf){var _a;let from=tr.changes.mapPos(this.from),to=tr.changes.mapPos(this.to,1);let pos=cur(tr.state);if((this.explicitPos<0?pos<=from:pos<this.from)||pos>to||type=="delete"&&cur(tr.startState)==this.from)return new ActiveSource(this.source,type=="input"&&conf.activateOnTyping?1/* Pending */:0/* Inactive */);let explicitPos=this.explicitPos<0?-1:tr.changes.mapPos(this.explicitPos),updated;if(checkValid(this.result.validFor,tr.state,from,to))return new ActiveResult(this.source,explicitPos,this.result,from,to);if(this.result.update&&(updated=this.result.update(this.result,from,to,new CompletionContext(tr.state,pos,explicitPos>=0))))return new ActiveResult(this.source,explicitPos,updated,updated.from,(_a=updated.to)!==null&&_a!==void 0?_a:cur(tr.state));return new ActiveSource(this.source,1/* Pending */,explicitPos);}handleChange(tr){return tr.changes.touchesRange(this.from,this.to)?new ActiveSource(this.source,0/* Inactive */):this.map(tr.changes);}map(mapping){return mapping.empty?this:new ActiveResult(this.source,this.explicitPos<0?-1:mapping.mapPos(this.explicitPos),this.result,mapping.mapPos(this.from),mapping.mapPos(this.to,1));}}function checkValid(validFor,state,from,to){if(!validFor)return false;let text=state.sliceDoc(from,to);return typeof validFor=="function"?validFor(text,from,to,state):ensureAnchor(validFor,true).test(text);}const startCompletionEffect=/*@__PURE__*/StateEffect.define();const closeCompletionEffect=/*@__PURE__*/StateEffect.define();const setActiveEffect=/*@__PURE__*/StateEffect.define({map(sources,mapping){return sources.map(s=>s.map(mapping));}});const setSelectedEffect=/*@__PURE__*/StateEffect.define();const completionState=/*@__PURE__*/StateField.define({create(){return CompletionState.start();},update(value,tr){return value.update(tr);},provide:f=>[showTooltip.from(f,val=>val.tooltip),EditorView.contentAttributes.from(f,state=>state.attrs)]});const CompletionInteractMargin=75;/**
4879
- Returns a command that moves the completion selection forward or
4880
- backward by the given amount.
4881
- */function moveCompletionSelection(forward,by="option"){return view=>{let cState=view.state.field(completionState,false);if(!cState||!cState.open||Date.now()-cState.open.timestamp<CompletionInteractMargin)return false;let step=1,tooltip;if(by=="page"&&(tooltip=getTooltip(view,cState.open.tooltip)))step=Math.max(2,Math.floor(tooltip.dom.offsetHeight/tooltip.dom.querySelector("li").offsetHeight)-1);let selected=cState.open.selected+step*(forward?1:-1),{length}=cState.open.options;if(selected<0)selected=by=="page"?0:length-1;else if(selected>=length)selected=by=="page"?length-1:0;view.dispatch({effects:setSelectedEffect.of(selected)});return true;};}/**
4882
- Accept the current completion.
4883
- */const acceptCompletion=view=>{let cState=view.state.field(completionState,false);if(view.state.readOnly||!cState||!cState.open||Date.now()-cState.open.timestamp<CompletionInteractMargin)return false;applyCompletion(view,cState.open.options[cState.open.selected]);return true;};/**
4884
- Explicitly start autocompletion.
4885
- */const startCompletion=view=>{let cState=view.state.field(completionState,false);if(!cState)return false;view.dispatch({effects:startCompletionEffect.of(true)});return true;};/**
4886
- Close the currently active completion.
4887
- */const closeCompletion=view=>{let cState=view.state.field(completionState,false);if(!cState||!cState.active.some(a=>a.state!=0/* Inactive */))return false;view.dispatch({effects:closeCompletionEffect.of(null)});return true;};class RunningQuery{constructor(active,context){this.active=active;this.context=context;this.time=Date.now();this.updates=[];// Note that 'undefined' means 'not done yet', whereas 'null' means
4888
- // 'query returned null'.
4889
- this.done=undefined;}}const DebounceTime=50,MaxUpdateCount=50,MinAbortTime=1000;const completionPlugin=/*@__PURE__*/ViewPlugin.fromClass(class{constructor(view){this.view=view;this.debounceUpdate=-1;this.running=[];this.debounceAccept=-1;this.composing=0/* None */;for(let active of view.state.field(completionState).active)if(active.state==1/* Pending */)this.startQuery(active);}update(update){let cState=update.state.field(completionState);if(!update.selectionSet&&!update.docChanged&&update.startState.field(completionState)==cState)return;let doesReset=update.transactions.some(tr=>{return (tr.selection||tr.docChanged)&&!getUserEvent(tr);});for(let i=0;i<this.running.length;i++){let query=this.running[i];if(doesReset||query.updates.length+update.transactions.length>MaxUpdateCount&&Date.now()-query.time>MinAbortTime){for(let handler of query.context.abortListeners){try{handler();}catch(e){logException(this.view.state,e);}}query.context.abortListeners=null;this.running.splice(i--,1);}else {query.updates.push(...update.transactions);}}if(this.debounceUpdate>-1)clearTimeout(this.debounceUpdate);this.debounceUpdate=cState.active.some(a=>a.state==1/* Pending */&&!this.running.some(q=>q.active.source==a.source))?setTimeout(()=>this.startUpdate(),DebounceTime):-1;if(this.composing!=0/* None */)for(let tr of update.transactions){if(getUserEvent(tr)=="input")this.composing=2/* Changed */;else if(this.composing==2/* Changed */&&tr.selection)this.composing=3/* ChangedAndMoved */;}}startUpdate(){this.debounceUpdate=-1;let{state}=this.view,cState=state.field(completionState);for(let active of cState.active){if(active.state==1/* Pending */&&!this.running.some(r=>r.active.source==active.source))this.startQuery(active);}}startQuery(active){let{state}=this.view,pos=cur(state);let context=new CompletionContext(state,pos,active.explicitPos==pos);let pending=new RunningQuery(active,context);this.running.push(pending);Promise.resolve(active.source(context)).then(result=>{if(!pending.context.aborted){pending.done=result||null;this.scheduleAccept();}},err=>{this.view.dispatch({effects:closeCompletionEffect.of(null)});logException(this.view.state,err);});}scheduleAccept(){if(this.running.every(q=>q.done!==undefined))this.accept();else if(this.debounceAccept<0)this.debounceAccept=setTimeout(()=>this.accept(),DebounceTime);}// For each finished query in this.running, try to create a result
4890
- // or, if appropriate, restart the query.
4891
- accept(){var _a;if(this.debounceAccept>-1)clearTimeout(this.debounceAccept);this.debounceAccept=-1;let updated=[];let conf=this.view.state.facet(completionConfig);for(let i=0;i<this.running.length;i++){let query=this.running[i];if(query.done===undefined)continue;this.running.splice(i--,1);if(query.done){let active=new ActiveResult(query.active.source,query.active.explicitPos,query.done,query.done.from,(_a=query.done.to)!==null&&_a!==void 0?_a:cur(query.updates.length?query.updates[0].startState:this.view.state));// Replay the transactions that happened since the start of
4892
- // the request and see if that preserves the result
4893
- for(let tr of query.updates)active=active.update(tr,conf);if(active.hasResult()){updated.push(active);continue;}}let current=this.view.state.field(completionState).active.find(a=>a.source==query.active.source);if(current&&current.state==1/* Pending */){if(query.done==null){// Explicitly failed. Should clear the pending status if it
4894
- // hasn't been re-set in the meantime.
4895
- let active=new ActiveSource(query.active.source,0/* Inactive */);for(let tr of query.updates)active=active.update(tr,conf);if(active.state!=1/* Pending */)updated.push(active);}else {// Cleared by subsequent transactions. Restart.
4896
- this.startQuery(current);}}}if(updated.length)this.view.dispatch({effects:setActiveEffect.of(updated)});}},{eventHandlers:{blur(){let state=this.view.state.field(completionState,false);if(state&&state.tooltip&&this.view.state.facet(completionConfig).closeOnBlur)this.view.dispatch({effects:closeCompletionEffect.of(null)});},compositionstart(){this.composing=1/* Started */;},compositionend(){if(this.composing==3/* ChangedAndMoved */){// Safari fires compositionend events synchronously, possibly
4897
- // from inside an update, so dispatch asynchronously to avoid reentrancy
4898
- setTimeout(()=>this.view.dispatch({effects:startCompletionEffect.of(false)}),20);}this.composing=0/* None */;}}});const baseTheme=/*@__PURE__*/EditorView.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",listStyle:"none",margin:0,padding:0,"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer",padding:"1px 3px",lineHeight:1.2}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"···"',opacity:0.5,display:"block",textAlign:"center"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"300px"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'ƒ'"}},".cm-completionIcon-class":{"&:after":{content:"'○'"}},".cm-completionIcon-interface":{"&:after":{content:"'◌'"}},".cm-completionIcon-variable":{"&:after":{content:"'𝑥'"}},".cm-completionIcon-constant":{"&:after":{content:"'𝐶'"}},".cm-completionIcon-type":{"&:after":{content:"'𝑡'"}},".cm-completionIcon-enum":{"&:after":{content:"'∪'"}},".cm-completionIcon-property":{"&:after":{content:"'□'"}},".cm-completionIcon-keyword":{"&:after":{content:"'🔑\uFE0E'"}// Disable emoji rendering
4899
- },".cm-completionIcon-namespace":{"&:after":{content:"'▢'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}});const closedBracket=/*@__PURE__*/new class extends RangeValue{}();closedBracket.startSide=1;closedBracket.endSide=-1;/**
4900
- Returns an extension that enables autocompletion.
4901
- */function autocompletion$1(config={}){return [completionState,completionConfig.of(config),completionPlugin,completionKeymapExt,baseTheme];}/**
4902
- Basic keybindings for autocompletion.
4903
-
4904
- - Ctrl-Space: [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion)
4905
- - Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion)
4906
- - ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)`
4907
- - ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)`
4908
- - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
4909
- - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
4910
- - Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion)
4911
- */const completionKeymap=[{key:"Ctrl-Space",run:startCompletion},{key:"Escape",run:closeCompletion},{key:"ArrowDown",run:/*@__PURE__*/moveCompletionSelection(true)},{key:"ArrowUp",run:/*@__PURE__*/moveCompletionSelection(false)},{key:"PageDown",run:/*@__PURE__*/moveCompletionSelection(true,"page")},{key:"PageUp",run:/*@__PURE__*/moveCompletionSelection(false,"page")},{key:"Enter",run:acceptCompletion}];const completionKeymapExt=/*@__PURE__*/Prec.highest(/*@__PURE__*/keymap.computeN([completionConfig],state=>state.facet(completionConfig).defaultKeymap?[completionKeymap]:[]));var variables=variables=>context=>{const options=variables.map(v=>({label:v.name,type:'variable',info:v.info,detail:v.detail}));// In most cases, use what is typed before the cursor
4912
- let nodeBefore=syntaxTree(context.state).resolve(context.pos,-1);// For the special case of empty nodes, we need to check the current node
4913
- // as well. The previous node could be part of another token, e.g.
4914
- // when typing functions "abs(".
4915
- let nextNode=nodeBefore.nextSibling;const isInEmptyNode=isNodeEmpty(nodeBefore)||nextNode&&nextNode.from===context.pos&&isNodeEmpty(nextNode);if(context.explicit&&isInEmptyNode){return {from:context.pos,options:options};}const result={from:nodeBefore.from,options:options};// Only auto-complete variables
4916
- if(nodeBefore.name!=='VariableName'){return null;}return result;};// helpers ///////////////////////////////
4917
- function isNodeEmpty(node){return node.from===node.to;}function autocompletion(context){return [autocompletion$1({override:[variables(context)]})];}/**
4392
+ // The score is a number that is more negative the worse the match
4393
+ // is. See `Penalty` above.
4394
+ match(word){if(this.pattern.length==0)return [0];if(word.length<this.pattern.length)return null;let{chars,folded,any,precise,byWord}=this;// For single-character queries, only match when they occur right
4395
+ // at the start
4396
+ if(chars.length==1){let first=codePointAt(word,0);return first==chars[0]?[0,0,codePointSize(first)]:first==folded[0]?[-200/* CaseFold */,0,codePointSize(first)]:null;}let direct=word.indexOf(this.pattern);if(direct==0)return [0,0,this.pattern.length];let len=chars.length,anyTo=0;if(direct<0){for(let i=0,e=Math.min(word.length,200);i<e&&anyTo<len;){let next=codePointAt(word,i);if(next==chars[anyTo]||next==folded[anyTo])any[anyTo++]=i;i+=codePointSize(next);}// No match, exit immediately
4397
+ if(anyTo<len)return null;}// This tracks the extent of the precise (non-folded, not
4398
+ // necessarily adjacent) match
4399
+ let preciseTo=0;// Tracks whether there is a match that hits only characters that
4400
+ // appear to be starting words. `byWordFolded` is set to true when
4401
+ // a case folded character is encountered in such a match
4402
+ let byWordTo=0,byWordFolded=false;// If we've found a partial adjacent match, these track its state
4403
+ let adjacentTo=0,adjacentStart=-1,adjacentEnd=-1;let hasLower=/[a-z]/.test(word),wordAdjacent=true;// Go over the option's text, scanning for the various kinds of matches
4404
+ for(let i=0,e=Math.min(word.length,200),prevType=0/* NonWord */;i<e&&byWordTo<len;){let next=codePointAt(word,i);if(direct<0){if(preciseTo<len&&next==chars[preciseTo])precise[preciseTo++]=i;if(adjacentTo<len){if(next==chars[adjacentTo]||next==folded[adjacentTo]){if(adjacentTo==0)adjacentStart=i;adjacentEnd=i+1;adjacentTo++;}else {adjacentTo=0;}}}let ch,type=next<0xff?next>=48&&next<=57||next>=97&&next<=122?2/* Lower */:next>=65&&next<=90?1/* Upper */:0/* NonWord */:(ch=fromCodePoint(next))!=ch.toLowerCase()?1/* Upper */:ch!=ch.toUpperCase()?2/* Lower */:0/* NonWord */;if(!i||type==1/* Upper */&&hasLower||prevType==0/* NonWord */&&type!=0/* NonWord */){if(chars[byWordTo]==next||folded[byWordTo]==next&&(byWordFolded=true))byWord[byWordTo++]=i;else if(byWord.length)wordAdjacent=false;}prevType=type;i+=codePointSize(next);}if(byWordTo==len&&byWord[0]==0&&wordAdjacent)return this.result(-100/* ByWord */+(byWordFolded?-200/* CaseFold */:0),byWord,word);if(adjacentTo==len&&adjacentStart==0)return [-200/* CaseFold */-word.length,0,adjacentEnd];if(direct>-1)return [-700/* NotStart */-word.length,direct,direct+this.pattern.length];if(adjacentTo==len)return [-200/* CaseFold */+-700/* NotStart */-word.length,adjacentStart,adjacentEnd];if(byWordTo==len)return this.result(-100/* ByWord */+(byWordFolded?-200/* CaseFold */:0)+-700/* NotStart */+(wordAdjacent?0:-1100/* Gap */),byWord,word);return chars.length==2?null:this.result((any[0]?-700/* NotStart */:0)+-200/* CaseFold */+-1100/* Gap */,any,word);}result(score,positions,word){let result=[score-word.length],i=1;for(let pos of positions){let to=pos+(this.astral?codePointSize(codePointAt(word,pos)):1);if(i>1&&result[i-1]==pos)result[i-1]=to;else {result[i++]=pos;result[i++]=to;}}return result;}}const completionConfig=/*@__PURE__*/Facet.define({combine(configs){return combineConfig(configs,{activateOnTyping:true,override:null,closeOnBlur:true,maxRenderedOptions:100,defaultKeymap:true,optionClass:()=>"",aboveCursor:false,icons:true,addToOptions:[]},{defaultKeymap:(a,b)=>a&&b,closeOnBlur:(a,b)=>a&&b,icons:(a,b)=>a&&b,optionClass:(a,b)=>c=>joinClass(a(c),b(c)),addToOptions:(a,b)=>a.concat(b)});}});function joinClass(a,b){return a?b?a+" "+b:a:b;}function optionContent(config){let content=config.addToOptions.slice();if(config.icons)content.push({render(completion){let icon=document.createElement("div");icon.classList.add("cm-completionIcon");if(completion.type)icon.classList.add(...completion.type.split(/\s+/g).map(cls=>"cm-completionIcon-"+cls));icon.setAttribute("aria-hidden","true");return icon;},position:20});content.push({render(completion,_s,match){let labelElt=document.createElement("span");labelElt.className="cm-completionLabel";let{label}=completion,off=0;for(let j=1;j<match.length;){let from=match[j++],to=match[j++];if(from>off)labelElt.appendChild(document.createTextNode(label.slice(off,from)));let span=labelElt.appendChild(document.createElement("span"));span.appendChild(document.createTextNode(label.slice(from,to)));span.className="cm-completionMatchedText";off=to;}if(off<label.length)labelElt.appendChild(document.createTextNode(label.slice(off)));return labelElt;},position:50},{render(completion){if(!completion.detail)return null;let detailElt=document.createElement("span");detailElt.className="cm-completionDetail";detailElt.textContent=completion.detail;return detailElt;},position:80});return content.sort((a,b)=>a.position-b.position).map(a=>a.render);}function rangeAroundSelected(total,selected,max){if(total<=max)return {from:0,to:total};if(selected<=total>>1){let off=Math.floor(selected/max);return {from:off*max,to:(off+1)*max};}let off=Math.floor((total-selected)/max);return {from:total-(off+1)*max,to:total-off*max};}class CompletionTooltip{constructor(view,stateField){this.view=view;this.stateField=stateField;this.info=null;this.placeInfo={read:()=>this.measureInfo(),write:pos=>this.positionInfo(pos),key:this};let cState=view.state.field(stateField);let{options,selected}=cState.open;let config=view.state.facet(completionConfig);this.optionContent=optionContent(config);this.optionClass=config.optionClass;this.range=rangeAroundSelected(options.length,selected,config.maxRenderedOptions);this.dom=document.createElement("div");this.dom.className="cm-tooltip-autocomplete";this.dom.addEventListener("mousedown",e=>{for(let dom=e.target,match;dom&&dom!=this.dom;dom=dom.parentNode){if(dom.nodeName=="LI"&&(match=/-(\d+)$/.exec(dom.id))&&+match[1]<options.length){applyCompletion(view,options[+match[1]]);e.preventDefault();return;}}});this.list=this.dom.appendChild(this.createListBox(options,cState.id,this.range));this.list.addEventListener("scroll",()=>{if(this.info)this.view.requestMeasure(this.placeInfo);});}mount(){this.updateSel();}update(update){if(update.state.field(this.stateField)!=update.startState.field(this.stateField))this.updateSel();}positioned(){if(this.info)this.view.requestMeasure(this.placeInfo);}updateSel(){let cState=this.view.state.field(this.stateField),open=cState.open;if(open.selected<this.range.from||open.selected>=this.range.to){this.range=rangeAroundSelected(open.options.length,open.selected,this.view.state.facet(completionConfig).maxRenderedOptions);this.list.remove();this.list=this.dom.appendChild(this.createListBox(open.options,cState.id,this.range));this.list.addEventListener("scroll",()=>{if(this.info)this.view.requestMeasure(this.placeInfo);});}if(this.updateSelectedOption(open.selected)){if(this.info){this.info.remove();this.info=null;}let{completion}=open.options[open.selected];let{info}=completion;if(!info)return;let infoResult=typeof info==='string'?document.createTextNode(info):info(completion);if(!infoResult)return;if('then'in infoResult){infoResult.then(node=>{if(node&&this.view.state.field(this.stateField,false)==cState)this.addInfoPane(node);}).catch(e=>logException(this.view.state,e,"completion info"));}else {this.addInfoPane(infoResult);}}}addInfoPane(content){let dom=this.info=document.createElement("div");dom.className="cm-tooltip cm-completionInfo";dom.appendChild(content);this.dom.appendChild(dom);this.view.requestMeasure(this.placeInfo);}updateSelectedOption(selected){let set=null;for(let opt=this.list.firstChild,i=this.range.from;opt;opt=opt.nextSibling,i++){if(i==selected){if(!opt.hasAttribute("aria-selected")){opt.setAttribute("aria-selected","true");set=opt;}}else {if(opt.hasAttribute("aria-selected"))opt.removeAttribute("aria-selected");}}if(set)scrollIntoView(this.list,set);return set;}measureInfo(){let sel=this.dom.querySelector("[aria-selected]");if(!sel||!this.info)return null;let listRect=this.dom.getBoundingClientRect();let infoRect=this.info.getBoundingClientRect();let selRect=sel.getBoundingClientRect();if(selRect.top>Math.min(innerHeight,listRect.bottom)-10||selRect.bottom<Math.max(0,listRect.top)+10)return null;let top=Math.max(0,Math.min(selRect.top,innerHeight-infoRect.height))-listRect.top;let left=this.view.textDirection==Direction.RTL;let spaceLeft=listRect.left,spaceRight=innerWidth-listRect.right;if(left&&spaceLeft<Math.min(infoRect.width,spaceRight))left=false;else if(!left&&spaceRight<Math.min(infoRect.width,spaceLeft))left=true;return {top,left};}positionInfo(pos){if(this.info){this.info.style.top=(pos?pos.top:-1e6)+"px";if(pos){this.info.classList.toggle("cm-completionInfo-left",pos.left);this.info.classList.toggle("cm-completionInfo-right",!pos.left);}}}createListBox(options,id,range){const ul=document.createElement("ul");ul.id=id;ul.setAttribute("role","listbox");ul.setAttribute("aria-expanded","true");ul.setAttribute("aria-label",this.view.state.phrase("Completions"));for(let i=range.from;i<range.to;i++){let{completion,match}=options[i];const li=ul.appendChild(document.createElement("li"));li.id=id+"-"+i;li.setAttribute("role","option");let cls=this.optionClass(completion);if(cls)li.className=cls;for(let source of this.optionContent){let node=source(completion,this.view.state,match);if(node)li.appendChild(node);}}if(range.from)ul.classList.add("cm-completionListIncompleteTop");if(range.to<options.length)ul.classList.add("cm-completionListIncompleteBottom");return ul;}}// We allocate a new function instance every time the completion
4405
+ // changes to force redrawing/repositioning of the tooltip
4406
+ function completionTooltip(stateField){return view=>new CompletionTooltip(view,stateField);}function scrollIntoView(container,element){let parent=container.getBoundingClientRect();let self=element.getBoundingClientRect();if(self.top<parent.top)container.scrollTop-=parent.top-self.top;else if(self.bottom>parent.bottom)container.scrollTop+=self.bottom-parent.bottom;}// Used to pick a preferred option when two options with the same
4407
+ // label occur in the result.
4408
+ function score(option){return (option.boost||0)*100+(option.apply?10:0)+(option.info?5:0)+(option.type?1:0);}function sortOptions(active,state){let options=[],i=0;for(let a of active)if(a.hasResult()){if(a.result.filter===false){let getMatch=a.result.getMatch;for(let option of a.result.options){let match=[1e9-i++];if(getMatch)for(let n of getMatch(option))match.push(n);options.push(new Option(option,a,match));}}else {let matcher=new FuzzyMatcher(state.sliceDoc(a.from,a.to)),match;for(let option of a.result.options)if(match=matcher.match(option.label)){if(option.boost!=null)match[0]+=option.boost;options.push(new Option(option,a,match));}}}let result=[],prev=null;for(let opt of options.sort(cmpOption)){if(!prev||prev.label!=opt.completion.label||prev.detail!=opt.completion.detail||prev.type!=null&&opt.completion.type!=null&&prev.type!=opt.completion.type||prev.apply!=opt.completion.apply)result.push(opt);else if(score(opt.completion)>score(prev))result[result.length-1]=opt;prev=opt.completion;}return result;}class CompletionDialog{constructor(options,attrs,tooltip,timestamp,selected){this.options=options;this.attrs=attrs;this.tooltip=tooltip;this.timestamp=timestamp;this.selected=selected;}setSelected(selected,id){return selected==this.selected||selected>=this.options.length?this:new CompletionDialog(this.options,makeAttrs(id,selected),this.tooltip,this.timestamp,selected);}static build(active,state,id,prev,conf){let options=sortOptions(active,state);if(!options.length)return null;let selected=0;if(prev&&prev.selected){let selectedValue=prev.options[prev.selected].completion;for(let i=0;i<options.length;i++)if(options[i].completion==selectedValue){selected=i;break;}}return new CompletionDialog(options,makeAttrs(id,selected),{pos:active.reduce((a,b)=>b.hasResult()?Math.min(a,b.from):a,1e8),create:completionTooltip(completionState),above:conf.aboveCursor},prev?prev.timestamp:Date.now(),selected);}map(changes){return new CompletionDialog(this.options,this.attrs,Object.assign(Object.assign({},this.tooltip),{pos:changes.mapPos(this.tooltip.pos)}),this.timestamp,this.selected);}}class CompletionState{constructor(active,id,open){this.active=active;this.id=id;this.open=open;}static start(){return new CompletionState(none,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null);}update(tr){let{state}=tr,conf=state.facet(completionConfig);let sources=conf.override||state.languageDataAt("autocomplete",cur(state)).map(asSource);let active=sources.map(source=>{let value=this.active.find(s=>s.source==source)||new ActiveSource(source,this.active.some(a=>a.state!=0/* Inactive */)?1/* Pending */:0/* Inactive */);return value.update(tr,conf);});if(active.length==this.active.length&&active.every((a,i)=>a==this.active[i]))active=this.active;let open=tr.selection||active.some(a=>a.hasResult()&&tr.changes.touchesRange(a.from,a.to))||!sameResults(active,this.active)?CompletionDialog.build(active,state,this.id,this.open,conf):this.open&&tr.docChanged?this.open.map(tr.changes):this.open;if(!open&&active.every(a=>a.state!=1/* Pending */)&&active.some(a=>a.hasResult()))active=active.map(a=>a.hasResult()?new ActiveSource(a.source,0/* Inactive */):a);for(let effect of tr.effects)if(effect.is(setSelectedEffect))open=open&&open.setSelected(effect.value,this.id);return active==this.active&&open==this.open?this:new CompletionState(active,this.id,open);}get tooltip(){return this.open?this.open.tooltip:null;}get attrs(){return this.open?this.open.attrs:baseAttrs;}}function sameResults(a,b){if(a==b)return true;for(let iA=0,iB=0;;){while(iA<a.length&&!a[iA].hasResult)iA++;while(iB<b.length&&!b[iB].hasResult)iB++;let endA=iA==a.length,endB=iB==b.length;if(endA||endB)return endA==endB;if(a[iA++].result!=b[iB++].result)return false;}}const baseAttrs={"aria-autocomplete":"list"};function makeAttrs(id,selected){return {"aria-autocomplete":"list","aria-haspopup":"listbox","aria-activedescendant":id+"-"+selected,"aria-controls":id};}const none=[];function cmpOption(a,b){let dScore=b.match[0]-a.match[0];if(dScore)return dScore;return a.completion.label.localeCompare(b.completion.label);}function getUserEvent(tr){return tr.isUserEvent("input.type")?"input":tr.isUserEvent("delete.backward")?"delete":null;}class ActiveSource{constructor(source,state,explicitPos=-1){this.source=source;this.state=state;this.explicitPos=explicitPos;}hasResult(){return false;}update(tr,conf){let event=getUserEvent(tr),value=this;if(event)value=value.handleUserEvent(tr,event,conf);else if(tr.docChanged)value=value.handleChange(tr);else if(tr.selection&&value.state!=0/* Inactive */)value=new ActiveSource(value.source,0/* Inactive */);for(let effect of tr.effects){if(effect.is(startCompletionEffect))value=new ActiveSource(value.source,1/* Pending */,effect.value?cur(tr.state):-1);else if(effect.is(closeCompletionEffect))value=new ActiveSource(value.source,0/* Inactive */);else if(effect.is(setActiveEffect))for(let active of effect.value)if(active.source==value.source)value=active;}return value;}handleUserEvent(tr,type,conf){return type=="delete"||!conf.activateOnTyping?this.map(tr.changes):new ActiveSource(this.source,1/* Pending */);}handleChange(tr){return tr.changes.touchesRange(cur(tr.startState))?new ActiveSource(this.source,0/* Inactive */):this.map(tr.changes);}map(changes){return changes.empty||this.explicitPos<0?this:new ActiveSource(this.source,this.state,changes.mapPos(this.explicitPos));}}class ActiveResult extends ActiveSource{constructor(source,explicitPos,result,from,to){super(source,2/* Result */,explicitPos);this.result=result;this.from=from;this.to=to;}hasResult(){return true;}handleUserEvent(tr,type,conf){var _a;let from=tr.changes.mapPos(this.from),to=tr.changes.mapPos(this.to,1);let pos=cur(tr.state);if((this.explicitPos<0?pos<=from:pos<this.from)||pos>to||type=="delete"&&cur(tr.startState)==this.from)return new ActiveSource(this.source,type=="input"&&conf.activateOnTyping?1/* Pending */:0/* Inactive */);let explicitPos=this.explicitPos<0?-1:tr.changes.mapPos(this.explicitPos),updated;if(checkValid(this.result.validFor,tr.state,from,to))return new ActiveResult(this.source,explicitPos,this.result,from,to);if(this.result.update&&(updated=this.result.update(this.result,from,to,new CompletionContext(tr.state,pos,explicitPos>=0))))return new ActiveResult(this.source,explicitPos,updated,updated.from,(_a=updated.to)!==null&&_a!==void 0?_a:cur(tr.state));return new ActiveSource(this.source,1/* Pending */,explicitPos);}handleChange(tr){return tr.changes.touchesRange(this.from,this.to)?new ActiveSource(this.source,0/* Inactive */):this.map(tr.changes);}map(mapping){return mapping.empty?this:new ActiveResult(this.source,this.explicitPos<0?-1:mapping.mapPos(this.explicitPos),this.result,mapping.mapPos(this.from),mapping.mapPos(this.to,1));}}function checkValid(validFor,state,from,to){if(!validFor)return false;let text=state.sliceDoc(from,to);return typeof validFor=="function"?validFor(text,from,to,state):ensureAnchor(validFor,true).test(text);}const startCompletionEffect=/*@__PURE__*/StateEffect.define();const closeCompletionEffect=/*@__PURE__*/StateEffect.define();const setActiveEffect=/*@__PURE__*/StateEffect.define({map(sources,mapping){return sources.map(s=>s.map(mapping));}});const setSelectedEffect=/*@__PURE__*/StateEffect.define();const completionState=/*@__PURE__*/StateField.define({create(){return CompletionState.start();},update(value,tr){return value.update(tr);},provide:f=>[showTooltip.from(f,val=>val.tooltip),EditorView.contentAttributes.from(f,state=>state.attrs)]});const CompletionInteractMargin=75;/**
4409
+ Returns a command that moves the completion selection forward or
4410
+ backward by the given amount.
4411
+ */function moveCompletionSelection(forward,by="option"){return view=>{let cState=view.state.field(completionState,false);if(!cState||!cState.open||Date.now()-cState.open.timestamp<CompletionInteractMargin)return false;let step=1,tooltip;if(by=="page"&&(tooltip=getTooltip(view,cState.open.tooltip)))step=Math.max(2,Math.floor(tooltip.dom.offsetHeight/tooltip.dom.querySelector("li").offsetHeight)-1);let selected=cState.open.selected+step*(forward?1:-1),{length}=cState.open.options;if(selected<0)selected=by=="page"?0:length-1;else if(selected>=length)selected=by=="page"?length-1:0;view.dispatch({effects:setSelectedEffect.of(selected)});return true;};}/**
4412
+ Accept the current completion.
4413
+ */const acceptCompletion=view=>{let cState=view.state.field(completionState,false);if(view.state.readOnly||!cState||!cState.open||Date.now()-cState.open.timestamp<CompletionInteractMargin)return false;applyCompletion(view,cState.open.options[cState.open.selected]);return true;};/**
4414
+ Explicitly start autocompletion.
4415
+ */const startCompletion=view=>{let cState=view.state.field(completionState,false);if(!cState)return false;view.dispatch({effects:startCompletionEffect.of(true)});return true;};/**
4416
+ Close the currently active completion.
4417
+ */const closeCompletion=view=>{let cState=view.state.field(completionState,false);if(!cState||!cState.active.some(a=>a.state!=0/* Inactive */))return false;view.dispatch({effects:closeCompletionEffect.of(null)});return true;};class RunningQuery{constructor(active,context){this.active=active;this.context=context;this.time=Date.now();this.updates=[];// Note that 'undefined' means 'not done yet', whereas 'null' means
4418
+ // 'query returned null'.
4419
+ this.done=undefined;}}const DebounceTime=50,MaxUpdateCount=50,MinAbortTime=1000;const completionPlugin=/*@__PURE__*/ViewPlugin.fromClass(class{constructor(view){this.view=view;this.debounceUpdate=-1;this.running=[];this.debounceAccept=-1;this.composing=0/* None */;for(let active of view.state.field(completionState).active)if(active.state==1/* Pending */)this.startQuery(active);}update(update){let cState=update.state.field(completionState);if(!update.selectionSet&&!update.docChanged&&update.startState.field(completionState)==cState)return;let doesReset=update.transactions.some(tr=>{return (tr.selection||tr.docChanged)&&!getUserEvent(tr);});for(let i=0;i<this.running.length;i++){let query=this.running[i];if(doesReset||query.updates.length+update.transactions.length>MaxUpdateCount&&Date.now()-query.time>MinAbortTime){for(let handler of query.context.abortListeners){try{handler();}catch(e){logException(this.view.state,e);}}query.context.abortListeners=null;this.running.splice(i--,1);}else {query.updates.push(...update.transactions);}}if(this.debounceUpdate>-1)clearTimeout(this.debounceUpdate);this.debounceUpdate=cState.active.some(a=>a.state==1/* Pending */&&!this.running.some(q=>q.active.source==a.source))?setTimeout(()=>this.startUpdate(),DebounceTime):-1;if(this.composing!=0/* None */)for(let tr of update.transactions){if(getUserEvent(tr)=="input")this.composing=2/* Changed */;else if(this.composing==2/* Changed */&&tr.selection)this.composing=3/* ChangedAndMoved */;}}startUpdate(){this.debounceUpdate=-1;let{state}=this.view,cState=state.field(completionState);for(let active of cState.active){if(active.state==1/* Pending */&&!this.running.some(r=>r.active.source==active.source))this.startQuery(active);}}startQuery(active){let{state}=this.view,pos=cur(state);let context=new CompletionContext(state,pos,active.explicitPos==pos);let pending=new RunningQuery(active,context);this.running.push(pending);Promise.resolve(active.source(context)).then(result=>{if(!pending.context.aborted){pending.done=result||null;this.scheduleAccept();}},err=>{this.view.dispatch({effects:closeCompletionEffect.of(null)});logException(this.view.state,err);});}scheduleAccept(){if(this.running.every(q=>q.done!==undefined))this.accept();else if(this.debounceAccept<0)this.debounceAccept=setTimeout(()=>this.accept(),DebounceTime);}// For each finished query in this.running, try to create a result
4420
+ // or, if appropriate, restart the query.
4421
+ accept(){var _a;if(this.debounceAccept>-1)clearTimeout(this.debounceAccept);this.debounceAccept=-1;let updated=[];let conf=this.view.state.facet(completionConfig);for(let i=0;i<this.running.length;i++){let query=this.running[i];if(query.done===undefined)continue;this.running.splice(i--,1);if(query.done){let active=new ActiveResult(query.active.source,query.active.explicitPos,query.done,query.done.from,(_a=query.done.to)!==null&&_a!==void 0?_a:cur(query.updates.length?query.updates[0].startState:this.view.state));// Replay the transactions that happened since the start of
4422
+ // the request and see if that preserves the result
4423
+ for(let tr of query.updates)active=active.update(tr,conf);if(active.hasResult()){updated.push(active);continue;}}let current=this.view.state.field(completionState).active.find(a=>a.source==query.active.source);if(current&&current.state==1/* Pending */){if(query.done==null){// Explicitly failed. Should clear the pending status if it
4424
+ // hasn't been re-set in the meantime.
4425
+ let active=new ActiveSource(query.active.source,0/* Inactive */);for(let tr of query.updates)active=active.update(tr,conf);if(active.state!=1/* Pending */)updated.push(active);}else {// Cleared by subsequent transactions. Restart.
4426
+ this.startQuery(current);}}}if(updated.length)this.view.dispatch({effects:setActiveEffect.of(updated)});}},{eventHandlers:{blur(){let state=this.view.state.field(completionState,false);if(state&&state.tooltip&&this.view.state.facet(completionConfig).closeOnBlur)this.view.dispatch({effects:closeCompletionEffect.of(null)});},compositionstart(){this.composing=1/* Started */;},compositionend(){if(this.composing==3/* ChangedAndMoved */){// Safari fires compositionend events synchronously, possibly
4427
+ // from inside an update, so dispatch asynchronously to avoid reentrancy
4428
+ setTimeout(()=>this.view.dispatch({effects:startCompletionEffect.of(false)}),20);}this.composing=0/* None */;}}});const baseTheme$1=/*@__PURE__*/EditorView.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",listStyle:"none",margin:0,padding:0,"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer",padding:"1px 3px",lineHeight:1.2}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"···"',opacity:0.5,display:"block",textAlign:"center"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"300px"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'ƒ'"}},".cm-completionIcon-class":{"&:after":{content:"'○'"}},".cm-completionIcon-interface":{"&:after":{content:"'◌'"}},".cm-completionIcon-variable":{"&:after":{content:"'𝑥'"}},".cm-completionIcon-constant":{"&:after":{content:"'𝐶'"}},".cm-completionIcon-type":{"&:after":{content:"'𝑡'"}},".cm-completionIcon-enum":{"&:after":{content:"'∪'"}},".cm-completionIcon-property":{"&:after":{content:"'□'"}},".cm-completionIcon-keyword":{"&:after":{content:"'🔑\uFE0E'"}// Disable emoji rendering
4429
+ },".cm-completionIcon-namespace":{"&:after":{content:"'▢'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}});const closedBracket=/*@__PURE__*/new class extends RangeValue{}();closedBracket.startSide=1;closedBracket.endSide=-1;/**
4430
+ Returns an extension that enables autocompletion.
4431
+ */function autocompletion$1(config={}){return [completionState,completionConfig.of(config),completionPlugin,completionKeymapExt,baseTheme$1];}/**
4432
+ Basic keybindings for autocompletion.
4433
+
4434
+ - Ctrl-Space: [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion)
4435
+ - Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion)
4436
+ - ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)`
4437
+ - ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)`
4438
+ - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
4439
+ - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
4440
+ - Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion)
4441
+ */const completionKeymap=[{key:"Ctrl-Space",run:startCompletion},{key:"Escape",run:closeCompletion},{key:"ArrowDown",run:/*@__PURE__*/moveCompletionSelection(true)},{key:"ArrowUp",run:/*@__PURE__*/moveCompletionSelection(false)},{key:"PageDown",run:/*@__PURE__*/moveCompletionSelection(true,"page")},{key:"PageUp",run:/*@__PURE__*/moveCompletionSelection(false,"page")},{key:"Enter",run:acceptCompletion}];const completionKeymapExt=/*@__PURE__*/Prec.highest(/*@__PURE__*/keymap.computeN([completionConfig],state=>state.facet(completionConfig).defaultKeymap?[completionKeymap]:[]));var variables=variables=>context=>{const options=variables.map(v=>({label:v.name,type:'variable',info:v.info,detail:v.detail}));// In most cases, use what is typed before the cursor
4442
+ let nodeBefore=syntaxTree(context.state).resolve(context.pos,-1);// For the special case of empty nodes, we need to check the current node
4443
+ // as well. The previous node could be part of another token, e.g.
4444
+ // when typing functions "abs(".
4445
+ let nextNode=nodeBefore.nextSibling;const isInEmptyNode=isNodeEmpty(nodeBefore)||nextNode&&nextNode.from===context.pos&&isNodeEmpty(nextNode);if(context.explicit&&isInEmptyNode){return {from:context.pos,options:options};}const result={from:nodeBefore.from,options:options};// Only auto-complete variables
4446
+ if(nodeBefore.name!=='VariableName'){return null;}return result;};// helpers ///////////////////////////////
4447
+ function isNodeEmpty(node){return node.from===node.to;}function autocompletion(context){return [autocompletion$1({override:[variables(context)]})];}// FIXME profile adding a per-Tree TreeNode cache, validating it by
4448
+ // parent pointer
4449
+ /// The default maximum length of a `TreeBuffer` node (1024).
4450
+ const DefaultBufferLength=1024;let nextPropID=0;class Range{constructor(from,to){this.from=from;this.to=to;}}/// Each [node type](#common.NodeType) or [individual tree](#common.Tree)
4451
+ /// can have metadata associated with it in props. Instances of this
4452
+ /// class represent prop names.
4453
+ class NodeProp{/// Create a new node prop type.
4454
+ constructor(config={}){this.id=nextPropID++;this.perNode=!!config.perNode;this.deserialize=config.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function");});}/// This is meant to be used with
4455
+ /// [`NodeSet.extend`](#common.NodeSet.extend) or
4456
+ /// [`LRParser.configure`](#lr.ParserConfig.props) to compute
4457
+ /// prop values for each node type in the set. Takes a [match
4458
+ /// object](#common.NodeType^match) or function that returns undefined
4459
+ /// if the node type doesn't get this prop, and the prop's value if
4460
+ /// it does.
4461
+ add(match){if(this.perNode)throw new RangeError("Can't add per-node props to node types");if(typeof match!="function")match=NodeType.match(match);return type=>{let result=match(type);return result===undefined?null:[this,result];};}}/// Prop that is used to describe matching delimiters. For opening
4462
+ /// delimiters, this holds an array of node names (written as a
4463
+ /// space-separated string when declaring this prop in a grammar)
4464
+ /// for the node types of closing delimiters that match it.
4465
+ NodeProp.closedBy=new NodeProp({deserialize:str=>str.split(" ")});/// The inverse of [`closedBy`](#common.NodeProp^closedBy). This is
4466
+ /// attached to closing delimiters, holding an array of node names
4467
+ /// of types of matching opening delimiters.
4468
+ NodeProp.openedBy=new NodeProp({deserialize:str=>str.split(" ")});/// Used to assign node types to groups (for example, all node
4469
+ /// types that represent an expression could be tagged with an
4470
+ /// `"Expression"` group).
4471
+ NodeProp.group=new NodeProp({deserialize:str=>str.split(" ")});/// The hash of the [context](#lr.ContextTracker.constructor)
4472
+ /// that the node was parsed in, if any. Used to limit reuse of
4473
+ /// contextual nodes.
4474
+ NodeProp.contextHash=new NodeProp({perNode:true});/// The distance beyond the end of the node that the tokenizer
4475
+ /// looked ahead for any of the tokens inside the node. (The LR
4476
+ /// parser only stores this when it is larger than 25, for
4477
+ /// efficiency reasons.)
4478
+ NodeProp.lookAhead=new NodeProp({perNode:true});/// This per-node prop is used to replace a given node, or part of a
4479
+ /// node, with another tree. This is useful to include trees from
4480
+ /// different languages.
4481
+ NodeProp.mounted=new NodeProp({perNode:true});const noProps=Object.create(null);/// Each node in a syntax tree has a node type associated with it.
4482
+ class NodeType{/// @internal
4483
+ constructor(/// The name of the node type. Not necessarily unique, but if the
4484
+ /// grammar was written properly, different node types with the
4485
+ /// same name within a node set should play the same semantic
4486
+ /// role.
4487
+ name,/// @internal
4488
+ props,/// The id of this node in its set. Corresponds to the term ids
4489
+ /// used in the parser.
4490
+ id,/// @internal
4491
+ flags=0){this.name=name;this.props=props;this.id=id;this.flags=flags;}static define(spec){let props=spec.props&&spec.props.length?Object.create(null):noProps;let flags=(spec.top?1/* Top */:0)|(spec.skipped?2/* Skipped */:0)|(spec.error?4/* Error */:0)|(spec.name==null?8/* Anonymous */:0);let type=new NodeType(spec.name||"",props,spec.id,flags);if(spec.props)for(let src of spec.props){if(!Array.isArray(src))src=src(type);if(src){if(src[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");props[src[0].id]=src[1];}}return type;}/// Retrieves a node prop for this type. Will return `undefined` if
4492
+ /// the prop isn't present on this node.
4493
+ prop(prop){return this.props[prop.id];}/// True when this is the top node of a grammar.
4494
+ get isTop(){return (this.flags&1/* Top */)>0;}/// True when this node is produced by a skip rule.
4495
+ get isSkipped(){return (this.flags&2/* Skipped */)>0;}/// Indicates whether this is an error node.
4496
+ get isError(){return (this.flags&4/* Error */)>0;}/// When true, this node type doesn't correspond to a user-declared
4497
+ /// named node, for example because it is used to cache repetition.
4498
+ get isAnonymous(){return (this.flags&8/* Anonymous */)>0;}/// Returns true when this node's name or one of its
4499
+ /// [groups](#common.NodeProp^group) matches the given string.
4500
+ is(name){if(typeof name=='string'){if(this.name==name)return true;let group=this.prop(NodeProp.group);return group?group.indexOf(name)>-1:false;}return this.id==name;}/// Create a function from node types to arbitrary values by
4501
+ /// specifying an object whose property names are node or
4502
+ /// [group](#common.NodeProp^group) names. Often useful with
4503
+ /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple
4504
+ /// names, separated by spaces, in a single property name to map
4505
+ /// multiple node names to a single value.
4506
+ static match(map){let direct=Object.create(null);for(let prop in map)for(let name of prop.split(" "))direct[name]=map[prop];return node=>{for(let groups=node.prop(NodeProp.group),i=-1;i<(groups?groups.length:0);i++){let found=direct[i<0?node.name:groups[i]];if(found)return found;}};}}/// An empty dummy node type to use when no actual type is available.
4507
+ NodeType.none=new NodeType("",Object.create(null),0,8/* Anonymous */);/// A node set holds a collection of node types. It is used to
4508
+ /// compactly represent trees by storing their type ids, rather than a
4509
+ /// full pointer to the type object, in a numeric array. Each parser
4510
+ /// [has](#lr.LRParser.nodeSet) a node set, and [tree
4511
+ /// buffers](#common.TreeBuffer) can only store collections of nodes
4512
+ /// from the same set. A set can have a maximum of 2**16 (65536) node
4513
+ /// types in it, so that the ids fit into 16-bit typed array slots.
4514
+ class NodeSet{/// Create a set with the given types. The `id` property of each
4515
+ /// type should correspond to its position within the array.
4516
+ constructor(/// The node types in this set, by id.
4517
+ types){this.types=types;for(let i=0;i<types.length;i++)if(types[i].id!=i)throw new RangeError("Node type ids should correspond to array positions when creating a node set");}/// Create a copy of this set with some node properties added. The
4518
+ /// arguments to this method should be created with
4519
+ /// [`NodeProp.add`](#common.NodeProp.add).
4520
+ extend(...props){let newTypes=[];for(let type of this.types){let newProps=null;for(let source of props){let add=source(type);if(add){if(!newProps)newProps=Object.assign({},type.props);newProps[add[0].id]=add[1];}}newTypes.push(newProps?new NodeType(type.name,newProps,type.id,type.flags):type);}return new NodeSet(newTypes);}}const CachedNode=new WeakMap(),CachedInnerNode=new WeakMap();/// Options that control iteration. Can be combined with the `|`
4521
+ /// operator to enable multiple ones.
4522
+ var IterMode;(function(IterMode){/// When enabled, iteration will only visit [`Tree`](#common.Tree)
4523
+ /// objects, not nodes packed into
4524
+ /// [`TreeBuffer`](#common.TreeBuffer)s.
4525
+ IterMode[IterMode["ExcludeBuffers"]=1]="ExcludeBuffers";/// Enable this to make iteration include anonymous nodes (such as
4526
+ /// the nodes that wrap repeated grammar constructs into a balanced
4527
+ /// tree).
4528
+ IterMode[IterMode["IncludeAnonymous"]=2]="IncludeAnonymous";/// By default, regular [mounted](#common.NodeProp^mounted) nodes
4529
+ /// replace their base node in iteration. Enable this to ignore them
4530
+ /// instead.
4531
+ IterMode[IterMode["IgnoreMounts"]=4]="IgnoreMounts";/// This option only applies in
4532
+ /// [`enter`](#common.SyntaxNode.enter)-style methods. It tells the
4533
+ /// library to not enter mounted overlays if one covers the given
4534
+ /// position.
4535
+ IterMode[IterMode["IgnoreOverlays"]=8]="IgnoreOverlays";})(IterMode||(IterMode={}));/// A piece of syntax tree. There are two ways to approach these
4536
+ /// trees: the way they are actually stored in memory, and the
4537
+ /// convenient way.
4538
+ ///
4539
+ /// Syntax trees are stored as a tree of `Tree` and `TreeBuffer`
4540
+ /// objects. By packing detail information into `TreeBuffer` leaf
4541
+ /// nodes, the representation is made a lot more memory-efficient.
4542
+ ///
4543
+ /// However, when you want to actually work with tree nodes, this
4544
+ /// representation is very awkward, so most client code will want to
4545
+ /// use the [`TreeCursor`](#common.TreeCursor) or
4546
+ /// [`SyntaxNode`](#common.SyntaxNode) interface instead, which provides
4547
+ /// a view on some part of this data structure, and can be used to
4548
+ /// move around to adjacent nodes.
4549
+ class Tree{/// Construct a new tree. See also [`Tree.build`](#common.Tree^build).
4550
+ constructor(/// The type of the top node.
4551
+ type,/// This node's child nodes.
4552
+ children,/// The positions (offsets relative to the start of this tree) of
4553
+ /// the children.
4554
+ positions,/// The total length of this tree
4555
+ length,/// Per-node [node props](#common.NodeProp) to associate with this node.
4556
+ props){this.type=type;this.children=children;this.positions=positions;this.length=length;/// @internal
4557
+ this.props=null;if(props&&props.length){this.props=Object.create(null);for(let[prop,value]of props)this.props[typeof prop=="number"?prop:prop.id]=value;}}/// @internal
4558
+ toString(){let mounted=this.prop(NodeProp.mounted);if(mounted&&!mounted.overlay)return mounted.tree.toString();let children="";for(let ch of this.children){let str=ch.toString();if(str){if(children)children+=",";children+=str;}}return !this.type.name?children:(/\W/.test(this.type.name)&&!this.type.isError?JSON.stringify(this.type.name):this.type.name)+(children.length?"("+children+")":"");}/// Get a [tree cursor](#common.TreeCursor) positioned at the top of
4559
+ /// the tree. Mode can be used to [control](#common.IterMode) which
4560
+ /// nodes the cursor visits.
4561
+ cursor(mode=0){return new TreeCursor(this.topNode,mode);}/// Get a [tree cursor](#common.TreeCursor) pointing into this tree
4562
+ /// at the given position and side (see
4563
+ /// [`moveTo`](#common.TreeCursor.moveTo).
4564
+ cursorAt(pos,side=0,mode=0){let scope=CachedNode.get(this)||this.topNode;let cursor=new TreeCursor(scope);cursor.moveTo(pos,side);CachedNode.set(this,cursor._tree);return cursor;}/// Get a [syntax node](#common.SyntaxNode) object for the top of the
4565
+ /// tree.
4566
+ get topNode(){return new TreeNode(this,0,0,null);}/// Get the [syntax node](#common.SyntaxNode) at the given position.
4567
+ /// If `side` is -1, this will move into nodes that end at the
4568
+ /// position. If 1, it'll move into nodes that start at the
4569
+ /// position. With 0, it'll only enter nodes that cover the position
4570
+ /// from both sides.
4571
+ resolve(pos,side=0){let node=resolveNode(CachedNode.get(this)||this.topNode,pos,side,false);CachedNode.set(this,node);return node;}/// Like [`resolve`](#common.Tree.resolve), but will enter
4572
+ /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
4573
+ /// pointing into the innermost overlaid tree at the given position
4574
+ /// (with parent links going through all parent structure, including
4575
+ /// the host trees).
4576
+ resolveInner(pos,side=0){let node=resolveNode(CachedInnerNode.get(this)||this.topNode,pos,side,true);CachedInnerNode.set(this,node);return node;}/// Iterate over the tree and its children, calling `enter` for any
4577
+ /// node that touches the `from`/`to` region (if given) before
4578
+ /// running over such a node's children, and `leave` (if given) when
4579
+ /// leaving the node. When `enter` returns `false`, that node will
4580
+ /// not have its children iterated over (or `leave` called).
4581
+ iterate(spec){let{enter,leave,from=0,to=this.length}=spec;for(let c=this.cursor((spec.mode||0)|IterMode.IncludeAnonymous);;){let entered=false;if(c.from<=to&&c.to>=from&&(c.type.isAnonymous||enter(c)!==false)){if(c.firstChild())continue;entered=true;}for(;;){if(entered&&leave&&!c.type.isAnonymous)leave(c);if(c.nextSibling())break;if(!c.parent())return;entered=true;}}}/// Get the value of the given [node prop](#common.NodeProp) for this
4582
+ /// node. Works with both per-node and per-type props.
4583
+ prop(prop){return !prop.perNode?this.type.prop(prop):this.props?this.props[prop.id]:undefined;}/// Returns the node's [per-node props](#common.NodeProp.perNode) in a
4584
+ /// format that can be passed to the [`Tree`](#common.Tree)
4585
+ /// constructor.
4586
+ get propValues(){let result=[];if(this.props)for(let id in this.props)result.push([+id,this.props[id]]);return result;}/// Balance the direct children of this tree, producing a copy of
4587
+ /// which may have children grouped into subtrees with type
4588
+ /// [`NodeType.none`](#common.NodeType^none).
4589
+ balance(config={}){return this.children.length<=8/* BranchFactor */?this: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)));}/// Build a tree from a postfix-ordered buffer of node information,
4590
+ /// or a cursor over such a buffer.
4591
+ static build(data){return buildTree(data);}}/// The empty tree
4592
+ Tree.empty=new Tree(NodeType.none,[],[],0);class FlatBufferCursor{constructor(buffer,index){this.buffer=buffer;this.index=index;}get id(){return this.buffer[this.index-4];}get start(){return this.buffer[this.index-3];}get end(){return this.buffer[this.index-2];}get size(){return this.buffer[this.index-1];}get pos(){return this.index;}next(){this.index-=4;}fork(){return new FlatBufferCursor(this.buffer,this.index);}}/// Tree buffers contain (type, start, end, endIndex) quads for each
4593
+ /// node. In such a buffer, nodes are stored in prefix order (parents
4594
+ /// before children, with the endIndex of the parent indicating which
4595
+ /// children belong to it)
4596
+ class TreeBuffer{/// Create a tree buffer.
4597
+ constructor(/// The buffer's content.
4598
+ buffer,/// The total length of the group of nodes in the buffer.
4599
+ length,/// The node set used in this buffer.
4600
+ set){this.buffer=buffer;this.length=length;this.set=set;}/// @internal
4601
+ get type(){return NodeType.none;}/// @internal
4602
+ toString(){let result=[];for(let index=0;index<this.buffer.length;){result.push(this.childString(index));index=this.buffer[index+3];}return result.join(",");}/// @internal
4603
+ childString(index){let id=this.buffer[index],endIndex=this.buffer[index+3];let type=this.set.types[id],result=type.name;if(/\W/.test(result)&&!type.isError)result=JSON.stringify(result);index+=4;if(endIndex==index)return result;let children=[];while(index<endIndex){children.push(this.childString(index));index=this.buffer[index+3];}return result+"("+children.join(",")+")";}/// @internal
4604
+ findChild(startIndex,endIndex,dir,pos,side){let{buffer}=this,pick=-1;for(let i=startIndex;i!=endIndex;i=buffer[i+3]){if(checkSide(side,pos,buffer[i+1],buffer[i+2])){pick=i;if(dir>0)break;}}return pick;}/// @internal
4605
+ slice(startI,endI,from,to){let b=this.buffer;let copy=new Uint16Array(endI-startI);for(let i=startI,j=0;i<endI;){copy[j++]=b[i++];copy[j++]=b[i++]-from;copy[j++]=b[i++]-from;copy[j++]=b[i++]-startI;}return new TreeBuffer(copy,to-from,this.set);}}function checkSide(side,pos,from,to){switch(side){case-2/* Before */:return from<pos;case-1/* AtOrBefore */:return to>=pos&&from<pos;case 0/* Around */:return from<pos&&to>pos;case 1/* AtOrAfter */:return from<=pos&&to>pos;case 2/* After */:return to>pos;case 4/* DontCare */:return true;}}function enterUnfinishedNodesBefore(node,pos){let scan=node.childBefore(pos);while(scan){let last=scan.lastChild;if(!last||last.to!=scan.to)break;if(last.type.isError&&last.from==last.to){node=scan;scan=last.prevSibling;}else {scan=last;}}return node;}function resolveNode(node,pos,side,overlays){var _a;// Move up to a node that actually holds the position, if possible
4606
+ while(node.from==node.to||(side<1?node.from>=pos:node.from>pos)||(side>-1?node.to<=pos:node.to<pos)){let parent=!overlays&&node instanceof TreeNode&&node.index<0?null:node.parent;if(!parent)return node;node=parent;}let mode=overlays?0:IterMode.IgnoreOverlays;// Must go up out of overlays when those do not overlap with pos
4607
+ if(overlays)for(let scan=node,parent=scan.parent;parent;scan=parent,parent=scan.parent){if(scan instanceof TreeNode&&scan.index<0&&((_a=parent.enter(pos,side,mode))===null||_a===void 0?void 0:_a.from)!=scan.from)node=parent;}for(;;){let inner=node.enter(pos,side,mode);if(!inner)return node;node=inner;}}class TreeNode{constructor(_tree,from,// Index in parent node, set to -1 if the node is not a direct child of _parent.node (overlay)
4608
+ index,_parent){this._tree=_tree;this.from=from;this.index=index;this._parent=_parent;}get type(){return this._tree.type;}get name(){return this._tree.type.name;}get to(){return this.from+this._tree.length;}nextChild(i,dir,pos,side,mode=0){for(let parent=this;;){for(let{children,positions}=parent._tree,e=dir>0?children.length:-1;i!=e;i+=dir){let next=children[i],start=positions[i]+parent.from;if(!checkSide(side,pos,start,start+next.length))continue;if(next instanceof TreeBuffer){if(mode&IterMode.ExcludeBuffers)continue;let index=next.findChild(0,next.buffer.length,dir,pos-start,side);if(index>-1)return new BufferNode(new BufferContext(parent,next,i,start),null,index);}else if(mode&IterMode.IncludeAnonymous||!next.type.isAnonymous||hasChild(next)){let mounted;if(!(mode&IterMode.IgnoreMounts)&&next.props&&(mounted=next.prop(NodeProp.mounted))&&!mounted.overlay)return new TreeNode(mounted.tree,start,i,parent);let inner=new TreeNode(next,start,i,parent);return mode&IterMode.IncludeAnonymous||!inner.type.isAnonymous?inner:inner.nextChild(dir<0?next.children.length-1:0,dir,pos,side);}}if(mode&IterMode.IncludeAnonymous||!parent.type.isAnonymous)return null;if(parent.index>=0)i=parent.index+dir;else i=dir<0?-1:parent._parent._tree.children.length;parent=parent._parent;if(!parent)return null;}}get firstChild(){return this.nextChild(0,1,0,4/* DontCare */);}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4/* DontCare */);}childAfter(pos){return this.nextChild(0,1,pos,2/* After */);}childBefore(pos){return this.nextChild(this._tree.children.length-1,-1,pos,-2/* Before */);}enter(pos,side,mode=0){let mounted;if(!(mode&IterMode.IgnoreOverlays)&&(mounted=this._tree.prop(NodeProp.mounted))&&mounted.overlay){let rPos=pos-this.from;for(let{from,to}of mounted.overlay){if((side>0?from<=rPos:from<rPos)&&(side<0?to>=rPos:to>rPos))return new TreeNode(mounted.tree,mounted.overlay[0].from+this.from,-1,this);}}return this.nextChild(0,1,pos,side,mode);}nextSignificantParent(){let val=this;while(val.type.isAnonymous&&val._parent)val=val._parent;return val;}get parent(){return this._parent?this._parent.nextSignificantParent():null;}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4/* DontCare */):null;}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4/* DontCare */):null;}cursor(mode=0){return new TreeCursor(this,mode);}get tree(){return this._tree;}toTree(){return this._tree;}resolve(pos,side=0){return resolveNode(this,pos,side,false);}resolveInner(pos,side=0){return resolveNode(this,pos,side,true);}enterUnfinishedNodesBefore(pos){return enterUnfinishedNodesBefore(this,pos);}getChild(type,before=null,after=null){let r=getChildren(this,type,before,after);return r.length?r[0]:null;}getChildren(type,before=null,after=null){return getChildren(this,type,before,after);}/// @internal
4609
+ toString(){return this._tree.toString();}get node(){return this;}matchContext(context){return matchNodeContext(this,context);}}function getChildren(node,type,before,after){let cur=node.cursor(),result=[];if(!cur.firstChild())return result;if(before!=null)while(!cur.type.is(before))if(!cur.nextSibling())return result;for(;;){if(after!=null&&cur.type.is(after))return result;if(cur.type.is(type))result.push(cur.node);if(!cur.nextSibling())return after==null?result:[];}}function matchNodeContext(node,context,i=context.length-1){for(let p=node.parent;i>=0;p=p.parent){if(!p)return false;if(!p.type.isAnonymous){if(context[i]&&context[i]!=p.name)return false;i--;}}return true;}class BufferContext{constructor(parent,buffer,index,start){this.parent=parent;this.buffer=buffer;this.index=index;this.start=start;}}class BufferNode{constructor(context,_parent,index){this.context=context;this._parent=_parent;this.index=index;this.type=context.buffer.set.types[context.buffer.buffer[index]];}get name(){return this.type.name;}get from(){return this.context.start+this.context.buffer.buffer[this.index+1];}get to(){return this.context.start+this.context.buffer.buffer[this.index+2];}child(dir,pos,side){let{buffer}=this.context;let index=buffer.findChild(this.index+4,buffer.buffer[this.index+3],dir,pos-this.context.start,side);return index<0?null:new BufferNode(this.context,this,index);}get firstChild(){return this.child(1,0,4/* DontCare */);}get lastChild(){return this.child(-1,0,4/* DontCare */);}childAfter(pos){return this.child(1,pos,2/* After */);}childBefore(pos){return this.child(-1,pos,-2/* Before */);}enter(pos,side,mode=0){if(mode&IterMode.ExcludeBuffers)return null;let{buffer}=this.context;let index=buffer.findChild(this.index+4,buffer.buffer[this.index+3],side>0?1:-1,pos-this.context.start,side);return index<0?null:new BufferNode(this.context,this,index);}get parent(){return this._parent||this.context.parent.nextSignificantParent();}externalSibling(dir){return this._parent?null:this.context.parent.nextChild(this.context.index+dir,dir,0,4/* DontCare */);}get nextSibling(){let{buffer}=this.context;let after=buffer.buffer[this.index+3];if(after<(this._parent?buffer.buffer[this._parent.index+3]:buffer.buffer.length))return new BufferNode(this.context,this._parent,after);return this.externalSibling(1);}get prevSibling(){let{buffer}=this.context;let parentStart=this._parent?this._parent.index+4:0;if(this.index==parentStart)return this.externalSibling(-1);return new BufferNode(this.context,this._parent,buffer.findChild(parentStart,this.index,-1,0,4/* DontCare */));}cursor(mode=0){return new TreeCursor(this,mode);}get tree(){return null;}toTree(){let children=[],positions=[];let{buffer}=this.context;let startI=this.index+4,endI=buffer.buffer[this.index+3];if(endI>startI){let from=buffer.buffer[this.index+1],to=buffer.buffer[this.index+2];children.push(buffer.slice(startI,endI,from,to));positions.push(0);}return new Tree(this.type,children,positions,this.to-this.from);}resolve(pos,side=0){return resolveNode(this,pos,side,false);}resolveInner(pos,side=0){return resolveNode(this,pos,side,true);}enterUnfinishedNodesBefore(pos){return enterUnfinishedNodesBefore(this,pos);}/// @internal
4610
+ toString(){return this.context.buffer.childString(this.index);}getChild(type,before=null,after=null){let r=getChildren(this,type,before,after);return r.length?r[0]:null;}getChildren(type,before=null,after=null){return getChildren(this,type,before,after);}get node(){return this;}matchContext(context){return matchNodeContext(this,context);}}/// A tree cursor object focuses on a given node in a syntax tree, and
4611
+ /// allows you to move to adjacent nodes.
4612
+ class TreeCursor{/// @internal
4613
+ constructor(node,/// @internal
4614
+ mode=0){this.mode=mode;/// @internal
4615
+ this.buffer=null;this.stack=[];/// @internal
4616
+ this.index=0;this.bufferNode=null;if(node instanceof TreeNode){this.yieldNode(node);}else {this._tree=node.context.parent;this.buffer=node.context;for(let n=node._parent;n;n=n._parent)this.stack.unshift(n.index);this.bufferNode=node;this.yieldBuf(node.index);}}/// Shorthand for `.type.name`.
4617
+ get name(){return this.type.name;}yieldNode(node){if(!node)return false;this._tree=node;this.type=node.type;this.from=node.from;this.to=node.to;return true;}yieldBuf(index,type){this.index=index;let{start,buffer}=this.buffer;this.type=type||buffer.set.types[buffer.buffer[index]];this.from=start+buffer.buffer[index+1];this.to=start+buffer.buffer[index+2];return true;}yield(node){if(!node)return false;if(node instanceof TreeNode){this.buffer=null;return this.yieldNode(node);}this.buffer=node.context;return this.yieldBuf(node.index,node.type);}/// @internal
4618
+ toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString();}/// @internal
4619
+ enterChild(dir,pos,side){if(!this.buffer)return this.yield(this._tree.nextChild(dir<0?this._tree._tree.children.length-1:0,dir,pos,side,this.mode));let{buffer}=this.buffer;let index=buffer.findChild(this.index+4,buffer.buffer[this.index+3],dir,pos-this.buffer.start,side);if(index<0)return false;this.stack.push(this.index);return this.yieldBuf(index);}/// Move the cursor to this node's first child. When this returns
4620
+ /// false, the node has no child, and the cursor has not been moved.
4621
+ firstChild(){return this.enterChild(1,0,4/* DontCare */);}/// Move the cursor to this node's last child.
4622
+ lastChild(){return this.enterChild(-1,0,4/* DontCare */);}/// Move the cursor to the first child that ends after `pos`.
4623
+ childAfter(pos){return this.enterChild(1,pos,2/* After */);}/// Move to the last child that starts before `pos`.
4624
+ childBefore(pos){return this.enterChild(-1,pos,-2/* Before */);}/// Move the cursor to the child around `pos`. If side is -1 the
4625
+ /// child may end at that position, when 1 it may start there. This
4626
+ /// will also enter [overlaid](#common.MountedTree.overlay)
4627
+ /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is
4628
+ /// set to false.
4629
+ enter(pos,side,mode=this.mode){if(!this.buffer)return this.yield(this._tree.enter(pos,side,mode));return mode&IterMode.ExcludeBuffers?false:this.enterChild(1,pos,side);}/// Move to the node's parent node, if this isn't the top node.
4630
+ parent(){if(!this.buffer)return this.yieldNode(this.mode&IterMode.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let parent=this.mode&IterMode.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();this.buffer=null;return this.yieldNode(parent);}/// @internal
4631
+ sibling(dir){if(!this.buffer)return !this._tree._parent?false:this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+dir,dir,0,4/* DontCare */,this.mode));let{buffer}=this.buffer,d=this.stack.length-1;if(dir<0){let parentStart=d<0?0:this.stack[d]+4;if(this.index!=parentStart)return this.yieldBuf(buffer.findChild(parentStart,this.index,-1,0,4/* DontCare */));}else {let after=buffer.buffer[this.index+3];if(after<(d<0?buffer.buffer.length:buffer.buffer[this.stack[d]+3]))return this.yieldBuf(after);}return d<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+dir,dir,0,4/* DontCare */,this.mode)):false;}/// Move to this node's next sibling, if any.
4632
+ nextSibling(){return this.sibling(1);}/// Move to this node's previous sibling, if any.
4633
+ prevSibling(){return this.sibling(-1);}atLastNode(dir){let index,parent,{buffer}=this;if(buffer){if(dir>0){if(this.index<buffer.buffer.buffer.length)return false;}else {for(let i=0;i<this.index;i++)if(buffer.buffer.buffer[i+3]<this.index)return false;}({index,parent}=buffer);}else {({index,_parent:parent}=this._tree);}for(;parent;({index,_parent:parent}=parent)){if(index>-1)for(let i=index+dir,e=dir<0?-1:parent._tree.children.length;i!=e;i+=dir){let child=parent._tree.children[i];if(this.mode&IterMode.IncludeAnonymous||child instanceof TreeBuffer||!child.type.isAnonymous||hasChild(child))return false;}}return true;}move(dir,enter){if(enter&&this.enterChild(dir,0,4/* DontCare */))return true;for(;;){if(this.sibling(dir))return true;if(this.atLastNode(dir)||!this.parent())return false;}}/// Move to the next node in a
4634
+ /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR))
4635
+ /// traversal, going from a node to its first child or, if the
4636
+ /// current node is empty or `enter` is false, its next sibling or
4637
+ /// the next sibling of the first parent node that has one.
4638
+ next(enter=true){return this.move(1,enter);}/// Move to the next node in a last-to-first pre-order traveral. A
4639
+ /// node is followed by its last child or, if it has none, its
4640
+ /// previous sibling or the previous sibling of the first parent
4641
+ /// node that has one.
4642
+ prev(enter=true){return this.move(-1,enter);}/// Move the cursor to the innermost node that covers `pos`. If
4643
+ /// `side` is -1, it will enter nodes that end at `pos`. If it is 1,
4644
+ /// it will enter nodes that start at `pos`.
4645
+ moveTo(pos,side=0){// Move up to a node that actually holds the position, if possible
4646
+ while(this.from==this.to||(side<1?this.from>=pos:this.from>pos)||(side>-1?this.to<=pos:this.to<pos))if(!this.parent())break;// Then scan down into child nodes as far as possible
4647
+ while(this.enterChild(1,pos,side)){}return this;}/// Get a [syntax node](#common.SyntaxNode) at the cursor's current
4648
+ /// position.
4649
+ get node(){if(!this.buffer)return this._tree;let cache=this.bufferNode,result=null,depth=0;if(cache&&cache.context==this.buffer){scan:for(let index=this.index,d=this.stack.length;d>=0;){for(let c=cache;c;c=c._parent)if(c.index==index){if(index==this.index)return c;result=c;depth=d+1;break scan;}index=this.stack[--d];}}for(let i=depth;i<this.stack.length;i++)result=new BufferNode(this.buffer,result,this.stack[i]);return this.bufferNode=new BufferNode(this.buffer,result,this.index);}/// Get the [tree](#common.Tree) that represents the current node, if
4650
+ /// any. Will return null when the node is in a [tree
4651
+ /// buffer](#common.TreeBuffer).
4652
+ get tree(){return this.buffer?null:this._tree._tree;}/// Iterate over the current node and all its descendants, calling
4653
+ /// `enter` when entering a node and `leave`, if given, when leaving
4654
+ /// one. When `enter` returns `false`, any children of that node are
4655
+ /// skipped, and `leave` isn't called for it.
4656
+ iterate(enter,leave){for(let depth=0;;){let mustLeave=false;if(this.type.isAnonymous||enter(this)!==false){if(this.firstChild()){depth++;continue;}if(!this.type.isAnonymous)mustLeave=true;}for(;;){if(mustLeave&&leave)leave(this);mustLeave=this.type.isAnonymous;if(this.nextSibling())break;if(!depth)return;this.parent();depth--;mustLeave=true;}}}/// Test whether the current node matches a given context—a sequence
4657
+ /// of direct parent node names. Empty strings in the context array
4658
+ /// are treated as wildcards.
4659
+ matchContext(context){if(!this.buffer)return matchNodeContext(this.node,context);let{buffer}=this.buffer,{types}=buffer.set;for(let i=context.length-1,d=this.stack.length-1;i>=0;d--){if(d<0)return matchNodeContext(this.node,context,i);let type=types[buffer.buffer[this.stack[d]]];if(!type.isAnonymous){if(context[i]&&context[i]!=type.name)return false;i--;}}return true;}}function hasChild(tree){return tree.children.some(ch=>ch instanceof TreeBuffer||!ch.type.isAnonymous||hasChild(ch));}function buildTree(data){var _a;let{buffer,nodeSet,maxBufferLength=DefaultBufferLength,reused=[],minRepeatType=nodeSet.types.length}=data;let cursor=Array.isArray(buffer)?new FlatBufferCursor(buffer,buffer.length):buffer;let types=nodeSet.types;let contextHash=0,lookAhead=0;function takeNode(parentStart,minPos,children,positions,inRepeat){let{id,start,end,size}=cursor;let lookAheadAtStart=lookAhead;while(size<0){cursor.next();if(size==-1/* Reuse */){let node=reused[id];children.push(node);positions.push(start-parentStart);return;}else if(size==-3/* ContextChange */){// Context change
4660
+ contextHash=id;return;}else if(size==-4/* LookAhead */){lookAhead=id;return;}else {throw new RangeError(`Unrecognized record size: ${size}`);}}let type=types[id],node,buffer;let startPos=start-parentStart;if(end-start<=maxBufferLength&&(buffer=findBufferSize(cursor.pos-minPos,inRepeat))){// Small enough for a buffer, and no reused nodes inside
4661
+ let data=new Uint16Array(buffer.size-buffer.skip);let endPos=cursor.pos-buffer.size,index=data.length;while(cursor.pos>endPos)index=copyToBuffer(buffer.start,data,index);node=new TreeBuffer(data,end-buffer.start,nodeSet);startPos=buffer.start-parentStart;}else {// Make it a node
4662
+ let endPos=cursor.pos-size;cursor.next();let localChildren=[],localPositions=[];let localInRepeat=id>=minRepeatType?id:-1;let lastGroup=0,lastEnd=end;while(cursor.pos>endPos){if(localInRepeat>=0&&cursor.id==localInRepeat&&cursor.size>=0){if(cursor.end<=lastEnd-maxBufferLength){makeRepeatLeaf(localChildren,localPositions,start,lastGroup,cursor.end,lastEnd,localInRepeat,lookAheadAtStart);lastGroup=localChildren.length;lastEnd=cursor.end;}cursor.next();}else {takeNode(start,endPos,localChildren,localPositions,localInRepeat);}}if(localInRepeat>=0&&lastGroup>0&&lastGroup<localChildren.length)makeRepeatLeaf(localChildren,localPositions,start,lastGroup,start,lastEnd,localInRepeat,lookAheadAtStart);localChildren.reverse();localPositions.reverse();if(localInRepeat>-1&&lastGroup>0){let make=makeBalanced(type);node=balanceRange(type,localChildren,localPositions,0,localChildren.length,0,end-start,make,make);}else {node=makeTree(type,localChildren,localPositions,end-start,lookAheadAtStart-end);}}children.push(node);positions.push(startPos);}function makeBalanced(type){return (children,positions,length)=>{let lookAhead=0,lastI=children.length-1,last,lookAheadProp;if(lastI>=0&&(last=children[lastI])instanceof Tree){if(!lastI&&last.type==type&&last.length==length)return last;if(lookAheadProp=last.prop(NodeProp.lookAhead))lookAhead=positions[lastI]+last.length+lookAheadProp;}return makeTree(type,children,positions,length,lookAhead);};}function makeRepeatLeaf(children,positions,base,i,from,to,type,lookAhead){let localChildren=[],localPositions=[];while(children.length>i){localChildren.push(children.pop());localPositions.push(positions.pop()+base-from);}children.push(makeTree(nodeSet.types[type],localChildren,localPositions,to-from,lookAhead-to));positions.push(from-base);}function makeTree(type,children,positions,length,lookAhead=0,props){if(contextHash){let pair=[NodeProp.contextHash,contextHash];props=props?[pair].concat(props):[pair];}if(lookAhead>25){let pair=[NodeProp.lookAhead,lookAhead];props=props?[pair].concat(props):[pair];}return new Tree(type,children,positions,length,props);}function findBufferSize(maxSize,inRepeat){// Scan through the buffer to find previous siblings that fit
4663
+ // together in a TreeBuffer, and don't contain any reused nodes
4664
+ // (which can't be stored in a buffer).
4665
+ // If `inRepeat` is > -1, ignore node boundaries of that type for
4666
+ // nesting, but make sure the end falls either at the start
4667
+ // (`maxSize`) or before such a node.
4668
+ let fork=cursor.fork();let size=0,start=0,skip=0,minStart=fork.end-maxBufferLength;let result={size:0,start:0,skip:0};scan:for(let minPos=fork.pos-maxSize;fork.pos>minPos;){let nodeSize=fork.size;// Pretend nested repeat nodes of the same type don't exist
4669
+ if(fork.id==inRepeat&&nodeSize>=0){// Except that we store the current state as a valid return
4670
+ // value.
4671
+ result.size=size;result.start=start;result.skip=skip;skip+=4;size+=4;fork.next();continue;}let startPos=fork.pos-nodeSize;if(nodeSize<0||startPos<minPos||fork.start<minStart)break;let localSkipped=fork.id>=minRepeatType?4:0;let nodeStart=fork.start;fork.next();while(fork.pos>startPos){if(fork.size<0){if(fork.size==-3/* ContextChange */)localSkipped+=4;else break scan;}else if(fork.id>=minRepeatType){localSkipped+=4;}fork.next();}start=nodeStart;size+=nodeSize;skip+=localSkipped;}if(inRepeat<0||size==maxSize){result.size=size;result.start=start;result.skip=skip;}return result.size>4?result:undefined;}function copyToBuffer(bufferStart,buffer,index){let{id,start,end,size}=cursor;cursor.next();if(size>=0&&id<minRepeatType){let startIndex=index;if(size>4){let endPos=cursor.pos-(size-4);while(cursor.pos>endPos)index=copyToBuffer(bufferStart,buffer,index);}buffer[--index]=startIndex;buffer[--index]=end-bufferStart;buffer[--index]=start-bufferStart;buffer[--index]=id;}else if(size==-3/* ContextChange */){contextHash=id;}else if(size==-4/* LookAhead */){lookAhead=id;}return index;}let children=[],positions=[];while(cursor.pos>0)takeNode(data.start||0,data.bufferStart||0,children,positions,-1);let length=(_a=data.length)!==null&&_a!==void 0?_a:children.length?positions[0]+children[0].length:0;return new Tree(types[data.topID],children.reverse(),positions.reverse(),length);}const nodeSizeCache=new WeakMap();function nodeSize(balanceType,node){if(!balanceType.isAnonymous||node instanceof TreeBuffer||node.type!=balanceType)return 1;let size=nodeSizeCache.get(node);if(size==null){size=1;for(let child of node.children){if(child.type!=balanceType||!(child instanceof Tree)){size=1;break;}size+=nodeSize(balanceType,child);}nodeSizeCache.set(node,size);}return size;}function balanceRange(// The type the balanced tree's inner nodes.
4672
+ balanceType,// The direct children and their positions
4673
+ children,positions,// The index range in children/positions to use
4674
+ from,to,// The start position of the nodes, relative to their parent.
4675
+ start,// Length of the outer node
4676
+ length,// Function to build the top node of the balanced tree
4677
+ mkTop,// Function to build internal nodes for the balanced tree
4678
+ mkTree){let total=0;for(let i=from;i<to;i++)total+=nodeSize(balanceType,children[i]);let maxChild=Math.ceil(total*1.5/8/* BranchFactor */);let localChildren=[],localPositions=[];function divide(children,positions,from,to,offset){for(let i=from;i<to;){let groupFrom=i,groupStart=positions[i],groupSize=nodeSize(balanceType,children[i]);i++;for(;i<to;i++){let nextSize=nodeSize(balanceType,children[i]);if(groupSize+nextSize>=maxChild)break;groupSize+=nextSize;}if(i==groupFrom+1){if(groupSize>maxChild){let only=children[groupFrom];// Only trees can have a size > 1
4679
+ divide(only.children,only.positions,0,only.children.length,positions[groupFrom]+offset);continue;}localChildren.push(children[groupFrom]);}else {let length=positions[i-1]+children[i-1].length-groupStart;localChildren.push(balanceRange(balanceType,children,positions,groupFrom,i,groupStart,length,null,mkTree));}localPositions.push(groupStart+offset-start);}}divide(children,positions,from,to,0);return (mkTop||mkTree)(localChildren,localPositions,length);}/// A superclass that parsers should extend.
4680
+ class Parser{/// Start a parse, returning a [partial parse](#common.PartialParse)
4681
+ /// object. [`fragments`](#common.TreeFragment) can be passed in to
4682
+ /// make the parse incremental.
4683
+ ///
4684
+ /// By default, the entire input is parsed. You can pass `ranges`,
4685
+ /// which should be a sorted array of non-empty, non-overlapping
4686
+ /// ranges, to parse only those ranges. The tree returned in that
4687
+ /// case will start at `ranges[0].from`.
4688
+ startParse(input,fragments,ranges){if(typeof input=="string")input=new StringInput(input);ranges=!ranges?[new Range(0,input.length)]:ranges.length?ranges.map(r=>new Range(r.from,r.to)):[new Range(0,0)];return this.createParse(input,fragments||[],ranges);}/// Run a full parse, returning the resulting tree.
4689
+ parse(input,fragments,ranges){let parse=this.startParse(input,fragments,ranges);for(;;){let done=parse.advance();if(done)return done;}}}class StringInput{constructor(string){this.string=string;}get length(){return this.string.length;}chunk(from){return this.string.slice(from);}get lineChunks(){return false;}read(from,to){return this.string.slice(from,to);}}new NodeProp({perNode:true});/// A parse stack. These are used internally by the parser to track
4690
+ /// parsing progress. They also provide some properties and methods
4691
+ /// that external code such as a tokenizer can use to get information
4692
+ /// about the parse state.
4693
+ class Stack{/// @internal
4694
+ constructor(/// The parse that this stack is part of @internal
4695
+ p,/// Holds state, input pos, buffer index triplets for all but the
4696
+ /// top state @internal
4697
+ stack,/// The current parse state @internal
4698
+ state,// The position at which the next reduce should take place. This
4699
+ // can be less than `this.pos` when skipped expressions have been
4700
+ // added to the stack (which should be moved outside of the next
4701
+ // reduction)
4702
+ /// @internal
4703
+ reducePos,/// The input position up to which this stack has parsed.
4704
+ pos,/// The dynamic score of the stack, including dynamic precedence
4705
+ /// and error-recovery penalties
4706
+ /// @internal
4707
+ score,// The output buffer. Holds (type, start, end, size) quads
4708
+ // representing nodes created by the parser, where `size` is
4709
+ // amount of buffer array entries covered by this node.
4710
+ /// @internal
4711
+ buffer,// The base offset of the buffer. When stacks are split, the split
4712
+ // instance shared the buffer history with its parent up to
4713
+ // `bufferBase`, which is the absolute offset (including the
4714
+ // offset of previous splits) into the buffer at which this stack
4715
+ // starts writing.
4716
+ /// @internal
4717
+ bufferBase,/// @internal
4718
+ curContext,/// @internal
4719
+ lookAhead=0,// A parent stack from which this was split off, if any. This is
4720
+ // set up so that it always points to a stack that has some
4721
+ // additional buffer content, never to a stack with an equal
4722
+ // `bufferBase`.
4723
+ /// @internal
4724
+ parent){this.p=p;this.stack=stack;this.state=state;this.reducePos=reducePos;this.pos=pos;this.score=score;this.buffer=buffer;this.bufferBase=bufferBase;this.curContext=curContext;this.lookAhead=lookAhead;this.parent=parent;}/// @internal
4725
+ toString(){return `[${this.stack.filter((_,i)=>i%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`;}// Start an empty stack
4726
+ /// @internal
4727
+ static start(p,state,pos=0){let cx=p.parser.context;return new Stack(p,[],state,pos,pos,0,[],0,cx?new StackContext(cx,cx.start):null,0,null);}/// The stack's current [context](#lr.ContextTracker) value, if
4728
+ /// any. Its type will depend on the context tracker's type
4729
+ /// parameter, or it will be `null` if there is no context
4730
+ /// tracker.
4731
+ get context(){return this.curContext?this.curContext.context:null;}// Push a state onto the stack, tracking its start position as well
4732
+ // as the buffer base at that point.
4733
+ /// @internal
4734
+ pushState(state,start){this.stack.push(this.state,start,this.bufferBase+this.buffer.length);this.state=state;}// Apply a reduce action
4735
+ /// @internal
4736
+ reduce(action){let depth=action>>19/* ReduceDepthShift */,type=action&65535/* ValueMask */;let{parser}=this.p;let dPrec=parser.dynamicPrecedence(type);if(dPrec)this.score+=dPrec;if(depth==0){this.pushState(parser.getGoto(this.state,type,true),this.reducePos);// Zero-depth reductions are a special case—they add stuff to
4737
+ // the stack without popping anything off.
4738
+ if(type<parser.minRepeatTerm)this.storeNode(type,this.reducePos,this.reducePos,4,true);this.reduceContext(type,this.reducePos);return;}// Find the base index into `this.stack`, content after which will
4739
+ // be dropped. Note that with `StayFlag` reductions we need to
4740
+ // consume two extra frames (the dummy parent node for the skipped
4741
+ // expression and the state that we'll be staying in, which should
4742
+ // be moved to `this.state`).
4743
+ let base=this.stack.length-(depth-1)*3-(action&262144/* StayFlag */?6:0);let start=this.stack[base-2];let bufferBase=this.stack[base-1],count=this.bufferBase+this.buffer.length-bufferBase;// Store normal terms or `R -> R R` repeat reductions
4744
+ if(type<parser.minRepeatTerm||action&131072/* RepeatFlag */){let pos=parser.stateFlag(this.state,1/* Skipped */)?this.pos:this.reducePos;this.storeNode(type,start,pos,count+4,true);}if(action&262144/* StayFlag */){this.state=this.stack[base];}else {let baseStateID=this.stack[base-3];this.state=parser.getGoto(baseStateID,type,true);}while(this.stack.length>base)this.stack.pop();this.reduceContext(type,start);}// Shift a value into the buffer
4745
+ /// @internal
4746
+ storeNode(term,start,end,size=4,isReduce=false){if(term==0/* Err */&&(!this.stack.length||this.stack[this.stack.length-1]<this.buffer.length+this.bufferBase)){// Try to omit/merge adjacent error nodes
4747
+ let cur=this,top=this.buffer.length;if(top==0&&cur.parent){top=cur.bufferBase-cur.parent.bufferBase;cur=cur.parent;}if(top>0&&cur.buffer[top-4]==0/* Err */&&cur.buffer[top-1]>-1){if(start==end)return;if(cur.buffer[top-2]>=start){cur.buffer[top-2]=end;return;}}}if(!isReduce||this.pos==end){// Simple case, just append
4748
+ this.buffer.push(term,start,end,size);}else {// There may be skipped nodes that have to be moved forward
4749
+ let index=this.buffer.length;if(index>0&&this.buffer[index-4]!=0/* Err */)while(index>0&&this.buffer[index-2]>end){// Move this record forward
4750
+ this.buffer[index]=this.buffer[index-4];this.buffer[index+1]=this.buffer[index-3];this.buffer[index+2]=this.buffer[index-2];this.buffer[index+3]=this.buffer[index-1];index-=4;if(size>4)size-=4;}this.buffer[index]=term;this.buffer[index+1]=start;this.buffer[index+2]=end;this.buffer[index+3]=size;}}// Apply a shift action
4751
+ /// @internal
4752
+ shift(action,next,nextEnd){let start=this.pos;if(action&131072/* GotoFlag */){this.pushState(action&65535/* ValueMask */,this.pos);}else if((action&262144/* StayFlag */)==0){// Regular shift
4753
+ let nextState=action,{parser}=this.p;if(nextEnd>this.pos||next<=parser.maxNode){this.pos=nextEnd;if(!parser.stateFlag(nextState,1/* Skipped */))this.reducePos=nextEnd;}this.pushState(nextState,start);this.shiftContext(next,start);if(next<=parser.maxNode)this.buffer.push(next,start,nextEnd,4);}else {// Shift-and-stay, which means this is a skipped token
4754
+ this.pos=nextEnd;this.shiftContext(next,start);if(next<=this.p.parser.maxNode)this.buffer.push(next,start,nextEnd,4);}}// Apply an action
4755
+ /// @internal
4756
+ apply(action,next,nextEnd){if(action&65536/* ReduceFlag */)this.reduce(action);else this.shift(action,next,nextEnd);}// Add a prebuilt (reused) node into the buffer.
4757
+ /// @internal
4758
+ useNode(value,next){let index=this.p.reused.length-1;if(index<0||this.p.reused[index]!=value){this.p.reused.push(value);index++;}let start=this.pos;this.reducePos=this.pos=start+value.length;this.pushState(next,start);this.buffer.push(index,start,this.reducePos,-1/* size == -1 means this is a reused value */);if(this.curContext)this.updateContext(this.curContext.tracker.reuse(this.curContext.context,value,this,this.p.stream.reset(this.pos-value.length)));}// Split the stack. Due to the buffer sharing and the fact
4759
+ // that `this.stack` tends to stay quite shallow, this isn't very
4760
+ // expensive.
4761
+ /// @internal
4762
+ split(){let parent=this;let off=parent.buffer.length;// Because the top of the buffer (after this.pos) may be mutated
4763
+ // to reorder reductions and skipped tokens, and shared buffers
4764
+ // should be immutable, this copies any outstanding skipped tokens
4765
+ // to the new buffer, and puts the base pointer before them.
4766
+ while(off>0&&parent.buffer[off-2]>parent.reducePos)off-=4;let buffer=parent.buffer.slice(off),base=parent.bufferBase+off;// Make sure parent points to an actual parent with content, if there is such a parent.
4767
+ while(parent&&base==parent.bufferBase)parent=parent.parent;return new Stack(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,buffer,base,this.curContext,this.lookAhead,parent);}// Try to recover from an error by 'deleting' (ignoring) one token.
4768
+ /// @internal
4769
+ recoverByDelete(next,nextEnd){let isNode=next<=this.p.parser.maxNode;if(isNode)this.storeNode(next,this.pos,nextEnd,4);this.storeNode(0/* Err */,this.pos,nextEnd,isNode?8:4);this.pos=this.reducePos=nextEnd;this.score-=190/* Delete */;}/// Check if the given term would be able to be shifted (optionally
4770
+ /// after some reductions) on this stack. This can be useful for
4771
+ /// external tokenizers that want to make sure they only provide a
4772
+ /// given token when it applies.
4773
+ canShift(term){for(let sim=new SimulatedStack(this);;){let action=this.p.parser.stateSlot(sim.state,4/* DefaultReduce */)||this.p.parser.hasAction(sim.state,term);if((action&65536/* ReduceFlag */)==0)return true;if(action==0)return false;sim.reduce(action);}}// Apply up to Recover.MaxNext recovery actions that conceptually
4774
+ // inserts some missing token or rule.
4775
+ /// @internal
4776
+ recoverByInsert(next){if(this.stack.length>=300/* MaxInsertStackDepth */)return [];let nextStates=this.p.parser.nextStates(this.state);if(nextStates.length>4/* MaxNext */<<1||this.stack.length>=120/* DampenInsertStackDepth */){let best=[];for(let i=0,s;i<nextStates.length;i+=2){if((s=nextStates[i+1])!=this.state&&this.p.parser.hasAction(s,next))best.push(nextStates[i],s);}if(this.stack.length<120/* DampenInsertStackDepth */)for(let i=0;best.length<4/* MaxNext */<<1&&i<nextStates.length;i+=2){let s=nextStates[i+1];if(!best.some((v,i)=>i&1&&v==s))best.push(nextStates[i],s);}nextStates=best;}let result=[];for(let i=0;i<nextStates.length&&result.length<4/* MaxNext */;i+=2){let s=nextStates[i+1];if(s==this.state)continue;let stack=this.split();stack.pushState(s,this.pos);stack.storeNode(0/* Err */,stack.pos,stack.pos,4,true);stack.shiftContext(nextStates[i],this.pos);stack.score-=200/* Insert */;result.push(stack);}return result;}// Force a reduce, if possible. Return false if that can't
4777
+ // be done.
4778
+ /// @internal
4779
+ forceReduce(){let reduce=this.p.parser.stateSlot(this.state,5/* ForcedReduce */);if((reduce&65536/* ReduceFlag */)==0)return false;let{parser}=this.p;if(!parser.validAction(this.state,reduce)){let depth=reduce>>19/* ReduceDepthShift */,term=reduce&65535/* ValueMask */;let target=this.stack.length-depth*3;if(target<0||parser.getGoto(this.stack[target],term,false)<0)return false;this.storeNode(0/* Err */,this.reducePos,this.reducePos,4,true);this.score-=100/* Reduce */;}this.reducePos=this.pos;this.reduce(reduce);return true;}/// @internal
4780
+ forceAll(){while(!this.p.parser.stateFlag(this.state,2/* Accepting */)){if(!this.forceReduce()){this.storeNode(0/* Err */,this.pos,this.pos,4,true);break;}}return this;}/// Check whether this state has no further actions (assumed to be a direct descendant of the
4781
+ /// top state, since any other states must be able to continue
4782
+ /// somehow). @internal
4783
+ get deadEnd(){if(this.stack.length!=3)return false;let{parser}=this.p;return parser.data[parser.stateSlot(this.state,1/* Actions */)]==65535/* End */&&!parser.stateSlot(this.state,4/* DefaultReduce */);}/// Restart the stack (put it back in its start state). Only safe
4784
+ /// when this.stack.length == 3 (state is directly below the top
4785
+ /// state). @internal
4786
+ restart(){this.state=this.stack[0];this.stack.length=0;}/// @internal
4787
+ sameState(other){if(this.state!=other.state||this.stack.length!=other.stack.length)return false;for(let i=0;i<this.stack.length;i+=3)if(this.stack[i]!=other.stack[i])return false;return true;}/// Get the parser used by this stack.
4788
+ get parser(){return this.p.parser;}/// Test whether a given dialect (by numeric ID, as exported from
4789
+ /// the terms file) is enabled.
4790
+ dialectEnabled(dialectID){return this.p.parser.dialect.flags[dialectID];}shiftContext(term,start){if(this.curContext)this.updateContext(this.curContext.tracker.shift(this.curContext.context,term,this,this.p.stream.reset(start)));}reduceContext(term,start){if(this.curContext)this.updateContext(this.curContext.tracker.reduce(this.curContext.context,term,this,this.p.stream.reset(start)));}/// @internal
4791
+ emitContext(){let last=this.buffer.length-1;if(last<0||this.buffer[last]!=-3)this.buffer.push(this.curContext.hash,this.reducePos,this.reducePos,-3);}/// @internal
4792
+ emitLookAhead(){let last=this.buffer.length-1;if(last<0||this.buffer[last]!=-4)this.buffer.push(this.lookAhead,this.reducePos,this.reducePos,-4);}updateContext(context){if(context!=this.curContext.context){let newCx=new StackContext(this.curContext.tracker,context);if(newCx.hash!=this.curContext.hash)this.emitContext();this.curContext=newCx;}}/// @internal
4793
+ setLookAhead(lookAhead){if(lookAhead>this.lookAhead){this.emitLookAhead();this.lookAhead=lookAhead;}}/// @internal
4794
+ close(){if(this.curContext&&this.curContext.tracker.strict)this.emitContext();if(this.lookAhead>0)this.emitLookAhead();}}class StackContext{constructor(tracker,context){this.tracker=tracker;this.context=context;this.hash=tracker.strict?tracker.hash(context):0;}}var Recover;(function(Recover){Recover[Recover["Insert"]=200]="Insert";Recover[Recover["Delete"]=190]="Delete";Recover[Recover["Reduce"]=100]="Reduce";Recover[Recover["MaxNext"]=4]="MaxNext";Recover[Recover["MaxInsertStackDepth"]=300]="MaxInsertStackDepth";Recover[Recover["DampenInsertStackDepth"]=120]="DampenInsertStackDepth";})(Recover||(Recover={}));// Used to cheaply run some reductions to scan ahead without mutating
4795
+ // an entire stack
4796
+ class SimulatedStack{constructor(start){this.start=start;this.state=start.state;this.stack=start.stack;this.base=this.stack.length;}reduce(action){let term=action&65535/* ValueMask */,depth=action>>19/* ReduceDepthShift */;if(depth==0){if(this.stack==this.start.stack)this.stack=this.stack.slice();this.stack.push(this.state,0,0);this.base+=3;}else {this.base-=(depth-1)*3;}let goto=this.start.p.parser.getGoto(this.stack[this.base-3],term,true);this.state=goto;}}// This is given to `Tree.build` to build a buffer, and encapsulates
4797
+ // the parent-stack-walking necessary to read the nodes.
4798
+ class StackBufferCursor{constructor(stack,pos,index){this.stack=stack;this.pos=pos;this.index=index;this.buffer=stack.buffer;if(this.index==0)this.maybeNext();}static create(stack,pos=stack.bufferBase+stack.buffer.length){return new StackBufferCursor(stack,pos,pos-stack.bufferBase);}maybeNext(){let next=this.stack.parent;if(next!=null){this.index=this.stack.bufferBase-next.bufferBase;this.stack=next;this.buffer=next.buffer;}}get id(){return this.buffer[this.index-4];}get start(){return this.buffer[this.index-3];}get end(){return this.buffer[this.index-2];}get size(){return this.buffer[this.index-1];}next(){this.index-=4;this.pos-=4;if(this.index==0)this.maybeNext();}fork(){return new StackBufferCursor(this.stack,this.pos,this.index);}}class CachedToken{constructor(){this.start=-1;this.value=-1;this.end=-1;this.extended=-1;this.lookAhead=0;this.mask=0;this.context=0;}}const nullToken=new CachedToken();/// [Tokenizers](#lr.ExternalTokenizer) interact with the input
4799
+ /// through this interface. It presents the input as a stream of
4800
+ /// characters, tracking lookahead and hiding the complexity of
4801
+ /// [ranges](#common.Parser.parse^ranges) from tokenizer code.
4802
+ class InputStream{/// @internal
4803
+ constructor(/// @internal
4804
+ input,/// @internal
4805
+ ranges){this.input=input;this.ranges=ranges;/// @internal
4806
+ this.chunk="";/// @internal
4807
+ this.chunkOff=0;/// Backup chunk
4808
+ this.chunk2="";this.chunk2Pos=0;/// The character code of the next code unit in the input, or -1
4809
+ /// when the stream is at the end of the input.
4810
+ this.next=-1;/// @internal
4811
+ this.token=nullToken;this.rangeIndex=0;this.pos=this.chunkPos=ranges[0].from;this.range=ranges[0];this.end=ranges[ranges.length-1].to;this.readNext();}resolveOffset(offset,assoc){let range=this.range,index=this.rangeIndex;let pos=this.pos+offset;while(pos<range.from){if(!index)return null;let next=this.ranges[--index];pos-=range.from-next.to;range=next;}while(assoc<0?pos>range.to:pos>=range.to){if(index==this.ranges.length-1)return null;let next=this.ranges[++index];pos+=next.from-range.to;range=next;}return pos;}/// Look at a code unit near the stream position. `.peek(0)` equals
4812
+ /// `.next`, `.peek(-1)` gives you the previous character, and so
4813
+ /// on.
4814
+ ///
4815
+ /// Note that looking around during tokenizing creates dependencies
4816
+ /// on potentially far-away content, which may reduce the
4817
+ /// effectiveness incremental parsing—when looking forward—or even
4818
+ /// cause invalid reparses when looking backward more than 25 code
4819
+ /// units, since the library does not track lookbehind.
4820
+ peek(offset){let idx=this.chunkOff+offset,pos,result;if(idx>=0&&idx<this.chunk.length){pos=this.pos+offset;result=this.chunk.charCodeAt(idx);}else {let resolved=this.resolveOffset(offset,1);if(resolved==null)return -1;pos=resolved;if(pos>=this.chunk2Pos&&pos<this.chunk2Pos+this.chunk2.length){result=this.chunk2.charCodeAt(pos-this.chunk2Pos);}else {let i=this.rangeIndex,range=this.range;while(range.to<=pos)range=this.ranges[++i];this.chunk2=this.input.chunk(this.chunk2Pos=pos);if(pos+this.chunk2.length>range.to)this.chunk2=this.chunk2.slice(0,range.to-pos);result=this.chunk2.charCodeAt(0);}}if(pos>=this.token.lookAhead)this.token.lookAhead=pos+1;return result;}/// Accept a token. By default, the end of the token is set to the
4821
+ /// current stream position, but you can pass an offset (relative to
4822
+ /// the stream position) to change that.
4823
+ acceptToken(token,endOffset=0){let end=endOffset?this.resolveOffset(endOffset,-1):this.pos;if(end==null||end<this.token.start)throw new RangeError("Token end out of bounds");this.token.value=token;this.token.end=end;}getChunk(){if(this.pos>=this.chunk2Pos&&this.pos<this.chunk2Pos+this.chunk2.length){let{chunk,chunkPos}=this;this.chunk=this.chunk2;this.chunkPos=this.chunk2Pos;this.chunk2=chunk;this.chunk2Pos=chunkPos;this.chunkOff=this.pos-this.chunkPos;}else {this.chunk2=this.chunk;this.chunk2Pos=this.chunkPos;let nextChunk=this.input.chunk(this.pos);let end=this.pos+nextChunk.length;this.chunk=end>this.range.to?nextChunk.slice(0,this.range.to-this.pos):nextChunk;this.chunkPos=this.pos;this.chunkOff=0;}}readNext(){if(this.chunkOff>=this.chunk.length){this.getChunk();if(this.chunkOff==this.chunk.length)return this.next=-1;}return this.next=this.chunk.charCodeAt(this.chunkOff);}/// Move the stream forward N (defaults to 1) code units. Returns
4824
+ /// the new value of [`next`](#lr.InputStream.next).
4825
+ advance(n=1){this.chunkOff+=n;while(this.pos+n>=this.range.to){if(this.rangeIndex==this.ranges.length-1)return this.setDone();n-=this.range.to-this.pos;this.range=this.ranges[++this.rangeIndex];this.pos=this.range.from;}this.pos+=n;if(this.pos>=this.token.lookAhead)this.token.lookAhead=this.pos+1;return this.readNext();}setDone(){this.pos=this.chunkPos=this.end;this.range=this.ranges[this.rangeIndex=this.ranges.length-1];this.chunk="";return this.next=-1;}/// @internal
4826
+ reset(pos,token){if(token){this.token=token;token.start=pos;token.lookAhead=pos+1;token.value=token.extended=-1;}else {this.token=nullToken;}if(this.pos!=pos){this.pos=pos;if(pos==this.end){this.setDone();return this;}while(pos<this.range.from)this.range=this.ranges[--this.rangeIndex];while(pos>=this.range.to)this.range=this.ranges[++this.rangeIndex];if(pos>=this.chunkPos&&pos<this.chunkPos+this.chunk.length){this.chunkOff=pos-this.chunkPos;}else {this.chunk="";this.chunkOff=0;}this.readNext();}return this;}/// @internal
4827
+ read(from,to){if(from>=this.chunkPos&&to<=this.chunkPos+this.chunk.length)return this.chunk.slice(from-this.chunkPos,to-this.chunkPos);if(from>=this.chunk2Pos&&to<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(from-this.chunk2Pos,to-this.chunk2Pos);if(from>=this.range.from&&to<=this.range.to)return this.input.read(from,to);let result="";for(let r of this.ranges){if(r.from>=to)break;if(r.to>from)result+=this.input.read(Math.max(r.from,from),Math.min(r.to,to));}return result;}}/// @internal
4828
+ class TokenGroup{constructor(data,id){this.data=data;this.id=id;}token(input,stack){readToken(this.data,input,stack,this.id);}}TokenGroup.prototype.contextual=TokenGroup.prototype.fallback=TokenGroup.prototype.extend=false;// Tokenizer data is stored a big uint16 array containing, for each
4829
+ // state:
4830
+ //
4831
+ // - A group bitmask, indicating what token groups are reachable from
4832
+ // this state, so that paths that can only lead to tokens not in
4833
+ // any of the current groups can be cut off early.
4834
+ //
4835
+ // - The position of the end of the state's sequence of accepting
4836
+ // tokens
4837
+ //
4838
+ // - The number of outgoing edges for the state
4839
+ //
4840
+ // - The accepting tokens, as (token id, group mask) pairs
4841
+ //
4842
+ // - The outgoing edges, as (start character, end character, state
4843
+ // index) triples, with end character being exclusive
4844
+ //
4845
+ // This function interprets that data, running through a stream as
4846
+ // long as new states with the a matching group mask can be reached,
4847
+ // and updating `token` when it matches a token.
4848
+ function readToken(data,input,stack,group){let state=0,groupMask=1<<group,{parser}=stack.p,{dialect}=parser;scan:for(;;){if((groupMask&data[state])==0)break;let accEnd=data[state+1];// Check whether this state can lead to a token in the current group
4849
+ // Accept tokens in this state, possibly overwriting
4850
+ // lower-precedence / shorter tokens
4851
+ for(let i=state+3;i<accEnd;i+=2)if((data[i+1]&groupMask)>0){let term=data[i];if(dialect.allows(term)&&(input.token.value==-1||input.token.value==term||parser.overrides(term,input.token.value))){input.acceptToken(term);break;}}// Do a binary search on the state's edges
4852
+ for(let next=input.next,low=0,high=data[state+2];low<high;){let mid=low+high>>1;let index=accEnd+mid+(mid<<1);let from=data[index],to=data[index+1];if(next<from)high=mid;else if(next>=to)low=mid+1;else {state=data[index+2];input.advance();continue scan;}}break;}}// See lezer-generator/src/encode.ts for comments about the encoding
4853
+ // used here
4854
+ function decodeArray(input,Type=Uint16Array){if(typeof input!="string")return input;let array=null;for(let pos=0,out=0;pos<input.length;){let value=0;for(;;){let next=input.charCodeAt(pos++),stop=false;if(next==126/* BigValCode */){value=65535/* BigVal */;break;}if(next>=92/* Gap2 */)next--;if(next>=34/* Gap1 */)next--;let digit=next-32/* Start */;if(digit>=46/* Base */){digit-=46/* Base */;stop=true;}value+=digit;if(stop)break;value*=46/* Base */;}if(array)array[out++]=value;else array=new Type(value);}return array;}// Environment variable used to control console output
4855
+ const verbose=typeof process!="undefined"&&process.env&&/\bparse\b/.test(process.env.LOG);let stackIDs=null;var Safety;(function(Safety){Safety[Safety["Margin"]=25]="Margin";})(Safety||(Safety={}));function cutAt(tree,pos,side){let cursor=tree.cursor(IterMode.IncludeAnonymous);cursor.moveTo(pos);for(;;){if(!(side<0?cursor.childBefore(pos):cursor.childAfter(pos)))for(;;){if((side<0?cursor.to<pos:cursor.from>pos)&&!cursor.type.isError)return side<0?Math.max(0,Math.min(cursor.to-1,pos-25/* Margin */)):Math.min(tree.length,Math.max(cursor.from+1,pos+25/* Margin */));if(side<0?cursor.prevSibling():cursor.nextSibling())break;if(!cursor.parent())return side<0?0:tree.length;}}}class FragmentCursor{constructor(fragments,nodeSet){this.fragments=fragments;this.nodeSet=nodeSet;this.i=0;this.fragment=null;this.safeFrom=-1;this.safeTo=-1;this.trees=[];this.start=[];this.index=[];this.nextFragment();}nextFragment(){let fr=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(fr){this.safeFrom=fr.openStart?cutAt(fr.tree,fr.from+fr.offset,1)-fr.offset:fr.from;this.safeTo=fr.openEnd?cutAt(fr.tree,fr.to+fr.offset,-1)-fr.offset:fr.to;while(this.trees.length){this.trees.pop();this.start.pop();this.index.pop();}this.trees.push(fr.tree);this.start.push(-fr.offset);this.index.push(0);this.nextStart=this.safeFrom;}else {this.nextStart=1e9;}}// `pos` must be >= any previously given `pos` for this cursor
4856
+ nodeAt(pos){if(pos<this.nextStart)return null;while(this.fragment&&this.safeTo<=pos)this.nextFragment();if(!this.fragment)return null;for(;;){let last=this.trees.length-1;if(last<0){// End of tree
4857
+ this.nextFragment();return null;}let top=this.trees[last],index=this.index[last];if(index==top.children.length){this.trees.pop();this.start.pop();this.index.pop();continue;}let next=top.children[index];let start=this.start[last]+top.positions[index];if(start>pos){this.nextStart=start;return null;}if(next instanceof Tree){if(start==pos){if(start<this.safeFrom)return null;let end=start+next.length;if(end<=this.safeTo){let lookAhead=next.prop(NodeProp.lookAhead);if(!lookAhead||end+lookAhead<this.fragment.to)return next;}}this.index[last]++;if(start+next.length>=Math.max(this.safeFrom,pos)){// Enter this node
4858
+ this.trees.push(next);this.start.push(start);this.index.push(0);}}else {this.index[last]++;this.nextStart=start+next.length;}}}}class TokenCache{constructor(parser,stream){this.stream=stream;this.tokens=[];this.mainToken=null;this.actions=[];this.tokens=parser.tokenizers.map(_=>new CachedToken());}getActions(stack){let actionIndex=0;let main=null;let{parser}=stack.p,{tokenizers}=parser;let mask=parser.stateSlot(stack.state,3/* TokenizerMask */);let context=stack.curContext?stack.curContext.hash:0;let lookAhead=0;for(let i=0;i<tokenizers.length;i++){if((1<<i&mask)==0)continue;let tokenizer=tokenizers[i],token=this.tokens[i];if(main&&!tokenizer.fallback)continue;if(tokenizer.contextual||token.start!=stack.pos||token.mask!=mask||token.context!=context){this.updateCachedToken(token,tokenizer,stack);token.mask=mask;token.context=context;}if(token.lookAhead>token.end+25/* Margin */)lookAhead=Math.max(token.lookAhead,lookAhead);if(token.value!=0/* Err */){let startIndex=actionIndex;if(token.extended>-1)actionIndex=this.addActions(stack,token.extended,token.end,actionIndex);actionIndex=this.addActions(stack,token.value,token.end,actionIndex);if(!tokenizer.extend){main=token;if(actionIndex>startIndex)break;}}}while(this.actions.length>actionIndex)this.actions.pop();if(lookAhead)stack.setLookAhead(lookAhead);if(!main&&stack.pos==this.stream.end){main=new CachedToken();main.value=stack.p.parser.eofTerm;main.start=main.end=stack.pos;actionIndex=this.addActions(stack,main.value,main.end,actionIndex);}this.mainToken=main;return this.actions;}getMainToken(stack){if(this.mainToken)return this.mainToken;let main=new CachedToken(),{pos,p}=stack;main.start=pos;main.end=Math.min(pos+1,p.stream.end);main.value=pos==p.stream.end?p.parser.eofTerm:0/* Err */;return main;}updateCachedToken(token,tokenizer,stack){tokenizer.token(this.stream.reset(stack.pos,token),stack);if(token.value>-1){let{parser}=stack.p;for(let i=0;i<parser.specialized.length;i++)if(parser.specialized[i]==token.value){let result=parser.specializers[i](this.stream.read(token.start,token.end),stack);if(result>=0&&stack.p.parser.dialect.allows(result>>1)){if((result&1)==0/* Specialize */)token.value=result>>1;else token.extended=result>>1;break;}}}else {token.value=0/* Err */;token.end=Math.min(stack.p.stream.end,stack.pos+1);}}putAction(action,token,end,index){// Don't add duplicate actions
4859
+ for(let i=0;i<index;i+=3)if(this.actions[i]==action)return index;this.actions[index++]=action;this.actions[index++]=token;this.actions[index++]=end;return index;}addActions(stack,token,end,index){let{state}=stack,{parser}=stack.p,{data}=parser;for(let set=0;set<2;set++){for(let i=parser.stateSlot(state,set?2/* Skip */:1/* Actions */);;i+=3){if(data[i]==65535/* End */){if(data[i+1]==1/* Next */){i=pair(data,i+2);}else {if(index==0&&data[i+1]==2/* Other */)index=this.putAction(pair(data,i+2),token,end,index);break;}}if(data[i]==token)index=this.putAction(pair(data,i+1),token,end,index);}}return index;}}var Rec;(function(Rec){Rec[Rec["Distance"]=5]="Distance";Rec[Rec["MaxRemainingPerStep"]=3]="MaxRemainingPerStep";// When two stacks have been running independently long enough to
4860
+ // add this many elements to their buffers, prune one.
4861
+ Rec[Rec["MinBufferLengthPrune"]=500]="MinBufferLengthPrune";Rec[Rec["ForceReduceLimit"]=10]="ForceReduceLimit";// Once a stack reaches this depth (in .stack.length) force-reduce
4862
+ // it back to CutTo to avoid creating trees that overflow the stack
4863
+ // on recursive traversal.
4864
+ Rec[Rec["CutDepth"]=15000]="CutDepth";Rec[Rec["CutTo"]=9000]="CutTo";})(Rec||(Rec={}));class Parse{constructor(parser,input,fragments,ranges){this.parser=parser;this.input=input;this.ranges=ranges;this.recovering=0;this.nextStackID=0x2654;// ♔, ♕, ♖, ♗, ♘, ♙, ♠, ♡, ♢, ♣, ♤, ♥, ♦, ♧
4865
+ this.minStackPos=0;this.reused=[];this.stoppedAt=null;this.stream=new InputStream(input,ranges);this.tokens=new TokenCache(parser,this.stream);this.topTerm=parser.top[1];let{from}=ranges[0];this.stacks=[Stack.start(this,parser.top[0],from)];this.fragments=fragments.length&&this.stream.end-from>parser.bufferLength*4?new FragmentCursor(fragments,parser.nodeSet):null;}get parsedPos(){return this.minStackPos;}// Move the parser forward. This will process all parse stacks at
4866
+ // `this.pos` and try to advance them to a further position. If no
4867
+ // stack for such a position is found, it'll start error-recovery.
4868
+ //
4869
+ // When the parse is finished, this will return a syntax tree. When
4870
+ // not, it returns `null`.
4871
+ advance(){let stacks=this.stacks,pos=this.minStackPos;// This will hold stacks beyond `pos`.
4872
+ let newStacks=this.stacks=[];let stopped,stoppedTokens;// Keep advancing any stacks at `pos` until they either move
4873
+ // forward or can't be advanced. Gather stacks that can't be
4874
+ // advanced further in `stopped`.
4875
+ for(let i=0;i<stacks.length;i++){let stack=stacks[i];for(;;){this.tokens.mainToken=null;if(stack.pos>pos){newStacks.push(stack);}else if(this.advanceStack(stack,newStacks,stacks)){continue;}else {if(!stopped){stopped=[];stoppedTokens=[];}stopped.push(stack);let tok=this.tokens.getMainToken(stack);stoppedTokens.push(tok.value,tok.end);}break;}}if(!newStacks.length){let finished=stopped&&findFinished(stopped);if(finished)return this.stackToTree(finished);if(this.parser.strict){if(verbose&&stopped)console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none"));throw new SyntaxError("No parse at "+pos);}if(!this.recovering)this.recovering=5/* Distance */;}if(this.recovering&&stopped){let finished=this.stoppedAt!=null&&stopped[0].pos>this.stoppedAt?stopped[0]:this.runRecovery(stopped,stoppedTokens,newStacks);if(finished)return this.stackToTree(finished.forceAll());}if(this.recovering){let maxRemaining=this.recovering==1?1:this.recovering*3/* MaxRemainingPerStep */;if(newStacks.length>maxRemaining){newStacks.sort((a,b)=>b.score-a.score);while(newStacks.length>maxRemaining)newStacks.pop();}if(newStacks.some(s=>s.reducePos>pos))this.recovering--;}else if(newStacks.length>1){// Prune stacks that are in the same state, or that have been
4876
+ // running without splitting for a while, to avoid getting stuck
4877
+ // with multiple successful stacks running endlessly on.
4878
+ outer:for(let i=0;i<newStacks.length-1;i++){let stack=newStacks[i];for(let j=i+1;j<newStacks.length;j++){let other=newStacks[j];if(stack.sameState(other)||stack.buffer.length>500/* MinBufferLengthPrune */&&other.buffer.length>500/* MinBufferLengthPrune */){if((stack.score-other.score||stack.buffer.length-other.buffer.length)>0){newStacks.splice(j--,1);}else {newStacks.splice(i--,1);continue outer;}}}}}this.minStackPos=newStacks[0].pos;for(let i=1;i<newStacks.length;i++)if(newStacks[i].pos<this.minStackPos)this.minStackPos=newStacks[i].pos;return null;}stopAt(pos){if(this.stoppedAt!=null&&this.stoppedAt<pos)throw new RangeError("Can't move stoppedAt forward");this.stoppedAt=pos;}// Returns an updated version of the given stack, or null if the
4879
+ // stack can't advance normally. When `split` and `stacks` are
4880
+ // given, stacks split off by ambiguous operations will be pushed to
4881
+ // `split`, or added to `stacks` if they move `pos` forward.
4882
+ advanceStack(stack,stacks,split){let start=stack.pos,{parser}=this;let base=verbose?this.stackID(stack)+" -> ":"";if(this.stoppedAt!=null&&start>this.stoppedAt)return stack.forceReduce()?stack:null;if(this.fragments){let strictCx=stack.curContext&&stack.curContext.tracker.strict,cxHash=strictCx?stack.curContext.hash:0;for(let cached=this.fragments.nodeAt(start);cached;){let match=this.parser.nodeSet.types[cached.type.id]==cached.type?parser.getGoto(stack.state,cached.type.id):-1;if(match>-1&&cached.length&&(!strictCx||(cached.prop(NodeProp.contextHash)||0)==cxHash)){stack.useNode(cached,match);if(verbose)console.log(base+this.stackID(stack)+` (via reuse of ${parser.getName(cached.type.id)})`);return true;}if(!(cached instanceof Tree)||cached.children.length==0||cached.positions[0]>0)break;let inner=cached.children[0];if(inner instanceof Tree&&cached.positions[0]==0)cached=inner;else break;}}let defaultReduce=parser.stateSlot(stack.state,4/* DefaultReduce */);if(defaultReduce>0){stack.reduce(defaultReduce);if(verbose)console.log(base+this.stackID(stack)+` (via always-reduce ${parser.getName(defaultReduce&65535/* ValueMask */)})`);return true;}if(stack.stack.length>=15000/* CutDepth */){while(stack.stack.length>9000/* CutTo */&&stack.forceReduce()){}}let actions=this.tokens.getActions(stack);for(let i=0;i<actions.length;){let action=actions[i++],term=actions[i++],end=actions[i++];let last=i==actions.length||!split;let localStack=last?stack:stack.split();localStack.apply(action,term,end);if(verbose)console.log(base+this.stackID(localStack)+` (via ${(action&65536/* ReduceFlag */)==0?"shift":`reduce of ${parser.getName(action&65535/* ValueMask */)}`} for ${parser.getName(term)} @ ${start}${localStack==stack?"":", split"})`);if(last)return true;else if(localStack.pos>start)stacks.push(localStack);else split.push(localStack);}return false;}// Advance a given stack forward as far as it will go. Returns the
4883
+ // (possibly updated) stack if it got stuck, or null if it moved
4884
+ // forward and was given to `pushStackDedup`.
4885
+ advanceFully(stack,newStacks){let pos=stack.pos;for(;;){if(!this.advanceStack(stack,null,null))return false;if(stack.pos>pos){pushStackDedup(stack,newStacks);return true;}}}runRecovery(stacks,tokens,newStacks){let finished=null,restarted=false;for(let i=0;i<stacks.length;i++){let stack=stacks[i],token=tokens[i<<1],tokenEnd=tokens[(i<<1)+1];let base=verbose?this.stackID(stack)+" -> ":"";if(stack.deadEnd){if(restarted)continue;restarted=true;stack.restart();if(verbose)console.log(base+this.stackID(stack)+" (restarted)");let done=this.advanceFully(stack,newStacks);if(done)continue;}let force=stack.split(),forceBase=base;for(let j=0;force.forceReduce()&&j<10/* ForceReduceLimit */;j++){if(verbose)console.log(forceBase+this.stackID(force)+" (via force-reduce)");let done=this.advanceFully(force,newStacks);if(done)break;if(verbose)forceBase=this.stackID(force)+" -> ";}for(let insert of stack.recoverByInsert(token)){if(verbose)console.log(base+this.stackID(insert)+" (via recover-insert)");this.advanceFully(insert,newStacks);}if(this.stream.end>stack.pos){if(tokenEnd==stack.pos){tokenEnd++;token=0/* Err */;}stack.recoverByDelete(token,tokenEnd);if(verbose)console.log(base+this.stackID(stack)+` (via recover-delete ${this.parser.getName(token)})`);pushStackDedup(stack,newStacks);}else if(!finished||finished.score<stack.score){finished=stack;}}return finished;}// Convert the stack's buffer to a syntax tree.
4886
+ stackToTree(stack){stack.close();return Tree.build({buffer:StackBufferCursor.create(stack),nodeSet:this.parser.nodeSet,topID:this.topTerm,maxBufferLength:this.parser.bufferLength,reused:this.reused,start:this.ranges[0].from,length:stack.pos-this.ranges[0].from,minRepeatType:this.parser.minRepeatTerm});}stackID(stack){let id=(stackIDs||(stackIDs=new WeakMap())).get(stack);if(!id)stackIDs.set(stack,id=String.fromCodePoint(this.nextStackID++));return id+stack;}}function pushStackDedup(stack,newStacks){for(let i=0;i<newStacks.length;i++){let other=newStacks[i];if(other.pos==stack.pos&&other.sameState(stack)){if(newStacks[i].score<stack.score)newStacks[i]=stack;return;}}newStacks.push(stack);}class Dialect{constructor(source,flags,disabled){this.source=source;this.flags=flags;this.disabled=disabled;}allows(term){return !this.disabled||this.disabled[term]==0;}}/// A parser holds the parse tables for a given grammar, as generated
4887
+ /// by `lezer-generator`.
4888
+ class LRParser extends Parser{/// @internal
4889
+ constructor(spec){super();/// @internal
4890
+ this.wrappers=[];if(spec.version!=14/* Version */)throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14/* Version */})`);let nodeNames=spec.nodeNames.split(" ");this.minRepeatTerm=nodeNames.length;for(let i=0;i<spec.repeatNodeCount;i++)nodeNames.push("");let topTerms=Object.keys(spec.topRules).map(r=>spec.topRules[r][1]);let nodeProps=[];for(let i=0;i<nodeNames.length;i++)nodeProps.push([]);function setProp(nodeID,prop,value){nodeProps[nodeID].push([prop,prop.deserialize(String(value))]);}if(spec.nodeProps)for(let propSpec of spec.nodeProps){let prop=propSpec[0];if(typeof prop=="string")prop=NodeProp[prop];for(let i=1;i<propSpec.length;){let next=propSpec[i++];if(next>=0){setProp(next,prop,propSpec[i++]);}else {let value=propSpec[i+-next];for(let j=-next;j>0;j--)setProp(propSpec[i++],prop,value);i++;}}}this.nodeSet=new NodeSet(nodeNames.map((name,i)=>NodeType.define({name:i>=this.minRepeatTerm?undefined:name,id:i,props:nodeProps[i],top:topTerms.indexOf(i)>-1,error:i==0,skipped:spec.skippedNodes&&spec.skippedNodes.indexOf(i)>-1})));if(spec.propSources)this.nodeSet=this.nodeSet.extend(...spec.propSources);this.strict=false;this.bufferLength=DefaultBufferLength;let tokenArray=decodeArray(spec.tokenData);this.context=spec.context;this.specialized=new Uint16Array(spec.specialized?spec.specialized.length:0);this.specializers=[];if(spec.specialized)for(let i=0;i<spec.specialized.length;i++){this.specialized[i]=spec.specialized[i].term;this.specializers[i]=spec.specialized[i].get;}this.states=decodeArray(spec.states,Uint32Array);this.data=decodeArray(spec.stateData);this.goto=decodeArray(spec.goto);this.maxTerm=spec.maxTerm;this.tokenizers=spec.tokenizers.map(value=>typeof value=="number"?new TokenGroup(tokenArray,value):value);this.topRules=spec.topRules;this.dialects=spec.dialects||{};this.dynamicPrecedences=spec.dynamicPrecedences||null;this.tokenPrecTable=spec.tokenPrec;this.termNames=spec.termNames||null;this.maxNode=this.nodeSet.types.length-1;this.dialect=this.parseDialect();this.top=this.topRules[Object.keys(this.topRules)[0]];}createParse(input,fragments,ranges){let parse=new Parse(this,input,fragments,ranges);for(let w of this.wrappers)parse=w(parse,input,fragments,ranges);return parse;}/// Get a goto table entry @internal
4891
+ getGoto(state,term,loose=false){let table=this.goto;if(term>=table[0])return -1;for(let pos=table[term+1];;){let groupTag=table[pos++],last=groupTag&1;let target=table[pos++];if(last&&loose)return target;for(let end=pos+(groupTag>>1);pos<end;pos++)if(table[pos]==state)return target;if(last)return -1;}}/// Check if this state has an action for a given terminal @internal
4892
+ hasAction(state,terminal){let data=this.data;for(let set=0;set<2;set++){for(let i=this.stateSlot(state,set?2/* Skip */:1/* Actions */),next;;i+=3){if((next=data[i])==65535/* End */){if(data[i+1]==1/* Next */)next=data[i=pair(data,i+2)];else if(data[i+1]==2/* Other */)return pair(data,i+2);else break;}if(next==terminal||next==0/* Err */)return pair(data,i+1);}}return 0;}/// @internal
4893
+ stateSlot(state,slot){return this.states[state*6/* Size */+slot];}/// @internal
4894
+ stateFlag(state,flag){return (this.stateSlot(state,0/* Flags */)&flag)>0;}/// @internal
4895
+ validAction(state,action){if(action==this.stateSlot(state,4/* DefaultReduce */))return true;for(let i=this.stateSlot(state,1/* Actions */);;i+=3){if(this.data[i]==65535/* End */){if(this.data[i+1]==1/* Next */)i=pair(this.data,i+2);else return false;}if(action==pair(this.data,i+1))return true;}}/// Get the states that can follow this one through shift actions or
4896
+ /// goto jumps. @internal
4897
+ nextStates(state){let result=[];for(let i=this.stateSlot(state,1/* Actions */);;i+=3){if(this.data[i]==65535/* End */){if(this.data[i+1]==1/* Next */)i=pair(this.data,i+2);else break;}if((this.data[i+2]&65536/* ReduceFlag */>>16)==0){let value=this.data[i+1];if(!result.some((v,i)=>i&1&&v==value))result.push(this.data[i],value);}}return result;}/// @internal
4898
+ overrides(token,prev){let iPrev=findOffset(this.data,this.tokenPrecTable,prev);return iPrev<0||findOffset(this.data,this.tokenPrecTable,token)<iPrev;}/// Configure the parser. Returns a new parser instance that has the
4899
+ /// given settings modified. Settings not provided in `config` are
4900
+ /// kept from the original parser.
4901
+ configure(config){// Hideous reflection-based kludge to make it easy to create a
4902
+ // slightly modified copy of a parser.
4903
+ let copy=Object.assign(Object.create(LRParser.prototype),this);if(config.props)copy.nodeSet=this.nodeSet.extend(...config.props);if(config.top){let info=this.topRules[config.top];if(!info)throw new RangeError(`Invalid top rule name ${config.top}`);copy.top=info;}if(config.tokenizers)copy.tokenizers=this.tokenizers.map(t=>{let found=config.tokenizers.find(r=>r.from==t);return found?found.to:t;});if(config.contextTracker)copy.context=config.contextTracker;if(config.dialect)copy.dialect=this.parseDialect(config.dialect);if(config.strict!=null)copy.strict=config.strict;if(config.wrap)copy.wrappers=copy.wrappers.concat(config.wrap);if(config.bufferLength!=null)copy.bufferLength=config.bufferLength;return copy;}/// Tells you whether any [parse wrappers](#lr.ParserConfig.wrap)
4904
+ /// are registered for this parser.
4905
+ hasWrappers(){return this.wrappers.length>0;}/// Returns the name associated with a given term. This will only
4906
+ /// work for all terms when the parser was generated with the
4907
+ /// `--names` option. By default, only the names of tagged terms are
4908
+ /// stored.
4909
+ getName(term){return this.termNames?this.termNames[term]:String(term<=this.maxNode&&this.nodeSet.types[term].name||term);}/// The eof term id is always allocated directly after the node
4910
+ /// types. @internal
4911
+ get eofTerm(){return this.maxNode+1;}/// The type of top node produced by the parser.
4912
+ get topNode(){return this.nodeSet.types[this.top[1]];}/// @internal
4913
+ dynamicPrecedence(term){let prec=this.dynamicPrecedences;return prec==null?0:prec[term]||0;}/// @internal
4914
+ parseDialect(dialect){let values=Object.keys(this.dialects),flags=values.map(()=>false);if(dialect)for(let part of dialect.split(" ")){let id=values.indexOf(part);if(id>=0)flags[id]=true;}let disabled=null;for(let i=0;i<values.length;i++)if(!flags[i]){for(let j=this.dialects[values[i]],id;(id=this.data[j++])!=65535/* End */;)(disabled||(disabled=new Uint8Array(this.maxTerm+1)))[id]=1;}return new Dialect(dialect,flags,disabled);}/// (used by the output of the parser generator) @internal
4915
+ static deserialize(spec){return new LRParser(spec);}}function pair(data,off){return data[off]|data[off+1]<<16;}function findOffset(data,start,term){for(let i=start,next;(next=data[i])!=65535/* End */;i++)if(next==term)return i-start;return -1;}function findFinished(stacks){let best=null;for(let stack of stacks){let stopped=stack.p.stoppedAt;if((stack.pos==stack.p.stream.end||stopped!=null&&stack.pos>stopped)&&stack.p.parser.stateFlag(stack.state,2/* Accepting */)&&(!best||best.score<stack.score))best=stack;}return best;}// This file was generated by lezer-generator. You probably shouldn't edit it.
4916
+ const spec_identifier={__proto__:null,for:10,in:18,return:23,if:26,then:28,else:30,some:34,every:36,satisfies:43,or:46,and:50,between:58,instance:82,of:85,days:93,time:95,duration:97,years:99,months:101,date:103,list:109,context:115,function:122,string:141,length:143,upper:145,case:147,lower:149,substring:151,before:153,after:155,starts:157,with:159,ends:161,contains:163,insert:165,index:167,distinct:169,values:171,met:173,by:175,overlaps:177,finished:179,started:181,day:183,year:185,week:187,month:189,get:191,value:193,entries:195,start:205,position:207,decimal:209,sep:211,separator:213,grouping:215,null:218,true:344,false:344,"?":232,external:248,method:265,signature:267,not:273};const parser=LRParser.deserialize({version:14,states:"!#UO]QPOOO&hQPOOO'sQPO'#FiO]QPO'#DOO*[QPO'#DOO,zQPO'#DrOOQO'#En'#EnOOQO'#Eo'#EoOOQO'#Ep'#EpO,zQPO'#EqOOQO'#F{'#F{OOQO'#Fz'#FzOOQO'#Es'#EsO-PQPO'#EvO-kQPO'#EwO0ZQPO'#ExO-PQPO'#EuOOQO'#Eu'#EuOOQO'#Fk'#FkO0bQPO'#FQOOQO'#GQ'#GQOOQO'#Fj'#FjOOQO'#FZ'#FZQ]QPOOO0pQPO'#C`O]QPO'#ChO0pQPO'#ClO0uQPO'#DsO0zQPO'#DsO1PQPO'#DsO1UQPO'#DsO1^QPO'#DsO1cQPO'#DsO1hQPO'#DsO1mQPO'#DsO1rQPO'#DsO1wQPO'#DsO1|QPO'#DsO2RQPO'#DsO2WQPO'#DsO2`QPO'#ErOOQO'#Er'#ErO2hQPO'#EyO2mQPO'#CzO5hQPO'#FqOOQO'#C|'#C|O5sQPO'#FXQOQPOOO5zQPOOO]QPO,59bO]QPO,59jO]QPO,59jO]QPO,59jO0pQPO,5:YO]QPO,5:[O8lQPO'#FwOOQO,5:^,5:^OOQO,5<T,5<TO]QPO,59^O]QPO,59`O]QPO,59bO;lQPO,59bO;sQPO,59pO;xQPO,59jOB]QPO,5;YOOQO,5;],5;]OOQO'#Cd'#CdOGqQPO'#DYOKoQPO'#EnOOQO'#GP'#GPOKtQPO,5;bOMQQPO'#CdOM_QPO,5;cOMfQPO'#FzONsQPO'#FyO! QQPO,5;dOOQO,5;a,5;aOOQO'#FS'#FSO! VQPO'#FRO! [QPO'#GSO! dQPO,5;lO! iQ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ji!cji!hji!jji!lji!mji!pji!rji!tji!uji!vji!xji!zji!{ji!|ji!}ji#Pji#Qji#Rji#aji#hji#sji$Yji$`ji$pji$qji$rji$wji$cjiqji^ji#rjiejiZji~Os!SOt!SOu!TOv!TOw!UO~P!#pOo!XOw!UOy!`O!e!WO$f!VOTriXri]riaribrigriirikrilrimrisritri!Pri!Qri!Rri!Tri!Wri!_ri!cri!hri!jri!lri!mri!pri!rri!tri!uri!vri!xri!zri!{ri!|ri!}ri#Pri#Qri#Rri#ari#hri#sri$Yri$`ri$pri$qri$rri$wri$criqri^ri#rrieriZri~Ou!TOv!TO~P!'lOurivri~P!'lOo!XOy!`O!e!WO$f!VOTriXri]riaribrigriirikrilrimrisritriurivri!Pri!Qri!Rri!Tri!Wri!_ri!cri!hri!jri!lri!mri!pri!rri!tri!uri!vri!xri!zri!{ri!|ri!}ri#Pri#Qri#Rri#ari#hri#sri$Yri$`ri$pri$qri$rri$wri$criqri^ri#rriZri_rieri~Owri$bri~P!+rO!c$_O~P&rO$h$`O~O$c$aOq$lX~Oq$cO~O#Z$dO~O#]$dO#^$dO~Oo!XOy!`O!e!WO$f!VOTfi]fiafibfigfi!Pfi!Qfi!Rfi!Tfi!Wfi!_fi!cfi!hfi!jfi!lfi!mfi!pfi!rfi!tfi!ufi!vfi!xfi!zfi!{fi!|fi!}fi#Pfi#Qfi#Rfi#afi#hfi#sfi$Yfi$`fi$pfi$qfi$rfi$wfi$cfiqfi^fi#rfiefiZfi~OX!_Oi!]Ok!ROl!ROm!^Os!SOt!SOu!TOv!TOw!UO~P!0lOo!XOy!`O!e!WO$f!VOThi]hiahibhighiihi!Phi!Qhi!Rhi!Thi!Whi!_hi!chi!hhi!jhi!lhi!mhi!phi!rhi!thi!uhi!vhi!xhi!zhi!{hi!|hi!}hi#Phi#Qhi#Rhi#ahi#hhi#shi$Yhi$`hi$phi$qhi$rhi$whi$chiqhi^hi#rhiehiZhi~OX!_Ok!ROl!ROm!^Os!SOt!SOu!TOv!T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edExpression some every InExpressions InExpression satisfies Disjunction or Conjunction and Comparison CompareOp CompareOp between PositiveUnaryTest ( PositiveUnaryTests ) ArithmeticExpression ArithOp ArithOp ArithOp ArithOp ArithOp InstanceOf instance of Type QualifiedName SpecialType days time duration years months date > ListType list < ContextType context ContextEntryTypes ContextEntryType FunctionType function ArgumentTypes ArgumentType PathExpression ] FilterExpression [ FunctionInvocation SpecialFunctionName string length upper case lower substring before after starts with ends contains insert index distinct values met by overlaps finished started day year week month get value entries NamedParameters NamedParameter ParameterName SpecialParameterName start position decimal sep separator grouping PositionalParameters null NumericLiteral StringLiteral BooleanLiteral DateTimeLiteral DateTimeConstructor VariableName ? SimplePositiveUnaryTest Interval ParenthesizedExpression List FunctionDefinition FormalParameters FormalParameter external FunctionBody } { Context ContextEntry Key SpecialKey method signature UnaryTests Wildcard not",maxTerm:177,nodeProps:[["group",-18,4,12,16,22,24,26,34,40,64,66,68,115,116,117,119,120,121,128,"Expression",-5,109,110,111,112,113,"Expression Literal"],["closedBy",31,")",67,"]",127,"}"],["openedBy",33,"(",65,"[",126,"{"]],skippedNodes:[0,1,2],repeatNodeCount:11,tokenData:"+Y~R|XY#{Y^#{pq#{qr$prs${tu%oxy&yyz'Oz{'T{|'b|}'g}!O'l!O!P'y!P!Q(c!Q![)n![!]*P!]!^*U!^!_*Z!_!`$v!`!a*j!a!b%o!c!}%o!}#O*t#P#Q*y#Q#R']#R#S%o#T#o%o#o#p+O#q#r+T#y#z#{$f$g#{#BY#BZ#{$IS$I_#{$I`$Ib%o$I|$JO#{$JT$JU#{$KV$KW#{$Kh%#t%o&/x&Et%o&FU&FV#{&FV;'S%o;'S;:j&s?&r?Ah%o?BY?Mn%o~$QY$[~X^#{pq#{#y#z#{$f$g#{#BY#BZ#{$IS$I_#{$I|$JO#{$JT$JU#{$KV$KW#{&FU&FV#{~$sP!_!`$v~${Ok~~%QU$q~OY${Zr${rs%ds#O${#O#P%i#P~${~%iO$q~~%lPO~${~%t_$`~tu%o!Q![%o!a!b%o!c!}%o#R#S%o#T#o%o1p4U%o$I`$Ib%o$Je$Jg%o$Kh%#t%o&/x&Et%o&FV;'S%o;'S;:j&s?&r?Ah%o?BY?Mn%o~&vP;=`<%l%o~'OOo~~'TOq~~'YPu~z{']~'bOw~~'gOs~~'lO$c~R'qPtP!`!a'tQ'yO$jQ~(OQ$f~!O!P(U!Q![(Z~(ZO$b~~(`P$p~!Q![(Z~(hQv~z{(n!P!Q)c~(qROz(nz{(z{~(n~(}TOz(nz{(z{!P(n!P!Q)^!Q~(n~)cOQ~~)hQP~OY)cZ~)c~)sQ$p~!O!P)y!Q![)n~)|P!Q![(Z~*UO$h~~*ZO$w~R*bP!XQlP!_!`*eP*jOlPR*qP!UQlP!_!`*e~*yO!e~~+OO!c~~+TO#s~~+YO#r~",tokenizers:[0,1],topRules:{"Expressions":[0,3],"UnaryTests":[1,134]},dynamicPrecedences:{"24":-1,"68":-1,"151":-1},specialized:[{term:154,get:value=>spec_identifier[value]||-1}],tokenPrec:0});const highlightTags=styleTags({VariableName:tags.variableName,NumericLiteral:tags.number,QualifiedName:tags.name,Name:tags.name,BooleanLiteral:tags.bool,StringLiteral:tags.string,LineComment:tags.lineComment,BlockComment:tags.blockComment,'( )':tags.paren,BuiltInFunctionName:tags.function(tags.variableName),BuiltInType:tags.function(tags.variableName),ListType:tags.function(tags.variableName),ContextType:tags.function(tags.variableName),FunctionType:tags.function(tags.variableName),DateAndTime:tags.function(tags.variableName),'DateTimeConstructor!':tags.function(tags.variableName),'for in return null':tags.atom,List:tags.list,Interval:tags.list});const parserWithMetadata=parser.configure({props:[highlightTags]});const FeelLanguage=LRLanguage.define({parser:parserWithMetadata});function language(){return new LanguageSupport(FeelLanguage,[]);}const FeelLinter=function(editorView){const messages=[];// don't lint if the Editor is empty
4917
+ if(editorView.state.doc.length===0){return messages;}const tree=syntaxTree(editorView.state);tree.iterate({enter:node=>{if(node.type.isError){const error=node.toString();/* The error has the pattern [⚠ || ⚠(NodeType)]. The regex extracts the node type from inside the brackets */const match=/\((.*?)\)/.exec(error);const nodeType=match&&match[1];let message;if(nodeType){message='unexpected '+nodeType;}else {message='expression expected';}messages.push({from:node.from,to:node.to,severity:'error',message:message,source:'syntaxError'});}}});return messages;};var syntaxLinter=linter$1(FeelLinter);var linter=[syntaxLinter];const baseTheme=EditorView.theme({'& .cm-content':{padding:'0px'},'& .cm-line':{padding:'0px'},'&.cm-editor.cm-focused':{outline:'none'}});const highlightTheme=EditorView.baseTheme({'& .variableName':{color:'#10f'},'& .number':{color:'#164'},'& .string':{color:'#a11'},'& .function':{color:'#aa3731',fontWeight:'bold'},'& .atom':{color:'#708'}});const syntaxClasses=syntaxHighlighting(HighlightStyle.define([{tag:tags.variableName,class:'variableName'},{tag:tags.name,class:'variableName'},{tag:tags.number,class:'number'},{tag:tags.string,class:'string'},{tag:tags.function(tags.variableName),class:'function'},{tag:tags.atom,class:'atom'}]));var theme=[baseTheme,highlightTheme,syntaxClasses];/**
4918
4918
  * Creates a FEEL editor in the supplied container
4919
4919
  *
4920
4920
  * @param {Object} config
4921
4921
  * @param {DOMNode} config.container
4922
4922
  * @param {Function} [config.onChange]
4923
4923
  * @param {Function} [config.onKeyDown]
4924
+ * @param {Function} [config.onLint]
4925
+ * @param {Boolean} [config.readOnly]
4924
4926
  * @param {String} [config.value]
4927
+ * @param {Array} [config.variables]
4925
4928
  *
4926
4929
  * @returns {Object} editor
4927
- */function FeelEditor({container,variables=[],onChange=()=>{},onKeyDown=()=>{},value='',readOnly=false}){const changeHandler=EditorView.updateListener.of(update=>{if(update.docChanged){onChange(update.state.doc.toString());}});const keyHandler=EditorView.domEventHandlers({keydown:onKeyDown});const extensions=[keymap.of([...defaultKeymap]),changeHandler,keyHandler,language(),autocompletion(variables),theme,linter];if(readOnly){extensions.push(EditorView.editable.of(false));}this._cmEditor=new EditorView({state:EditorState.create({doc:value,extensions:extensions}),parent:container});return this;}/**
4930
+ */function FeelEditor({container,onChange=()=>{},onKeyDown=()=>{},onLint=()=>{},readOnly=false,value='',variables=[]}){const changeHandler=EditorView.updateListener.of(update=>{if(update.docChanged){onChange(update.state.doc.toString());}});const lintHandler=EditorView.updateListener.of(update=>{const diagnosticEffects=update.transactions.flatMap(t=>t.effects).filter(effect=>effect.is(setDiagnosticsEffect));if(!diagnosticEffects.length){return;}const messages=diagnosticEffects.flatMap(effect=>effect.value);onLint(messages);});const keyHandler=EditorView.domEventHandlers({keydown:onKeyDown});const extensions=[keymap.of([...defaultKeymap]),changeHandler,keyHandler,language(),autocompletion(variables),theme,linter,lintHandler];if(readOnly){extensions.push(EditorView.editable.of(false));}this._cmEditor=new EditorView({state:EditorState.create({doc:value,extensions:extensions}),parent:container});return this;}/**
4928
4931
  * Replaces the content of the Editor
4929
4932
  *
4930
4933
  * @param {String} value
4931
4934
  */FeelEditor.prototype.setValue=function(value){this._cmEditor.dispatch({changes:{from:0,to:this._cmEditor.state.doc.length,insert:value}});};/**
4932
4935
  * Sets the focus in the editor.
4933
- */FeelEditor.prototype.focus=function(){this._cmEditor.focus();};/**
4936
+ */FeelEditor.prototype.focus=function(position){const cmEditor=this._cmEditor;cmEditor.focus();if(typeof position==='number'){const end=cmEditor.state.doc.length;cmEditor.dispatch({selection:{anchor:position<=end?position:end}});}};/**
4934
4937
  * Returns the current selection ranges. If no text is selected, a single
4935
4938
  * range with the start and end index at the cursor position will be returned.
4936
4939
  *
@@ -4939,19 +4942,19 @@ function isNodeEmpty(node){return node.from===node.to;}function autocompletion(c
4939
4942
  */FeelEditor.prototype.getSelection=function(){return this._cmEditor.state.selection;};
4940
4943
 
4941
4944
  const useBufferedFocus = function (editor, ref) {
4942
- const [buffer, setBuffer] = useState(false);
4945
+ const [buffer, setBuffer] = useState(undefined);
4943
4946
  ref.current = useMemo(() => ({
4944
- focus: () => {
4947
+ focus: argument => {
4945
4948
  if (editor) {
4946
- editor.focus();
4949
+ editor.focus(argument);
4947
4950
  } else {
4948
- setBuffer(true);
4951
+ setBuffer(argument);
4949
4952
  }
4950
4953
  }
4951
4954
  }), [editor]);
4952
4955
  useEffect(() => {
4953
- if (buffer && editor) {
4954
- editor.focus();
4956
+ if (typeof buffer !== 'undefined' && editor) {
4957
+ editor.focus(buffer);
4955
4958
  setBuffer(false);
4956
4959
  }
4957
4960
  }, [editor, buffer]);
@@ -4962,6 +4965,7 @@ const CodeEditor = forwardRef((props, ref) => {
4962
4965
  value,
4963
4966
  onInput,
4964
4967
  onFeelToggle,
4968
+ onLint = () => {},
4965
4969
  disabled,
4966
4970
  variables
4967
4971
  } = props;
@@ -4998,11 +5002,13 @@ const CodeEditor = forwardRef((props, ref) => {
4998
5002
  container: inputRef.current,
4999
5003
  onChange: handleInput,
5000
5004
  onKeyDown: onKeyDown,
5005
+ onLint: onLint,
5001
5006
  value: localValue,
5002
5007
  variables: variables
5003
5008
  });
5004
5009
  setEditor(editor);
5005
5010
  return () => {
5011
+ onLint([]);
5006
5012
  inputRef.current.innerHTML = '';
5007
5013
  setEditor(null);
5008
5014
  };
@@ -5019,12 +5025,18 @@ const CodeEditor = forwardRef((props, ref) => {
5019
5025
  editor.setValue(value);
5020
5026
  setLocalValue(value);
5021
5027
  }, [value]);
5028
+
5029
+ const handleClick = () => {
5030
+ ref.current.focus();
5031
+ };
5032
+
5022
5033
  return jsx("div", {
5023
5034
  class: classnames('bio-properties-panel-feel-editor-container', disabled ? 'disabled' : null),
5024
5035
  children: jsx("div", {
5025
5036
  name: props.name,
5026
5037
  class: classnames('bio-properties-panel-input', localValue ? 'edited' : null),
5027
- ref: inputRef
5038
+ ref: inputRef,
5039
+ onClick: handleClick
5028
5040
  })
5029
5041
  });
5030
5042
  });
@@ -5088,16 +5100,27 @@ function FeelTextfield(props) {
5088
5100
  id,
5089
5101
  label,
5090
5102
  onInput,
5103
+ onError,
5091
5104
  feel,
5092
5105
  value = '',
5093
5106
  disabled = false,
5094
5107
  OptionalComponent = OptionalFeelInput
5095
5108
  } = props;
5096
5109
  const [localValue, _setLocalValue] = useState(value);
5097
- const ref = useShowEntryEvent(id);
5110
+ const editorRef = useShowEntryEvent(id);
5111
+ const containerRef = useRef();
5098
5112
  const feelActive = localValue.startsWith('=') || feel === 'required';
5099
5113
  const feelOnlyValue = localValue.substring(1);
5100
- const [focus, setFocus] = useState();
5114
+ const [focus, _setFocus] = useState(undefined);
5115
+
5116
+ const setFocus = (offset = 0) => {
5117
+ const hasFocus = containerRef.current.contains(document.activeElement); // Keep carret position if it is already focused, otherwise focus at the end
5118
+
5119
+ const position = hasFocus ? document.activeElement.selectionStart : Infinity;
5120
+
5121
+ _setFocus(position + offset);
5122
+ };
5123
+
5101
5124
  const handleInputCallback = useMemo(() => {
5102
5125
  return debounce(newValue => {
5103
5126
  onInput(newValue);
@@ -5138,14 +5161,26 @@ function FeelTextfield(props) {
5138
5161
  setLocalValue(newValue);
5139
5162
 
5140
5163
  if (!feelActive && newValue.startsWith('=')) {
5141
- setFocus(true);
5164
+ // focus is behind `=` sign that will be removed
5165
+ setFocus(-1);
5142
5166
  }
5143
5167
  };
5144
5168
 
5169
+ const handleLint = useStaticCallback(lint => {
5170
+ if (!(lint && lint.length)) {
5171
+ onError(undefined);
5172
+ return;
5173
+ }
5174
+
5175
+ const error = lint[0];
5176
+ const message = `${error.source}: ${error.message}`;
5177
+ onError(message);
5178
+ });
5145
5179
  useEffect(() => {
5146
- if (focus) {
5147
- ref.current.focus();
5148
- setFocus(false);
5180
+ if (typeof focus !== 'undefined') {
5181
+ editorRef.current.focus(focus);
5182
+
5183
+ _setFocus(undefined);
5149
5184
  }
5150
5185
  }, [focus]);
5151
5186
  useEffect(() => {
@@ -5160,13 +5195,47 @@ function FeelTextfield(props) {
5160
5195
  }
5161
5196
 
5162
5197
  setLocalValue(value);
5163
- }, [value]);
5198
+ }, [value]); // copy-paste integration
5199
+
5200
+ useEffect(() => {
5201
+ const copyHandler = event => {
5202
+ if (!feelActive) {
5203
+ return;
5204
+ }
5205
+
5206
+ event.clipboardData.setData('application/FEEL', event.clipboardData.getData('text'));
5207
+ };
5208
+
5209
+ const pasteHandler = event => {
5210
+ if (feelActive) {
5211
+ return;
5212
+ }
5213
+
5214
+ const data = event.clipboardData.getData('application/FEEL');
5215
+
5216
+ if (data) {
5217
+ setTimeout(() => {
5218
+ handleFeelToggle();
5219
+ setFocus();
5220
+ });
5221
+ }
5222
+ };
5223
+
5224
+ containerRef.current.addEventListener('copy', copyHandler);
5225
+ containerRef.current.addEventListener('cut', copyHandler);
5226
+ containerRef.current.addEventListener('paste', pasteHandler);
5227
+ return () => {
5228
+ containerRef.current.removeEventListener('copy', copyHandler);
5229
+ containerRef.current.removeEventListener('cut', copyHandler);
5230
+ containerRef.current.removeEventListener('paste', pasteHandler);
5231
+ };
5232
+ }, [containerRef, feelActive, handleFeelToggle, setFocus]);
5164
5233
  return jsxs("div", {
5165
5234
  class: "bio-properties-panel-feel-entry",
5166
5235
  children: [jsxs("label", {
5167
5236
  for: prefixId$6(id),
5168
5237
  class: "bio-properties-panel-label",
5169
- onClick: () => setFocus(true),
5238
+ onClick: () => setFocus(),
5170
5239
  children: [label, jsx(FeelIcon, {
5171
5240
  label: label,
5172
5241
  feel: feel,
@@ -5175,6 +5244,7 @@ function FeelTextfield(props) {
5175
5244
  })]
5176
5245
  }), jsxs("div", {
5177
5246
  class: "bio-properties-panel-feel-container",
5247
+ ref: containerRef,
5178
5248
  children: [jsx(FeelIndicator, {
5179
5249
  active: feelActive,
5180
5250
  disabled: feel !== 'optional' || disabled,
@@ -5188,13 +5258,14 @@ function FeelTextfield(props) {
5188
5258
  handleFeelToggle();
5189
5259
  setFocus(true);
5190
5260
  },
5261
+ onLint: handleLint,
5191
5262
  value: feelOnlyValue,
5192
5263
  variables: props.variables,
5193
- ref: ref
5264
+ ref: editorRef
5194
5265
  }) : jsx(OptionalComponent, { ...props,
5195
5266
  onInput: handleLocalInput,
5196
5267
  value: localValue,
5197
- ref: ref
5268
+ ref: editorRef
5198
5269
  })]
5199
5270
  })]
5200
5271
  });
@@ -5211,7 +5282,7 @@ const OptionalFeelInput = forwardRef((props, ref) => {
5211
5282
  // this ensures clean editing experience when switching with the keyboard
5212
5283
 
5213
5284
  ref.current = {
5214
- focus: () => {
5285
+ focus: position => {
5215
5286
  const input = inputRef.current;
5216
5287
 
5217
5288
  if (!input) {
@@ -5219,7 +5290,14 @@ const OptionalFeelInput = forwardRef((props, ref) => {
5219
5290
  }
5220
5291
 
5221
5292
  input.focus();
5222
- input.setSelectionRange(0, 0);
5293
+
5294
+ if (typeof position === 'number') {
5295
+ if (position > value.length) {
5296
+ position = value.length;
5297
+ }
5298
+
5299
+ input.setSelectionRange(position, position);
5300
+ }
5223
5301
  }
5224
5302
  };
5225
5303
  return jsx("input", {
@@ -5303,6 +5381,7 @@ function FeelEntry(props) {
5303
5381
  } = props;
5304
5382
  const [cachedInvalidValue, setCachedInvalidValue] = useState(null);
5305
5383
  const [validationError, setValidationError] = useState(null);
5384
+ const [localError, setLocalError] = useState(null);
5306
5385
  let value = getValue(element);
5307
5386
  const previousValue = usePrevious(value);
5308
5387
  useEffect(() => {
@@ -5329,13 +5408,16 @@ function FeelEntry(props) {
5329
5408
 
5330
5409
  setValidationError(newValidationError);
5331
5410
  });
5411
+ const onError = useCallback(err => {
5412
+ setLocalError(err);
5413
+ }, []);
5332
5414
 
5333
5415
  if (previousValue === value && validationError) {
5334
5416
  value = cachedInvalidValue;
5335
5417
  }
5336
5418
 
5337
5419
  const temporaryError = useError(id);
5338
- const error = temporaryError || validationError;
5420
+ const error = temporaryError || validationError || localError;
5339
5421
  return jsxs("div", {
5340
5422
  class: classnames(props.class, 'bio-properties-panel-entry', error ? 'has-error' : ''),
5341
5423
  "data-entry-id": id,
@@ -5346,6 +5428,7 @@ function FeelEntry(props) {
5346
5428
  id: id,
5347
5429
  label: label,
5348
5430
  onInput: onInput,
5431
+ onError: onError,
5349
5432
  example: props.example,
5350
5433
  show: show,
5351
5434
  value: value,