@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.js CHANGED
@@ -18,7 +18,7 @@ var ArrowIcon = function ArrowIcon(props) {
18
18
  return jsxRuntime.jsx("svg", { ...props,
19
19
  children: jsxRuntime.jsx("path", {
20
20
  fillRule: "evenodd",
21
- 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"
21
+ 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"
22
22
  })
23
23
  });
24
24
  };
@@ -33,7 +33,7 @@ var CreateIcon = function CreateIcon(props) {
33
33
  return jsxRuntime.jsx("svg", { ...props,
34
34
  children: jsxRuntime.jsx("path", {
35
35
  fillRule: "evenodd",
36
- 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"
36
+ 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"
37
37
  })
38
38
  });
39
39
  };
@@ -48,7 +48,7 @@ var DeleteIcon = function DeleteIcon(props) {
48
48
  return jsxRuntime.jsx("svg", { ...props,
49
49
  children: jsxRuntime.jsx("path", {
50
50
  fillRule: "evenodd",
51
- 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"
51
+ 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"
52
52
  })
53
53
  });
54
54
  };
@@ -64,7 +64,7 @@ var ExternalLinkIcon = function ExternalLinkIcon(props) {
64
64
  children: jsxRuntime.jsx("path", {
65
65
  fillRule: "evenodd",
66
66
  clipRule: "evenodd",
67
- 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",
67
+ 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",
68
68
  fill: "#818798"
69
69
  })
70
70
  });
@@ -80,15 +80,15 @@ ExternalLinkIcon.defaultProps = {
80
80
  var FeelRequiredIcon = function FeelRequiredIcon(props) {
81
81
  return jsxRuntime.jsxs("svg", { ...props,
82
82
  children: [jsxRuntime.jsx("path", {
83
- d: "M5.8 7.06V5.95h4.307v1.11H5.8zm0 3.071v-1.11h4.307v1.11H5.8z",
83
+ d: "M5.8 7.06V5.95h4.307v1.11H5.8Zm0 3.071v-1.11h4.307v1.11H5.8Z",
84
84
  fill: "currentColor"
85
85
  }), jsxRuntime.jsx("path", {
86
86
  fillRule: "evenodd",
87
87
  clipRule: "evenodd",
88
- d: "M8 3.268A4.732 4.732 0 1 0 12.732 8H14a6 6 0 1 1-6-6v1.268z",
88
+ d: "M8 3.268A4.732 4.732 0 1 0 12.732 8H14a6 6 0 1 1-6-6v1.268Z",
89
89
  fill: "currentColor"
90
90
  }), jsxRuntime.jsx("path", {
91
- 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",
91
+ 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",
92
92
  fill: "currentColor"
93
93
  })]
94
94
  });
@@ -103,12 +103,12 @@ FeelRequiredIcon.defaultProps = {
103
103
  var FeelOptionalIcon = function FeelOptionalIcon(props) {
104
104
  return jsxRuntime.jsxs("svg", { ...props,
105
105
  children: [jsxRuntime.jsx("path", {
106
- d: "M5.845 7.04V5.93h4.307v1.11H5.845zm0 3.07V9h4.307v1.11H5.845z",
106
+ d: "M5.845 7.04V5.93h4.307v1.11H5.845Zm0 3.07V9h4.307v1.11H5.845Z",
107
107
  fill: "currentColor"
108
108
  }), jsxRuntime.jsx("path", {
109
109
  fillRule: "evenodd",
110
110
  clipRule: "evenodd",
111
- 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",
111
+ 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",
112
112
  fill: "currentColor"
113
113
  })]
114
114
  });
@@ -433,7 +433,7 @@ function useShowEntryEvent(id) {
433
433
  }
434
434
  }
435
435
  }, [id]);
436
- hooks.useEffect(() => {
436
+ hooks.useLayoutEffect(() => {
437
437
  if (focus.current && ref.current) {
438
438
  if (minDash.isFunction(ref.current.focus)) {
439
439
  ref.current.focus();
@@ -4091,476 +4091,7 @@ direction `dir`. Only the `brackets` and `maxScanDistance`
4091
4091
  properties are used from `config`, if given. Returns null if no
4092
4092
  bracket was found at `pos`, or a match result otherwise.
4093
4093
  */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
4094
- 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
4095
- // parent pointer
4096
- /// The default maximum length of a `TreeBuffer` node (1024).
4097
- 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)
4098
- /// can have metadata associated with it in props. Instances of this
4099
- /// class represent prop names.
4100
- class NodeProp{/// Create a new node prop type.
4101
- 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
4102
- /// [`NodeSet.extend`](#common.NodeSet.extend) or
4103
- /// [`LRParser.configure`](#lr.ParserConfig.props) to compute
4104
- /// prop values for each node type in the set. Takes a [match
4105
- /// object](#common.NodeType^match) or function that returns undefined
4106
- /// if the node type doesn't get this prop, and the prop's value if
4107
- /// it does.
4108
- 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
4109
- /// delimiters, this holds an array of node names (written as a
4110
- /// space-separated string when declaring this prop in a grammar)
4111
- /// for the node types of closing delimiters that match it.
4112
- NodeProp.closedBy=new NodeProp({deserialize:str=>str.split(" ")});/// The inverse of [`closedBy`](#common.NodeProp^closedBy). This is
4113
- /// attached to closing delimiters, holding an array of node names
4114
- /// of types of matching opening delimiters.
4115
- NodeProp.openedBy=new NodeProp({deserialize:str=>str.split(" ")});/// Used to assign node types to groups (for example, all node
4116
- /// types that represent an expression could be tagged with an
4117
- /// `"Expression"` group).
4118
- NodeProp.group=new NodeProp({deserialize:str=>str.split(" ")});/// The hash of the [context](#lr.ContextTracker.constructor)
4119
- /// that the node was parsed in, if any. Used to limit reuse of
4120
- /// contextual nodes.
4121
- NodeProp.contextHash=new NodeProp({perNode:true});/// The distance beyond the end of the node that the tokenizer
4122
- /// looked ahead for any of the tokens inside the node. (The LR
4123
- /// parser only stores this when it is larger than 25, for
4124
- /// efficiency reasons.)
4125
- NodeProp.lookAhead=new NodeProp({perNode:true});/// This per-node prop is used to replace a given node, or part of a
4126
- /// node, with another tree. This is useful to include trees from
4127
- /// different languages.
4128
- NodeProp.mounted=new NodeProp({perNode:true});const noProps=Object.create(null);/// Each node in a syntax tree has a node type associated with it.
4129
- class NodeType{/// @internal
4130
- constructor(/// The name of the node type. Not necessarily unique, but if the
4131
- /// grammar was written properly, different node types with the
4132
- /// same name within a node set should play the same semantic
4133
- /// role.
4134
- name,/// @internal
4135
- props,/// The id of this node in its set. Corresponds to the term ids
4136
- /// used in the parser.
4137
- id,/// @internal
4138
- 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
4139
- /// the prop isn't present on this node.
4140
- prop(prop){return this.props[prop.id];}/// True when this is the top node of a grammar.
4141
- get isTop(){return (this.flags&1/* Top */)>0;}/// True when this node is produced by a skip rule.
4142
- get isSkipped(){return (this.flags&2/* Skipped */)>0;}/// Indicates whether this is an error node.
4143
- get isError(){return (this.flags&4/* Error */)>0;}/// When true, this node type doesn't correspond to a user-declared
4144
- /// named node, for example because it is used to cache repetition.
4145
- get isAnonymous(){return (this.flags&8/* Anonymous */)>0;}/// Returns true when this node's name or one of its
4146
- /// [groups](#common.NodeProp^group) matches the given string.
4147
- 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
4148
- /// specifying an object whose property names are node or
4149
- /// [group](#common.NodeProp^group) names. Often useful with
4150
- /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple
4151
- /// names, separated by spaces, in a single property name to map
4152
- /// multiple node names to a single value.
4153
- 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.
4154
- NodeType.none=new NodeType("",Object.create(null),0,8/* Anonymous */);/// A node set holds a collection of node types. It is used to
4155
- /// compactly represent trees by storing their type ids, rather than a
4156
- /// full pointer to the type object, in a numeric array. Each parser
4157
- /// [has](#lr.LRParser.nodeSet) a node set, and [tree
4158
- /// buffers](#common.TreeBuffer) can only store collections of nodes
4159
- /// from the same set. A set can have a maximum of 2**16 (65536) node
4160
- /// types in it, so that the ids fit into 16-bit typed array slots.
4161
- class NodeSet{/// Create a set with the given types. The `id` property of each
4162
- /// type should correspond to its position within the array.
4163
- constructor(/// The node types in this set, by id.
4164
- 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
4165
- /// arguments to this method should be created with
4166
- /// [`NodeProp.add`](#common.NodeProp.add).
4167
- 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 `|`
4168
- /// operator to enable multiple ones.
4169
- var IterMode;(function(IterMode){/// When enabled, iteration will only visit [`Tree`](#common.Tree)
4170
- /// objects, not nodes packed into
4171
- /// [`TreeBuffer`](#common.TreeBuffer)s.
4172
- IterMode[IterMode["ExcludeBuffers"]=1]="ExcludeBuffers";/// Enable this to make iteration include anonymous nodes (such as
4173
- /// the nodes that wrap repeated grammar constructs into a balanced
4174
- /// tree).
4175
- IterMode[IterMode["IncludeAnonymous"]=2]="IncludeAnonymous";/// By default, regular [mounted](#common.NodeProp^mounted) nodes
4176
- /// replace their base node in iteration. Enable this to ignore them
4177
- /// instead.
4178
- IterMode[IterMode["IgnoreMounts"]=4]="IgnoreMounts";/// This option only applies in
4179
- /// [`enter`](#common.SyntaxNode.enter)-style methods. It tells the
4180
- /// library to not enter mounted overlays if one covers the given
4181
- /// position.
4182
- IterMode[IterMode["IgnoreOverlays"]=8]="IgnoreOverlays";})(IterMode||(IterMode={}));/// A piece of syntax tree. There are two ways to approach these
4183
- /// trees: the way they are actually stored in memory, and the
4184
- /// convenient way.
4185
- ///
4186
- /// Syntax trees are stored as a tree of `Tree` and `TreeBuffer`
4187
- /// objects. By packing detail information into `TreeBuffer` leaf
4188
- /// nodes, the representation is made a lot more memory-efficient.
4189
- ///
4190
- /// However, when you want to actually work with tree nodes, this
4191
- /// representation is very awkward, so most client code will want to
4192
- /// use the [`TreeCursor`](#common.TreeCursor) or
4193
- /// [`SyntaxNode`](#common.SyntaxNode) interface instead, which provides
4194
- /// a view on some part of this data structure, and can be used to
4195
- /// move around to adjacent nodes.
4196
- class Tree{/// Construct a new tree. See also [`Tree.build`](#common.Tree^build).
4197
- constructor(/// The type of the top node.
4198
- type,/// This node's child nodes.
4199
- children,/// The positions (offsets relative to the start of this tree) of
4200
- /// the children.
4201
- positions,/// The total length of this tree
4202
- length,/// Per-node [node props](#common.NodeProp) to associate with this node.
4203
- props){this.type=type;this.children=children;this.positions=positions;this.length=length;/// @internal
4204
- 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
4205
- 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
4206
- /// the tree. Mode can be used to [control](#common.IterMode) which
4207
- /// nodes the cursor visits.
4208
- cursor(mode=0){return new TreeCursor(this.topNode,mode);}/// Get a [tree cursor](#common.TreeCursor) pointing into this tree
4209
- /// at the given position and side (see
4210
- /// [`moveTo`](#common.TreeCursor.moveTo).
4211
- 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
4212
- /// tree.
4213
- get topNode(){return new TreeNode(this,0,0,null);}/// Get the [syntax node](#common.SyntaxNode) at the given position.
4214
- /// If `side` is -1, this will move into nodes that end at the
4215
- /// position. If 1, it'll move into nodes that start at the
4216
- /// position. With 0, it'll only enter nodes that cover the position
4217
- /// from both sides.
4218
- 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
4219
- /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
4220
- /// pointing into the innermost overlaid tree at the given position
4221
- /// (with parent links going through all parent structure, including
4222
- /// the host trees).
4223
- 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
4224
- /// node that touches the `from`/`to` region (if given) before
4225
- /// running over such a node's children, and `leave` (if given) when
4226
- /// leaving the node. When `enter` returns `false`, that node will
4227
- /// not have its children iterated over (or `leave` called).
4228
- 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
4229
- /// node. Works with both per-node and per-type props.
4230
- 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
4231
- /// format that can be passed to the [`Tree`](#common.Tree)
4232
- /// constructor.
4233
- 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
4234
- /// which may have children grouped into subtrees with type
4235
- /// [`NodeType.none`](#common.NodeType^none).
4236
- 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,
4237
- /// or a cursor over such a buffer.
4238
- static build(data){return buildTree(data);}}/// The empty tree
4239
- 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
4240
- /// node. In such a buffer, nodes are stored in prefix order (parents
4241
- /// before children, with the endIndex of the parent indicating which
4242
- /// children belong to it)
4243
- class TreeBuffer{/// Create a tree buffer.
4244
- constructor(/// The buffer's content.
4245
- buffer,/// The total length of the group of nodes in the buffer.
4246
- length,/// The node set used in this buffer.
4247
- set){this.buffer=buffer;this.length=length;this.set=set;}/// @internal
4248
- get type(){return NodeType.none;}/// @internal
4249
- 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
4250
- 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
4251
- 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
4252
- 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
4253
- 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
4254
- 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)
4255
- 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
4256
- 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
4257
- 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
4258
- /// allows you to move to adjacent nodes.
4259
- class TreeCursor{/// @internal
4260
- constructor(node,/// @internal
4261
- mode=0){this.mode=mode;/// @internal
4262
- this.buffer=null;this.stack=[];/// @internal
4263
- 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`.
4264
- 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
4265
- toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString();}/// @internal
4266
- 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
4267
- /// false, the node has no child, and the cursor has not been moved.
4268
- firstChild(){return this.enterChild(1,0,4/* DontCare */);}/// Move the cursor to this node's last child.
4269
- lastChild(){return this.enterChild(-1,0,4/* DontCare */);}/// Move the cursor to the first child that ends after `pos`.
4270
- childAfter(pos){return this.enterChild(1,pos,2/* After */);}/// Move to the last child that starts before `pos`.
4271
- childBefore(pos){return this.enterChild(-1,pos,-2/* Before */);}/// Move the cursor to the child around `pos`. If side is -1 the
4272
- /// child may end at that position, when 1 it may start there. This
4273
- /// will also enter [overlaid](#common.MountedTree.overlay)
4274
- /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is
4275
- /// set to false.
4276
- 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.
4277
- 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
4278
- 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.
4279
- nextSibling(){return this.sibling(1);}/// Move to this node's previous sibling, if any.
4280
- 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
4281
- /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR))
4282
- /// traversal, going from a node to its first child or, if the
4283
- /// current node is empty or `enter` is false, its next sibling or
4284
- /// the next sibling of the first parent node that has one.
4285
- next(enter=true){return this.move(1,enter);}/// Move to the next node in a last-to-first pre-order traveral. A
4286
- /// node is followed by its last child or, if it has none, its
4287
- /// previous sibling or the previous sibling of the first parent
4288
- /// node that has one.
4289
- prev(enter=true){return this.move(-1,enter);}/// Move the cursor to the innermost node that covers `pos`. If
4290
- /// `side` is -1, it will enter nodes that end at `pos`. If it is 1,
4291
- /// it will enter nodes that start at `pos`.
4292
- moveTo(pos,side=0){// Move up to a node that actually holds the position, if possible
4293
- 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
4294
- while(this.enterChild(1,pos,side)){}return this;}/// Get a [syntax node](#common.SyntaxNode) at the cursor's current
4295
- /// position.
4296
- 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
4297
- /// any. Will return null when the node is in a [tree
4298
- /// buffer](#common.TreeBuffer).
4299
- get tree(){return this.buffer?null:this._tree._tree;}/// Iterate over the current node and all its descendants, calling
4300
- /// `enter` when entering a node and `leave`, if given, when leaving
4301
- /// one. When `enter` returns `false`, any children of that node are
4302
- /// skipped, and `leave` isn't called for it.
4303
- 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
4304
- /// of direct parent node names. Empty strings in the context array
4305
- /// are treated as wildcards.
4306
- 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
4307
- 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
4308
- 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
4309
- 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
4310
- // together in a TreeBuffer, and don't contain any reused nodes
4311
- // (which can't be stored in a buffer).
4312
- // If `inRepeat` is > -1, ignore node boundaries of that type for
4313
- // nesting, but make sure the end falls either at the start
4314
- // (`maxSize`) or before such a node.
4315
- 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
4316
- if(fork.id==inRepeat&&nodeSize>=0){// Except that we store the current state as a valid return
4317
- // value.
4318
- 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.
4319
- balanceType,// The direct children and their positions
4320
- children,positions,// The index range in children/positions to use
4321
- from,to,// The start position of the nodes, relative to their parent.
4322
- start,// Length of the outer node
4323
- length,// Function to build the top node of the balanced tree
4324
- mkTop,// Function to build internal nodes for the balanced tree
4325
- 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
4326
- 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.
4327
- class Parser{/// Start a parse, returning a [partial parse](#common.PartialParse)
4328
- /// object. [`fragments`](#common.TreeFragment) can be passed in to
4329
- /// make the parse incremental.
4330
- ///
4331
- /// By default, the entire input is parsed. You can pass `ranges`,
4332
- /// which should be a sorted array of non-empty, non-overlapping
4333
- /// ranges, to parse only those ranges. The tree returned in that
4334
- /// case will start at `ranges[0].from`.
4335
- 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.
4336
- 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
4337
- /// parsing progress. They also provide some properties and methods
4338
- /// that external code such as a tokenizer can use to get information
4339
- /// about the parse state.
4340
- class Stack{/// @internal
4341
- constructor(/// The parse that this stack is part of @internal
4342
- p,/// Holds state, input pos, buffer index triplets for all but the
4343
- /// top state @internal
4344
- stack,/// The current parse state @internal
4345
- state,// The position at which the next reduce should take place. This
4346
- // can be less than `this.pos` when skipped expressions have been
4347
- // added to the stack (which should be moved outside of the next
4348
- // reduction)
4349
- /// @internal
4350
- reducePos,/// The input position up to which this stack has parsed.
4351
- pos,/// The dynamic score of the stack, including dynamic precedence
4352
- /// and error-recovery penalties
4353
- /// @internal
4354
- score,// The output buffer. Holds (type, start, end, size) quads
4355
- // representing nodes created by the parser, where `size` is
4356
- // amount of buffer array entries covered by this node.
4357
- /// @internal
4358
- buffer,// The base offset of the buffer. When stacks are split, the split
4359
- // instance shared the buffer history with its parent up to
4360
- // `bufferBase`, which is the absolute offset (including the
4361
- // offset of previous splits) into the buffer at which this stack
4362
- // starts writing.
4363
- /// @internal
4364
- bufferBase,/// @internal
4365
- curContext,/// @internal
4366
- lookAhead=0,// A parent stack from which this was split off, if any. This is
4367
- // set up so that it always points to a stack that has some
4368
- // additional buffer content, never to a stack with an equal
4369
- // `bufferBase`.
4370
- /// @internal
4371
- 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
4372
- toString(){return `[${this.stack.filter((_,i)=>i%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`;}// Start an empty stack
4373
- /// @internal
4374
- 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
4375
- /// any. Its type will depend on the context tracker's type
4376
- /// parameter, or it will be `null` if there is no context
4377
- /// tracker.
4378
- get context(){return this.curContext?this.curContext.context:null;}// Push a state onto the stack, tracking its start position as well
4379
- // as the buffer base at that point.
4380
- /// @internal
4381
- pushState(state,start){this.stack.push(this.state,start,this.bufferBase+this.buffer.length);this.state=state;}// Apply a reduce action
4382
- /// @internal
4383
- 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
4384
- // the stack without popping anything off.
4385
- 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
4386
- // be dropped. Note that with `StayFlag` reductions we need to
4387
- // consume two extra frames (the dummy parent node for the skipped
4388
- // expression and the state that we'll be staying in, which should
4389
- // be moved to `this.state`).
4390
- 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
4391
- 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
4392
- /// @internal
4393
- 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
4394
- 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
4395
- this.buffer.push(term,start,end,size);}else {// There may be skipped nodes that have to be moved forward
4396
- 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
4397
- 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
4398
- /// @internal
4399
- 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
4400
- 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
4401
- this.pos=nextEnd;this.shiftContext(next,start);if(next<=this.p.parser.maxNode)this.buffer.push(next,start,nextEnd,4);}}// Apply an action
4402
- /// @internal
4403
- 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.
4404
- /// @internal
4405
- 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
4406
- // that `this.stack` tends to stay quite shallow, this isn't very
4407
- // expensive.
4408
- /// @internal
4409
- split(){let parent=this;let off=parent.buffer.length;// Because the top of the buffer (after this.pos) may be mutated
4410
- // to reorder reductions and skipped tokens, and shared buffers
4411
- // should be immutable, this copies any outstanding skipped tokens
4412
- // to the new buffer, and puts the base pointer before them.
4413
- 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.
4414
- 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.
4415
- /// @internal
4416
- 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
4417
- /// after some reductions) on this stack. This can be useful for
4418
- /// external tokenizers that want to make sure they only provide a
4419
- /// given token when it applies.
4420
- 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
4421
- // inserts some missing token or rule.
4422
- /// @internal
4423
- 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
4424
- // be done.
4425
- /// @internal
4426
- 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
4427
- 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
4428
- /// top state, since any other states must be able to continue
4429
- /// somehow). @internal
4430
- 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
4431
- /// when this.stack.length == 3 (state is directly below the top
4432
- /// state). @internal
4433
- restart(){this.state=this.stack[0];this.stack.length=0;}/// @internal
4434
- 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.
4435
- get parser(){return this.p.parser;}/// Test whether a given dialect (by numeric ID, as exported from
4436
- /// the terms file) is enabled.
4437
- 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
4438
- 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
4439
- 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
4440
- setLookAhead(lookAhead){if(lookAhead>this.lookAhead){this.emitLookAhead();this.lookAhead=lookAhead;}}/// @internal
4441
- 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
4442
- // an entire stack
4443
- 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
4444
- // the parent-stack-walking necessary to read the nodes.
4445
- 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
4446
- /// through this interface. It presents the input as a stream of
4447
- /// characters, tracking lookahead and hiding the complexity of
4448
- /// [ranges](#common.Parser.parse^ranges) from tokenizer code.
4449
- class InputStream{/// @internal
4450
- constructor(/// @internal
4451
- input,/// @internal
4452
- ranges){this.input=input;this.ranges=ranges;/// @internal
4453
- this.chunk="";/// @internal
4454
- this.chunkOff=0;/// Backup chunk
4455
- this.chunk2="";this.chunk2Pos=0;/// The character code of the next code unit in the input, or -1
4456
- /// when the stream is at the end of the input.
4457
- this.next=-1;/// @internal
4458
- 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
4459
- /// `.next`, `.peek(-1)` gives you the previous character, and so
4460
- /// on.
4461
- ///
4462
- /// Note that looking around during tokenizing creates dependencies
4463
- /// on potentially far-away content, which may reduce the
4464
- /// effectiveness incremental parsing—when looking forward—or even
4465
- /// cause invalid reparses when looking backward more than 25 code
4466
- /// units, since the library does not track lookbehind.
4467
- 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
4468
- /// current stream position, but you can pass an offset (relative to
4469
- /// the stream position) to change that.
4470
- 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
4471
- /// the new value of [`next`](#lr.InputStream.next).
4472
- 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
4473
- 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
4474
- 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
4475
- 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
4476
- // state:
4477
- //
4478
- // - A group bitmask, indicating what token groups are reachable from
4479
- // this state, so that paths that can only lead to tokens not in
4480
- // any of the current groups can be cut off early.
4481
- //
4482
- // - The position of the end of the state's sequence of accepting
4483
- // tokens
4484
- //
4485
- // - The number of outgoing edges for the state
4486
- //
4487
- // - The accepting tokens, as (token id, group mask) pairs
4488
- //
4489
- // - The outgoing edges, as (start character, end character, state
4490
- // index) triples, with end character being exclusive
4491
- //
4492
- // This function interprets that data, running through a stream as
4493
- // long as new states with the a matching group mask can be reached,
4494
- // and updating `token` when it matches a token.
4495
- 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
4496
- // Accept tokens in this state, possibly overwriting
4497
- // lower-precedence / shorter tokens
4498
- 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
4499
- 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
4500
- // used here
4501
- 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
4502
- 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
4503
- 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
4504
- 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
4505
- 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
4506
- 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
4507
- // add this many elements to their buffers, prune one.
4508
- Rec[Rec["MinBufferLengthPrune"]=500]="MinBufferLengthPrune";Rec[Rec["ForceReduceLimit"]=10]="ForceReduceLimit";// Once a stack reaches this depth (in .stack.length) force-reduce
4509
- // it back to CutTo to avoid creating trees that overflow the stack
4510
- // on recursive traversal.
4511
- 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;// ♔, ♕, ♖, ♗, ♘, ♙, ♠, ♡, ♢, ♣, ♤, ♥, ♦, ♧
4512
- 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
4513
- // `this.pos` and try to advance them to a further position. If no
4514
- // stack for such a position is found, it'll start error-recovery.
4515
- //
4516
- // When the parse is finished, this will return a syntax tree. When
4517
- // not, it returns `null`.
4518
- advance(){let stacks=this.stacks,pos=this.minStackPos;// This will hold stacks beyond `pos`.
4519
- let newStacks=this.stacks=[];let stopped,stoppedTokens;// Keep advancing any stacks at `pos` until they either move
4520
- // forward or can't be advanced. Gather stacks that can't be
4521
- // advanced further in `stopped`.
4522
- 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
4523
- // running without splitting for a while, to avoid getting stuck
4524
- // with multiple successful stacks running endlessly on.
4525
- 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
4526
- // stack can't advance normally. When `split` and `stacks` are
4527
- // given, stacks split off by ambiguous operations will be pushed to
4528
- // `split`, or added to `stacks` if they move `pos` forward.
4529
- 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
4530
- // (possibly updated) stack if it got stuck, or null if it moved
4531
- // forward and was given to `pushStackDedup`.
4532
- 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.
4533
- 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
4534
- /// by `lezer-generator`.
4535
- class LRParser extends Parser{/// @internal
4536
- constructor(spec){super();/// @internal
4537
- 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
4538
- 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
4539
- 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
4540
- stateSlot(state,slot){return this.states[state*6/* Size */+slot];}/// @internal
4541
- stateFlag(state,flag){return (this.stateSlot(state,0/* Flags */)&flag)>0;}/// @internal
4542
- 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
4543
- /// goto jumps. @internal
4544
- 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
4545
- 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
4546
- /// given settings modified. Settings not provided in `config` are
4547
- /// kept from the original parser.
4548
- configure(config){// Hideous reflection-based kludge to make it easy to create a
4549
- // slightly modified copy of a parser.
4550
- 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)
4551
- /// are registered for this parser.
4552
- hasWrappers(){return this.wrappers.length>0;}/// Returns the name associated with a given term. This will only
4553
- /// work for all terms when the parser was generated with the
4554
- /// `--names` option. By default, only the names of tagged terms are
4555
- /// stored.
4556
- 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
4557
- /// types. @internal
4558
- get eofTerm(){return this.maxNode+1;}/// The type of top node produced by the parser.
4559
- get topNode(){return this.nodeSet.types[this.top[1]];}/// @internal
4560
- dynamicPrecedence(term){let prec=this.dynamicPrecedences;return prec==null?0:prec[term]||0;}/// @internal
4561
- 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
4562
- 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.
4563
- 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'#G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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,[]);}/**
4094
+ 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;}/**
4564
4095
  Comment or uncomment the current selection. Will use line comments
4565
4096
  if available, otherwise falling back to block comments.
4566
4097
  */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;};}/**
@@ -4817,8 +4348,7 @@ this.moveSelection((this.selectedIndex+1)%this.items.length);}else if(event.keyC
4817
4348
  this.moveSelection(0);}else if(event.keyCode==35){// End
4818
4349
  this.moveSelection(this.items.length-1);}else if(event.keyCode==13){// Enter
4819
4350
  this.view.focus();}else if(event.keyCode>=65&&event.keyCode<=90&&this.selectedIndex>=0){// A-Z
4820
- 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
4821
- 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];/**
4351
+ 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}}});/**
4822
4352
  An instance of this is passed to completion source functions.
4823
4353
  */class CompletionContext{/**
4824
4354
  Create a new completion context. (Mostly useful for testing
@@ -4867,78 +4397,551 @@ this.any=[];this.precise=[];this.byWord=[];for(let p=0;p<pattern.length;){let ch
4867
4397
  // with the match score, followed by any number of `from, to` pairs
4868
4398
  // indicating the matched parts of `word`.
4869
4399
  //
4870
- // The score is a number that is more negative the worse the match
4871
- // is. See `Penalty` above.
4872
- 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
4873
- // at the start
4874
- 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
4875
- if(anyTo<len)return null;}// This tracks the extent of the precise (non-folded, not
4876
- // necessarily adjacent) match
4877
- let preciseTo=0;// Tracks whether there is a match that hits only characters that
4878
- // appear to be starting words. `byWordFolded` is set to true when
4879
- // a case folded character is encountered in such a match
4880
- let byWordTo=0,byWordFolded=false;// If we've found a partial adjacent match, these track its state
4881
- 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
4882
- 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
4883
- // changes to force redrawing/repositioning of the tooltip
4884
- 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
4885
- // label occur in the result.
4886
- 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;/**
4887
- Returns a command that moves the completion selection forward or
4888
- backward by the given amount.
4889
- */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;};}/**
4890
- Accept the current completion.
4891
- */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;};/**
4892
- Explicitly start autocompletion.
4893
- */const startCompletion=view=>{let cState=view.state.field(completionState,false);if(!cState)return false;view.dispatch({effects:startCompletionEffect.of(true)});return true;};/**
4894
- Close the currently active completion.
4895
- */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
4896
- // 'query returned null'.
4897
- 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
4898
- // or, if appropriate, restart the query.
4899
- 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
4900
- // the request and see if that preserves the result
4901
- 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
4902
- // hasn't been re-set in the meantime.
4903
- 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.
4904
- 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
4905
- // from inside an update, so dispatch asynchronously to avoid reentrancy
4906
- 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
4907
- },".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;/**
4908
- Returns an extension that enables autocompletion.
4909
- */function autocompletion$1(config={}){return [completionState,completionConfig.of(config),completionPlugin,completionKeymapExt,baseTheme];}/**
4910
- Basic keybindings for autocompletion.
4911
-
4912
- - Ctrl-Space: [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion)
4913
- - Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion)
4914
- - ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)`
4915
- - ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)`
4916
- - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
4917
- - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
4918
- - Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion)
4919
- */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
4920
- let nodeBefore=syntaxTree(context.state).resolve(context.pos,-1);// For the special case of empty nodes, we need to check the current node
4921
- // as well. The previous node could be part of another token, e.g.
4922
- // when typing functions "abs(".
4923
- 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
4924
- if(nodeBefore.name!=='VariableName'){return null;}return result;};// helpers ///////////////////////////////
4925
- function isNodeEmpty(node){return node.from===node.to;}function autocompletion(context){return [autocompletion$1({override:[variables(context)]})];}/**
4400
+ // The score is a number that is more negative the worse the match
4401
+ // is. See `Penalty` above.
4402
+ 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
4403
+ // at the start
4404
+ 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
4405
+ if(anyTo<len)return null;}// This tracks the extent of the precise (non-folded, not
4406
+ // necessarily adjacent) match
4407
+ let preciseTo=0;// Tracks whether there is a match that hits only characters that
4408
+ // appear to be starting words. `byWordFolded` is set to true when
4409
+ // a case folded character is encountered in such a match
4410
+ let byWordTo=0,byWordFolded=false;// If we've found a partial adjacent match, these track its state
4411
+ 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
4412
+ 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
4413
+ // changes to force redrawing/repositioning of the tooltip
4414
+ 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
4415
+ // label occur in the result.
4416
+ 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;/**
4417
+ Returns a command that moves the completion selection forward or
4418
+ backward by the given amount.
4419
+ */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;};}/**
4420
+ Accept the current completion.
4421
+ */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;};/**
4422
+ Explicitly start autocompletion.
4423
+ */const startCompletion=view=>{let cState=view.state.field(completionState,false);if(!cState)return false;view.dispatch({effects:startCompletionEffect.of(true)});return true;};/**
4424
+ Close the currently active completion.
4425
+ */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
4426
+ // 'query returned null'.
4427
+ 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
4428
+ // or, if appropriate, restart the query.
4429
+ 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
4430
+ // the request and see if that preserves the result
4431
+ 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
4432
+ // hasn't been re-set in the meantime.
4433
+ 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.
4434
+ 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
4435
+ // from inside an update, so dispatch asynchronously to avoid reentrancy
4436
+ 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
4437
+ },".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;/**
4438
+ Returns an extension that enables autocompletion.
4439
+ */function autocompletion$1(config={}){return [completionState,completionConfig.of(config),completionPlugin,completionKeymapExt,baseTheme$1];}/**
4440
+ Basic keybindings for autocompletion.
4441
+
4442
+ - Ctrl-Space: [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion)
4443
+ - Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion)
4444
+ - ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)`
4445
+ - ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)`
4446
+ - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
4447
+ - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
4448
+ - Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion)
4449
+ */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
4450
+ let nodeBefore=syntaxTree(context.state).resolve(context.pos,-1);// For the special case of empty nodes, we need to check the current node
4451
+ // as well. The previous node could be part of another token, e.g.
4452
+ // when typing functions "abs(".
4453
+ 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
4454
+ if(nodeBefore.name!=='VariableName'){return null;}return result;};// helpers ///////////////////////////////
4455
+ 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
4456
+ // parent pointer
4457
+ /// The default maximum length of a `TreeBuffer` node (1024).
4458
+ 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)
4459
+ /// can have metadata associated with it in props. Instances of this
4460
+ /// class represent prop names.
4461
+ class NodeProp{/// Create a new node prop type.
4462
+ 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
4463
+ /// [`NodeSet.extend`](#common.NodeSet.extend) or
4464
+ /// [`LRParser.configure`](#lr.ParserConfig.props) to compute
4465
+ /// prop values for each node type in the set. Takes a [match
4466
+ /// object](#common.NodeType^match) or function that returns undefined
4467
+ /// if the node type doesn't get this prop, and the prop's value if
4468
+ /// it does.
4469
+ 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
4470
+ /// delimiters, this holds an array of node names (written as a
4471
+ /// space-separated string when declaring this prop in a grammar)
4472
+ /// for the node types of closing delimiters that match it.
4473
+ NodeProp.closedBy=new NodeProp({deserialize:str=>str.split(" ")});/// The inverse of [`closedBy`](#common.NodeProp^closedBy). This is
4474
+ /// attached to closing delimiters, holding an array of node names
4475
+ /// of types of matching opening delimiters.
4476
+ NodeProp.openedBy=new NodeProp({deserialize:str=>str.split(" ")});/// Used to assign node types to groups (for example, all node
4477
+ /// types that represent an expression could be tagged with an
4478
+ /// `"Expression"` group).
4479
+ NodeProp.group=new NodeProp({deserialize:str=>str.split(" ")});/// The hash of the [context](#lr.ContextTracker.constructor)
4480
+ /// that the node was parsed in, if any. Used to limit reuse of
4481
+ /// contextual nodes.
4482
+ NodeProp.contextHash=new NodeProp({perNode:true});/// The distance beyond the end of the node that the tokenizer
4483
+ /// looked ahead for any of the tokens inside the node. (The LR
4484
+ /// parser only stores this when it is larger than 25, for
4485
+ /// efficiency reasons.)
4486
+ NodeProp.lookAhead=new NodeProp({perNode:true});/// This per-node prop is used to replace a given node, or part of a
4487
+ /// node, with another tree. This is useful to include trees from
4488
+ /// different languages.
4489
+ NodeProp.mounted=new NodeProp({perNode:true});const noProps=Object.create(null);/// Each node in a syntax tree has a node type associated with it.
4490
+ class NodeType{/// @internal
4491
+ constructor(/// The name of the node type. Not necessarily unique, but if the
4492
+ /// grammar was written properly, different node types with the
4493
+ /// same name within a node set should play the same semantic
4494
+ /// role.
4495
+ name,/// @internal
4496
+ props,/// The id of this node in its set. Corresponds to the term ids
4497
+ /// used in the parser.
4498
+ id,/// @internal
4499
+ 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
4500
+ /// the prop isn't present on this node.
4501
+ prop(prop){return this.props[prop.id];}/// True when this is the top node of a grammar.
4502
+ get isTop(){return (this.flags&1/* Top */)>0;}/// True when this node is produced by a skip rule.
4503
+ get isSkipped(){return (this.flags&2/* Skipped */)>0;}/// Indicates whether this is an error node.
4504
+ get isError(){return (this.flags&4/* Error */)>0;}/// When true, this node type doesn't correspond to a user-declared
4505
+ /// named node, for example because it is used to cache repetition.
4506
+ get isAnonymous(){return (this.flags&8/* Anonymous */)>0;}/// Returns true when this node's name or one of its
4507
+ /// [groups](#common.NodeProp^group) matches the given string.
4508
+ 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
4509
+ /// specifying an object whose property names are node or
4510
+ /// [group](#common.NodeProp^group) names. Often useful with
4511
+ /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple
4512
+ /// names, separated by spaces, in a single property name to map
4513
+ /// multiple node names to a single value.
4514
+ 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.
4515
+ NodeType.none=new NodeType("",Object.create(null),0,8/* Anonymous */);/// A node set holds a collection of node types. It is used to
4516
+ /// compactly represent trees by storing their type ids, rather than a
4517
+ /// full pointer to the type object, in a numeric array. Each parser
4518
+ /// [has](#lr.LRParser.nodeSet) a node set, and [tree
4519
+ /// buffers](#common.TreeBuffer) can only store collections of nodes
4520
+ /// from the same set. A set can have a maximum of 2**16 (65536) node
4521
+ /// types in it, so that the ids fit into 16-bit typed array slots.
4522
+ class NodeSet{/// Create a set with the given types. The `id` property of each
4523
+ /// type should correspond to its position within the array.
4524
+ constructor(/// The node types in this set, by id.
4525
+ 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
4526
+ /// arguments to this method should be created with
4527
+ /// [`NodeProp.add`](#common.NodeProp.add).
4528
+ 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 `|`
4529
+ /// operator to enable multiple ones.
4530
+ var IterMode;(function(IterMode){/// When enabled, iteration will only visit [`Tree`](#common.Tree)
4531
+ /// objects, not nodes packed into
4532
+ /// [`TreeBuffer`](#common.TreeBuffer)s.
4533
+ IterMode[IterMode["ExcludeBuffers"]=1]="ExcludeBuffers";/// Enable this to make iteration include anonymous nodes (such as
4534
+ /// the nodes that wrap repeated grammar constructs into a balanced
4535
+ /// tree).
4536
+ IterMode[IterMode["IncludeAnonymous"]=2]="IncludeAnonymous";/// By default, regular [mounted](#common.NodeProp^mounted) nodes
4537
+ /// replace their base node in iteration. Enable this to ignore them
4538
+ /// instead.
4539
+ IterMode[IterMode["IgnoreMounts"]=4]="IgnoreMounts";/// This option only applies in
4540
+ /// [`enter`](#common.SyntaxNode.enter)-style methods. It tells the
4541
+ /// library to not enter mounted overlays if one covers the given
4542
+ /// position.
4543
+ IterMode[IterMode["IgnoreOverlays"]=8]="IgnoreOverlays";})(IterMode||(IterMode={}));/// A piece of syntax tree. There are two ways to approach these
4544
+ /// trees: the way they are actually stored in memory, and the
4545
+ /// convenient way.
4546
+ ///
4547
+ /// Syntax trees are stored as a tree of `Tree` and `TreeBuffer`
4548
+ /// objects. By packing detail information into `TreeBuffer` leaf
4549
+ /// nodes, the representation is made a lot more memory-efficient.
4550
+ ///
4551
+ /// However, when you want to actually work with tree nodes, this
4552
+ /// representation is very awkward, so most client code will want to
4553
+ /// use the [`TreeCursor`](#common.TreeCursor) or
4554
+ /// [`SyntaxNode`](#common.SyntaxNode) interface instead, which provides
4555
+ /// a view on some part of this data structure, and can be used to
4556
+ /// move around to adjacent nodes.
4557
+ class Tree{/// Construct a new tree. See also [`Tree.build`](#common.Tree^build).
4558
+ constructor(/// The type of the top node.
4559
+ type,/// This node's child nodes.
4560
+ children,/// The positions (offsets relative to the start of this tree) of
4561
+ /// the children.
4562
+ positions,/// The total length of this tree
4563
+ length,/// Per-node [node props](#common.NodeProp) to associate with this node.
4564
+ props){this.type=type;this.children=children;this.positions=positions;this.length=length;/// @internal
4565
+ 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
4566
+ 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
4567
+ /// the tree. Mode can be used to [control](#common.IterMode) which
4568
+ /// nodes the cursor visits.
4569
+ cursor(mode=0){return new TreeCursor(this.topNode,mode);}/// Get a [tree cursor](#common.TreeCursor) pointing into this tree
4570
+ /// at the given position and side (see
4571
+ /// [`moveTo`](#common.TreeCursor.moveTo).
4572
+ 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
4573
+ /// tree.
4574
+ get topNode(){return new TreeNode(this,0,0,null);}/// Get the [syntax node](#common.SyntaxNode) at the given position.
4575
+ /// If `side` is -1, this will move into nodes that end at the
4576
+ /// position. If 1, it'll move into nodes that start at the
4577
+ /// position. With 0, it'll only enter nodes that cover the position
4578
+ /// from both sides.
4579
+ 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
4580
+ /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
4581
+ /// pointing into the innermost overlaid tree at the given position
4582
+ /// (with parent links going through all parent structure, including
4583
+ /// the host trees).
4584
+ 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
4585
+ /// node that touches the `from`/`to` region (if given) before
4586
+ /// running over such a node's children, and `leave` (if given) when
4587
+ /// leaving the node. When `enter` returns `false`, that node will
4588
+ /// not have its children iterated over (or `leave` called).
4589
+ 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
4590
+ /// node. Works with both per-node and per-type props.
4591
+ 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
4592
+ /// format that can be passed to the [`Tree`](#common.Tree)
4593
+ /// constructor.
4594
+ 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
4595
+ /// which may have children grouped into subtrees with type
4596
+ /// [`NodeType.none`](#common.NodeType^none).
4597
+ 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,
4598
+ /// or a cursor over such a buffer.
4599
+ static build(data){return buildTree(data);}}/// The empty tree
4600
+ 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
4601
+ /// node. In such a buffer, nodes are stored in prefix order (parents
4602
+ /// before children, with the endIndex of the parent indicating which
4603
+ /// children belong to it)
4604
+ class TreeBuffer{/// Create a tree buffer.
4605
+ constructor(/// The buffer's content.
4606
+ buffer,/// The total length of the group of nodes in the buffer.
4607
+ length,/// The node set used in this buffer.
4608
+ set){this.buffer=buffer;this.length=length;this.set=set;}/// @internal
4609
+ get type(){return NodeType.none;}/// @internal
4610
+ 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
4611
+ 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
4612
+ 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
4613
+ 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
4614
+ 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
4615
+ 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)
4616
+ 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
4617
+ 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
4618
+ 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
4619
+ /// allows you to move to adjacent nodes.
4620
+ class TreeCursor{/// @internal
4621
+ constructor(node,/// @internal
4622
+ mode=0){this.mode=mode;/// @internal
4623
+ this.buffer=null;this.stack=[];/// @internal
4624
+ 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`.
4625
+ 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
4626
+ toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString();}/// @internal
4627
+ 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
4628
+ /// false, the node has no child, and the cursor has not been moved.
4629
+ firstChild(){return this.enterChild(1,0,4/* DontCare */);}/// Move the cursor to this node's last child.
4630
+ lastChild(){return this.enterChild(-1,0,4/* DontCare */);}/// Move the cursor to the first child that ends after `pos`.
4631
+ childAfter(pos){return this.enterChild(1,pos,2/* After */);}/// Move to the last child that starts before `pos`.
4632
+ childBefore(pos){return this.enterChild(-1,pos,-2/* Before */);}/// Move the cursor to the child around `pos`. If side is -1 the
4633
+ /// child may end at that position, when 1 it may start there. This
4634
+ /// will also enter [overlaid](#common.MountedTree.overlay)
4635
+ /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is
4636
+ /// set to false.
4637
+ 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.
4638
+ 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
4639
+ 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.
4640
+ nextSibling(){return this.sibling(1);}/// Move to this node's previous sibling, if any.
4641
+ 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
4642
+ /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR))
4643
+ /// traversal, going from a node to its first child or, if the
4644
+ /// current node is empty or `enter` is false, its next sibling or
4645
+ /// the next sibling of the first parent node that has one.
4646
+ next(enter=true){return this.move(1,enter);}/// Move to the next node in a last-to-first pre-order traveral. A
4647
+ /// node is followed by its last child or, if it has none, its
4648
+ /// previous sibling or the previous sibling of the first parent
4649
+ /// node that has one.
4650
+ prev(enter=true){return this.move(-1,enter);}/// Move the cursor to the innermost node that covers `pos`. If
4651
+ /// `side` is -1, it will enter nodes that end at `pos`. If it is 1,
4652
+ /// it will enter nodes that start at `pos`.
4653
+ moveTo(pos,side=0){// Move up to a node that actually holds the position, if possible
4654
+ 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
4655
+ while(this.enterChild(1,pos,side)){}return this;}/// Get a [syntax node](#common.SyntaxNode) at the cursor's current
4656
+ /// position.
4657
+ 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
4658
+ /// any. Will return null when the node is in a [tree
4659
+ /// buffer](#common.TreeBuffer).
4660
+ get tree(){return this.buffer?null:this._tree._tree;}/// Iterate over the current node and all its descendants, calling
4661
+ /// `enter` when entering a node and `leave`, if given, when leaving
4662
+ /// one. When `enter` returns `false`, any children of that node are
4663
+ /// skipped, and `leave` isn't called for it.
4664
+ 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
4665
+ /// of direct parent node names. Empty strings in the context array
4666
+ /// are treated as wildcards.
4667
+ 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
4668
+ 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
4669
+ 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
4670
+ 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
4671
+ // together in a TreeBuffer, and don't contain any reused nodes
4672
+ // (which can't be stored in a buffer).
4673
+ // If `inRepeat` is > -1, ignore node boundaries of that type for
4674
+ // nesting, but make sure the end falls either at the start
4675
+ // (`maxSize`) or before such a node.
4676
+ 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
4677
+ if(fork.id==inRepeat&&nodeSize>=0){// Except that we store the current state as a valid return
4678
+ // value.
4679
+ 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.
4680
+ balanceType,// The direct children and their positions
4681
+ children,positions,// The index range in children/positions to use
4682
+ from,to,// The start position of the nodes, relative to their parent.
4683
+ start,// Length of the outer node
4684
+ length,// Function to build the top node of the balanced tree
4685
+ mkTop,// Function to build internal nodes for the balanced tree
4686
+ 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
4687
+ 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.
4688
+ class Parser{/// Start a parse, returning a [partial parse](#common.PartialParse)
4689
+ /// object. [`fragments`](#common.TreeFragment) can be passed in to
4690
+ /// make the parse incremental.
4691
+ ///
4692
+ /// By default, the entire input is parsed. You can pass `ranges`,
4693
+ /// which should be a sorted array of non-empty, non-overlapping
4694
+ /// ranges, to parse only those ranges. The tree returned in that
4695
+ /// case will start at `ranges[0].from`.
4696
+ 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.
4697
+ 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
4698
+ /// parsing progress. They also provide some properties and methods
4699
+ /// that external code such as a tokenizer can use to get information
4700
+ /// about the parse state.
4701
+ class Stack{/// @internal
4702
+ constructor(/// The parse that this stack is part of @internal
4703
+ p,/// Holds state, input pos, buffer index triplets for all but the
4704
+ /// top state @internal
4705
+ stack,/// The current parse state @internal
4706
+ state,// The position at which the next reduce should take place. This
4707
+ // can be less than `this.pos` when skipped expressions have been
4708
+ // added to the stack (which should be moved outside of the next
4709
+ // reduction)
4710
+ /// @internal
4711
+ reducePos,/// The input position up to which this stack has parsed.
4712
+ pos,/// The dynamic score of the stack, including dynamic precedence
4713
+ /// and error-recovery penalties
4714
+ /// @internal
4715
+ score,// The output buffer. Holds (type, start, end, size) quads
4716
+ // representing nodes created by the parser, where `size` is
4717
+ // amount of buffer array entries covered by this node.
4718
+ /// @internal
4719
+ buffer,// The base offset of the buffer. When stacks are split, the split
4720
+ // instance shared the buffer history with its parent up to
4721
+ // `bufferBase`, which is the absolute offset (including the
4722
+ // offset of previous splits) into the buffer at which this stack
4723
+ // starts writing.
4724
+ /// @internal
4725
+ bufferBase,/// @internal
4726
+ curContext,/// @internal
4727
+ lookAhead=0,// A parent stack from which this was split off, if any. This is
4728
+ // set up so that it always points to a stack that has some
4729
+ // additional buffer content, never to a stack with an equal
4730
+ // `bufferBase`.
4731
+ /// @internal
4732
+ 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
4733
+ toString(){return `[${this.stack.filter((_,i)=>i%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`;}// Start an empty stack
4734
+ /// @internal
4735
+ 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
4736
+ /// any. Its type will depend on the context tracker's type
4737
+ /// parameter, or it will be `null` if there is no context
4738
+ /// tracker.
4739
+ get context(){return this.curContext?this.curContext.context:null;}// Push a state onto the stack, tracking its start position as well
4740
+ // as the buffer base at that point.
4741
+ /// @internal
4742
+ pushState(state,start){this.stack.push(this.state,start,this.bufferBase+this.buffer.length);this.state=state;}// Apply a reduce action
4743
+ /// @internal
4744
+ 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
4745
+ // the stack without popping anything off.
4746
+ 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
4747
+ // be dropped. Note that with `StayFlag` reductions we need to
4748
+ // consume two extra frames (the dummy parent node for the skipped
4749
+ // expression and the state that we'll be staying in, which should
4750
+ // be moved to `this.state`).
4751
+ 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
4752
+ 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
4753
+ /// @internal
4754
+ 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
4755
+ 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
4756
+ this.buffer.push(term,start,end,size);}else {// There may be skipped nodes that have to be moved forward
4757
+ 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
4758
+ 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
4759
+ /// @internal
4760
+ 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
4761
+ 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
4762
+ this.pos=nextEnd;this.shiftContext(next,start);if(next<=this.p.parser.maxNode)this.buffer.push(next,start,nextEnd,4);}}// Apply an action
4763
+ /// @internal
4764
+ 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.
4765
+ /// @internal
4766
+ 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
4767
+ // that `this.stack` tends to stay quite shallow, this isn't very
4768
+ // expensive.
4769
+ /// @internal
4770
+ split(){let parent=this;let off=parent.buffer.length;// Because the top of the buffer (after this.pos) may be mutated
4771
+ // to reorder reductions and skipped tokens, and shared buffers
4772
+ // should be immutable, this copies any outstanding skipped tokens
4773
+ // to the new buffer, and puts the base pointer before them.
4774
+ 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.
4775
+ 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.
4776
+ /// @internal
4777
+ 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
4778
+ /// after some reductions) on this stack. This can be useful for
4779
+ /// external tokenizers that want to make sure they only provide a
4780
+ /// given token when it applies.
4781
+ 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
4782
+ // inserts some missing token or rule.
4783
+ /// @internal
4784
+ 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
4785
+ // be done.
4786
+ /// @internal
4787
+ 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
4788
+ 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
4789
+ /// top state, since any other states must be able to continue
4790
+ /// somehow). @internal
4791
+ 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
4792
+ /// when this.stack.length == 3 (state is directly below the top
4793
+ /// state). @internal
4794
+ restart(){this.state=this.stack[0];this.stack.length=0;}/// @internal
4795
+ 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.
4796
+ get parser(){return this.p.parser;}/// Test whether a given dialect (by numeric ID, as exported from
4797
+ /// the terms file) is enabled.
4798
+ 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
4799
+ 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
4800
+ 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
4801
+ setLookAhead(lookAhead){if(lookAhead>this.lookAhead){this.emitLookAhead();this.lookAhead=lookAhead;}}/// @internal
4802
+ 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
4803
+ // an entire stack
4804
+ 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
4805
+ // the parent-stack-walking necessary to read the nodes.
4806
+ 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
4807
+ /// through this interface. It presents the input as a stream of
4808
+ /// characters, tracking lookahead and hiding the complexity of
4809
+ /// [ranges](#common.Parser.parse^ranges) from tokenizer code.
4810
+ class InputStream{/// @internal
4811
+ constructor(/// @internal
4812
+ input,/// @internal
4813
+ ranges){this.input=input;this.ranges=ranges;/// @internal
4814
+ this.chunk="";/// @internal
4815
+ this.chunkOff=0;/// Backup chunk
4816
+ this.chunk2="";this.chunk2Pos=0;/// The character code of the next code unit in the input, or -1
4817
+ /// when the stream is at the end of the input.
4818
+ this.next=-1;/// @internal
4819
+ 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
4820
+ /// `.next`, `.peek(-1)` gives you the previous character, and so
4821
+ /// on.
4822
+ ///
4823
+ /// Note that looking around during tokenizing creates dependencies
4824
+ /// on potentially far-away content, which may reduce the
4825
+ /// effectiveness incremental parsing—when looking forward—or even
4826
+ /// cause invalid reparses when looking backward more than 25 code
4827
+ /// units, since the library does not track lookbehind.
4828
+ 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
4829
+ /// current stream position, but you can pass an offset (relative to
4830
+ /// the stream position) to change that.
4831
+ 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
4832
+ /// the new value of [`next`](#lr.InputStream.next).
4833
+ 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
4834
+ 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
4835
+ 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
4836
+ 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
4837
+ // state:
4838
+ //
4839
+ // - A group bitmask, indicating what token groups are reachable from
4840
+ // this state, so that paths that can only lead to tokens not in
4841
+ // any of the current groups can be cut off early.
4842
+ //
4843
+ // - The position of the end of the state's sequence of accepting
4844
+ // tokens
4845
+ //
4846
+ // - The number of outgoing edges for the state
4847
+ //
4848
+ // - The accepting tokens, as (token id, group mask) pairs
4849
+ //
4850
+ // - The outgoing edges, as (start character, end character, state
4851
+ // index) triples, with end character being exclusive
4852
+ //
4853
+ // This function interprets that data, running through a stream as
4854
+ // long as new states with the a matching group mask can be reached,
4855
+ // and updating `token` when it matches a token.
4856
+ 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
4857
+ // Accept tokens in this state, possibly overwriting
4858
+ // lower-precedence / shorter tokens
4859
+ 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
4860
+ 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
4861
+ // used here
4862
+ 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
4863
+ 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
4864
+ 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
4865
+ 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
4866
+ 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
4867
+ 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
4868
+ // add this many elements to their buffers, prune one.
4869
+ Rec[Rec["MinBufferLengthPrune"]=500]="MinBufferLengthPrune";Rec[Rec["ForceReduceLimit"]=10]="ForceReduceLimit";// Once a stack reaches this depth (in .stack.length) force-reduce
4870
+ // it back to CutTo to avoid creating trees that overflow the stack
4871
+ // on recursive traversal.
4872
+ 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;// ♔, ♕, ♖, ♗, ♘, ♙, ♠, ♡, ♢, ♣, ♤, ♥, ♦, ♧
4873
+ 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
4874
+ // `this.pos` and try to advance them to a further position. If no
4875
+ // stack for such a position is found, it'll start error-recovery.
4876
+ //
4877
+ // When the parse is finished, this will return a syntax tree. When
4878
+ // not, it returns `null`.
4879
+ advance(){let stacks=this.stacks,pos=this.minStackPos;// This will hold stacks beyond `pos`.
4880
+ let newStacks=this.stacks=[];let stopped,stoppedTokens;// Keep advancing any stacks at `pos` until they either move
4881
+ // forward or can't be advanced. Gather stacks that can't be
4882
+ // advanced further in `stopped`.
4883
+ 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
4884
+ // running without splitting for a while, to avoid getting stuck
4885
+ // with multiple successful stacks running endlessly on.
4886
+ 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
4887
+ // stack can't advance normally. When `split` and `stacks` are
4888
+ // given, stacks split off by ambiguous operations will be pushed to
4889
+ // `split`, or added to `stacks` if they move `pos` forward.
4890
+ 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
4891
+ // (possibly updated) stack if it got stuck, or null if it moved
4892
+ // forward and was given to `pushStackDedup`.
4893
+ 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.
4894
+ 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
4895
+ /// by `lezer-generator`.
4896
+ class LRParser extends Parser{/// @internal
4897
+ constructor(spec){super();/// @internal
4898
+ 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
4899
+ 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
4900
+ 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
4901
+ stateSlot(state,slot){return this.states[state*6/* Size */+slot];}/// @internal
4902
+ stateFlag(state,flag){return (this.stateSlot(state,0/* Flags */)&flag)>0;}/// @internal
4903
+ 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
4904
+ /// goto jumps. @internal
4905
+ 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
4906
+ 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
4907
+ /// given settings modified. Settings not provided in `config` are
4908
+ /// kept from the original parser.
4909
+ configure(config){// Hideous reflection-based kludge to make it easy to create a
4910
+ // slightly modified copy of a parser.
4911
+ 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)
4912
+ /// are registered for this parser.
4913
+ hasWrappers(){return this.wrappers.length>0;}/// Returns the name associated with a given term. This will only
4914
+ /// work for all terms when the parser was generated with the
4915
+ /// `--names` option. By default, only the names of tagged terms are
4916
+ /// stored.
4917
+ 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
4918
+ /// types. @internal
4919
+ get eofTerm(){return this.maxNode+1;}/// The type of top node produced by the parser.
4920
+ get topNode(){return this.nodeSet.types[this.top[1]];}/// @internal
4921
+ dynamicPrecedence(term){let prec=this.dynamicPrecedences;return prec==null?0:prec[term]||0;}/// @internal
4922
+ 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
4923
+ 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.
4924
+ 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! iQPO'#FTOOQO-E9X-E9XO! nQPO'#FmOOQO'#Cb'#CbO! vQPO'#CcO! {QPO,58zO!!QQPO,59SO!!XQPO'#Fp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RQ%R$SQ%X$`Q%[$eS%j%W%lQ%y%eQ%z%fQ&a&rQ&k&dQ&l&eQ&m&fQ&n&hQ&o&iQ&v&pQ&w&qQ&x&tQ&z&uS&|&y&}Q'O&{Q'Q&sQ'S&jQ'U'^Q'V'_Q'W'`Q'Y'hQ'k'bQ'l'cQ'm'dQ'n'fQ'o'gQ's'pQ't'qQ'v'rS'y'u'zQ'{'xQ(U'}Q(V(OQ(W(PQ(X(RQ(Y(SQ(^(ZQ(_([Q(a(]S(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,[]);}const FeelLinter=function(editorView){const messages=[];// don't lint if the Editor is empty
4925
+ 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];/**
4926
4926
  * Creates a FEEL editor in the supplied container
4927
4927
  *
4928
4928
  * @param {Object} config
4929
4929
  * @param {DOMNode} config.container
4930
4930
  * @param {Function} [config.onChange]
4931
4931
  * @param {Function} [config.onKeyDown]
4932
+ * @param {Function} [config.onLint]
4933
+ * @param {Boolean} [config.readOnly]
4932
4934
  * @param {String} [config.value]
4935
+ * @param {Array} [config.variables]
4933
4936
  *
4934
4937
  * @returns {Object} editor
4935
- */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;}/**
4938
+ */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;}/**
4936
4939
  * Replaces the content of the Editor
4937
4940
  *
4938
4941
  * @param {String} value
4939
4942
  */FeelEditor.prototype.setValue=function(value){this._cmEditor.dispatch({changes:{from:0,to:this._cmEditor.state.doc.length,insert:value}});};/**
4940
4943
  * Sets the focus in the editor.
4941
- */FeelEditor.prototype.focus=function(){this._cmEditor.focus();};/**
4944
+ */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}});}};/**
4942
4945
  * Returns the current selection ranges. If no text is selected, a single
4943
4946
  * range with the start and end index at the cursor position will be returned.
4944
4947
  *
@@ -4947,19 +4950,19 @@ function isNodeEmpty(node){return node.from===node.to;}function autocompletion(c
4947
4950
  */FeelEditor.prototype.getSelection=function(){return this._cmEditor.state.selection;};
4948
4951
 
4949
4952
  const useBufferedFocus = function (editor, ref) {
4950
- const [buffer, setBuffer] = hooks.useState(false);
4953
+ const [buffer, setBuffer] = hooks.useState(undefined);
4951
4954
  ref.current = hooks.useMemo(() => ({
4952
- focus: () => {
4955
+ focus: argument => {
4953
4956
  if (editor) {
4954
- editor.focus();
4957
+ editor.focus(argument);
4955
4958
  } else {
4956
- setBuffer(true);
4959
+ setBuffer(argument);
4957
4960
  }
4958
4961
  }
4959
4962
  }), [editor]);
4960
4963
  hooks.useEffect(() => {
4961
- if (buffer && editor) {
4962
- editor.focus();
4964
+ if (typeof buffer !== 'undefined' && editor) {
4965
+ editor.focus(buffer);
4963
4966
  setBuffer(false);
4964
4967
  }
4965
4968
  }, [editor, buffer]);
@@ -4970,6 +4973,7 @@ const CodeEditor = compat.forwardRef((props, ref) => {
4970
4973
  value,
4971
4974
  onInput,
4972
4975
  onFeelToggle,
4976
+ onLint = () => {},
4973
4977
  disabled,
4974
4978
  variables
4975
4979
  } = props;
@@ -5006,11 +5010,13 @@ const CodeEditor = compat.forwardRef((props, ref) => {
5006
5010
  container: inputRef.current,
5007
5011
  onChange: handleInput,
5008
5012
  onKeyDown: onKeyDown,
5013
+ onLint: onLint,
5009
5014
  value: localValue,
5010
5015
  variables: variables
5011
5016
  });
5012
5017
  setEditor(editor);
5013
5018
  return () => {
5019
+ onLint([]);
5014
5020
  inputRef.current.innerHTML = '';
5015
5021
  setEditor(null);
5016
5022
  };
@@ -5027,12 +5033,18 @@ const CodeEditor = compat.forwardRef((props, ref) => {
5027
5033
  editor.setValue(value);
5028
5034
  setLocalValue(value);
5029
5035
  }, [value]);
5036
+
5037
+ const handleClick = () => {
5038
+ ref.current.focus();
5039
+ };
5040
+
5030
5041
  return jsxRuntime.jsx("div", {
5031
5042
  class: classnames__default["default"]('bio-properties-panel-feel-editor-container', disabled ? 'disabled' : null),
5032
5043
  children: jsxRuntime.jsx("div", {
5033
5044
  name: props.name,
5034
5045
  class: classnames__default["default"]('bio-properties-panel-input', localValue ? 'edited' : null),
5035
- ref: inputRef
5046
+ ref: inputRef,
5047
+ onClick: handleClick
5036
5048
  })
5037
5049
  });
5038
5050
  });
@@ -5096,16 +5108,27 @@ function FeelTextfield(props) {
5096
5108
  id,
5097
5109
  label,
5098
5110
  onInput,
5111
+ onError,
5099
5112
  feel,
5100
5113
  value = '',
5101
5114
  disabled = false,
5102
5115
  OptionalComponent = OptionalFeelInput
5103
5116
  } = props;
5104
5117
  const [localValue, _setLocalValue] = hooks.useState(value);
5105
- const ref = useShowEntryEvent(id);
5118
+ const editorRef = useShowEntryEvent(id);
5119
+ const containerRef = hooks.useRef();
5106
5120
  const feelActive = localValue.startsWith('=') || feel === 'required';
5107
5121
  const feelOnlyValue = localValue.substring(1);
5108
- const [focus, setFocus] = hooks.useState();
5122
+ const [focus, _setFocus] = hooks.useState(undefined);
5123
+
5124
+ const setFocus = (offset = 0) => {
5125
+ const hasFocus = containerRef.current.contains(document.activeElement); // Keep carret position if it is already focused, otherwise focus at the end
5126
+
5127
+ const position = hasFocus ? document.activeElement.selectionStart : Infinity;
5128
+
5129
+ _setFocus(position + offset);
5130
+ };
5131
+
5109
5132
  const handleInputCallback = hooks.useMemo(() => {
5110
5133
  return debounce(newValue => {
5111
5134
  onInput(newValue);
@@ -5146,14 +5169,26 @@ function FeelTextfield(props) {
5146
5169
  setLocalValue(newValue);
5147
5170
 
5148
5171
  if (!feelActive && newValue.startsWith('=')) {
5149
- setFocus(true);
5172
+ // focus is behind `=` sign that will be removed
5173
+ setFocus(-1);
5150
5174
  }
5151
5175
  };
5152
5176
 
5177
+ const handleLint = useStaticCallback(lint => {
5178
+ if (!(lint && lint.length)) {
5179
+ onError(undefined);
5180
+ return;
5181
+ }
5182
+
5183
+ const error = lint[0];
5184
+ const message = `${error.source}: ${error.message}`;
5185
+ onError(message);
5186
+ });
5153
5187
  hooks.useEffect(() => {
5154
- if (focus) {
5155
- ref.current.focus();
5156
- setFocus(false);
5188
+ if (typeof focus !== 'undefined') {
5189
+ editorRef.current.focus(focus);
5190
+
5191
+ _setFocus(undefined);
5157
5192
  }
5158
5193
  }, [focus]);
5159
5194
  hooks.useEffect(() => {
@@ -5168,13 +5203,47 @@ function FeelTextfield(props) {
5168
5203
  }
5169
5204
 
5170
5205
  setLocalValue(value);
5171
- }, [value]);
5206
+ }, [value]); // copy-paste integration
5207
+
5208
+ hooks.useEffect(() => {
5209
+ const copyHandler = event => {
5210
+ if (!feelActive) {
5211
+ return;
5212
+ }
5213
+
5214
+ event.clipboardData.setData('application/FEEL', event.clipboardData.getData('text'));
5215
+ };
5216
+
5217
+ const pasteHandler = event => {
5218
+ if (feelActive) {
5219
+ return;
5220
+ }
5221
+
5222
+ const data = event.clipboardData.getData('application/FEEL');
5223
+
5224
+ if (data) {
5225
+ setTimeout(() => {
5226
+ handleFeelToggle();
5227
+ setFocus();
5228
+ });
5229
+ }
5230
+ };
5231
+
5232
+ containerRef.current.addEventListener('copy', copyHandler);
5233
+ containerRef.current.addEventListener('cut', copyHandler);
5234
+ containerRef.current.addEventListener('paste', pasteHandler);
5235
+ return () => {
5236
+ containerRef.current.removeEventListener('copy', copyHandler);
5237
+ containerRef.current.removeEventListener('cut', copyHandler);
5238
+ containerRef.current.removeEventListener('paste', pasteHandler);
5239
+ };
5240
+ }, [containerRef, feelActive, handleFeelToggle, setFocus]);
5172
5241
  return jsxRuntime.jsxs("div", {
5173
5242
  class: "bio-properties-panel-feel-entry",
5174
5243
  children: [jsxRuntime.jsxs("label", {
5175
5244
  for: prefixId$6(id),
5176
5245
  class: "bio-properties-panel-label",
5177
- onClick: () => setFocus(true),
5246
+ onClick: () => setFocus(),
5178
5247
  children: [label, jsxRuntime.jsx(FeelIcon, {
5179
5248
  label: label,
5180
5249
  feel: feel,
@@ -5183,6 +5252,7 @@ function FeelTextfield(props) {
5183
5252
  })]
5184
5253
  }), jsxRuntime.jsxs("div", {
5185
5254
  class: "bio-properties-panel-feel-container",
5255
+ ref: containerRef,
5186
5256
  children: [jsxRuntime.jsx(FeelIndicator, {
5187
5257
  active: feelActive,
5188
5258
  disabled: feel !== 'optional' || disabled,
@@ -5196,13 +5266,14 @@ function FeelTextfield(props) {
5196
5266
  handleFeelToggle();
5197
5267
  setFocus(true);
5198
5268
  },
5269
+ onLint: handleLint,
5199
5270
  value: feelOnlyValue,
5200
5271
  variables: props.variables,
5201
- ref: ref
5272
+ ref: editorRef
5202
5273
  }) : jsxRuntime.jsx(OptionalComponent, { ...props,
5203
5274
  onInput: handleLocalInput,
5204
5275
  value: localValue,
5205
- ref: ref
5276
+ ref: editorRef
5206
5277
  })]
5207
5278
  })]
5208
5279
  });
@@ -5219,7 +5290,7 @@ const OptionalFeelInput = compat.forwardRef((props, ref) => {
5219
5290
  // this ensures clean editing experience when switching with the keyboard
5220
5291
 
5221
5292
  ref.current = {
5222
- focus: () => {
5293
+ focus: position => {
5223
5294
  const input = inputRef.current;
5224
5295
 
5225
5296
  if (!input) {
@@ -5227,7 +5298,14 @@ const OptionalFeelInput = compat.forwardRef((props, ref) => {
5227
5298
  }
5228
5299
 
5229
5300
  input.focus();
5230
- input.setSelectionRange(0, 0);
5301
+
5302
+ if (typeof position === 'number') {
5303
+ if (position > value.length) {
5304
+ position = value.length;
5305
+ }
5306
+
5307
+ input.setSelectionRange(position, position);
5308
+ }
5231
5309
  }
5232
5310
  };
5233
5311
  return jsxRuntime.jsx("input", {
@@ -5311,6 +5389,7 @@ function FeelEntry(props) {
5311
5389
  } = props;
5312
5390
  const [cachedInvalidValue, setCachedInvalidValue] = hooks.useState(null);
5313
5391
  const [validationError, setValidationError] = hooks.useState(null);
5392
+ const [localError, setLocalError] = hooks.useState(null);
5314
5393
  let value = getValue(element);
5315
5394
  const previousValue = usePrevious(value);
5316
5395
  hooks.useEffect(() => {
@@ -5337,13 +5416,16 @@ function FeelEntry(props) {
5337
5416
 
5338
5417
  setValidationError(newValidationError);
5339
5418
  });
5419
+ const onError = hooks.useCallback(err => {
5420
+ setLocalError(err);
5421
+ }, []);
5340
5422
 
5341
5423
  if (previousValue === value && validationError) {
5342
5424
  value = cachedInvalidValue;
5343
5425
  }
5344
5426
 
5345
5427
  const temporaryError = useError(id);
5346
- const error = temporaryError || validationError;
5428
+ const error = temporaryError || validationError || localError;
5347
5429
  return jsxRuntime.jsxs("div", {
5348
5430
  class: classnames__default["default"](props.class, 'bio-properties-panel-entry', error ? 'has-error' : ''),
5349
5431
  "data-entry-id": id,
@@ -5354,6 +5436,7 @@ function FeelEntry(props) {
5354
5436
  id: id,
5355
5437
  label: label,
5356
5438
  onInput: onInput,
5439
+ onError: onError,
5357
5440
  example: props.example,
5358
5441
  show: show,
5359
5442
  value: value,