@bpmn-io/properties-panel 0.17.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -460,8 +460,9 @@ function useShowEntryEvent(id) {
460
460
 
461
461
  function useStickyIntersectionObserver(ref, scrollContainerSelector, setSticky) {
462
462
  useEffect(() => {
463
- // return early if IntersectionObserver is not available
464
- if (!IntersectionObserver) {
463
+ const Observer = IntersectionObserver; // return early if IntersectionObserver is not available
464
+
465
+ if (!Observer) {
465
466
  return;
466
467
  }
467
468
 
@@ -469,12 +470,14 @@ function useStickyIntersectionObserver(ref, scrollContainerSelector, setSticky)
469
470
 
470
471
  if (ref.current) {
471
472
  const scrollContainer = query(scrollContainerSelector);
472
- observer = new IntersectionObserver(entries => {
473
- if (entries[0].intersectionRatio < 1) {
474
- setSticky(true);
475
- } else if (entries[0].intersectionRatio === 1) {
476
- setSticky(false);
477
- }
473
+ observer = new Observer(entries => {
474
+ entries.forEach(entry => {
475
+ if (entry.intersectionRatio < 1) {
476
+ setSticky(true);
477
+ } else if (entry.intersectionRatio === 1) {
478
+ setSticky(false);
479
+ }
480
+ });
478
481
  }, {
479
482
  root: scrollContainer,
480
483
  rootMargin: '0px 0px 999999% 0px',
@@ -490,7 +493,7 @@ function useStickyIntersectionObserver(ref, scrollContainerSelector, setSticky)
490
493
  observer.unobserve(ref.current);
491
494
  }
492
495
  };
493
- }, [ref]);
496
+ }, [ref, scrollContainerSelector, setSticky]);
494
497
  }
495
498
 
496
499
  /**
@@ -1308,7 +1311,7 @@ function CheckboxEntry(props) {
1308
1311
  label: label,
1309
1312
  onChange: setValue,
1310
1313
  value: value
1311
- }), error && jsx("div", {
1314
+ }, element), error && jsx("div", {
1312
1315
  class: "bio-properties-panel-error",
1313
1316
  children: error
1314
1317
  }), jsx(Description, {
@@ -1409,6 +1412,10 @@ Find the code point at the given position in a string (like the
1409
1412
  [`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt)
1410
1413
  string method).
1411
1414
  */function codePointAt(str,pos){let code0=str.charCodeAt(pos);if(!surrogateHigh(code0)||pos+1==str.length)return code0;let code1=str.charCodeAt(pos+1);if(!surrogateLow(code1))return code0;return (code0-0xd800<<10)+(code1-0xdc00)+0x10000;}/**
1415
+ Given a Unicode codepoint, return the JavaScript string that
1416
+ respresents it (like
1417
+ [`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)).
1418
+ */function fromCodePoint(code){if(code<=0xffff)return String.fromCharCode(code);code-=0x10000;return String.fromCharCode((code>>10)+0xd800,(code&1023)+0xdc00);}/**
1412
1419
  The amount of positions a character takes up a JavaScript string.
1413
1420
  */function codePointSize(code){return code<0x10000?1:2;}const DefaultSplit=/\r\n?|\n/;/**
1414
1421
  Distinguishes different ways in which positions can be mapped.
@@ -1880,7 +1887,7 @@ collaborative editing.
1880
1887
  */Transaction.remote=/*@__PURE__*/Annotation.define();function joinRanges(a,b){let result=[];for(let iA=0,iB=0;;){let from,to;if(iA<a.length&&(iB==b.length||b[iB]>=a[iA])){from=a[iA++];to=a[iA++];}else if(iB<b.length){from=b[iB++];to=b[iB++];}else return result;if(!result.length||result[result.length-1]<from)result.push(from,to);else if(result[result.length-1]<to)result[result.length-1]=to;}}function mergeTransaction(a,b,sequential){var _a;let mapForA,mapForB,changes;if(sequential){mapForA=b.changes;mapForB=ChangeSet.empty(b.changes.length);changes=a.changes.compose(b.changes);}else {mapForA=b.changes.map(a.changes);mapForB=a.changes.mapDesc(b.changes,true);changes=a.changes.compose(mapForA);}return {changes,selection:b.selection?b.selection.map(mapForB):(_a=a.selection)===null||_a===void 0?void 0:_a.map(mapForA),effects:StateEffect.mapEffects(a.effects,mapForA).concat(StateEffect.mapEffects(b.effects,mapForB)),annotations:a.annotations.length?a.annotations.concat(b.annotations):b.annotations,scrollIntoView:a.scrollIntoView||b.scrollIntoView};}function resolveTransactionInner(state,spec,docSize){let sel=spec.selection,annotations=asArray(spec.annotations);if(spec.userEvent)annotations=annotations.concat(Transaction.userEvent.of(spec.userEvent));return {changes:spec.changes instanceof ChangeSet?spec.changes:ChangeSet.of(spec.changes||[],docSize,state.facet(lineSeparator)),selection:sel&&(sel instanceof EditorSelection?sel:EditorSelection.single(sel.anchor,sel.head)),effects:asArray(spec.effects),annotations,scrollIntoView:!!spec.scrollIntoView};}function resolveTransaction(state,specs,filter){let s=resolveTransactionInner(state,specs.length?specs[0]:{},state.doc.length);if(specs.length&&specs[0].filter===false)filter=false;for(let i=1;i<specs.length;i++){if(specs[i].filter===false)filter=false;let seq=!!specs[i].sequential;s=mergeTransaction(s,resolveTransactionInner(state,specs[i],seq?s.changes.newLength:state.doc.length),seq);}let tr=Transaction.create(state,s.changes,s.selection,s.effects,s.annotations,s.scrollIntoView);return extendTransaction(filter?filterTransaction(tr):tr);}// Finish a transaction by applying filters if necessary.
1881
1888
  function filterTransaction(tr){let state=tr.startState;// Change filters
1882
1889
  let result=true;for(let filter of state.facet(changeFilter)){let value=filter(tr);if(value===false){result=false;break;}if(Array.isArray(value))result=result===true?value:joinRanges(result,value);}if(result!==true){let changes,back;if(result===false){back=tr.changes.invertedDesc;changes=ChangeSet.empty(state.doc.length);}else {let filtered=tr.changes.filter(result);changes=filtered.changes;back=filtered.filtered.invertedDesc;}tr=Transaction.create(state,changes,tr.selection&&tr.selection.map(back),StateEffect.mapEffects(tr.effects,back),tr.annotations,tr.scrollIntoView);}// Transaction filters
1883
- let filters=state.facet(transactionFilter);for(let i=filters.length-1;i>=0;i--){let filtered=filters[i](tr);if(filtered instanceof Transaction)tr=filtered;else if(Array.isArray(filtered)&&filtered.length==1&&filtered[0]instanceof Transaction)tr=filtered[0];else tr=resolveTransaction(state,asArray(filtered),false);}return tr;}function extendTransaction(tr){let state=tr.startState,extenders=state.facet(transactionExtender),spec=tr;for(let i=extenders.length-1;i>=0;i--){let extension=extenders[i](tr);if(extension&&Object.keys(extension).length)spec=mergeTransaction(tr,resolveTransactionInner(state,extension,tr.changes.newLength),true);}return spec==tr?tr:Transaction.create(state,tr.changes,tr.selection,spec.effects,spec.annotations,spec.scrollIntoView);}const none=[];function asArray(value){return value==null?none:Array.isArray(value)?value:[value];}/**
1890
+ let filters=state.facet(transactionFilter);for(let i=filters.length-1;i>=0;i--){let filtered=filters[i](tr);if(filtered instanceof Transaction)tr=filtered;else if(Array.isArray(filtered)&&filtered.length==1&&filtered[0]instanceof Transaction)tr=filtered[0];else tr=resolveTransaction(state,asArray(filtered),false);}return tr;}function extendTransaction(tr){let state=tr.startState,extenders=state.facet(transactionExtender),spec=tr;for(let i=extenders.length-1;i>=0;i--){let extension=extenders[i](tr);if(extension&&Object.keys(extension).length)spec=mergeTransaction(tr,resolveTransactionInner(state,extension,tr.changes.newLength),true);}return spec==tr?tr:Transaction.create(state,tr.changes,tr.selection,spec.effects,spec.annotations,spec.scrollIntoView);}const none$1=[];function asArray(value){return value==null?none$1:Array.isArray(value)?value:[value];}/**
1884
1891
  The categories produced by a [character
1885
1892
  categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used
1886
1893
  do things like selecting by word.
@@ -2434,7 +2441,7 @@ merge(from,to,source,hasStart,openStart,openEnd){if(source){if(!(source instance
2434
2441
  addLineDeco(deco){let attrs=deco.spec.attributes,cls=deco.spec.class;if(attrs)this.attrs=combineAttrs(attrs,this.attrs||{});if(cls)this.attrs=combineAttrs({class:cls},this.attrs||{});}domAtPos(pos){return inlineDOMAtPos(this.dom,this.children,pos);}reuseDOM(node){if(node.nodeName=="DIV"){this.setDOM(node);this.dirty|=4/* Attrs */|2/* Node */;}}sync(track){var _a;if(!this.dom){this.setDOM(document.createElement("div"));this.dom.className="cm-line";this.prevAttrs=this.attrs?null:undefined;}else if(this.dirty&4/* Attrs */){clearAttributes(this.dom);this.dom.className="cm-line";this.prevAttrs=this.attrs?null:undefined;}if(this.prevAttrs!==undefined){updateAttrs(this.dom,this.prevAttrs,this.attrs);this.dom.classList.add("cm-line");this.prevAttrs=undefined;}super.sync(track);let last=this.dom.lastChild;while(last&&ContentView.get(last)instanceof MarkView)last=last.lastChild;if(!last||!this.length||last.nodeName!="BR"&&((_a=ContentView.get(last))===null||_a===void 0?void 0:_a.isEditable)==false&&(!browser.ios||!this.children.some(ch=>ch instanceof TextView))){let hack=document.createElement("BR");hack.cmIgnore=true;this.dom.appendChild(hack);}}measureTextSize(){if(this.children.length==0||this.length>20)return null;let totalWidth=0;for(let child of this.children){if(!(child instanceof TextView))return null;let rects=clientRectsFor(child.dom);if(rects.length!=1)return null;totalWidth+=rects[0].width;}return {lineHeight:this.dom.getBoundingClientRect().height,charWidth:totalWidth/this.length};}coordsAt(pos,side){return coordsInChildren(this,pos,side);}become(_other){return false;}get type(){return BlockType.Text;}static find(docView,pos){for(let i=0,off=0;i<docView.children.length;i++){let block=docView.children[i],end=off+block.length;if(end>=pos){if(block instanceof LineView)return block;if(end>pos)break;}off=end+block.breakAfter;}return null;}}class BlockWidgetView extends ContentView{constructor(widget,length,type){super();this.widget=widget;this.length=length;this.type=type;this.breakAfter=0;this.prevWidget=null;}merge(from,to,source,_takeDeco,openStart,openEnd){if(source&&(!(source instanceof BlockWidgetView)||!this.widget.compare(source.widget)||from>0&&openStart<=0||to<this.length&&openEnd<=0))return false;this.length=from+(source?source.length:0)+(this.length-to);return true;}domAtPos(pos){return pos==0?DOMPos.before(this.dom):DOMPos.after(this.dom,pos==this.length);}split(at){let len=this.length-at;this.length=at;let end=new BlockWidgetView(this.widget,len,this.type);end.breakAfter=this.breakAfter;return end;}get children(){return noChildren;}sync(){if(!this.dom||!this.widget.updateDOM(this.dom)){if(this.dom&&this.prevWidget)this.prevWidget.destroy(this.dom);this.prevWidget=null;this.setDOM(this.widget.toDOM(this.editorView));this.dom.contentEditable="false";}}get overrideDOMText(){return this.parent?this.parent.view.state.doc.slice(this.posAtStart,this.posAtEnd):Text.empty;}domBoundsAround(){return null;}become(other){if(other instanceof BlockWidgetView&&other.type==this.type&&other.widget.constructor==this.widget.constructor){if(!other.widget.eq(this.widget))this.markDirty(true);if(this.dom&&!this.prevWidget)this.prevWidget=this.widget;this.widget=other.widget;this.length=other.length;this.breakAfter=other.breakAfter;return true;}return false;}ignoreMutation(){return true;}ignoreEvent(event){return this.widget.ignoreEvent(event);}destroy(){super.destroy();if(this.dom)this.widget.destroy(this.dom);}}class ContentBuilder{constructor(doc,pos,end,disallowBlockEffectsFor){this.doc=doc;this.pos=pos;this.end=end;this.disallowBlockEffectsFor=disallowBlockEffectsFor;this.content=[];this.curLine=null;this.breakAtStart=0;this.pendingBuffer=0/* No */;// Set to false directly after a widget that covers the position after it
2435
2442
  this.atCursorPos=true;this.openStart=-1;this.openEnd=-1;this.text="";this.textOff=0;this.cursor=doc.iter();this.skip=pos;}posCovered(){if(this.content.length==0)return !this.breakAtStart&&this.doc.lineAt(this.pos).from!=this.pos;let last=this.content[this.content.length-1];return !last.breakAfter&&!(last instanceof BlockWidgetView&&last.type==BlockType.WidgetBefore);}getLine(){if(!this.curLine){this.content.push(this.curLine=new LineView());this.atCursorPos=true;}return this.curLine;}flushBuffer(active){if(this.pendingBuffer){this.curLine.append(wrapMarks(new WidgetBufferView(-1),active),active.length);this.pendingBuffer=0/* No */;}}addBlockWidget(view){this.flushBuffer([]);this.curLine=null;this.content.push(view);}finish(openEnd){if(!openEnd)this.flushBuffer([]);else this.pendingBuffer=0/* No */;if(!this.posCovered())this.getLine();}buildText(length,active,openStart){while(length>0){if(this.textOff==this.text.length){let{value,lineBreak,done}=this.cursor.next(this.skip);this.skip=0;if(done)throw new Error("Ran out of text content when drawing inline views");if(lineBreak){if(!this.posCovered())this.getLine();if(this.content.length)this.content[this.content.length-1].breakAfter=1;else this.breakAtStart=1;this.flushBuffer([]);this.curLine=null;length--;continue;}else {this.text=value;this.textOff=0;}}let take=Math.min(this.text.length-this.textOff,length,512/* Chunk */);this.flushBuffer(active.slice(0,openStart));this.getLine().append(wrapMarks(new TextView(this.text.slice(this.textOff,this.textOff+take)),active),openStart);this.atCursorPos=true;this.textOff+=take;length-=take;openStart=0;}}span(from,to,active,openStart){this.buildText(to-from,active,openStart);this.pos=to;if(this.openStart<0)this.openStart=openStart;}point(from,to,deco,active,openStart,index){if(this.disallowBlockEffectsFor[index]&&deco instanceof PointDecoration){if(deco.block)throw new RangeError("Block decorations may not be specified via plugins");if(to>this.doc.lineAt(this.pos).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins");}let len=to-from;if(deco instanceof PointDecoration){if(deco.block){let{type}=deco;if(type==BlockType.WidgetAfter&&!this.posCovered())this.getLine();this.addBlockWidget(new BlockWidgetView(deco.widget||new NullWidget("div"),len,type));}else {let view=WidgetView.create(deco.widget||new NullWidget("span"),len,deco.startSide);let cursorBefore=this.atCursorPos&&!view.isEditable&&openStart<=active.length&&(from<to||deco.startSide>0);let cursorAfter=!view.isEditable&&(from<to||deco.startSide<=0);let line=this.getLine();if(this.pendingBuffer==2/* IfCursor */&&!cursorBefore)this.pendingBuffer=0/* No */;this.flushBuffer(active);if(cursorBefore){line.append(wrapMarks(new WidgetBufferView(1),active),openStart);openStart=active.length+Math.max(0,openStart-active.length);}line.append(wrapMarks(view,active),openStart);this.atCursorPos=cursorAfter;this.pendingBuffer=!cursorAfter?0/* No */:from<to?1/* Yes */:2/* IfCursor */;}}else if(this.doc.lineAt(this.pos).from==this.pos){// Line decoration
2436
2443
  this.getLine().addLineDeco(deco);}if(len){// Advance the iterator past the replaced content
2437
- if(this.textOff+len<=this.text.length){this.textOff+=len;}else {this.skip+=len-(this.text.length-this.textOff);this.text="";this.textOff=0;}this.pos=to;}if(this.openStart<0)this.openStart=openStart;}static build(text,from,to,decorations,dynamicDecorationMap){let builder=new ContentBuilder(text,from,to,dynamicDecorationMap);builder.openEnd=RangeSet.spans(decorations,from,to,builder);if(builder.openStart<0)builder.openStart=builder.openEnd;builder.finish(builder.openEnd);return builder;}}function wrapMarks(view,active){for(let mark of active)view=new MarkView(mark,[view],view.length);return view;}class NullWidget extends WidgetType{constructor(tag){super();this.tag=tag;}eq(other){return other.tag==this.tag;}toDOM(){return document.createElement(this.tag);}updateDOM(elt){return elt.nodeName.toLowerCase()==this.tag;}}const clickAddsSelectionRange=/*@__PURE__*/Facet.define();const dragMovesSelection$1=/*@__PURE__*/Facet.define();const mouseSelectionStyle=/*@__PURE__*/Facet.define();const exceptionSink=/*@__PURE__*/Facet.define();const updateListener=/*@__PURE__*/Facet.define();const inputHandler=/*@__PURE__*/Facet.define();const perLineTextDirection=/*@__PURE__*/Facet.define({combine:values=>values.some(x=>x)});class ScrollTarget{constructor(range,y="nearest",x="nearest",yMargin=5,xMargin=5){this.range=range;this.y=y;this.x=x;this.yMargin=yMargin;this.xMargin=xMargin;}map(changes){return changes.empty?this:new ScrollTarget(this.range.map(changes),this.y,this.x,this.yMargin,this.xMargin);}}const scrollIntoView=/*@__PURE__*/StateEffect.define({map:(t,ch)=>t.map(ch)});/**
2444
+ if(this.textOff+len<=this.text.length){this.textOff+=len;}else {this.skip+=len-(this.text.length-this.textOff);this.text="";this.textOff=0;}this.pos=to;}if(this.openStart<0)this.openStart=openStart;}static build(text,from,to,decorations,dynamicDecorationMap){let builder=new ContentBuilder(text,from,to,dynamicDecorationMap);builder.openEnd=RangeSet.spans(decorations,from,to,builder);if(builder.openStart<0)builder.openStart=builder.openEnd;builder.finish(builder.openEnd);return builder;}}function wrapMarks(view,active){for(let mark of active)view=new MarkView(mark,[view],view.length);return view;}class NullWidget extends WidgetType{constructor(tag){super();this.tag=tag;}eq(other){return other.tag==this.tag;}toDOM(){return document.createElement(this.tag);}updateDOM(elt){return elt.nodeName.toLowerCase()==this.tag;}}const clickAddsSelectionRange=/*@__PURE__*/Facet.define();const dragMovesSelection$1=/*@__PURE__*/Facet.define();const mouseSelectionStyle=/*@__PURE__*/Facet.define();const exceptionSink=/*@__PURE__*/Facet.define();const updateListener=/*@__PURE__*/Facet.define();const inputHandler=/*@__PURE__*/Facet.define();const perLineTextDirection=/*@__PURE__*/Facet.define({combine:values=>values.some(x=>x)});class ScrollTarget{constructor(range,y="nearest",x="nearest",yMargin=5,xMargin=5){this.range=range;this.y=y;this.x=x;this.yMargin=yMargin;this.xMargin=xMargin;}map(changes){return changes.empty?this:new ScrollTarget(this.range.map(changes),this.y,this.x,this.yMargin,this.xMargin);}}const scrollIntoView$1=/*@__PURE__*/StateEffect.define({map:(t,ch)=>t.map(ch)});/**
2438
2445
  Log or report an unhandled exception in client code. Should
2439
2446
  probably only be used by extension code that allows client code to
2440
2447
  provide functions, and calls those functions in a context where an
@@ -2952,7 +2959,7 @@ transactions for editing actions.
2952
2959
  [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead, which uses this
2953
2960
  as a primitive.
2954
2961
  */update(transactions){if(this.updateState!=0/* Idle */)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let redrawn=false,attrsChanged=false,update;let state=this.state;for(let tr of transactions){if(tr.startState!=state)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");state=tr.state;}if(this.destroyed){this.viewState.state=state;return;}this.observer.clear();// When the phrases change, redraw the editor
2955
- if(state.facet(EditorState.phrases)!=this.state.facet(EditorState.phrases))return this.setState(state);update=ViewUpdate.create(this,state,transactions);let scrollTarget=this.viewState.scrollTarget;try{this.updateState=2/* Updating */;for(let tr of transactions){if(scrollTarget)scrollTarget=scrollTarget.map(tr.changes);if(tr.scrollIntoView){let{main}=tr.state.selection;scrollTarget=new ScrollTarget(main.empty?main:EditorSelection.cursor(main.head,main.head>main.anchor?-1:1));}for(let e of tr.effects)if(e.is(scrollIntoView))scrollTarget=e.value;}this.viewState.update(update,scrollTarget);this.bidiCache=CachedOrder.update(this.bidiCache,update.changes);if(!update.empty){this.updatePlugins(update);this.inputState.update(update);}redrawn=this.docView.update(update);if(this.state.facet(styleModule)!=this.styleModules)this.mountStyles();attrsChanged=this.updateAttrs();this.showAnnouncements(transactions);this.docView.updateSelection(redrawn,transactions.some(tr=>tr.isUserEvent("select.pointer")));}finally{this.updateState=0/* Idle */;}if(update.startState.facet(theme$1)!=update.state.facet(theme$1))this.viewState.mustMeasureContent=true;if(redrawn||attrsChanged||scrollTarget||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)this.requestMeasure();if(!update.empty)for(let listener of this.state.facet(updateListener))listener(update);}/**
2962
+ if(state.facet(EditorState.phrases)!=this.state.facet(EditorState.phrases))return this.setState(state);update=ViewUpdate.create(this,state,transactions);let scrollTarget=this.viewState.scrollTarget;try{this.updateState=2/* Updating */;for(let tr of transactions){if(scrollTarget)scrollTarget=scrollTarget.map(tr.changes);if(tr.scrollIntoView){let{main}=tr.state.selection;scrollTarget=new ScrollTarget(main.empty?main:EditorSelection.cursor(main.head,main.head>main.anchor?-1:1));}for(let e of tr.effects)if(e.is(scrollIntoView$1))scrollTarget=e.value;}this.viewState.update(update,scrollTarget);this.bidiCache=CachedOrder.update(this.bidiCache,update.changes);if(!update.empty){this.updatePlugins(update);this.inputState.update(update);}redrawn=this.docView.update(update);if(this.state.facet(styleModule)!=this.styleModules)this.mountStyles();attrsChanged=this.updateAttrs();this.showAnnouncements(transactions);this.docView.updateSelection(redrawn,transactions.some(tr=>tr.isUserEvent("select.pointer")));}finally{this.updateState=0/* Idle */;}if(update.startState.facet(theme$1)!=update.state.facet(theme$1))this.viewState.mustMeasureContent=true;if(redrawn||attrsChanged||scrollTarget||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)this.requestMeasure();if(!update.empty)for(let listener of this.state.facet(updateListener))listener(update);}/**
2956
2963
  Reset the view to the given state. (This will cause the entire
2957
2964
  document to be redrawn and all view plugins to be reinitialized,
2958
2965
  so you should probably only use it when the new state isn't
@@ -3108,7 +3115,7 @@ return (document.hasFocus()||browser.safari&&((_a=this.inputState)===null||_a===
3108
3115
  Returns an effect that can be
3109
3116
  [added](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) to a transaction to
3110
3117
  cause it to scroll the given position or range into view.
3111
- */static scrollIntoView(pos,options={}){return scrollIntoView.of(new ScrollTarget(typeof pos=="number"?EditorSelection.cursor(pos):pos,options.y,options.x,options.yMargin,options.xMargin));}/**
3118
+ */static scrollIntoView(pos,options={}){return scrollIntoView$1.of(new ScrollTarget(typeof pos=="number"?EditorSelection.cursor(pos):pos,options.y,options.x,options.yMargin,options.xMargin));}/**
3112
3119
  Returns an extension that can be used to add DOM event handlers.
3113
3120
  The value should be an object mapping event names to handler
3114
3121
  functions. For any given event, such functions are ordered by
@@ -3251,9 +3258,9 @@ for a given key, no further handlers are called.
3251
3258
  */const keymap=/*@__PURE__*/Facet.define({enables:handleKeyEvents});const Keymaps=/*@__PURE__*/new WeakMap();// This is hidden behind an indirection, rather than directly computed
3252
3259
  // by the facet, to keep internal types out of the facet's type.
3253
3260
  function getKeymap(state){let bindings=state.facet(keymap);let map=Keymaps.get(bindings);if(!map)Keymaps.set(bindings,map=buildKeymap(bindings.reduce((a,b)=>a.concat(b),[])));return map;}let storedPrefix=null;const PrefixTimeout=4000;function buildKeymap(bindings,platform=currentPlatform){let bound=Object.create(null);let isPrefix=Object.create(null);let checkPrefix=(name,is)=>{let current=isPrefix[name];if(current==null)isPrefix[name]=is;else if(current!=is)throw new Error("Key binding "+name+" is used both as a regular binding and as a multi-stroke prefix");};let add=(scope,key,command,preventDefault)=>{let scopeObj=bound[scope]||(bound[scope]=Object.create(null));let parts=key.split(/ (?!$)/).map(k=>normalizeKeyName(k,platform));for(let i=1;i<parts.length;i++){let prefix=parts.slice(0,i).join(" ");checkPrefix(prefix,true);if(!scopeObj[prefix])scopeObj[prefix]={preventDefault:true,commands:[view=>{let ourObj=storedPrefix={view,prefix,scope};setTimeout(()=>{if(storedPrefix==ourObj)storedPrefix=null;},PrefixTimeout);return true;}]};}let full=parts.join(" ");checkPrefix(full,false);let binding=scopeObj[full]||(scopeObj[full]={preventDefault:false,commands:[]});binding.commands.push(command);if(preventDefault)binding.preventDefault=true;};for(let b of bindings){let name=b[platform]||b.key;if(!name)continue;for(let scope of b.scope?b.scope.split(" "):["editor"]){add(scope,name,b.run,b.preventDefault);if(b.shift)add(scope,"Shift-"+name,b.shift,b.preventDefault);}}return bound;}function runHandlers(map,event,view,scope){let name=keyName(event),isChar=name.length==1&&name!=" ";let prefix="",fallthrough=false;if(storedPrefix&&storedPrefix.view==view&&storedPrefix.scope==scope){prefix=storedPrefix.prefix+" ";if(fallthrough=modifierCodes.indexOf(event.keyCode)<0)storedPrefix=null;}let runFor=binding=>{if(binding){for(let cmd of binding.commands)if(cmd(view))return true;if(binding.preventDefault)fallthrough=true;}return false;};let scopeObj=map[scope],baseName;if(scopeObj){if(runFor(scopeObj[prefix+modifiers(name,event,!isChar)]))return true;if(isChar&&(event.shiftKey||event.altKey||event.metaKey)&&(baseName=base[event.keyCode])&&baseName!=name){if(runFor(scopeObj[prefix+modifiers(baseName,event,true)]))return true;}else if(isChar&&event.shiftKey){if(runFor(scopeObj[prefix+modifiers(name,event,true)]))return true;}}return fallthrough;}const Outside="-10000px";class TooltipViewManager{constructor(view,facet,createTooltipView){this.facet=facet;this.createTooltipView=createTooltipView;this.input=view.state.facet(facet);this.tooltips=this.input.filter(t=>t);this.tooltipViews=this.tooltips.map(createTooltipView);}update(update){let input=update.state.facet(this.facet);let tooltips=input.filter(x=>x);if(input===this.input){for(let t of this.tooltipViews)if(t.update)t.update(update);return false;}let tooltipViews=[];for(let i=0;i<tooltips.length;i++){let tip=tooltips[i],known=-1;if(!tip)continue;for(let i=0;i<this.tooltips.length;i++){let other=this.tooltips[i];if(other&&other.create==tip.create)known=i;}if(known<0){tooltipViews[i]=this.createTooltipView(tip);}else {let tooltipView=tooltipViews[i]=this.tooltipViews[known];if(tooltipView.update)tooltipView.update(update);}}for(let t of this.tooltipViews)if(tooltipViews.indexOf(t)<0)t.dom.remove();this.input=input;this.tooltips=tooltips;this.tooltipViews=tooltipViews;return true;}}function windowSpace(){return {top:0,left:0,bottom:innerHeight,right:innerWidth};}const tooltipConfig=/*@__PURE__*/Facet.define({combine:values=>{var _a,_b,_c;return {position:browser.ios?"absolute":((_a=values.find(conf=>conf.position))===null||_a===void 0?void 0:_a.position)||"fixed",parent:((_b=values.find(conf=>conf.parent))===null||_b===void 0?void 0:_b.parent)||null,tooltipSpace:((_c=values.find(conf=>conf.tooltipSpace))===null||_c===void 0?void 0:_c.tooltipSpace)||windowSpace};}});const tooltipPlugin=/*@__PURE__*/ViewPlugin.fromClass(class{constructor(view){var _a;this.view=view;this.inView=true;this.lastTransaction=0;this.measureTimeout=-1;let config=view.state.facet(tooltipConfig);this.position=config.position;this.parent=config.parent;this.classes=view.themeClasses;this.createContainer();this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this};this.manager=new TooltipViewManager(view,showTooltip,t=>this.createTooltip(t));this.intersectionObserver=typeof IntersectionObserver=="function"?new IntersectionObserver(entries=>{if(Date.now()>this.lastTransaction-50&&entries.length>0&&entries[entries.length-1].intersectionRatio<1)this.measureSoon();},{threshold:[1]}):null;this.observeIntersection();(_a=view.dom.ownerDocument.defaultView)===null||_a===void 0?void 0:_a.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this));this.maybeMeasure();}createContainer(){if(this.parent){this.container=document.createElement("div");this.container.style.position="relative";this.container.className=this.view.themeClasses;this.parent.appendChild(this.container);}else {this.container=this.view.dom;}}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let tooltip of this.manager.tooltipViews)this.intersectionObserver.observe(tooltip.dom);}}measureSoon(){if(this.measureTimeout<0)this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1;this.maybeMeasure();},50);}update(update){if(update.transactions.length)this.lastTransaction=Date.now();let updated=this.manager.update(update);if(updated)this.observeIntersection();let shouldMeasure=updated||update.geometryChanged;let newConfig=update.state.facet(tooltipConfig);if(newConfig.position!=this.position){this.position=newConfig.position;for(let t of this.manager.tooltipViews)t.dom.style.position=this.position;shouldMeasure=true;}if(newConfig.parent!=this.parent){if(this.parent)this.container.remove();this.parent=newConfig.parent;this.createContainer();for(let t of this.manager.tooltipViews)this.container.appendChild(t.dom);shouldMeasure=true;}else if(this.parent&&this.view.themeClasses!=this.classes){this.classes=this.container.className=this.view.themeClasses;}if(shouldMeasure)this.maybeMeasure();}createTooltip(tooltip){let tooltipView=tooltip.create(this.view);tooltipView.dom.classList.add("cm-tooltip");if(tooltip.arrow&&!tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let arrow=document.createElement("div");arrow.className="cm-tooltip-arrow";tooltipView.dom.appendChild(arrow);}tooltipView.dom.style.position=this.position;tooltipView.dom.style.top=Outside;this.container.appendChild(tooltipView.dom);if(tooltipView.mount)tooltipView.mount(this.view);return tooltipView;}destroy(){var _a,_b;(_a=this.view.dom.ownerDocument.defaultView)===null||_a===void 0?void 0:_a.removeEventListener("resize",this.measureSoon);for(let{dom}of this.manager.tooltipViews)dom.remove();(_b=this.intersectionObserver)===null||_b===void 0?void 0:_b.disconnect();clearTimeout(this.measureTimeout);}readMeasure(){let editor=this.view.dom.getBoundingClientRect();return {editor,parent:this.parent?this.container.getBoundingClientRect():editor,pos:this.manager.tooltips.map((t,i)=>{let tv=this.manager.tooltipViews[i];return tv.getCoords?tv.getCoords(t.pos):this.view.coordsAtPos(t.pos);}),size:this.manager.tooltipViews.map(({dom})=>dom.getBoundingClientRect()),space:this.view.state.facet(tooltipConfig).tooltipSpace(this.view)};}writeMeasure(measured){let{editor,space}=measured;let others=[];for(let i=0;i<this.manager.tooltips.length;i++){let tooltip=this.manager.tooltips[i],tView=this.manager.tooltipViews[i],{dom}=tView;let pos=measured.pos[i],size=measured.size[i];// Hide tooltips that are outside of the editor.
3254
- if(!pos||pos.bottom<=Math.max(editor.top,space.top)||pos.top>=Math.min(editor.bottom,space.bottom)||pos.right<Math.max(editor.left,space.left)-.1||pos.left>Math.min(editor.right,space.right)+.1){dom.style.top=Outside;continue;}let arrow=tooltip.arrow?tView.dom.querySelector(".cm-tooltip-arrow"):null;let arrowHeight=arrow?7/* Size */:0;let width=size.right-size.left,height=size.bottom-size.top;let offset=tView.offset||noOffset,ltr=this.view.textDirection==Direction.LTR;let left=size.width>space.right-space.left?ltr?space.left:space.right-size.width:ltr?Math.min(pos.left-(arrow?14/* Offset */:0)+offset.x,space.right-width):Math.max(space.left,pos.left-width+(arrow?14/* Offset */:0)-offset.x);let above=!!tooltip.above;if(!tooltip.strictSide&&(above?pos.top-(size.bottom-size.top)-offset.y<space.top:pos.bottom+(size.bottom-size.top)+offset.y>space.bottom)&&above==space.bottom-pos.bottom>pos.top-space.top)above=!above;let top=above?pos.top-height-arrowHeight-offset.y:pos.bottom+arrowHeight+offset.y;let right=left+width;if(tView.overlap!==true)for(let r of others)if(r.left<right&&r.right>left&&r.top<top+height&&r.bottom>top)top=above?r.top-height-2-arrowHeight:r.bottom+arrowHeight+2;if(this.position=="absolute"){dom.style.top=top-measured.parent.top+"px";dom.style.left=left-measured.parent.left+"px";}else {dom.style.top=top+"px";dom.style.left=left+"px";}if(arrow)arrow.style.left=`${pos.left+(ltr?offset.x:-offset.x)-(left+14/* Offset */-7/* Size */)}px`;if(tView.overlap!==true)others.push({left,top,right,bottom:top+height});dom.classList.toggle("cm-tooltip-above",above);dom.classList.toggle("cm-tooltip-below",!above);if(tView.positioned)tView.positioned();}}maybeMeasure(){if(this.manager.tooltips.length){if(this.view.inView)this.view.requestMeasure(this.measureReq);if(this.inView!=this.view.inView){this.inView=this.view.inView;if(!this.inView)for(let tv of this.manager.tooltipViews)tv.dom.style.top=Outside;}}}},{eventHandlers:{scroll(){this.maybeMeasure();}}});const baseTheme$2=/*@__PURE__*/EditorView.baseTheme({".cm-tooltip":{zIndex:100},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:`${7/* Size */}px`,width:`${7/* Size */*2}px`,position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:`${7/* Size */}px solid transparent`,borderRight:`${7/* Size */}px solid transparent`},".cm-tooltip-above &":{bottom:`-${7/* Size */}px`,"&:before":{borderTop:`${7/* Size */}px solid #bbb`},"&:after":{borderTop:`${7/* Size */}px solid #f5f5f5`,bottom:"1px"}},".cm-tooltip-below &":{top:`-${7/* Size */}px`,"&:before":{borderBottom:`${7/* Size */}px solid #bbb`},"&:after":{borderBottom:`${7/* Size */}px solid #f5f5f5`,top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}});const noOffset={x:0,y:0};/**
3261
+ if(!pos||pos.bottom<=Math.max(editor.top,space.top)||pos.top>=Math.min(editor.bottom,space.bottom)||pos.right<Math.max(editor.left,space.left)-.1||pos.left>Math.min(editor.right,space.right)+.1){dom.style.top=Outside;continue;}let arrow=tooltip.arrow?tView.dom.querySelector(".cm-tooltip-arrow"):null;let arrowHeight=arrow?7/* Size */:0;let width=size.right-size.left,height=size.bottom-size.top;let offset=tView.offset||noOffset,ltr=this.view.textDirection==Direction.LTR;let left=size.width>space.right-space.left?ltr?space.left:space.right-size.width:ltr?Math.min(pos.left-(arrow?14/* Offset */:0)+offset.x,space.right-width):Math.max(space.left,pos.left-width+(arrow?14/* Offset */:0)-offset.x);let above=!!tooltip.above;if(!tooltip.strictSide&&(above?pos.top-(size.bottom-size.top)-offset.y<space.top:pos.bottom+(size.bottom-size.top)+offset.y>space.bottom)&&above==space.bottom-pos.bottom>pos.top-space.top)above=!above;let top=above?pos.top-height-arrowHeight-offset.y:pos.bottom+arrowHeight+offset.y;let right=left+width;if(tView.overlap!==true)for(let r of others)if(r.left<right&&r.right>left&&r.top<top+height&&r.bottom>top)top=above?r.top-height-2-arrowHeight:r.bottom+arrowHeight+2;if(this.position=="absolute"){dom.style.top=top-measured.parent.top+"px";dom.style.left=left-measured.parent.left+"px";}else {dom.style.top=top+"px";dom.style.left=left+"px";}if(arrow)arrow.style.left=`${pos.left+(ltr?offset.x:-offset.x)-(left+14/* Offset */-7/* Size */)}px`;if(tView.overlap!==true)others.push({left,top,right,bottom:top+height});dom.classList.toggle("cm-tooltip-above",above);dom.classList.toggle("cm-tooltip-below",!above);if(tView.positioned)tView.positioned();}}maybeMeasure(){if(this.manager.tooltips.length){if(this.view.inView)this.view.requestMeasure(this.measureReq);if(this.inView!=this.view.inView){this.inView=this.view.inView;if(!this.inView)for(let tv of this.manager.tooltipViews)tv.dom.style.top=Outside;}}}},{eventHandlers:{scroll(){this.maybeMeasure();}}});const baseTheme$3=/*@__PURE__*/EditorView.baseTheme({".cm-tooltip":{zIndex:100},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:`${7/* Size */}px`,width:`${7/* Size */*2}px`,position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:`${7/* Size */}px solid transparent`,borderRight:`${7/* Size */}px solid transparent`},".cm-tooltip-above &":{bottom:`-${7/* Size */}px`,"&:before":{borderTop:`${7/* Size */}px solid #bbb`},"&:after":{borderTop:`${7/* Size */}px solid #f5f5f5`,bottom:"1px"}},".cm-tooltip-below &":{top:`-${7/* Size */}px`,"&:before":{borderBottom:`${7/* Size */}px solid #bbb`},"&:after":{borderBottom:`${7/* Size */}px solid #f5f5f5`,top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}});const noOffset={x:0,y:0};/**
3255
3262
  Facet to which an extension can add a value to show a tooltip.
3256
- */const showTooltip=/*@__PURE__*/Facet.define({enables:[tooltipPlugin,baseTheme$2]});const showHoverTooltip=/*@__PURE__*/Facet.define();class HoverTooltipHost{constructor(view){this.view=view;this.mounted=false;this.dom=document.createElement("div");this.dom.classList.add("cm-tooltip-hover");this.manager=new TooltipViewManager(view,showHoverTooltip,t=>this.createHostedView(t));}// Needs to be static so that host tooltip instances always match
3263
+ */const showTooltip=/*@__PURE__*/Facet.define({enables:[tooltipPlugin,baseTheme$3]});const showHoverTooltip=/*@__PURE__*/Facet.define();class HoverTooltipHost{constructor(view){this.view=view;this.mounted=false;this.dom=document.createElement("div");this.dom.classList.add("cm-tooltip-hover");this.manager=new TooltipViewManager(view,showHoverTooltip,t=>this.createHostedView(t));}// Needs to be static so that host tooltip instances always match
3257
3264
  static create(view){return new HoverTooltipHost(view);}createHostedView(tooltip){let hostedView=tooltip.create(this.view);hostedView.dom.classList.add("cm-tooltip-section");this.dom.appendChild(hostedView.dom);if(this.mounted&&hostedView.mount)hostedView.mount(this.view);return hostedView;}mount(view){for(let hostedView of this.manager.tooltipViews){if(hostedView.mount)hostedView.mount(view);}this.mounted=true;}positioned(){for(let hostedView of this.manager.tooltipViews){if(hostedView.positioned)hostedView.positioned();}}update(update){this.manager.update(update);}}const showHoverTooltipHost=/*@__PURE__*/showTooltip.compute([showHoverTooltip],state=>{let tooltips=state.facet(showHoverTooltip).filter(t=>t);if(tooltips.length===0)return null;return {pos:Math.min(...tooltips.map(t=>t.pos)),end:Math.max(...tooltips.filter(t=>t.end!=null).map(t=>t.end)),create:HoverTooltipHost.create,above:tooltips[0].above,arrow:tooltips.some(t=>t.arrow)};});class HoverPlugin{constructor(view,source,field,setHover,hoverTime){this.view=view;this.source=source;this.field=field;this.setHover=setHover;this.hoverTime=hoverTime;this.hoverTimeout=-1;this.restartTimeout=-1;this.pending=null;this.lastMove={x:0,y:0,target:view.dom,time:0};this.checkHover=this.checkHover.bind(this);view.dom.addEventListener("mouseleave",this.mouseleave=this.mouseleave.bind(this));view.dom.addEventListener("mousemove",this.mousemove=this.mousemove.bind(this));}update(){if(this.pending){this.pending=null;clearTimeout(this.restartTimeout);this.restartTimeout=setTimeout(()=>this.startHover(),20);}}get active(){return this.view.state.field(this.field);}checkHover(){this.hoverTimeout=-1;if(this.active)return;let hovered=Date.now()-this.lastMove.time;if(hovered<this.hoverTime)this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime-hovered);else this.startHover();}startHover(){clearTimeout(this.restartTimeout);let{lastMove}=this;let pos=this.view.contentDOM.contains(lastMove.target)?this.view.posAtCoords(lastMove):null;if(pos==null)return;let posCoords=this.view.coordsAtPos(pos);if(posCoords==null||lastMove.y<posCoords.top||lastMove.y>posCoords.bottom||lastMove.x<posCoords.left-this.view.defaultCharacterWidth||lastMove.x>posCoords.right+this.view.defaultCharacterWidth)return;let bidi=this.view.bidiSpans(this.view.state.doc.lineAt(pos)).find(s=>s.from<=pos&&s.to>=pos);let rtl=bidi&&bidi.dir==Direction.RTL?-1:1;let open=this.source(this.view,pos,lastMove.x<posCoords.left?-rtl:rtl);if(open===null||open===void 0?void 0:open.then){let pending=this.pending={pos};open.then(result=>{if(this.pending==pending){this.pending=null;if(result)this.view.dispatch({effects:this.setHover.of(result)});}},e=>logException(this.view.state,e,"hover tooltip"));}else if(open){this.view.dispatch({effects:this.setHover.of(open)});}}mousemove(event){var _a;this.lastMove={x:event.clientX,y:event.clientY,target:event.target,time:Date.now()};if(this.hoverTimeout<0)this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime);let tooltip=this.active;if(tooltip&&!isInTooltip(this.lastMove.target)||this.pending){let{pos}=tooltip||this.pending,end=(_a=tooltip===null||tooltip===void 0?void 0:tooltip.end)!==null&&_a!==void 0?_a:pos;if(pos==end?this.view.posAtCoords(this.lastMove)!=pos:!isOverRange(this.view,pos,end,event.clientX,event.clientY,6/* MaxDist */)){this.view.dispatch({effects:this.setHover.of(null)});this.pending=null;}}}mouseleave(){clearTimeout(this.hoverTimeout);this.hoverTimeout=-1;if(this.active)this.view.dispatch({effects:this.setHover.of(null)});}destroy(){clearTimeout(this.hoverTimeout);this.view.dom.removeEventListener("mouseleave",this.mouseleave);this.view.dom.removeEventListener("mousemove",this.mousemove);}}function isInTooltip(elt){for(let cur=elt;cur;cur=cur.parentNode)if(cur.nodeType==1&&cur.classList.contains("cm-tooltip"))return true;return false;}function isOverRange(view,from,to,x,y,margin){let range=document.createRange();let fromDOM=view.domAtPos(from),toDOM=view.domAtPos(to);range.setEnd(toDOM.node,toDOM.offset);range.setStart(fromDOM.node,fromDOM.offset);let rects=range.getClientRects();range.detach();for(let i=0;i<rects.length;i++){let rect=rects[i];let dist=Math.max(rect.top-y,y-rect.bottom,rect.left-x,x-rect.right);if(dist<=margin)return true;}return false;}/**
3258
3265
  Set up a hover tooltip, which shows up when the pointer hovers
3259
3266
  over ranges of text. The callback is called when the mouse hovers
@@ -3266,7 +3273,9 @@ pointer is before the position, 1 if after the position.
3266
3273
  Note that all hover tooltips are hosted within a single tooltip
3267
3274
  container element. This allows multiple tooltips over the same
3268
3275
  range to be "merged" together without overlapping.
3269
- */function hoverTooltip(source,options={}){let setHover=StateEffect.define();let hoverState=StateField.define({create(){return null;},update(value,tr){if(value&&(options.hideOnChange&&(tr.docChanged||tr.selection)||options.hideOn&&options.hideOn(tr,value)))return null;if(value&&tr.docChanged){let newPos=tr.changes.mapPos(value.pos,-1,MapMode.TrackDel);if(newPos==null)return null;let copy=Object.assign(Object.create(null),value);copy.pos=newPos;if(value.end!=null)copy.end=tr.changes.mapPos(value.end);value=copy;}for(let effect of tr.effects){if(effect.is(setHover))value=effect.value;if(effect.is(closeHoverTooltipEffect))value=null;}return value;},provide:f=>showHoverTooltip.from(f)});return [hoverState,ViewPlugin.define(view=>new HoverPlugin(view,source,hoverState,setHover,options.hoverTime||300/* Time */)),showHoverTooltipHost];}const closeHoverTooltipEffect=/*@__PURE__*/StateEffect.define();const panelConfig=/*@__PURE__*/Facet.define({combine(configs){let topContainer,bottomContainer;for(let c of configs){topContainer=topContainer||c.topContainer;bottomContainer=bottomContainer||c.bottomContainer;}return {topContainer,bottomContainer};}});const panelPlugin=/*@__PURE__*/ViewPlugin.fromClass(class{constructor(view){this.input=view.state.facet(showPanel);this.specs=this.input.filter(s=>s);this.panels=this.specs.map(spec=>spec(view));let conf=view.state.facet(panelConfig);this.top=new PanelGroup(view,true,conf.topContainer);this.bottom=new PanelGroup(view,false,conf.bottomContainer);this.top.sync(this.panels.filter(p=>p.top));this.bottom.sync(this.panels.filter(p=>!p.top));for(let p of this.panels){p.dom.classList.add("cm-panel");if(p.mount)p.mount();}}update(update){let conf=update.state.facet(panelConfig);if(this.top.container!=conf.topContainer){this.top.sync([]);this.top=new PanelGroup(update.view,true,conf.topContainer);}if(this.bottom.container!=conf.bottomContainer){this.bottom.sync([]);this.bottom=new PanelGroup(update.view,false,conf.bottomContainer);}this.top.syncClasses();this.bottom.syncClasses();let input=update.state.facet(showPanel);if(input!=this.input){let specs=input.filter(x=>x);let panels=[],top=[],bottom=[],mount=[];for(let spec of specs){let known=this.specs.indexOf(spec),panel;if(known<0){panel=spec(update.view);mount.push(panel);}else {panel=this.panels[known];if(panel.update)panel.update(update);}panels.push(panel);(panel.top?top:bottom).push(panel);}this.specs=specs;this.panels=panels;this.top.sync(top);this.bottom.sync(bottom);for(let p of mount){p.dom.classList.add("cm-panel");if(p.mount)p.mount();}}else {for(let p of this.panels)if(p.update)p.update(update);}}destroy(){this.top.sync([]);this.bottom.sync([]);}},{provide:plugin=>EditorView.scrollMargins.of(view=>{let value=view.plugin(plugin);return value&&{top:value.top.scrollMargin(),bottom:value.bottom.scrollMargin()};})});class PanelGroup{constructor(view,top,container){this.view=view;this.top=top;this.container=container;this.dom=undefined;this.classes="";this.panels=[];this.syncClasses();}sync(panels){for(let p of this.panels)if(p.destroy&&panels.indexOf(p)<0)p.destroy();this.panels=panels;this.syncDOM();}syncDOM(){if(this.panels.length==0){if(this.dom){this.dom.remove();this.dom=undefined;}return;}if(!this.dom){this.dom=document.createElement("div");this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom";this.dom.style[this.top?"top":"bottom"]="0";let parent=this.container||this.view.dom;parent.insertBefore(this.dom,this.top?parent.firstChild:null);}let curDOM=this.dom.firstChild;for(let panel of this.panels){if(panel.dom.parentNode==this.dom){while(curDOM!=panel.dom)curDOM=rm(curDOM);curDOM=curDOM.nextSibling;}else {this.dom.insertBefore(panel.dom,curDOM);}}while(curDOM)curDOM=rm(curDOM);}scrollMargin(){return !this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top);}syncClasses(){if(!this.container||this.classes==this.view.themeClasses)return;for(let cls of this.classes.split(" "))if(cls)this.container.classList.remove(cls);for(let cls of (this.classes=this.view.themeClasses).split(" "))if(cls)this.container.classList.add(cls);}}function rm(node){let next=node.nextSibling;node.remove();return next;}/**
3276
+ */function hoverTooltip(source,options={}){let setHover=StateEffect.define();let hoverState=StateField.define({create(){return null;},update(value,tr){if(value&&(options.hideOnChange&&(tr.docChanged||tr.selection)||options.hideOn&&options.hideOn(tr,value)))return null;if(value&&tr.docChanged){let newPos=tr.changes.mapPos(value.pos,-1,MapMode.TrackDel);if(newPos==null)return null;let copy=Object.assign(Object.create(null),value);copy.pos=newPos;if(value.end!=null)copy.end=tr.changes.mapPos(value.end);value=copy;}for(let effect of tr.effects){if(effect.is(setHover))value=effect.value;if(effect.is(closeHoverTooltipEffect))value=null;}return value;},provide:f=>showHoverTooltip.from(f)});return [hoverState,ViewPlugin.define(view=>new HoverPlugin(view,source,hoverState,setHover,options.hoverTime||300/* Time */)),showHoverTooltipHost];}/**
3277
+ Get the active tooltip view for a given tooltip, if available.
3278
+ */function getTooltip(view,tooltip){let plugin=view.plugin(tooltipPlugin);if(!plugin)return null;let found=plugin.manager.tooltips.indexOf(tooltip);return found<0?null:plugin.manager.tooltipViews[found];}const closeHoverTooltipEffect=/*@__PURE__*/StateEffect.define();const panelConfig=/*@__PURE__*/Facet.define({combine(configs){let topContainer,bottomContainer;for(let c of configs){topContainer=topContainer||c.topContainer;bottomContainer=bottomContainer||c.bottomContainer;}return {topContainer,bottomContainer};}});const panelPlugin=/*@__PURE__*/ViewPlugin.fromClass(class{constructor(view){this.input=view.state.facet(showPanel);this.specs=this.input.filter(s=>s);this.panels=this.specs.map(spec=>spec(view));let conf=view.state.facet(panelConfig);this.top=new PanelGroup(view,true,conf.topContainer);this.bottom=new PanelGroup(view,false,conf.bottomContainer);this.top.sync(this.panels.filter(p=>p.top));this.bottom.sync(this.panels.filter(p=>!p.top));for(let p of this.panels){p.dom.classList.add("cm-panel");if(p.mount)p.mount();}}update(update){let conf=update.state.facet(panelConfig);if(this.top.container!=conf.topContainer){this.top.sync([]);this.top=new PanelGroup(update.view,true,conf.topContainer);}if(this.bottom.container!=conf.bottomContainer){this.bottom.sync([]);this.bottom=new PanelGroup(update.view,false,conf.bottomContainer);}this.top.syncClasses();this.bottom.syncClasses();let input=update.state.facet(showPanel);if(input!=this.input){let specs=input.filter(x=>x);let panels=[],top=[],bottom=[],mount=[];for(let spec of specs){let known=this.specs.indexOf(spec),panel;if(known<0){panel=spec(update.view);mount.push(panel);}else {panel=this.panels[known];if(panel.update)panel.update(update);}panels.push(panel);(panel.top?top:bottom).push(panel);}this.specs=specs;this.panels=panels;this.top.sync(top);this.bottom.sync(bottom);for(let p of mount){p.dom.classList.add("cm-panel");if(p.mount)p.mount();}}else {for(let p of this.panels)if(p.update)p.update(update);}}destroy(){this.top.sync([]);this.bottom.sync([]);}},{provide:plugin=>EditorView.scrollMargins.of(view=>{let value=view.plugin(plugin);return value&&{top:value.top.scrollMargin(),bottom:value.bottom.scrollMargin()};})});class PanelGroup{constructor(view,top,container){this.view=view;this.top=top;this.container=container;this.dom=undefined;this.classes="";this.panels=[];this.syncClasses();}sync(panels){for(let p of this.panels)if(p.destroy&&panels.indexOf(p)<0)p.destroy();this.panels=panels;this.syncDOM();}syncDOM(){if(this.panels.length==0){if(this.dom){this.dom.remove();this.dom=undefined;}return;}if(!this.dom){this.dom=document.createElement("div");this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom";this.dom.style[this.top?"top":"bottom"]="0";let parent=this.container||this.view.dom;parent.insertBefore(this.dom,this.top?parent.firstChild:null);}let curDOM=this.dom.firstChild;for(let panel of this.panels){if(panel.dom.parentNode==this.dom){while(curDOM!=panel.dom)curDOM=rm(curDOM);curDOM=curDOM.nextSibling;}else {this.dom.insertBefore(panel.dom,curDOM);}}while(curDOM)curDOM=rm(curDOM);}scrollMargin(){return !this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top);}syncClasses(){if(!this.container||this.classes==this.view.themeClasses)return;for(let cls of this.classes.split(" "))if(cls)this.container.classList.remove(cls);for(let cls of (this.classes=this.view.themeClasses).split(" "))if(cls)this.container.classList.add(cls);}}function rm(node){let next=node.nextSibling;node.remove();return next;}/**
3270
3279
  Opening a panel is done by providing a constructor function for
3271
3280
  the panel through this facet. (The panel is closed again when its
3272
3281
  constructor is no longer provided.) Values of `null` are ignored.
@@ -4074,476 +4083,7 @@ direction `dir`. Only the `brackets` and `maxScanDistance`
4074
4083
  properties are used from `config`, if given. Returns null if no
4075
4084
  bracket was found at `pos`, or a match result otherwise.
4076
4085
  */function matchBrackets(state,pos,dir,config={}){let maxScanDistance=config.maxScanDistance||DefaultScanDist,brackets=config.brackets||DefaultBrackets;let tree=syntaxTree(state),node=tree.resolveInner(pos,dir);for(let cur=node;cur;cur=cur.parent){let matches=matchingNodes(cur.type,dir,brackets);if(matches&&cur.from<cur.to)return matchMarkedBrackets(state,pos,dir,cur,matches,brackets);}return matchPlainBrackets(state,pos,dir,tree,node.type,maxScanDistance,brackets);}function matchMarkedBrackets(_state,_pos,dir,token,matching,brackets){let parent=token.parent,firstToken={from:token.from,to:token.to};let depth=0,cursor=parent===null||parent===void 0?void 0:parent.cursor();if(cursor&&(dir<0?cursor.childBefore(token.from):cursor.childAfter(token.to)))do{if(dir<0?cursor.to<=token.from:cursor.from>=token.to){if(depth==0&&matching.indexOf(cursor.type.name)>-1&&cursor.from<cursor.to){return {start:firstToken,end:{from:cursor.from,to:cursor.to},matched:true};}else if(matchingNodes(cursor.type,dir,brackets)){depth++;}else if(matchingNodes(cursor.type,-dir,brackets)){depth--;if(depth==0)return {start:firstToken,end:cursor.from==cursor.to?undefined:{from:cursor.from,to:cursor.to},matched:false};}}}while(dir<0?cursor.prevSibling():cursor.nextSibling());return {start:firstToken,matched:false};}function matchPlainBrackets(state,pos,dir,tree,tokenType,maxScanDistance,brackets){let startCh=dir<0?state.sliceDoc(pos-1,pos):state.sliceDoc(pos,pos+1);let bracket=brackets.indexOf(startCh);if(bracket<0||bracket%2==0!=dir>0)return null;let startToken={from:dir<0?pos-1:pos,to:dir>0?pos+1:pos};let iter=state.doc.iterRange(pos,dir>0?state.doc.length:0),depth=0;for(let distance=0;!iter.next().done&&distance<=maxScanDistance;){let text=iter.value;if(dir<0)distance+=text.length;let basePos=pos+distance*dir;for(let pos=dir>0?0:text.length-1,end=dir>0?text.length:-1;pos!=end;pos+=dir){let found=brackets.indexOf(text[pos]);if(found<0||tree.resolve(basePos+pos,1).type!=tokenType)continue;if(found%2==0==dir>0){depth++;}else if(depth==1){// Closing
4077
- 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
4078
- // parent pointer
4079
- /// The default maximum length of a `TreeBuffer` node (1024).
4080
- 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)
4081
- /// can have metadata associated with it in props. Instances of this
4082
- /// class represent prop names.
4083
- class NodeProp{/// Create a new node prop type.
4084
- 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
4085
- /// [`NodeSet.extend`](#common.NodeSet.extend) or
4086
- /// [`LRParser.configure`](#lr.ParserConfig.props) to compute
4087
- /// prop values for each node type in the set. Takes a [match
4088
- /// object](#common.NodeType^match) or function that returns undefined
4089
- /// if the node type doesn't get this prop, and the prop's value if
4090
- /// it does.
4091
- 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
4092
- /// delimiters, this holds an array of node names (written as a
4093
- /// space-separated string when declaring this prop in a grammar)
4094
- /// for the node types of closing delimiters that match it.
4095
- NodeProp.closedBy=new NodeProp({deserialize:str=>str.split(" ")});/// The inverse of [`closedBy`](#common.NodeProp^closedBy). This is
4096
- /// attached to closing delimiters, holding an array of node names
4097
- /// of types of matching opening delimiters.
4098
- NodeProp.openedBy=new NodeProp({deserialize:str=>str.split(" ")});/// Used to assign node types to groups (for example, all node
4099
- /// types that represent an expression could be tagged with an
4100
- /// `"Expression"` group).
4101
- NodeProp.group=new NodeProp({deserialize:str=>str.split(" ")});/// The hash of the [context](#lr.ContextTracker.constructor)
4102
- /// that the node was parsed in, if any. Used to limit reuse of
4103
- /// contextual nodes.
4104
- NodeProp.contextHash=new NodeProp({perNode:true});/// The distance beyond the end of the node that the tokenizer
4105
- /// looked ahead for any of the tokens inside the node. (The LR
4106
- /// parser only stores this when it is larger than 25, for
4107
- /// efficiency reasons.)
4108
- NodeProp.lookAhead=new NodeProp({perNode:true});/// This per-node prop is used to replace a given node, or part of a
4109
- /// node, with another tree. This is useful to include trees from
4110
- /// different languages.
4111
- NodeProp.mounted=new NodeProp({perNode:true});const noProps=Object.create(null);/// Each node in a syntax tree has a node type associated with it.
4112
- class NodeType{/// @internal
4113
- constructor(/// The name of the node type. Not necessarily unique, but if the
4114
- /// grammar was written properly, different node types with the
4115
- /// same name within a node set should play the same semantic
4116
- /// role.
4117
- name,/// @internal
4118
- props,/// The id of this node in its set. Corresponds to the term ids
4119
- /// used in the parser.
4120
- id,/// @internal
4121
- 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
4122
- /// the prop isn't present on this node.
4123
- prop(prop){return this.props[prop.id];}/// True when this is the top node of a grammar.
4124
- get isTop(){return (this.flags&1/* Top */)>0;}/// True when this node is produced by a skip rule.
4125
- get isSkipped(){return (this.flags&2/* Skipped */)>0;}/// Indicates whether this is an error node.
4126
- get isError(){return (this.flags&4/* Error */)>0;}/// When true, this node type doesn't correspond to a user-declared
4127
- /// named node, for example because it is used to cache repetition.
4128
- get isAnonymous(){return (this.flags&8/* Anonymous */)>0;}/// Returns true when this node's name or one of its
4129
- /// [groups](#common.NodeProp^group) matches the given string.
4130
- 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
4131
- /// specifying an object whose property names are node or
4132
- /// [group](#common.NodeProp^group) names. Often useful with
4133
- /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple
4134
- /// names, separated by spaces, in a single property name to map
4135
- /// multiple node names to a single value.
4136
- 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.
4137
- NodeType.none=new NodeType("",Object.create(null),0,8/* Anonymous */);/// A node set holds a collection of node types. It is used to
4138
- /// compactly represent trees by storing their type ids, rather than a
4139
- /// full pointer to the type object, in a numeric array. Each parser
4140
- /// [has](#lr.LRParser.nodeSet) a node set, and [tree
4141
- /// buffers](#common.TreeBuffer) can only store collections of nodes
4142
- /// from the same set. A set can have a maximum of 2**16 (65536) node
4143
- /// types in it, so that the ids fit into 16-bit typed array slots.
4144
- class NodeSet{/// Create a set with the given types. The `id` property of each
4145
- /// type should correspond to its position within the array.
4146
- constructor(/// The node types in this set, by id.
4147
- 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
4148
- /// arguments to this method should be created with
4149
- /// [`NodeProp.add`](#common.NodeProp.add).
4150
- 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 `|`
4151
- /// operator to enable multiple ones.
4152
- var IterMode;(function(IterMode){/// When enabled, iteration will only visit [`Tree`](#common.Tree)
4153
- /// objects, not nodes packed into
4154
- /// [`TreeBuffer`](#common.TreeBuffer)s.
4155
- IterMode[IterMode["ExcludeBuffers"]=1]="ExcludeBuffers";/// Enable this to make iteration include anonymous nodes (such as
4156
- /// the nodes that wrap repeated grammar constructs into a balanced
4157
- /// tree).
4158
- IterMode[IterMode["IncludeAnonymous"]=2]="IncludeAnonymous";/// By default, regular [mounted](#common.NodeProp^mounted) nodes
4159
- /// replace their base node in iteration. Enable this to ignore them
4160
- /// instead.
4161
- IterMode[IterMode["IgnoreMounts"]=4]="IgnoreMounts";/// This option only applies in
4162
- /// [`enter`](#common.SyntaxNode.enter)-style methods. It tells the
4163
- /// library to not enter mounted overlays if one covers the given
4164
- /// position.
4165
- IterMode[IterMode["IgnoreOverlays"]=8]="IgnoreOverlays";})(IterMode||(IterMode={}));/// A piece of syntax tree. There are two ways to approach these
4166
- /// trees: the way they are actually stored in memory, and the
4167
- /// convenient way.
4168
- ///
4169
- /// Syntax trees are stored as a tree of `Tree` and `TreeBuffer`
4170
- /// objects. By packing detail information into `TreeBuffer` leaf
4171
- /// nodes, the representation is made a lot more memory-efficient.
4172
- ///
4173
- /// However, when you want to actually work with tree nodes, this
4174
- /// representation is very awkward, so most client code will want to
4175
- /// use the [`TreeCursor`](#common.TreeCursor) or
4176
- /// [`SyntaxNode`](#common.SyntaxNode) interface instead, which provides
4177
- /// a view on some part of this data structure, and can be used to
4178
- /// move around to adjacent nodes.
4179
- class Tree{/// Construct a new tree. See also [`Tree.build`](#common.Tree^build).
4180
- constructor(/// The type of the top node.
4181
- type,/// This node's child nodes.
4182
- children,/// The positions (offsets relative to the start of this tree) of
4183
- /// the children.
4184
- positions,/// The total length of this tree
4185
- length,/// Per-node [node props](#common.NodeProp) to associate with this node.
4186
- props){this.type=type;this.children=children;this.positions=positions;this.length=length;/// @internal
4187
- 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
4188
- 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
4189
- /// the tree. Mode can be used to [control](#common.IterMode) which
4190
- /// nodes the cursor visits.
4191
- cursor(mode=0){return new TreeCursor(this.topNode,mode);}/// Get a [tree cursor](#common.TreeCursor) pointing into this tree
4192
- /// at the given position and side (see
4193
- /// [`moveTo`](#common.TreeCursor.moveTo).
4194
- 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
4195
- /// tree.
4196
- get topNode(){return new TreeNode(this,0,0,null);}/// Get the [syntax node](#common.SyntaxNode) at the given position.
4197
- /// If `side` is -1, this will move into nodes that end at the
4198
- /// position. If 1, it'll move into nodes that start at the
4199
- /// position. With 0, it'll only enter nodes that cover the position
4200
- /// from both sides.
4201
- 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
4202
- /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
4203
- /// pointing into the innermost overlaid tree at the given position
4204
- /// (with parent links going through all parent structure, including
4205
- /// the host trees).
4206
- 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
4207
- /// node that touches the `from`/`to` region (if given) before
4208
- /// running over such a node's children, and `leave` (if given) when
4209
- /// leaving the node. When `enter` returns `false`, that node will
4210
- /// not have its children iterated over (or `leave` called).
4211
- 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
4212
- /// node. Works with both per-node and per-type props.
4213
- 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
4214
- /// format that can be passed to the [`Tree`](#common.Tree)
4215
- /// constructor.
4216
- 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
4217
- /// which may have children grouped into subtrees with type
4218
- /// [`NodeType.none`](#common.NodeType^none).
4219
- 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,
4220
- /// or a cursor over such a buffer.
4221
- static build(data){return buildTree(data);}}/// The empty tree
4222
- 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
4223
- /// node. In such a buffer, nodes are stored in prefix order (parents
4224
- /// before children, with the endIndex of the parent indicating which
4225
- /// children belong to it)
4226
- class TreeBuffer{/// Create a tree buffer.
4227
- constructor(/// The buffer's content.
4228
- buffer,/// The total length of the group of nodes in the buffer.
4229
- length,/// The node set used in this buffer.
4230
- set){this.buffer=buffer;this.length=length;this.set=set;}/// @internal
4231
- get type(){return NodeType.none;}/// @internal
4232
- 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
4233
- 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
4234
- 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
4235
- 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
4236
- 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
4237
- 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)
4238
- 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
4239
- 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
4240
- 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
4241
- /// allows you to move to adjacent nodes.
4242
- class TreeCursor{/// @internal
4243
- constructor(node,/// @internal
4244
- mode=0){this.mode=mode;/// @internal
4245
- this.buffer=null;this.stack=[];/// @internal
4246
- 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`.
4247
- 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
4248
- toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString();}/// @internal
4249
- 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
4250
- /// false, the node has no child, and the cursor has not been moved.
4251
- firstChild(){return this.enterChild(1,0,4/* DontCare */);}/// Move the cursor to this node's last child.
4252
- lastChild(){return this.enterChild(-1,0,4/* DontCare */);}/// Move the cursor to the first child that ends after `pos`.
4253
- childAfter(pos){return this.enterChild(1,pos,2/* After */);}/// Move to the last child that starts before `pos`.
4254
- childBefore(pos){return this.enterChild(-1,pos,-2/* Before */);}/// Move the cursor to the child around `pos`. If side is -1 the
4255
- /// child may end at that position, when 1 it may start there. This
4256
- /// will also enter [overlaid](#common.MountedTree.overlay)
4257
- /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is
4258
- /// set to false.
4259
- 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.
4260
- 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
4261
- 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.
4262
- nextSibling(){return this.sibling(1);}/// Move to this node's previous sibling, if any.
4263
- 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
4264
- /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR))
4265
- /// traversal, going from a node to its first child or, if the
4266
- /// current node is empty or `enter` is false, its next sibling or
4267
- /// the next sibling of the first parent node that has one.
4268
- next(enter=true){return this.move(1,enter);}/// Move to the next node in a last-to-first pre-order traveral. A
4269
- /// node is followed by its last child or, if it has none, its
4270
- /// previous sibling or the previous sibling of the first parent
4271
- /// node that has one.
4272
- prev(enter=true){return this.move(-1,enter);}/// Move the cursor to the innermost node that covers `pos`. If
4273
- /// `side` is -1, it will enter nodes that end at `pos`. If it is 1,
4274
- /// it will enter nodes that start at `pos`.
4275
- moveTo(pos,side=0){// Move up to a node that actually holds the position, if possible
4276
- 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
4277
- while(this.enterChild(1,pos,side)){}return this;}/// Get a [syntax node](#common.SyntaxNode) at the cursor's current
4278
- /// position.
4279
- 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
4280
- /// any. Will return null when the node is in a [tree
4281
- /// buffer](#common.TreeBuffer).
4282
- get tree(){return this.buffer?null:this._tree._tree;}/// Iterate over the current node and all its descendants, calling
4283
- /// `enter` when entering a node and `leave`, if given, when leaving
4284
- /// one. When `enter` returns `false`, any children of that node are
4285
- /// skipped, and `leave` isn't called for it.
4286
- 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
4287
- /// of direct parent node names. Empty strings in the context array
4288
- /// are treated as wildcards.
4289
- 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
4290
- 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
4291
- 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
4292
- 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
4293
- // together in a TreeBuffer, and don't contain any reused nodes
4294
- // (which can't be stored in a buffer).
4295
- // If `inRepeat` is > -1, ignore node boundaries of that type for
4296
- // nesting, but make sure the end falls either at the start
4297
- // (`maxSize`) or before such a node.
4298
- 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
4299
- if(fork.id==inRepeat&&nodeSize>=0){// Except that we store the current state as a valid return
4300
- // value.
4301
- 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.
4302
- balanceType,// The direct children and their positions
4303
- children,positions,// The index range in children/positions to use
4304
- from,to,// The start position of the nodes, relative to their parent.
4305
- start,// Length of the outer node
4306
- length,// Function to build the top node of the balanced tree
4307
- mkTop,// Function to build internal nodes for the balanced tree
4308
- 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
4309
- 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.
4310
- class Parser{/// Start a parse, returning a [partial parse](#common.PartialParse)
4311
- /// object. [`fragments`](#common.TreeFragment) can be passed in to
4312
- /// make the parse incremental.
4313
- ///
4314
- /// By default, the entire input is parsed. You can pass `ranges`,
4315
- /// which should be a sorted array of non-empty, non-overlapping
4316
- /// ranges, to parse only those ranges. The tree returned in that
4317
- /// case will start at `ranges[0].from`.
4318
- 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.
4319
- 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
4320
- /// parsing progress. They also provide some properties and methods
4321
- /// that external code such as a tokenizer can use to get information
4322
- /// about the parse state.
4323
- class Stack{/// @internal
4324
- constructor(/// The parse that this stack is part of @internal
4325
- p,/// Holds state, input pos, buffer index triplets for all but the
4326
- /// top state @internal
4327
- stack,/// The current parse state @internal
4328
- state,// The position at which the next reduce should take place. This
4329
- // can be less than `this.pos` when skipped expressions have been
4330
- // added to the stack (which should be moved outside of the next
4331
- // reduction)
4332
- /// @internal
4333
- reducePos,/// The input position up to which this stack has parsed.
4334
- pos,/// The dynamic score of the stack, including dynamic precedence
4335
- /// and error-recovery penalties
4336
- /// @internal
4337
- score,// The output buffer. Holds (type, start, end, size) quads
4338
- // representing nodes created by the parser, where `size` is
4339
- // amount of buffer array entries covered by this node.
4340
- /// @internal
4341
- buffer,// The base offset of the buffer. When stacks are split, the split
4342
- // instance shared the buffer history with its parent up to
4343
- // `bufferBase`, which is the absolute offset (including the
4344
- // offset of previous splits) into the buffer at which this stack
4345
- // starts writing.
4346
- /// @internal
4347
- bufferBase,/// @internal
4348
- curContext,/// @internal
4349
- lookAhead=0,// A parent stack from which this was split off, if any. This is
4350
- // set up so that it always points to a stack that has some
4351
- // additional buffer content, never to a stack with an equal
4352
- // `bufferBase`.
4353
- /// @internal
4354
- 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
4355
- toString(){return `[${this.stack.filter((_,i)=>i%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`;}// Start an empty stack
4356
- /// @internal
4357
- 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
4358
- /// any. Its type will depend on the context tracker's type
4359
- /// parameter, or it will be `null` if there is no context
4360
- /// tracker.
4361
- get context(){return this.curContext?this.curContext.context:null;}// Push a state onto the stack, tracking its start position as well
4362
- // as the buffer base at that point.
4363
- /// @internal
4364
- pushState(state,start){this.stack.push(this.state,start,this.bufferBase+this.buffer.length);this.state=state;}// Apply a reduce action
4365
- /// @internal
4366
- 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
4367
- // the stack without popping anything off.
4368
- 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
4369
- // be dropped. Note that with `StayFlag` reductions we need to
4370
- // consume two extra frames (the dummy parent node for the skipped
4371
- // expression and the state that we'll be staying in, which should
4372
- // be moved to `this.state`).
4373
- 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
4374
- 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
4375
- /// @internal
4376
- 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
4377
- 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
4378
- this.buffer.push(term,start,end,size);}else {// There may be skipped nodes that have to be moved forward
4379
- 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
4380
- 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
4381
- /// @internal
4382
- 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
4383
- 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
4384
- this.pos=nextEnd;this.shiftContext(next,start);if(next<=this.p.parser.maxNode)this.buffer.push(next,start,nextEnd,4);}}// Apply an action
4385
- /// @internal
4386
- 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.
4387
- /// @internal
4388
- 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
4389
- // that `this.stack` tends to stay quite shallow, this isn't very
4390
- // expensive.
4391
- /// @internal
4392
- split(){let parent=this;let off=parent.buffer.length;// Because the top of the buffer (after this.pos) may be mutated
4393
- // to reorder reductions and skipped tokens, and shared buffers
4394
- // should be immutable, this copies any outstanding skipped tokens
4395
- // to the new buffer, and puts the base pointer before them.
4396
- 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.
4397
- 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.
4398
- /// @internal
4399
- 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
4400
- /// after some reductions) on this stack. This can be useful for
4401
- /// external tokenizers that want to make sure they only provide a
4402
- /// given token when it applies.
4403
- 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
4404
- // inserts some missing token or rule.
4405
- /// @internal
4406
- 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
4407
- // be done.
4408
- /// @internal
4409
- 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
4410
- 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
4411
- /// top state, since any other states must be able to continue
4412
- /// somehow). @internal
4413
- 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
4414
- /// when this.stack.length == 3 (state is directly below the top
4415
- /// state). @internal
4416
- restart(){this.state=this.stack[0];this.stack.length=0;}/// @internal
4417
- 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.
4418
- get parser(){return this.p.parser;}/// Test whether a given dialect (by numeric ID, as exported from
4419
- /// the terms file) is enabled.
4420
- 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
4421
- 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
4422
- 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
4423
- setLookAhead(lookAhead){if(lookAhead>this.lookAhead){this.emitLookAhead();this.lookAhead=lookAhead;}}/// @internal
4424
- 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
4425
- // an entire stack
4426
- 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
4427
- // the parent-stack-walking necessary to read the nodes.
4428
- 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
4429
- /// through this interface. It presents the input as a stream of
4430
- /// characters, tracking lookahead and hiding the complexity of
4431
- /// [ranges](#common.Parser.parse^ranges) from tokenizer code.
4432
- class InputStream{/// @internal
4433
- constructor(/// @internal
4434
- input,/// @internal
4435
- ranges){this.input=input;this.ranges=ranges;/// @internal
4436
- this.chunk="";/// @internal
4437
- this.chunkOff=0;/// Backup chunk
4438
- this.chunk2="";this.chunk2Pos=0;/// The character code of the next code unit in the input, or -1
4439
- /// when the stream is at the end of the input.
4440
- this.next=-1;/// @internal
4441
- 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
4442
- /// `.next`, `.peek(-1)` gives you the previous character, and so
4443
- /// on.
4444
- ///
4445
- /// Note that looking around during tokenizing creates dependencies
4446
- /// on potentially far-away content, which may reduce the
4447
- /// effectiveness incremental parsing—when looking forward—or even
4448
- /// cause invalid reparses when looking backward more than 25 code
4449
- /// units, since the library does not track lookbehind.
4450
- 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
4451
- /// current stream position, but you can pass an offset (relative to
4452
- /// the stream position) to change that.
4453
- 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
4454
- /// the new value of [`next`](#lr.InputStream.next).
4455
- 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
4456
- 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
4457
- 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
4458
- 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
4459
- // state:
4460
- //
4461
- // - A group bitmask, indicating what token groups are reachable from
4462
- // this state, so that paths that can only lead to tokens not in
4463
- // any of the current groups can be cut off early.
4464
- //
4465
- // - The position of the end of the state's sequence of accepting
4466
- // tokens
4467
- //
4468
- // - The number of outgoing edges for the state
4469
- //
4470
- // - The accepting tokens, as (token id, group mask) pairs
4471
- //
4472
- // - The outgoing edges, as (start character, end character, state
4473
- // index) triples, with end character being exclusive
4474
- //
4475
- // This function interprets that data, running through a stream as
4476
- // long as new states with the a matching group mask can be reached,
4477
- // and updating `token` when it matches a token.
4478
- 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
4479
- // Accept tokens in this state, possibly overwriting
4480
- // lower-precedence / shorter tokens
4481
- 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
4482
- 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
4483
- // used here
4484
- 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
4485
- 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
4486
- 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
4487
- 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
4488
- 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
4489
- 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
4490
- // add this many elements to their buffers, prune one.
4491
- Rec[Rec["MinBufferLengthPrune"]=500]="MinBufferLengthPrune";Rec[Rec["ForceReduceLimit"]=10]="ForceReduceLimit";// Once a stack reaches this depth (in .stack.length) force-reduce
4492
- // it back to CutTo to avoid creating trees that overflow the stack
4493
- // on recursive traversal.
4494
- 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;// ♔, ♕, ♖, ♗, ♘, ♙, ♠, ♡, ♢, ♣, ♤, ♥, ♦, ♧
4495
- 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
4496
- // `this.pos` and try to advance them to a further position. If no
4497
- // stack for such a position is found, it'll start error-recovery.
4498
- //
4499
- // When the parse is finished, this will return a syntax tree. When
4500
- // not, it returns `null`.
4501
- advance(){let stacks=this.stacks,pos=this.minStackPos;// This will hold stacks beyond `pos`.
4502
- let newStacks=this.stacks=[];let stopped,stoppedTokens;// Keep advancing any stacks at `pos` until they either move
4503
- // forward or can't be advanced. Gather stacks that can't be
4504
- // advanced further in `stopped`.
4505
- 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
4506
- // running without splitting for a while, to avoid getting stuck
4507
- // with multiple successful stacks running endlessly on.
4508
- 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
4509
- // stack can't advance normally. When `split` and `stacks` are
4510
- // given, stacks split off by ambiguous operations will be pushed to
4511
- // `split`, or added to `stacks` if they move `pos` forward.
4512
- 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
4513
- // (possibly updated) stack if it got stuck, or null if it moved
4514
- // forward and was given to `pushStackDedup`.
4515
- 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.
4516
- 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
4517
- /// by `lezer-generator`.
4518
- class LRParser extends Parser{/// @internal
4519
- constructor(spec){super();/// @internal
4520
- 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
4521
- 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
4522
- 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
4523
- stateSlot(state,slot){return this.states[state*6/* Size */+slot];}/// @internal
4524
- stateFlag(state,flag){return (this.stateSlot(state,0/* Flags */)&flag)>0;}/// @internal
4525
- 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
4526
- /// goto jumps. @internal
4527
- 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
4528
- 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
4529
- /// given settings modified. Settings not provided in `config` are
4530
- /// kept from the original parser.
4531
- configure(config){// Hideous reflection-based kludge to make it easy to create a
4532
- // slightly modified copy of a parser.
4533
- 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)
4534
- /// are registered for this parser.
4535
- hasWrappers(){return this.wrappers.length>0;}/// Returns the name associated with a given term. This will only
4536
- /// work for all terms when the parser was generated with the
4537
- /// `--names` option. By default, only the names of tagged terms are
4538
- /// stored.
4539
- 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
4540
- /// types. @internal
4541
- get eofTerm(){return this.maxNode+1;}/// The type of top node produced by the parser.
4542
- get topNode(){return this.nodeSet.types[this.top[1]];}/// @internal
4543
- dynamicPrecedence(term){let prec=this.dynamicPrecedences;return prec==null?0:prec[term]||0;}/// @internal
4544
- 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
4545
- 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.
4546
- 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'#FXQOQ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$nXk$nXl$nXm$nXo$nXq$nXs$nXt$nXu$nXv$nXw$nXy$nX!e$nX$b$sX$f$nX!c$nX$c$nX~O$c#rO!c$mXq$mX~P&rO!c#tO~O$h#uO~O$c#vO#r$vX~O#r#xO~O#y#yO~O$c#zOZ$aX~OX#|O~OZ#}O~O^$OO~P&rO$c$POe$dX~OX$RO~Oe$SO~O!S$TO~O#O$UO#P$UO~O#O$UO~O!P$VO~O#Y#eO#[#fO#_#fO$`!dOq$uP~O$c#UO$Y$eaq$ea~Oo!XOy!`O!e!WO$f!VOTjiXji]jiajibjigjiijikjiljimji!Pji!Qji!Rji!Tji!Wji!_ji!cji!hji!jji!lji!mji!pji!rji!tji!uji!vji!xji!zji!{ji!|ji!}ji#Pji#Qji#Rji#aji#hji#sji$Yji$`ji$pji$qji$rji$wji$cjiqji^ji#rjiejiZji~Os!SOt!SOu!TOv!TOw!UO~P!#pOo!XOw!UOy!`O!e!WO$f!VOTriXri]riaribrigriirikrilrimrisritri!Pri!Qri!Rri!Tri!Wri!_ri!cri!hri!jri!lri!mri!pri!rri!tri!uri!vri!xri!zri!{ri!|ri!}ri#Pri#Qri#Rri#ari#hri#sri$Yri$`ri$pri$qri$rri$wri$criqri^ri#rrieriZri~Ou!TOv!TO~P!'lOurivri~P!'lOo!XOy!`O!e!WO$f!VOTriXri]riaribrigriirikrilrimrisritriurivri!Pri!Qri!Rri!Tri!Wri!_ri!cri!hri!jri!lri!mri!pri!rri!tri!uri!vri!xri!zri!{ri!|ri!}ri#Pri#Qri#Rri#ari#hri#sri$Yri$`ri$pri$qri$rri$wri$criqri^ri#rriZri_rieri~Owri$bri~P!+rO!c$_O~P&rO$h$`O~O$c$aOq$lX~Oq$cO~O#Z$dO~O#]$dO#^$dO~Oo!XOy!`O!e!WO$f!VOTfi]fiafibfigfi!Pfi!Qfi!Rfi!Tfi!Wfi!_fi!cfi!hfi!jfi!lfi!mfi!pfi!rfi!tfi!ufi!vfi!xfi!zfi!{fi!|fi!}fi#Pf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'y'{(U(V(W(X(Y(^(_(a(c(e(g(j(o(rR!cXR#b!XQ!m_R#c!X$rZOPRSgi!O!R!S!T!U!W!X![!]!^!_#U#W#r#u#|#}$O$R$S$`$e%W%e%f%l&c&d&e&f&g&h&i&j&p&q&r&s&t&u&y&{&}'R'^'_'`'b'c'd'e'f'g'h'i'p'q'r'u'x'z'|'}(O(P(Q(R(S(T(Z([(](`(b(d(f(l(m(w({U!g]`#pV!k^_#jW!h]^_#jQ!n`R$r#pX$Y#T'j(x(|R!rc",nodeNames:"⚠ LineComment BlockComment Expressions ForExpression for InExpressions InExpression Name in IterationContext return IfExpression if then else QuantifiedExpression some every InExpressions InExpression satisfies Disjunction or Conjunction and Comparison CompareOp CompareOp between PositiveUnaryTest ( PositiveUnaryTests ) ArithmeticExpression ArithOp ArithOp ArithOp ArithOp ArithOp InstanceOf instance of Type QualifiedName SpecialType days time duration years months date > ListType list < ContextType context ContextEntryTypes ContextEntryType FunctionType function ArgumentTypes ArgumentType PathExpression ] FilterExpression [ FunctionInvocation SpecialFunctionName string length upper case lower substring before after starts with ends contains insert index distinct values met by overlaps finished started day year week month get value entries NamedParameters NamedParameter ParameterName SpecialParameterName start position decimal sep separator grouping PositionalParameters null NumericLiteral StringLiteral BooleanLiteral DateTimeLiteral DateTimeConstructor VariableName ? SimplePositiveUnaryTest Interval ParenthesizedExpression List FunctionDefinition FormalParameters FormalParameter external FunctionBody } { Context ContextEntry Key SpecialKey method signature UnaryTests Wildcard not",maxTerm:177,nodeProps:[["group",-18,4,12,16,22,24,26,34,40,64,66,68,115,116,117,119,120,121,128,"Expression",-5,109,110,111,112,113,"Expression Literal"],["closedBy",31,")",67,"]",127,"}"],["openedBy",33,"(",65,"[",126,"{"]],skippedNodes:[0,1,2],repeatNodeCount:11,tokenData:"+Y~R|XY#{Y^#{pq#{qr$prs${tu%oxy&yyz'Oz{'T{|'b|}'g}!O'l!O!P'y!P!Q(c!Q![)n![!]*P!]!^*U!^!_*Z!_!`$v!`!a*j!a!b%o!c!}%o!}#O*t#P#Q*y#Q#R']#R#S%o#T#o%o#o#p+O#q#r+T#y#z#{$f$g#{#BY#BZ#{$IS$I_#{$I`$Ib%o$I|$JO#{$JT$JU#{$KV$KW#{$Kh%#t%o&/x&Et%o&FU&FV#{&FV;'S%o;'S;:j&s?&r?Ah%o?BY?Mn%o~$QY$[~X^#{pq#{#y#z#{$f$g#{#BY#BZ#{$IS$I_#{$I|$JO#{$JT$JU#{$KV$KW#{&FU&FV#{~$sP!_!`$v~${Ok~~%QU$q~OY${Zr${rs%ds#O${#O#P%i#P~${~%iO$q~~%lPO~${~%t_$`~tu%o!Q![%o!a!b%o!c!}%o#R#S%o#T#o%o1p4U%o$I`$Ib%o$Je$Jg%o$Kh%#t%o&/x&Et%o&FV;'S%o;'S;:j&s?&r?Ah%o?BY?Mn%o~&vP;=`<%l%o~'OOo~~'TOq~~'YPu~z{']~'bOw~~'gOs~~'lO$c~R'qPtP!`!a'tQ'yO$jQ~(OQ$f~!O!P(U!Q![(Z~(ZO$b~~(`P$p~!Q![(Z~(hQv~z{(n!P!Q)c~(qROz(nz{(z{~(n~(}TOz(nz{(z{!P(n!P!Q)^!Q~(n~)cOQ~~)hQP~OY)cZ~)c~)sQ$p~!O!P)y!Q![)n~)|P!Q![(Z~*UO$h~~*ZO$w~R*bP!XQlP!_!`*eP*jOlPR*qP!UQlP!_!`*e~*yO!e~~+OO!c~~+TO#s~~+YO#r~",tokenizers:[0,1],topRules:{"Expressions":[0,3],"UnaryTests":[1,134]},dynamicPrecedences:{"24":-1,"68":-1,"151":-1},specialized:[{term:154,get:value=>spec_identifier[value]||-1}],tokenPrec:0});const highlightTags=styleTags({VariableName:tags.variableName,NumericLiteral:tags.number,QualifiedName:tags.name,Name:tags.name,BooleanLiteral:tags.bool,StringLiteral:tags.string,LineComment:tags.lineComment,BlockComment:tags.blockComment,'( )':tags.paren,BuiltInFunctionName:tags.function(tags.variableName),BuiltInType:tags.function(tags.variableName),ListType:tags.function(tags.variableName),ContextType:tags.function(tags.variableName),FunctionType:tags.function(tags.variableName),DateAndTime:tags.function(tags.variableName),'DateTimeConstructor!':tags.function(tags.variableName),'for in return null':tags.atom,List:tags.list,Interval:tags.list});const parserWithMetadata=parser.configure({props:[highlightTags]});const FeelLanguage=LRLanguage.define({parser:parserWithMetadata});function language(){return new LanguageSupport(FeelLanguage,[]);}/**
4086
+ return {start:startToken,end:{from:basePos+pos,to:basePos+pos+1},matched:found>>1==bracket>>1};}else {depth--;}}if(dir>0)distance+=text.length;}return iter.done?{start:startToken,matched:false}:null;}const noTokens=/*@__PURE__*/Object.create(null);const typeArray=[NodeType$1.none];const warned=[];const defaultTable=/*@__PURE__*/Object.create(null);for(let[legacyName,name]of [["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","typeName"],["attribute","propertyName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])defaultTable[legacyName]=/*@__PURE__*/createTokenType(noTokens,name);function warnForPart(part,msg){if(warned.indexOf(part)>-1)return;warned.push(part);console.warn(msg);}function createTokenType(extra,tagStr){let tag=null;for(let part of tagStr.split(".")){let value=extra[part]||tags[part];if(!value){warnForPart(part,`Unknown highlighting tag ${part}`);}else if(typeof value=="function"){if(!tag)warnForPart(part,`Modifier ${part} used at start of tag`);else tag=value(tag);}else {if(tag)warnForPart(part,`Tag ${part} used as modifier`);else tag=value;}}if(!tag)return 0;let name=tagStr.replace(/ /g,"_"),type=NodeType$1.define({id:typeArray.length,name,props:[styleTags({[name]:tag})]});typeArray.push(type);return type.id;}/**
4547
4087
  Comment or uncomment the current selection. Will use line comments
4548
4088
  if available, otherwise falling back to block comments.
4549
4089
  */const toggleComment=target=>{let config=getConfig(target.state);return config.line?toggleLineComment(target):config.block?toggleBlockCommentByLine(target):false;};function command(f,option){return ({state,dispatch})=>{if(state.readOnly)return false;let tr=f(option,state);if(!tr)return false;dispatch(state.update(tr));return true;};}/**
@@ -4780,7 +4320,7 @@ The default keymap. Includes all bindings from
4780
4320
  - Shift-Alt-a: [`toggleBlockComment`](https://codemirror.net/6/docs/ref/#commands.toggleBlockComment).
4781
4321
  */const defaultKeymap=/*@__PURE__*/[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:cursorSyntaxLeft,shift:selectSyntaxLeft},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:cursorSyntaxRight,shift:selectSyntaxRight},{key:"Alt-ArrowUp",run:moveLineUp},{key:"Shift-Alt-ArrowUp",run:copyLineUp},{key:"Alt-ArrowDown",run:moveLineDown},{key:"Shift-Alt-ArrowDown",run:copyLineDown},{key:"Escape",run:simplifySelection},{key:"Mod-Enter",run:insertBlankLine},{key:"Alt-l",mac:"Ctrl-l",run:selectLine},{key:"Mod-i",run:selectParentSyntax,preventDefault:true},{key:"Mod-[",run:indentLess},{key:"Mod-]",run:indentMore},{key:"Mod-Alt-\\",run:indentSelection},{key:"Shift-Mod-k",run:deleteLine},{key:"Shift-Mod-\\",run:cursorMatchingBracket},{key:"Mod-/",run:toggleComment},{key:"Alt-A",run:toggleBlockComment}].concat(standardKeymap);function crelt(){var elt=arguments[0];if(typeof elt=="string")elt=document.createElement(elt);var i=1,next=arguments[1];if(next&&typeof next=="object"&&next.nodeType==null&&!Array.isArray(next)){for(var name in next)if(Object.prototype.hasOwnProperty.call(next,name)){var value=next[name];if(typeof value=="string")elt.setAttribute(name,value);else if(value!=null)elt[name]=value;}i++;}for(;i<arguments.length;i++)add(elt,arguments[i]);return elt;}function add(elt,child){if(typeof child=="string"){elt.appendChild(document.createTextNode(child));}else if(child==null);else if(child.nodeType!=null){elt.appendChild(child);}else if(Array.isArray(child)){for(var i=0;i<child.length;i++)add(elt,child[i]);}else {throw new RangeError("Unsupported child node: "+child);}}class SelectedDiagnostic{constructor(from,to,diagnostic){this.from=from;this.to=to;this.diagnostic=diagnostic;}}class LintState{constructor(diagnostics,panel,selected){this.diagnostics=diagnostics;this.panel=panel;this.selected=selected;}static init(diagnostics,panel,state){// Filter the list of diagnostics for which to create markers
4782
4322
  let markedDiagnostics=diagnostics;let diagnosticFilter=state.facet(lintConfig).markerFilter;if(diagnosticFilter)markedDiagnostics=diagnosticFilter(markedDiagnostics);let ranges=Decoration.set(markedDiagnostics.map(d=>{// For zero-length ranges or ranges covering only a line break, create a widget
4783
- return d.from==d.to||d.from==d.to-1&&state.doc.lineAt(d.from).to==d.from?Decoration.widget({widget:new DiagnosticWidget(d),diagnostic:d}).range(d.from):Decoration.mark({attributes:{class:"cm-lintRange cm-lintRange-"+d.severity},diagnostic:d}).range(d.from,d.to);}),true);return new LintState(ranges,panel,findDiagnostic(ranges));}}function findDiagnostic(diagnostics,diagnostic=null,after=0){let found=null;diagnostics.between(after,1e9,(from,to,{spec})=>{if(diagnostic&&spec.diagnostic!=diagnostic)return;found=new SelectedDiagnostic(from,to,spec.diagnostic);return false;});return found;}function hideTooltip(tr,tooltip){return !!(tr.effects.some(e=>e.is(setDiagnosticsEffect))||tr.changes.touchesRange(tooltip.pos));}function maybeEnableLint(state,effects){return state.field(lintState,false)?effects:effects.concat(StateEffect.appendConfig.of([lintState,EditorView.decorations.compute([lintState],state=>{let{selected,panel}=state.field(lintState);return !selected||!panel||selected.from==selected.to?Decoration.none:Decoration.set([activeMark.range(selected.from,selected.to)]);}),hoverTooltip(lintTooltip,{hideOn:hideTooltip}),baseTheme$1]));}/**
4323
+ return d.from==d.to||d.from==d.to-1&&state.doc.lineAt(d.from).to==d.from?Decoration.widget({widget:new DiagnosticWidget(d),diagnostic:d}).range(d.from):Decoration.mark({attributes:{class:"cm-lintRange cm-lintRange-"+d.severity},diagnostic:d}).range(d.from,d.to);}),true);return new LintState(ranges,panel,findDiagnostic(ranges));}}function findDiagnostic(diagnostics,diagnostic=null,after=0){let found=null;diagnostics.between(after,1e9,(from,to,{spec})=>{if(diagnostic&&spec.diagnostic!=diagnostic)return;found=new SelectedDiagnostic(from,to,spec.diagnostic);return false;});return found;}function hideTooltip(tr,tooltip){return !!(tr.effects.some(e=>e.is(setDiagnosticsEffect))||tr.changes.touchesRange(tooltip.pos));}function maybeEnableLint(state,effects){return state.field(lintState,false)?effects:effects.concat(StateEffect.appendConfig.of([lintState,EditorView.decorations.compute([lintState],state=>{let{selected,panel}=state.field(lintState);return !selected||!panel||selected.from==selected.to?Decoration.none:Decoration.set([activeMark.range(selected.from,selected.to)]);}),hoverTooltip(lintTooltip,{hideOn:hideTooltip}),baseTheme$2]));}/**
4784
4324
  Returns a transaction spec which updates the current set of
4785
4325
  diagnostics, and enables the lint extension if if wasn't already
4786
4326
  active.
@@ -4800,7 +4340,580 @@ this.moveSelection((this.selectedIndex+1)%this.items.length);}else if(event.keyC
4800
4340
  this.moveSelection(0);}else if(event.keyCode==35){// End
4801
4341
  this.moveSelection(this.items.length-1);}else if(event.keyCode==13){// Enter
4802
4342
  this.view.focus();}else if(event.keyCode>=65&&event.keyCode<=90&&this.selectedIndex>=0){// A-Z
4803
- 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$1=/*@__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
4343
+ let{diagnostic}=this.items[this.selectedIndex],keys=assignKeys(diagnostic.actions);for(let i=0;i<keys.length;i++)if(keys[i].toUpperCase().charCodeAt(0)==event.keyCode){let found=findDiagnostic(this.view.state.field(lintState).diagnostics,diagnostic);if(found)diagnostic.actions[i].apply(view,found.from,found.to);}}else {return;}event.preventDefault();};let onclick=event=>{for(let i=0;i<this.items.length;i++){if(this.items[i].dom.contains(event.target))this.moveSelection(i);}};this.list=crelt("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown,onclick});this.dom=crelt("div",{class:"cm-panel-lint"},this.list,crelt("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>closeLintPanel(this.view)},"×"));this.update();}get selectedIndex(){let selected=this.view.state.field(lintState).selected;if(!selected)return -1;for(let i=0;i<this.items.length;i++)if(this.items[i].diagnostic==selected.diagnostic)return i;return -1;}update(){let{diagnostics,selected}=this.view.state.field(lintState);let i=0,needsSync=false,newSelectedItem=null;diagnostics.between(0,this.view.state.doc.length,(_start,_end,{spec})=>{let found=-1,item;for(let j=i;j<this.items.length;j++)if(this.items[j].diagnostic==spec.diagnostic){found=j;break;}if(found<0){item=new PanelItem(this.view,spec.diagnostic);this.items.splice(i,0,item);needsSync=true;}else {item=this.items[found];if(found>i){this.items.splice(i,found-i);needsSync=true;}}if(selected&&item.diagnostic==selected.diagnostic){if(!item.dom.hasAttribute("aria-selected")){item.dom.setAttribute("aria-selected","true");newSelectedItem=item;}}else if(item.dom.hasAttribute("aria-selected")){item.dom.removeAttribute("aria-selected");}i++;});while(i<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0)){needsSync=true;this.items.pop();}if(this.items.length==0){this.items.push(new PanelItem(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")}));needsSync=true;}if(newSelectedItem){this.list.setAttribute("aria-activedescendant",newSelectedItem.id);this.view.requestMeasure({key:this,read:()=>({sel:newSelectedItem.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel,panel})=>{if(sel.top<panel.top)this.list.scrollTop-=panel.top-sel.top;else if(sel.bottom>panel.bottom)this.list.scrollTop+=sel.bottom-panel.bottom;}});}else if(this.selectedIndex<0){this.list.removeAttribute("aria-activedescendant");}if(needsSync)this.sync();}sync(){let domPos=this.list.firstChild;function rm(){let prev=domPos;domPos=prev.nextSibling;prev.remove();}for(let item of this.items){if(item.dom.parentNode==this.list){while(domPos!=item.dom)rm();domPos=item.dom.nextSibling;}else {this.list.insertBefore(item.dom,domPos);}}while(domPos)rm();}moveSelection(selectedIndex){if(this.selectedIndex<0)return;let field=this.view.state.field(lintState);let selection=findDiagnostic(field.diagnostics,this.items[selectedIndex].diagnostic);if(!selection)return;this.view.dispatch({selection:{anchor:selection.from,head:selection.to},scrollIntoView:true,effects:movePanelSelection.of(selection)});}static open(view){return new LintPanel(view);}}function svg(content,attrs=`viewBox="0 0 40 40"`){return `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${attrs}>${encodeURIComponent(content)}</svg>')`;}function underline(color){return svg(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${color}" fill="none" stroke-width=".7"/>`,`width="6" height="3"`);}const baseTheme$2=/*@__PURE__*/EditorView.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:/*@__PURE__*/underline("#d11")},".cm-lintRange-warning":{backgroundImage:/*@__PURE__*/underline("orange")},".cm-lintRange-info":{backgroundImage:/*@__PURE__*/underline("#999")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}});/**
4344
+ An instance of this is passed to completion source functions.
4345
+ */class CompletionContext{/**
4346
+ Create a new completion context. (Mostly useful for testing
4347
+ completion sources—in the editor, the extension will create
4348
+ these for you.)
4349
+ */constructor(/**
4350
+ The editor state that the completion happens in.
4351
+ */state,/**
4352
+ The position at which the completion is happening.
4353
+ */pos,/**
4354
+ Indicates whether completion was activated explicitly, or
4355
+ implicitly by typing. The usual way to respond to this is to
4356
+ only return completions when either there is part of a
4357
+ completable entity before the cursor, or `explicit` is true.
4358
+ */explicit){this.state=state;this.pos=pos;this.explicit=explicit;/**
4359
+ @internal
4360
+ */this.abortListeners=[];}/**
4361
+ Get the extent, content, and (if there is a token) type of the
4362
+ token before `this.pos`.
4363
+ */tokenBefore(types){let token=syntaxTree(this.state).resolveInner(this.pos,-1);while(token&&types.indexOf(token.name)<0)token=token.parent;return token?{from:token.from,to:this.pos,text:this.state.sliceDoc(token.from,this.pos),type:token.type}:null;}/**
4364
+ Get the match of the given expression directly before the
4365
+ cursor.
4366
+ */matchBefore(expr){let line=this.state.doc.lineAt(this.pos);let start=Math.max(line.from,this.pos-250);let str=line.text.slice(start-line.from,this.pos-line.from);let found=str.search(ensureAnchor(expr,false));return found<0?null:{from:start+found,to:this.pos,text:str.slice(found)};}/**
4367
+ Yields true when the query has been aborted. Can be useful in
4368
+ asynchronous queries to avoid doing work that will be ignored.
4369
+ */get aborted(){return this.abortListeners==null;}/**
4370
+ Allows you to register abort handlers, which will be called when
4371
+ the query is
4372
+ [aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted).
4373
+ */addEventListener(type,listener){if(type=="abort"&&this.abortListeners)this.abortListeners.push(listener);}}function toSet(chars){let flat=Object.keys(chars).join("");let words=/\w/.test(flat);if(words)flat=flat.replace(/\w/g,"");return `[${words?"\\w":""}${flat.replace(/[^\w\s]/g,"\\$&")}]`;}function prefixMatch(options){let first=Object.create(null),rest=Object.create(null);for(let{label}of options){first[label[0]]=true;for(let i=1;i<label.length;i++)rest[label[i]]=true;}let source=toSet(first)+toSet(rest)+"*$";return [new RegExp("^"+source),new RegExp(source)];}/**
4374
+ Given a a fixed array of options, return an autocompleter that
4375
+ completes them.
4376
+ */function completeFromList(list){let options=list.map(o=>typeof o=="string"?{label:o}:o);let[validFor,match]=options.every(o=>/^\w+$/.test(o.label))?[/\w*$/,/\w+$/]:prefixMatch(options);return context=>{let token=context.matchBefore(match);return token||context.explicit?{from:token?token.from:context.pos,options,validFor}:null;};}class Option{constructor(completion,source,match){this.completion=completion;this.source=source;this.match=match;}}function cur(state){return state.selection.main.head;}// Make sure the given regexp has a $ at its end and, if `start` is
4377
+ // true, a ^ at its start.
4378
+ function ensureAnchor(expr,start){var _a;let{source}=expr;let addStart=start&&source[0]!="^",addEnd=source[source.length-1]!="$";if(!addStart&&!addEnd)return expr;return new RegExp(`${addStart?"^":""}(?:${source})${addEnd?"$":""}`,(_a=expr.flags)!==null&&_a!==void 0?_a:expr.ignoreCase?"i":"");}/**
4379
+ Helper function that returns a transaction spec which inserts a
4380
+ completion's text in the main selection range, and any other
4381
+ selection range that has the same text in front of it.
4382
+ */function insertCompletionText(state,text,from,to){return Object.assign(Object.assign({},state.changeByRange(range=>{if(range==state.selection.main)return {changes:{from:from,to:to,insert:text},range:EditorSelection.cursor(from+text.length)};let len=to-from;if(!range.empty||len&&state.sliceDoc(range.from-len,range.from)!=state.sliceDoc(from,to))return {range};return {changes:{from:range.from-len,to:range.from,insert:text},range:EditorSelection.cursor(range.from-len+text.length)};})),{userEvent:"input.complete"});}function applyCompletion(view,option){const apply=option.completion.apply||option.completion.label;let result=option.source;if(typeof apply=="string")view.dispatch(insertCompletionText(view.state,apply,result.from,result.to));else apply(view,option.completion,result.from,result.to);}const SourceCache=/*@__PURE__*/new WeakMap();function asSource(source){if(!Array.isArray(source))return source;let known=SourceCache.get(source);if(!known)SourceCache.set(source,known=completeFromList(source));return known;}// A pattern matcher for fuzzy completion matching. Create an instance
4383
+ // once for a pattern, and then use that to match any number of
4384
+ // completions.
4385
+ class FuzzyMatcher{constructor(pattern){this.pattern=pattern;this.chars=[];this.folded=[];// Buffers reused by calls to `match` to track matched character
4386
+ // positions.
4387
+ this.any=[];this.precise=[];this.byWord=[];for(let p=0;p<pattern.length;){let char=codePointAt(pattern,p),size=codePointSize(char);this.chars.push(char);let part=pattern.slice(p,p+size),upper=part.toUpperCase();this.folded.push(codePointAt(upper==part?part.toLowerCase():upper,0));p+=size;}this.astral=pattern.length!=this.chars.length;}// Matches a given word (completion) against the pattern (input).
4388
+ // Will return null for no match, and otherwise an array that starts
4389
+ // with the match score, followed by any number of `from, to` pairs
4390
+ // indicating the matched parts of `word`.
4391
+ //
4392
+ // The score is a number that is more negative the worse the match
4393
+ // is. See `Penalty` above.
4394
+ match(word){if(this.pattern.length==0)return [0];if(word.length<this.pattern.length)return null;let{chars,folded,any,precise,byWord}=this;// For single-character queries, only match when they occur right
4395
+ // at the start
4396
+ if(chars.length==1){let first=codePointAt(word,0);return first==chars[0]?[0,0,codePointSize(first)]:first==folded[0]?[-200/* CaseFold */,0,codePointSize(first)]:null;}let direct=word.indexOf(this.pattern);if(direct==0)return [0,0,this.pattern.length];let len=chars.length,anyTo=0;if(direct<0){for(let i=0,e=Math.min(word.length,200);i<e&&anyTo<len;){let next=codePointAt(word,i);if(next==chars[anyTo]||next==folded[anyTo])any[anyTo++]=i;i+=codePointSize(next);}// No match, exit immediately
4397
+ if(anyTo<len)return null;}// This tracks the extent of the precise (non-folded, not
4398
+ // necessarily adjacent) match
4399
+ let preciseTo=0;// Tracks whether there is a match that hits only characters that
4400
+ // appear to be starting words. `byWordFolded` is set to true when
4401
+ // a case folded character is encountered in such a match
4402
+ let byWordTo=0,byWordFolded=false;// If we've found a partial adjacent match, these track its state
4403
+ let adjacentTo=0,adjacentStart=-1,adjacentEnd=-1;let hasLower=/[a-z]/.test(word),wordAdjacent=true;// Go over the option's text, scanning for the various kinds of matches
4404
+ for(let i=0,e=Math.min(word.length,200),prevType=0/* NonWord */;i<e&&byWordTo<len;){let next=codePointAt(word,i);if(direct<0){if(preciseTo<len&&next==chars[preciseTo])precise[preciseTo++]=i;if(adjacentTo<len){if(next==chars[adjacentTo]||next==folded[adjacentTo]){if(adjacentTo==0)adjacentStart=i;adjacentEnd=i+1;adjacentTo++;}else {adjacentTo=0;}}}let ch,type=next<0xff?next>=48&&next<=57||next>=97&&next<=122?2/* Lower */:next>=65&&next<=90?1/* Upper */:0/* NonWord */:(ch=fromCodePoint(next))!=ch.toLowerCase()?1/* Upper */:ch!=ch.toUpperCase()?2/* Lower */:0/* NonWord */;if(!i||type==1/* Upper */&&hasLower||prevType==0/* NonWord */&&type!=0/* NonWord */){if(chars[byWordTo]==next||folded[byWordTo]==next&&(byWordFolded=true))byWord[byWordTo++]=i;else if(byWord.length)wordAdjacent=false;}prevType=type;i+=codePointSize(next);}if(byWordTo==len&&byWord[0]==0&&wordAdjacent)return this.result(-100/* ByWord */+(byWordFolded?-200/* CaseFold */:0),byWord,word);if(adjacentTo==len&&adjacentStart==0)return [-200/* CaseFold */-word.length,0,adjacentEnd];if(direct>-1)return [-700/* NotStart */-word.length,direct,direct+this.pattern.length];if(adjacentTo==len)return [-200/* CaseFold */+-700/* NotStart */-word.length,adjacentStart,adjacentEnd];if(byWordTo==len)return this.result(-100/* ByWord */+(byWordFolded?-200/* CaseFold */:0)+-700/* NotStart */+(wordAdjacent?0:-1100/* Gap */),byWord,word);return chars.length==2?null:this.result((any[0]?-700/* NotStart */:0)+-200/* CaseFold */+-1100/* Gap */,any,word);}result(score,positions,word){let result=[score-word.length],i=1;for(let pos of positions){let to=pos+(this.astral?codePointSize(codePointAt(word,pos)):1);if(i>1&&result[i-1]==pos)result[i-1]=to;else {result[i++]=pos;result[i++]=to;}}return result;}}const completionConfig=/*@__PURE__*/Facet.define({combine(configs){return combineConfig(configs,{activateOnTyping:true,override:null,closeOnBlur:true,maxRenderedOptions:100,defaultKeymap:true,optionClass:()=>"",aboveCursor:false,icons:true,addToOptions:[]},{defaultKeymap:(a,b)=>a&&b,closeOnBlur:(a,b)=>a&&b,icons:(a,b)=>a&&b,optionClass:(a,b)=>c=>joinClass(a(c),b(c)),addToOptions:(a,b)=>a.concat(b)});}});function joinClass(a,b){return a?b?a+" "+b:a:b;}function optionContent(config){let content=config.addToOptions.slice();if(config.icons)content.push({render(completion){let icon=document.createElement("div");icon.classList.add("cm-completionIcon");if(completion.type)icon.classList.add(...completion.type.split(/\s+/g).map(cls=>"cm-completionIcon-"+cls));icon.setAttribute("aria-hidden","true");return icon;},position:20});content.push({render(completion,_s,match){let labelElt=document.createElement("span");labelElt.className="cm-completionLabel";let{label}=completion,off=0;for(let j=1;j<match.length;){let from=match[j++],to=match[j++];if(from>off)labelElt.appendChild(document.createTextNode(label.slice(off,from)));let span=labelElt.appendChild(document.createElement("span"));span.appendChild(document.createTextNode(label.slice(from,to)));span.className="cm-completionMatchedText";off=to;}if(off<label.length)labelElt.appendChild(document.createTextNode(label.slice(off)));return labelElt;},position:50},{render(completion){if(!completion.detail)return null;let detailElt=document.createElement("span");detailElt.className="cm-completionDetail";detailElt.textContent=completion.detail;return detailElt;},position:80});return content.sort((a,b)=>a.position-b.position).map(a=>a.render);}function rangeAroundSelected(total,selected,max){if(total<=max)return {from:0,to:total};if(selected<=total>>1){let off=Math.floor(selected/max);return {from:off*max,to:(off+1)*max};}let off=Math.floor((total-selected)/max);return {from:total-(off+1)*max,to:total-off*max};}class CompletionTooltip{constructor(view,stateField){this.view=view;this.stateField=stateField;this.info=null;this.placeInfo={read:()=>this.measureInfo(),write:pos=>this.positionInfo(pos),key:this};let cState=view.state.field(stateField);let{options,selected}=cState.open;let config=view.state.facet(completionConfig);this.optionContent=optionContent(config);this.optionClass=config.optionClass;this.range=rangeAroundSelected(options.length,selected,config.maxRenderedOptions);this.dom=document.createElement("div");this.dom.className="cm-tooltip-autocomplete";this.dom.addEventListener("mousedown",e=>{for(let dom=e.target,match;dom&&dom!=this.dom;dom=dom.parentNode){if(dom.nodeName=="LI"&&(match=/-(\d+)$/.exec(dom.id))&&+match[1]<options.length){applyCompletion(view,options[+match[1]]);e.preventDefault();return;}}});this.list=this.dom.appendChild(this.createListBox(options,cState.id,this.range));this.list.addEventListener("scroll",()=>{if(this.info)this.view.requestMeasure(this.placeInfo);});}mount(){this.updateSel();}update(update){if(update.state.field(this.stateField)!=update.startState.field(this.stateField))this.updateSel();}positioned(){if(this.info)this.view.requestMeasure(this.placeInfo);}updateSel(){let cState=this.view.state.field(this.stateField),open=cState.open;if(open.selected<this.range.from||open.selected>=this.range.to){this.range=rangeAroundSelected(open.options.length,open.selected,this.view.state.facet(completionConfig).maxRenderedOptions);this.list.remove();this.list=this.dom.appendChild(this.createListBox(open.options,cState.id,this.range));this.list.addEventListener("scroll",()=>{if(this.info)this.view.requestMeasure(this.placeInfo);});}if(this.updateSelectedOption(open.selected)){if(this.info){this.info.remove();this.info=null;}let{completion}=open.options[open.selected];let{info}=completion;if(!info)return;let infoResult=typeof info==='string'?document.createTextNode(info):info(completion);if(!infoResult)return;if('then'in infoResult){infoResult.then(node=>{if(node&&this.view.state.field(this.stateField,false)==cState)this.addInfoPane(node);}).catch(e=>logException(this.view.state,e,"completion info"));}else {this.addInfoPane(infoResult);}}}addInfoPane(content){let dom=this.info=document.createElement("div");dom.className="cm-tooltip cm-completionInfo";dom.appendChild(content);this.dom.appendChild(dom);this.view.requestMeasure(this.placeInfo);}updateSelectedOption(selected){let set=null;for(let opt=this.list.firstChild,i=this.range.from;opt;opt=opt.nextSibling,i++){if(i==selected){if(!opt.hasAttribute("aria-selected")){opt.setAttribute("aria-selected","true");set=opt;}}else {if(opt.hasAttribute("aria-selected"))opt.removeAttribute("aria-selected");}}if(set)scrollIntoView(this.list,set);return set;}measureInfo(){let sel=this.dom.querySelector("[aria-selected]");if(!sel||!this.info)return null;let listRect=this.dom.getBoundingClientRect();let infoRect=this.info.getBoundingClientRect();let selRect=sel.getBoundingClientRect();if(selRect.top>Math.min(innerHeight,listRect.bottom)-10||selRect.bottom<Math.max(0,listRect.top)+10)return null;let top=Math.max(0,Math.min(selRect.top,innerHeight-infoRect.height))-listRect.top;let left=this.view.textDirection==Direction.RTL;let spaceLeft=listRect.left,spaceRight=innerWidth-listRect.right;if(left&&spaceLeft<Math.min(infoRect.width,spaceRight))left=false;else if(!left&&spaceRight<Math.min(infoRect.width,spaceLeft))left=true;return {top,left};}positionInfo(pos){if(this.info){this.info.style.top=(pos?pos.top:-1e6)+"px";if(pos){this.info.classList.toggle("cm-completionInfo-left",pos.left);this.info.classList.toggle("cm-completionInfo-right",!pos.left);}}}createListBox(options,id,range){const ul=document.createElement("ul");ul.id=id;ul.setAttribute("role","listbox");ul.setAttribute("aria-expanded","true");ul.setAttribute("aria-label",this.view.state.phrase("Completions"));for(let i=range.from;i<range.to;i++){let{completion,match}=options[i];const li=ul.appendChild(document.createElement("li"));li.id=id+"-"+i;li.setAttribute("role","option");let cls=this.optionClass(completion);if(cls)li.className=cls;for(let source of this.optionContent){let node=source(completion,this.view.state,match);if(node)li.appendChild(node);}}if(range.from)ul.classList.add("cm-completionListIncompleteTop");if(range.to<options.length)ul.classList.add("cm-completionListIncompleteBottom");return ul;}}// We allocate a new function instance every time the completion
4405
+ // changes to force redrawing/repositioning of the tooltip
4406
+ function completionTooltip(stateField){return view=>new CompletionTooltip(view,stateField);}function scrollIntoView(container,element){let parent=container.getBoundingClientRect();let self=element.getBoundingClientRect();if(self.top<parent.top)container.scrollTop-=parent.top-self.top;else if(self.bottom>parent.bottom)container.scrollTop+=self.bottom-parent.bottom;}// Used to pick a preferred option when two options with the same
4407
+ // label occur in the result.
4408
+ function score(option){return (option.boost||0)*100+(option.apply?10:0)+(option.info?5:0)+(option.type?1:0);}function sortOptions(active,state){let options=[],i=0;for(let a of active)if(a.hasResult()){if(a.result.filter===false){let getMatch=a.result.getMatch;for(let option of a.result.options){let match=[1e9-i++];if(getMatch)for(let n of getMatch(option))match.push(n);options.push(new Option(option,a,match));}}else {let matcher=new FuzzyMatcher(state.sliceDoc(a.from,a.to)),match;for(let option of a.result.options)if(match=matcher.match(option.label)){if(option.boost!=null)match[0]+=option.boost;options.push(new Option(option,a,match));}}}let result=[],prev=null;for(let opt of options.sort(cmpOption)){if(!prev||prev.label!=opt.completion.label||prev.detail!=opt.completion.detail||prev.type!=null&&opt.completion.type!=null&&prev.type!=opt.completion.type||prev.apply!=opt.completion.apply)result.push(opt);else if(score(opt.completion)>score(prev))result[result.length-1]=opt;prev=opt.completion;}return result;}class CompletionDialog{constructor(options,attrs,tooltip,timestamp,selected){this.options=options;this.attrs=attrs;this.tooltip=tooltip;this.timestamp=timestamp;this.selected=selected;}setSelected(selected,id){return selected==this.selected||selected>=this.options.length?this:new CompletionDialog(this.options,makeAttrs(id,selected),this.tooltip,this.timestamp,selected);}static build(active,state,id,prev,conf){let options=sortOptions(active,state);if(!options.length)return null;let selected=0;if(prev&&prev.selected){let selectedValue=prev.options[prev.selected].completion;for(let i=0;i<options.length;i++)if(options[i].completion==selectedValue){selected=i;break;}}return new CompletionDialog(options,makeAttrs(id,selected),{pos:active.reduce((a,b)=>b.hasResult()?Math.min(a,b.from):a,1e8),create:completionTooltip(completionState),above:conf.aboveCursor},prev?prev.timestamp:Date.now(),selected);}map(changes){return new CompletionDialog(this.options,this.attrs,Object.assign(Object.assign({},this.tooltip),{pos:changes.mapPos(this.tooltip.pos)}),this.timestamp,this.selected);}}class CompletionState{constructor(active,id,open){this.active=active;this.id=id;this.open=open;}static start(){return new CompletionState(none,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null);}update(tr){let{state}=tr,conf=state.facet(completionConfig);let sources=conf.override||state.languageDataAt("autocomplete",cur(state)).map(asSource);let active=sources.map(source=>{let value=this.active.find(s=>s.source==source)||new ActiveSource(source,this.active.some(a=>a.state!=0/* Inactive */)?1/* Pending */:0/* Inactive */);return value.update(tr,conf);});if(active.length==this.active.length&&active.every((a,i)=>a==this.active[i]))active=this.active;let open=tr.selection||active.some(a=>a.hasResult()&&tr.changes.touchesRange(a.from,a.to))||!sameResults(active,this.active)?CompletionDialog.build(active,state,this.id,this.open,conf):this.open&&tr.docChanged?this.open.map(tr.changes):this.open;if(!open&&active.every(a=>a.state!=1/* Pending */)&&active.some(a=>a.hasResult()))active=active.map(a=>a.hasResult()?new ActiveSource(a.source,0/* Inactive */):a);for(let effect of tr.effects)if(effect.is(setSelectedEffect))open=open&&open.setSelected(effect.value,this.id);return active==this.active&&open==this.open?this:new CompletionState(active,this.id,open);}get tooltip(){return this.open?this.open.tooltip:null;}get attrs(){return this.open?this.open.attrs:baseAttrs;}}function sameResults(a,b){if(a==b)return true;for(let iA=0,iB=0;;){while(iA<a.length&&!a[iA].hasResult)iA++;while(iB<b.length&&!b[iB].hasResult)iB++;let endA=iA==a.length,endB=iB==b.length;if(endA||endB)return endA==endB;if(a[iA++].result!=b[iB++].result)return false;}}const baseAttrs={"aria-autocomplete":"list"};function makeAttrs(id,selected){return {"aria-autocomplete":"list","aria-haspopup":"listbox","aria-activedescendant":id+"-"+selected,"aria-controls":id};}const none=[];function cmpOption(a,b){let dScore=b.match[0]-a.match[0];if(dScore)return dScore;return a.completion.label.localeCompare(b.completion.label);}function getUserEvent(tr){return tr.isUserEvent("input.type")?"input":tr.isUserEvent("delete.backward")?"delete":null;}class ActiveSource{constructor(source,state,explicitPos=-1){this.source=source;this.state=state;this.explicitPos=explicitPos;}hasResult(){return false;}update(tr,conf){let event=getUserEvent(tr),value=this;if(event)value=value.handleUserEvent(tr,event,conf);else if(tr.docChanged)value=value.handleChange(tr);else if(tr.selection&&value.state!=0/* Inactive */)value=new ActiveSource(value.source,0/* Inactive */);for(let effect of tr.effects){if(effect.is(startCompletionEffect))value=new ActiveSource(value.source,1/* Pending */,effect.value?cur(tr.state):-1);else if(effect.is(closeCompletionEffect))value=new ActiveSource(value.source,0/* Inactive */);else if(effect.is(setActiveEffect))for(let active of effect.value)if(active.source==value.source)value=active;}return value;}handleUserEvent(tr,type,conf){return type=="delete"||!conf.activateOnTyping?this.map(tr.changes):new ActiveSource(this.source,1/* Pending */);}handleChange(tr){return tr.changes.touchesRange(cur(tr.startState))?new ActiveSource(this.source,0/* Inactive */):this.map(tr.changes);}map(changes){return changes.empty||this.explicitPos<0?this:new ActiveSource(this.source,this.state,changes.mapPos(this.explicitPos));}}class ActiveResult extends ActiveSource{constructor(source,explicitPos,result,from,to){super(source,2/* Result */,explicitPos);this.result=result;this.from=from;this.to=to;}hasResult(){return true;}handleUserEvent(tr,type,conf){var _a;let from=tr.changes.mapPos(this.from),to=tr.changes.mapPos(this.to,1);let pos=cur(tr.state);if((this.explicitPos<0?pos<=from:pos<this.from)||pos>to||type=="delete"&&cur(tr.startState)==this.from)return new ActiveSource(this.source,type=="input"&&conf.activateOnTyping?1/* Pending */:0/* Inactive */);let explicitPos=this.explicitPos<0?-1:tr.changes.mapPos(this.explicitPos),updated;if(checkValid(this.result.validFor,tr.state,from,to))return new ActiveResult(this.source,explicitPos,this.result,from,to);if(this.result.update&&(updated=this.result.update(this.result,from,to,new CompletionContext(tr.state,pos,explicitPos>=0))))return new ActiveResult(this.source,explicitPos,updated,updated.from,(_a=updated.to)!==null&&_a!==void 0?_a:cur(tr.state));return new ActiveSource(this.source,1/* Pending */,explicitPos);}handleChange(tr){return tr.changes.touchesRange(this.from,this.to)?new ActiveSource(this.source,0/* Inactive */):this.map(tr.changes);}map(mapping){return mapping.empty?this:new ActiveResult(this.source,this.explicitPos<0?-1:mapping.mapPos(this.explicitPos),this.result,mapping.mapPos(this.from),mapping.mapPos(this.to,1));}}function checkValid(validFor,state,from,to){if(!validFor)return false;let text=state.sliceDoc(from,to);return typeof validFor=="function"?validFor(text,from,to,state):ensureAnchor(validFor,true).test(text);}const startCompletionEffect=/*@__PURE__*/StateEffect.define();const closeCompletionEffect=/*@__PURE__*/StateEffect.define();const setActiveEffect=/*@__PURE__*/StateEffect.define({map(sources,mapping){return sources.map(s=>s.map(mapping));}});const setSelectedEffect=/*@__PURE__*/StateEffect.define();const completionState=/*@__PURE__*/StateField.define({create(){return CompletionState.start();},update(value,tr){return value.update(tr);},provide:f=>[showTooltip.from(f,val=>val.tooltip),EditorView.contentAttributes.from(f,state=>state.attrs)]});const CompletionInteractMargin=75;/**
4409
+ Returns a command that moves the completion selection forward or
4410
+ backward by the given amount.
4411
+ */function moveCompletionSelection(forward,by="option"){return view=>{let cState=view.state.field(completionState,false);if(!cState||!cState.open||Date.now()-cState.open.timestamp<CompletionInteractMargin)return false;let step=1,tooltip;if(by=="page"&&(tooltip=getTooltip(view,cState.open.tooltip)))step=Math.max(2,Math.floor(tooltip.dom.offsetHeight/tooltip.dom.querySelector("li").offsetHeight)-1);let selected=cState.open.selected+step*(forward?1:-1),{length}=cState.open.options;if(selected<0)selected=by=="page"?0:length-1;else if(selected>=length)selected=by=="page"?length-1:0;view.dispatch({effects:setSelectedEffect.of(selected)});return true;};}/**
4412
+ Accept the current completion.
4413
+ */const acceptCompletion=view=>{let cState=view.state.field(completionState,false);if(view.state.readOnly||!cState||!cState.open||Date.now()-cState.open.timestamp<CompletionInteractMargin)return false;applyCompletion(view,cState.open.options[cState.open.selected]);return true;};/**
4414
+ Explicitly start autocompletion.
4415
+ */const startCompletion=view=>{let cState=view.state.field(completionState,false);if(!cState)return false;view.dispatch({effects:startCompletionEffect.of(true)});return true;};/**
4416
+ Close the currently active completion.
4417
+ */const closeCompletion=view=>{let cState=view.state.field(completionState,false);if(!cState||!cState.active.some(a=>a.state!=0/* Inactive */))return false;view.dispatch({effects:closeCompletionEffect.of(null)});return true;};class RunningQuery{constructor(active,context){this.active=active;this.context=context;this.time=Date.now();this.updates=[];// Note that 'undefined' means 'not done yet', whereas 'null' means
4418
+ // 'query returned null'.
4419
+ this.done=undefined;}}const DebounceTime=50,MaxUpdateCount=50,MinAbortTime=1000;const completionPlugin=/*@__PURE__*/ViewPlugin.fromClass(class{constructor(view){this.view=view;this.debounceUpdate=-1;this.running=[];this.debounceAccept=-1;this.composing=0/* None */;for(let active of view.state.field(completionState).active)if(active.state==1/* Pending */)this.startQuery(active);}update(update){let cState=update.state.field(completionState);if(!update.selectionSet&&!update.docChanged&&update.startState.field(completionState)==cState)return;let doesReset=update.transactions.some(tr=>{return (tr.selection||tr.docChanged)&&!getUserEvent(tr);});for(let i=0;i<this.running.length;i++){let query=this.running[i];if(doesReset||query.updates.length+update.transactions.length>MaxUpdateCount&&Date.now()-query.time>MinAbortTime){for(let handler of query.context.abortListeners){try{handler();}catch(e){logException(this.view.state,e);}}query.context.abortListeners=null;this.running.splice(i--,1);}else {query.updates.push(...update.transactions);}}if(this.debounceUpdate>-1)clearTimeout(this.debounceUpdate);this.debounceUpdate=cState.active.some(a=>a.state==1/* Pending */&&!this.running.some(q=>q.active.source==a.source))?setTimeout(()=>this.startUpdate(),DebounceTime):-1;if(this.composing!=0/* None */)for(let tr of update.transactions){if(getUserEvent(tr)=="input")this.composing=2/* Changed */;else if(this.composing==2/* Changed */&&tr.selection)this.composing=3/* ChangedAndMoved */;}}startUpdate(){this.debounceUpdate=-1;let{state}=this.view,cState=state.field(completionState);for(let active of cState.active){if(active.state==1/* Pending */&&!this.running.some(r=>r.active.source==active.source))this.startQuery(active);}}startQuery(active){let{state}=this.view,pos=cur(state);let context=new CompletionContext(state,pos,active.explicitPos==pos);let pending=new RunningQuery(active,context);this.running.push(pending);Promise.resolve(active.source(context)).then(result=>{if(!pending.context.aborted){pending.done=result||null;this.scheduleAccept();}},err=>{this.view.dispatch({effects:closeCompletionEffect.of(null)});logException(this.view.state,err);});}scheduleAccept(){if(this.running.every(q=>q.done!==undefined))this.accept();else if(this.debounceAccept<0)this.debounceAccept=setTimeout(()=>this.accept(),DebounceTime);}// For each finished query in this.running, try to create a result
4420
+ // or, if appropriate, restart the query.
4421
+ accept(){var _a;if(this.debounceAccept>-1)clearTimeout(this.debounceAccept);this.debounceAccept=-1;let updated=[];let conf=this.view.state.facet(completionConfig);for(let i=0;i<this.running.length;i++){let query=this.running[i];if(query.done===undefined)continue;this.running.splice(i--,1);if(query.done){let active=new ActiveResult(query.active.source,query.active.explicitPos,query.done,query.done.from,(_a=query.done.to)!==null&&_a!==void 0?_a:cur(query.updates.length?query.updates[0].startState:this.view.state));// Replay the transactions that happened since the start of
4422
+ // the request and see if that preserves the result
4423
+ for(let tr of query.updates)active=active.update(tr,conf);if(active.hasResult()){updated.push(active);continue;}}let current=this.view.state.field(completionState).active.find(a=>a.source==query.active.source);if(current&&current.state==1/* Pending */){if(query.done==null){// Explicitly failed. Should clear the pending status if it
4424
+ // hasn't been re-set in the meantime.
4425
+ let active=new ActiveSource(query.active.source,0/* Inactive */);for(let tr of query.updates)active=active.update(tr,conf);if(active.state!=1/* Pending */)updated.push(active);}else {// Cleared by subsequent transactions. Restart.
4426
+ this.startQuery(current);}}}if(updated.length)this.view.dispatch({effects:setActiveEffect.of(updated)});}},{eventHandlers:{blur(){let state=this.view.state.field(completionState,false);if(state&&state.tooltip&&this.view.state.facet(completionConfig).closeOnBlur)this.view.dispatch({effects:closeCompletionEffect.of(null)});},compositionstart(){this.composing=1/* Started */;},compositionend(){if(this.composing==3/* ChangedAndMoved */){// Safari fires compositionend events synchronously, possibly
4427
+ // from inside an update, so dispatch asynchronously to avoid reentrancy
4428
+ setTimeout(()=>this.view.dispatch({effects:startCompletionEffect.of(false)}),20);}this.composing=0/* None */;}}});const baseTheme$1=/*@__PURE__*/EditorView.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",listStyle:"none",margin:0,padding:0,"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer",padding:"1px 3px",lineHeight:1.2}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"···"',opacity:0.5,display:"block",textAlign:"center"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"300px"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'ƒ'"}},".cm-completionIcon-class":{"&:after":{content:"'○'"}},".cm-completionIcon-interface":{"&:after":{content:"'◌'"}},".cm-completionIcon-variable":{"&:after":{content:"'𝑥'"}},".cm-completionIcon-constant":{"&:after":{content:"'𝐶'"}},".cm-completionIcon-type":{"&:after":{content:"'𝑡'"}},".cm-completionIcon-enum":{"&:after":{content:"'∪'"}},".cm-completionIcon-property":{"&:after":{content:"'□'"}},".cm-completionIcon-keyword":{"&:after":{content:"'🔑\uFE0E'"}// Disable emoji rendering
4429
+ },".cm-completionIcon-namespace":{"&:after":{content:"'▢'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}});const closedBracket=/*@__PURE__*/new class extends RangeValue{}();closedBracket.startSide=1;closedBracket.endSide=-1;/**
4430
+ Returns an extension that enables autocompletion.
4431
+ */function autocompletion$1(config={}){return [completionState,completionConfig.of(config),completionPlugin,completionKeymapExt,baseTheme$1];}/**
4432
+ Basic keybindings for autocompletion.
4433
+
4434
+ - Ctrl-Space: [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion)
4435
+ - Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion)
4436
+ - ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)`
4437
+ - ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)`
4438
+ - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
4439
+ - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
4440
+ - Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion)
4441
+ */const completionKeymap=[{key:"Ctrl-Space",run:startCompletion},{key:"Escape",run:closeCompletion},{key:"ArrowDown",run:/*@__PURE__*/moveCompletionSelection(true)},{key:"ArrowUp",run:/*@__PURE__*/moveCompletionSelection(false)},{key:"PageDown",run:/*@__PURE__*/moveCompletionSelection(true,"page")},{key:"PageUp",run:/*@__PURE__*/moveCompletionSelection(false,"page")},{key:"Enter",run:acceptCompletion}];const completionKeymapExt=/*@__PURE__*/Prec.highest(/*@__PURE__*/keymap.computeN([completionConfig],state=>state.facet(completionConfig).defaultKeymap?[completionKeymap]:[]));var variables=variables=>context=>{const options=variables.map(v=>({label:v.name,type:'variable',info:v.info,detail:v.detail}));// In most cases, use what is typed before the cursor
4442
+ let nodeBefore=syntaxTree(context.state).resolve(context.pos,-1);// For the special case of empty nodes, we need to check the current node
4443
+ // as well. The previous node could be part of another token, e.g.
4444
+ // when typing functions "abs(".
4445
+ let nextNode=nodeBefore.nextSibling;const isInEmptyNode=isNodeEmpty(nodeBefore)||nextNode&&nextNode.from===context.pos&&isNodeEmpty(nextNode);if(context.explicit&&isInEmptyNode){return {from:context.pos,options:options};}const result={from:nodeBefore.from,options:options};// Only auto-complete variables
4446
+ if(nodeBefore.name!=='VariableName'){return null;}return result;};// helpers ///////////////////////////////
4447
+ function isNodeEmpty(node){return node.from===node.to;}function autocompletion(context){return [autocompletion$1({override:[variables(context)]})];}// FIXME profile adding a per-Tree TreeNode cache, validating it by
4448
+ // parent pointer
4449
+ /// The default maximum length of a `TreeBuffer` node (1024).
4450
+ const DefaultBufferLength=1024;let nextPropID=0;class Range{constructor(from,to){this.from=from;this.to=to;}}/// Each [node type](#common.NodeType) or [individual tree](#common.Tree)
4451
+ /// can have metadata associated with it in props. Instances of this
4452
+ /// class represent prop names.
4453
+ class NodeProp{/// Create a new node prop type.
4454
+ constructor(config={}){this.id=nextPropID++;this.perNode=!!config.perNode;this.deserialize=config.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function");});}/// This is meant to be used with
4455
+ /// [`NodeSet.extend`](#common.NodeSet.extend) or
4456
+ /// [`LRParser.configure`](#lr.ParserConfig.props) to compute
4457
+ /// prop values for each node type in the set. Takes a [match
4458
+ /// object](#common.NodeType^match) or function that returns undefined
4459
+ /// if the node type doesn't get this prop, and the prop's value if
4460
+ /// it does.
4461
+ add(match){if(this.perNode)throw new RangeError("Can't add per-node props to node types");if(typeof match!="function")match=NodeType.match(match);return type=>{let result=match(type);return result===undefined?null:[this,result];};}}/// Prop that is used to describe matching delimiters. For opening
4462
+ /// delimiters, this holds an array of node names (written as a
4463
+ /// space-separated string when declaring this prop in a grammar)
4464
+ /// for the node types of closing delimiters that match it.
4465
+ NodeProp.closedBy=new NodeProp({deserialize:str=>str.split(" ")});/// The inverse of [`closedBy`](#common.NodeProp^closedBy). This is
4466
+ /// attached to closing delimiters, holding an array of node names
4467
+ /// of types of matching opening delimiters.
4468
+ NodeProp.openedBy=new NodeProp({deserialize:str=>str.split(" ")});/// Used to assign node types to groups (for example, all node
4469
+ /// types that represent an expression could be tagged with an
4470
+ /// `"Expression"` group).
4471
+ NodeProp.group=new NodeProp({deserialize:str=>str.split(" ")});/// The hash of the [context](#lr.ContextTracker.constructor)
4472
+ /// that the node was parsed in, if any. Used to limit reuse of
4473
+ /// contextual nodes.
4474
+ NodeProp.contextHash=new NodeProp({perNode:true});/// The distance beyond the end of the node that the tokenizer
4475
+ /// looked ahead for any of the tokens inside the node. (The LR
4476
+ /// parser only stores this when it is larger than 25, for
4477
+ /// efficiency reasons.)
4478
+ NodeProp.lookAhead=new NodeProp({perNode:true});/// This per-node prop is used to replace a given node, or part of a
4479
+ /// node, with another tree. This is useful to include trees from
4480
+ /// different languages.
4481
+ NodeProp.mounted=new NodeProp({perNode:true});const noProps=Object.create(null);/// Each node in a syntax tree has a node type associated with it.
4482
+ class NodeType{/// @internal
4483
+ constructor(/// The name of the node type. Not necessarily unique, but if the
4484
+ /// grammar was written properly, different node types with the
4485
+ /// same name within a node set should play the same semantic
4486
+ /// role.
4487
+ name,/// @internal
4488
+ props,/// The id of this node in its set. Corresponds to the term ids
4489
+ /// used in the parser.
4490
+ id,/// @internal
4491
+ flags=0){this.name=name;this.props=props;this.id=id;this.flags=flags;}static define(spec){let props=spec.props&&spec.props.length?Object.create(null):noProps;let flags=(spec.top?1/* Top */:0)|(spec.skipped?2/* Skipped */:0)|(spec.error?4/* Error */:0)|(spec.name==null?8/* Anonymous */:0);let type=new NodeType(spec.name||"",props,spec.id,flags);if(spec.props)for(let src of spec.props){if(!Array.isArray(src))src=src(type);if(src){if(src[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");props[src[0].id]=src[1];}}return type;}/// Retrieves a node prop for this type. Will return `undefined` if
4492
+ /// the prop isn't present on this node.
4493
+ prop(prop){return this.props[prop.id];}/// True when this is the top node of a grammar.
4494
+ get isTop(){return (this.flags&1/* Top */)>0;}/// True when this node is produced by a skip rule.
4495
+ get isSkipped(){return (this.flags&2/* Skipped */)>0;}/// Indicates whether this is an error node.
4496
+ get isError(){return (this.flags&4/* Error */)>0;}/// When true, this node type doesn't correspond to a user-declared
4497
+ /// named node, for example because it is used to cache repetition.
4498
+ get isAnonymous(){return (this.flags&8/* Anonymous */)>0;}/// Returns true when this node's name or one of its
4499
+ /// [groups](#common.NodeProp^group) matches the given string.
4500
+ is(name){if(typeof name=='string'){if(this.name==name)return true;let group=this.prop(NodeProp.group);return group?group.indexOf(name)>-1:false;}return this.id==name;}/// Create a function from node types to arbitrary values by
4501
+ /// specifying an object whose property names are node or
4502
+ /// [group](#common.NodeProp^group) names. Often useful with
4503
+ /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple
4504
+ /// names, separated by spaces, in a single property name to map
4505
+ /// multiple node names to a single value.
4506
+ static match(map){let direct=Object.create(null);for(let prop in map)for(let name of prop.split(" "))direct[name]=map[prop];return node=>{for(let groups=node.prop(NodeProp.group),i=-1;i<(groups?groups.length:0);i++){let found=direct[i<0?node.name:groups[i]];if(found)return found;}};}}/// An empty dummy node type to use when no actual type is available.
4507
+ NodeType.none=new NodeType("",Object.create(null),0,8/* Anonymous */);/// A node set holds a collection of node types. It is used to
4508
+ /// compactly represent trees by storing their type ids, rather than a
4509
+ /// full pointer to the type object, in a numeric array. Each parser
4510
+ /// [has](#lr.LRParser.nodeSet) a node set, and [tree
4511
+ /// buffers](#common.TreeBuffer) can only store collections of nodes
4512
+ /// from the same set. A set can have a maximum of 2**16 (65536) node
4513
+ /// types in it, so that the ids fit into 16-bit typed array slots.
4514
+ class NodeSet{/// Create a set with the given types. The `id` property of each
4515
+ /// type should correspond to its position within the array.
4516
+ constructor(/// The node types in this set, by id.
4517
+ types){this.types=types;for(let i=0;i<types.length;i++)if(types[i].id!=i)throw new RangeError("Node type ids should correspond to array positions when creating a node set");}/// Create a copy of this set with some node properties added. The
4518
+ /// arguments to this method should be created with
4519
+ /// [`NodeProp.add`](#common.NodeProp.add).
4520
+ extend(...props){let newTypes=[];for(let type of this.types){let newProps=null;for(let source of props){let add=source(type);if(add){if(!newProps)newProps=Object.assign({},type.props);newProps[add[0].id]=add[1];}}newTypes.push(newProps?new NodeType(type.name,newProps,type.id,type.flags):type);}return new NodeSet(newTypes);}}const CachedNode=new WeakMap(),CachedInnerNode=new WeakMap();/// Options that control iteration. Can be combined with the `|`
4521
+ /// operator to enable multiple ones.
4522
+ var IterMode;(function(IterMode){/// When enabled, iteration will only visit [`Tree`](#common.Tree)
4523
+ /// objects, not nodes packed into
4524
+ /// [`TreeBuffer`](#common.TreeBuffer)s.
4525
+ IterMode[IterMode["ExcludeBuffers"]=1]="ExcludeBuffers";/// Enable this to make iteration include anonymous nodes (such as
4526
+ /// the nodes that wrap repeated grammar constructs into a balanced
4527
+ /// tree).
4528
+ IterMode[IterMode["IncludeAnonymous"]=2]="IncludeAnonymous";/// By default, regular [mounted](#common.NodeProp^mounted) nodes
4529
+ /// replace their base node in iteration. Enable this to ignore them
4530
+ /// instead.
4531
+ IterMode[IterMode["IgnoreMounts"]=4]="IgnoreMounts";/// This option only applies in
4532
+ /// [`enter`](#common.SyntaxNode.enter)-style methods. It tells the
4533
+ /// library to not enter mounted overlays if one covers the given
4534
+ /// position.
4535
+ IterMode[IterMode["IgnoreOverlays"]=8]="IgnoreOverlays";})(IterMode||(IterMode={}));/// A piece of syntax tree. There are two ways to approach these
4536
+ /// trees: the way they are actually stored in memory, and the
4537
+ /// convenient way.
4538
+ ///
4539
+ /// Syntax trees are stored as a tree of `Tree` and `TreeBuffer`
4540
+ /// objects. By packing detail information into `TreeBuffer` leaf
4541
+ /// nodes, the representation is made a lot more memory-efficient.
4542
+ ///
4543
+ /// However, when you want to actually work with tree nodes, this
4544
+ /// representation is very awkward, so most client code will want to
4545
+ /// use the [`TreeCursor`](#common.TreeCursor) or
4546
+ /// [`SyntaxNode`](#common.SyntaxNode) interface instead, which provides
4547
+ /// a view on some part of this data structure, and can be used to
4548
+ /// move around to adjacent nodes.
4549
+ class Tree{/// Construct a new tree. See also [`Tree.build`](#common.Tree^build).
4550
+ constructor(/// The type of the top node.
4551
+ type,/// This node's child nodes.
4552
+ children,/// The positions (offsets relative to the start of this tree) of
4553
+ /// the children.
4554
+ positions,/// The total length of this tree
4555
+ length,/// Per-node [node props](#common.NodeProp) to associate with this node.
4556
+ props){this.type=type;this.children=children;this.positions=positions;this.length=length;/// @internal
4557
+ this.props=null;if(props&&props.length){this.props=Object.create(null);for(let[prop,value]of props)this.props[typeof prop=="number"?prop:prop.id]=value;}}/// @internal
4558
+ toString(){let mounted=this.prop(NodeProp.mounted);if(mounted&&!mounted.overlay)return mounted.tree.toString();let children="";for(let ch of this.children){let str=ch.toString();if(str){if(children)children+=",";children+=str;}}return !this.type.name?children:(/\W/.test(this.type.name)&&!this.type.isError?JSON.stringify(this.type.name):this.type.name)+(children.length?"("+children+")":"");}/// Get a [tree cursor](#common.TreeCursor) positioned at the top of
4559
+ /// the tree. Mode can be used to [control](#common.IterMode) which
4560
+ /// nodes the cursor visits.
4561
+ cursor(mode=0){return new TreeCursor(this.topNode,mode);}/// Get a [tree cursor](#common.TreeCursor) pointing into this tree
4562
+ /// at the given position and side (see
4563
+ /// [`moveTo`](#common.TreeCursor.moveTo).
4564
+ cursorAt(pos,side=0,mode=0){let scope=CachedNode.get(this)||this.topNode;let cursor=new TreeCursor(scope);cursor.moveTo(pos,side);CachedNode.set(this,cursor._tree);return cursor;}/// Get a [syntax node](#common.SyntaxNode) object for the top of the
4565
+ /// tree.
4566
+ get topNode(){return new TreeNode(this,0,0,null);}/// Get the [syntax node](#common.SyntaxNode) at the given position.
4567
+ /// If `side` is -1, this will move into nodes that end at the
4568
+ /// position. If 1, it'll move into nodes that start at the
4569
+ /// position. With 0, it'll only enter nodes that cover the position
4570
+ /// from both sides.
4571
+ resolve(pos,side=0){let node=resolveNode(CachedNode.get(this)||this.topNode,pos,side,false);CachedNode.set(this,node);return node;}/// Like [`resolve`](#common.Tree.resolve), but will enter
4572
+ /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
4573
+ /// pointing into the innermost overlaid tree at the given position
4574
+ /// (with parent links going through all parent structure, including
4575
+ /// the host trees).
4576
+ resolveInner(pos,side=0){let node=resolveNode(CachedInnerNode.get(this)||this.topNode,pos,side,true);CachedInnerNode.set(this,node);return node;}/// Iterate over the tree and its children, calling `enter` for any
4577
+ /// node that touches the `from`/`to` region (if given) before
4578
+ /// running over such a node's children, and `leave` (if given) when
4579
+ /// leaving the node. When `enter` returns `false`, that node will
4580
+ /// not have its children iterated over (or `leave` called).
4581
+ iterate(spec){let{enter,leave,from=0,to=this.length}=spec;for(let c=this.cursor((spec.mode||0)|IterMode.IncludeAnonymous);;){let entered=false;if(c.from<=to&&c.to>=from&&(c.type.isAnonymous||enter(c)!==false)){if(c.firstChild())continue;entered=true;}for(;;){if(entered&&leave&&!c.type.isAnonymous)leave(c);if(c.nextSibling())break;if(!c.parent())return;entered=true;}}}/// Get the value of the given [node prop](#common.NodeProp) for this
4582
+ /// node. Works with both per-node and per-type props.
4583
+ prop(prop){return !prop.perNode?this.type.prop(prop):this.props?this.props[prop.id]:undefined;}/// Returns the node's [per-node props](#common.NodeProp.perNode) in a
4584
+ /// format that can be passed to the [`Tree`](#common.Tree)
4585
+ /// constructor.
4586
+ get propValues(){let result=[];if(this.props)for(let id in this.props)result.push([+id,this.props[id]]);return result;}/// Balance the direct children of this tree, producing a copy of
4587
+ /// which may have children grouped into subtrees with type
4588
+ /// [`NodeType.none`](#common.NodeType^none).
4589
+ balance(config={}){return this.children.length<=8/* BranchFactor */?this:balanceRange(NodeType.none,this.children,this.positions,0,this.children.length,0,this.length,(children,positions,length)=>new Tree(this.type,children,positions,length,this.propValues),config.makeTree||((children,positions,length)=>new Tree(NodeType.none,children,positions,length)));}/// Build a tree from a postfix-ordered buffer of node information,
4590
+ /// or a cursor over such a buffer.
4591
+ static build(data){return buildTree(data);}}/// The empty tree
4592
+ Tree.empty=new Tree(NodeType.none,[],[],0);class FlatBufferCursor{constructor(buffer,index){this.buffer=buffer;this.index=index;}get id(){return this.buffer[this.index-4];}get start(){return this.buffer[this.index-3];}get end(){return this.buffer[this.index-2];}get size(){return this.buffer[this.index-1];}get pos(){return this.index;}next(){this.index-=4;}fork(){return new FlatBufferCursor(this.buffer,this.index);}}/// Tree buffers contain (type, start, end, endIndex) quads for each
4593
+ /// node. In such a buffer, nodes are stored in prefix order (parents
4594
+ /// before children, with the endIndex of the parent indicating which
4595
+ /// children belong to it)
4596
+ class TreeBuffer{/// Create a tree buffer.
4597
+ constructor(/// The buffer's content.
4598
+ buffer,/// The total length of the group of nodes in the buffer.
4599
+ length,/// The node set used in this buffer.
4600
+ set){this.buffer=buffer;this.length=length;this.set=set;}/// @internal
4601
+ get type(){return NodeType.none;}/// @internal
4602
+ toString(){let result=[];for(let index=0;index<this.buffer.length;){result.push(this.childString(index));index=this.buffer[index+3];}return result.join(",");}/// @internal
4603
+ childString(index){let id=this.buffer[index],endIndex=this.buffer[index+3];let type=this.set.types[id],result=type.name;if(/\W/.test(result)&&!type.isError)result=JSON.stringify(result);index+=4;if(endIndex==index)return result;let children=[];while(index<endIndex){children.push(this.childString(index));index=this.buffer[index+3];}return result+"("+children.join(",")+")";}/// @internal
4604
+ findChild(startIndex,endIndex,dir,pos,side){let{buffer}=this,pick=-1;for(let i=startIndex;i!=endIndex;i=buffer[i+3]){if(checkSide(side,pos,buffer[i+1],buffer[i+2])){pick=i;if(dir>0)break;}}return pick;}/// @internal
4605
+ slice(startI,endI,from,to){let b=this.buffer;let copy=new Uint16Array(endI-startI);for(let i=startI,j=0;i<endI;){copy[j++]=b[i++];copy[j++]=b[i++]-from;copy[j++]=b[i++]-from;copy[j++]=b[i++]-startI;}return new TreeBuffer(copy,to-from,this.set);}}function checkSide(side,pos,from,to){switch(side){case-2/* Before */:return from<pos;case-1/* AtOrBefore */:return to>=pos&&from<pos;case 0/* Around */:return from<pos&&to>pos;case 1/* AtOrAfter */:return from<=pos&&to>pos;case 2/* After */:return to>pos;case 4/* DontCare */:return true;}}function enterUnfinishedNodesBefore(node,pos){let scan=node.childBefore(pos);while(scan){let last=scan.lastChild;if(!last||last.to!=scan.to)break;if(last.type.isError&&last.from==last.to){node=scan;scan=last.prevSibling;}else {scan=last;}}return node;}function resolveNode(node,pos,side,overlays){var _a;// Move up to a node that actually holds the position, if possible
4606
+ while(node.from==node.to||(side<1?node.from>=pos:node.from>pos)||(side>-1?node.to<=pos:node.to<pos)){let parent=!overlays&&node instanceof TreeNode&&node.index<0?null:node.parent;if(!parent)return node;node=parent;}let mode=overlays?0:IterMode.IgnoreOverlays;// Must go up out of overlays when those do not overlap with pos
4607
+ if(overlays)for(let scan=node,parent=scan.parent;parent;scan=parent,parent=scan.parent){if(scan instanceof TreeNode&&scan.index<0&&((_a=parent.enter(pos,side,mode))===null||_a===void 0?void 0:_a.from)!=scan.from)node=parent;}for(;;){let inner=node.enter(pos,side,mode);if(!inner)return node;node=inner;}}class TreeNode{constructor(_tree,from,// Index in parent node, set to -1 if the node is not a direct child of _parent.node (overlay)
4608
+ index,_parent){this._tree=_tree;this.from=from;this.index=index;this._parent=_parent;}get type(){return this._tree.type;}get name(){return this._tree.type.name;}get to(){return this.from+this._tree.length;}nextChild(i,dir,pos,side,mode=0){for(let parent=this;;){for(let{children,positions}=parent._tree,e=dir>0?children.length:-1;i!=e;i+=dir){let next=children[i],start=positions[i]+parent.from;if(!checkSide(side,pos,start,start+next.length))continue;if(next instanceof TreeBuffer){if(mode&IterMode.ExcludeBuffers)continue;let index=next.findChild(0,next.buffer.length,dir,pos-start,side);if(index>-1)return new BufferNode(new BufferContext(parent,next,i,start),null,index);}else if(mode&IterMode.IncludeAnonymous||!next.type.isAnonymous||hasChild(next)){let mounted;if(!(mode&IterMode.IgnoreMounts)&&next.props&&(mounted=next.prop(NodeProp.mounted))&&!mounted.overlay)return new TreeNode(mounted.tree,start,i,parent);let inner=new TreeNode(next,start,i,parent);return mode&IterMode.IncludeAnonymous||!inner.type.isAnonymous?inner:inner.nextChild(dir<0?next.children.length-1:0,dir,pos,side);}}if(mode&IterMode.IncludeAnonymous||!parent.type.isAnonymous)return null;if(parent.index>=0)i=parent.index+dir;else i=dir<0?-1:parent._parent._tree.children.length;parent=parent._parent;if(!parent)return null;}}get firstChild(){return this.nextChild(0,1,0,4/* DontCare */);}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4/* DontCare */);}childAfter(pos){return this.nextChild(0,1,pos,2/* After */);}childBefore(pos){return this.nextChild(this._tree.children.length-1,-1,pos,-2/* Before */);}enter(pos,side,mode=0){let mounted;if(!(mode&IterMode.IgnoreOverlays)&&(mounted=this._tree.prop(NodeProp.mounted))&&mounted.overlay){let rPos=pos-this.from;for(let{from,to}of mounted.overlay){if((side>0?from<=rPos:from<rPos)&&(side<0?to>=rPos:to>rPos))return new TreeNode(mounted.tree,mounted.overlay[0].from+this.from,-1,this);}}return this.nextChild(0,1,pos,side,mode);}nextSignificantParent(){let val=this;while(val.type.isAnonymous&&val._parent)val=val._parent;return val;}get parent(){return this._parent?this._parent.nextSignificantParent():null;}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4/* DontCare */):null;}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4/* DontCare */):null;}cursor(mode=0){return new TreeCursor(this,mode);}get tree(){return this._tree;}toTree(){return this._tree;}resolve(pos,side=0){return resolveNode(this,pos,side,false);}resolveInner(pos,side=0){return resolveNode(this,pos,side,true);}enterUnfinishedNodesBefore(pos){return enterUnfinishedNodesBefore(this,pos);}getChild(type,before=null,after=null){let r=getChildren(this,type,before,after);return r.length?r[0]:null;}getChildren(type,before=null,after=null){return getChildren(this,type,before,after);}/// @internal
4609
+ toString(){return this._tree.toString();}get node(){return this;}matchContext(context){return matchNodeContext(this,context);}}function getChildren(node,type,before,after){let cur=node.cursor(),result=[];if(!cur.firstChild())return result;if(before!=null)while(!cur.type.is(before))if(!cur.nextSibling())return result;for(;;){if(after!=null&&cur.type.is(after))return result;if(cur.type.is(type))result.push(cur.node);if(!cur.nextSibling())return after==null?result:[];}}function matchNodeContext(node,context,i=context.length-1){for(let p=node.parent;i>=0;p=p.parent){if(!p)return false;if(!p.type.isAnonymous){if(context[i]&&context[i]!=p.name)return false;i--;}}return true;}class BufferContext{constructor(parent,buffer,index,start){this.parent=parent;this.buffer=buffer;this.index=index;this.start=start;}}class BufferNode{constructor(context,_parent,index){this.context=context;this._parent=_parent;this.index=index;this.type=context.buffer.set.types[context.buffer.buffer[index]];}get name(){return this.type.name;}get from(){return this.context.start+this.context.buffer.buffer[this.index+1];}get to(){return this.context.start+this.context.buffer.buffer[this.index+2];}child(dir,pos,side){let{buffer}=this.context;let index=buffer.findChild(this.index+4,buffer.buffer[this.index+3],dir,pos-this.context.start,side);return index<0?null:new BufferNode(this.context,this,index);}get firstChild(){return this.child(1,0,4/* DontCare */);}get lastChild(){return this.child(-1,0,4/* DontCare */);}childAfter(pos){return this.child(1,pos,2/* After */);}childBefore(pos){return this.child(-1,pos,-2/* Before */);}enter(pos,side,mode=0){if(mode&IterMode.ExcludeBuffers)return null;let{buffer}=this.context;let index=buffer.findChild(this.index+4,buffer.buffer[this.index+3],side>0?1:-1,pos-this.context.start,side);return index<0?null:new BufferNode(this.context,this,index);}get parent(){return this._parent||this.context.parent.nextSignificantParent();}externalSibling(dir){return this._parent?null:this.context.parent.nextChild(this.context.index+dir,dir,0,4/* DontCare */);}get nextSibling(){let{buffer}=this.context;let after=buffer.buffer[this.index+3];if(after<(this._parent?buffer.buffer[this._parent.index+3]:buffer.buffer.length))return new BufferNode(this.context,this._parent,after);return this.externalSibling(1);}get prevSibling(){let{buffer}=this.context;let parentStart=this._parent?this._parent.index+4:0;if(this.index==parentStart)return this.externalSibling(-1);return new BufferNode(this.context,this._parent,buffer.findChild(parentStart,this.index,-1,0,4/* DontCare */));}cursor(mode=0){return new TreeCursor(this,mode);}get tree(){return null;}toTree(){let children=[],positions=[];let{buffer}=this.context;let startI=this.index+4,endI=buffer.buffer[this.index+3];if(endI>startI){let from=buffer.buffer[this.index+1],to=buffer.buffer[this.index+2];children.push(buffer.slice(startI,endI,from,to));positions.push(0);}return new Tree(this.type,children,positions,this.to-this.from);}resolve(pos,side=0){return resolveNode(this,pos,side,false);}resolveInner(pos,side=0){return resolveNode(this,pos,side,true);}enterUnfinishedNodesBefore(pos){return enterUnfinishedNodesBefore(this,pos);}/// @internal
4610
+ toString(){return this.context.buffer.childString(this.index);}getChild(type,before=null,after=null){let r=getChildren(this,type,before,after);return r.length?r[0]:null;}getChildren(type,before=null,after=null){return getChildren(this,type,before,after);}get node(){return this;}matchContext(context){return matchNodeContext(this,context);}}/// A tree cursor object focuses on a given node in a syntax tree, and
4611
+ /// allows you to move to adjacent nodes.
4612
+ class TreeCursor{/// @internal
4613
+ constructor(node,/// @internal
4614
+ mode=0){this.mode=mode;/// @internal
4615
+ this.buffer=null;this.stack=[];/// @internal
4616
+ this.index=0;this.bufferNode=null;if(node instanceof TreeNode){this.yieldNode(node);}else {this._tree=node.context.parent;this.buffer=node.context;for(let n=node._parent;n;n=n._parent)this.stack.unshift(n.index);this.bufferNode=node;this.yieldBuf(node.index);}}/// Shorthand for `.type.name`.
4617
+ get name(){return this.type.name;}yieldNode(node){if(!node)return false;this._tree=node;this.type=node.type;this.from=node.from;this.to=node.to;return true;}yieldBuf(index,type){this.index=index;let{start,buffer}=this.buffer;this.type=type||buffer.set.types[buffer.buffer[index]];this.from=start+buffer.buffer[index+1];this.to=start+buffer.buffer[index+2];return true;}yield(node){if(!node)return false;if(node instanceof TreeNode){this.buffer=null;return this.yieldNode(node);}this.buffer=node.context;return this.yieldBuf(node.index,node.type);}/// @internal
4618
+ toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString();}/// @internal
4619
+ enterChild(dir,pos,side){if(!this.buffer)return this.yield(this._tree.nextChild(dir<0?this._tree._tree.children.length-1:0,dir,pos,side,this.mode));let{buffer}=this.buffer;let index=buffer.findChild(this.index+4,buffer.buffer[this.index+3],dir,pos-this.buffer.start,side);if(index<0)return false;this.stack.push(this.index);return this.yieldBuf(index);}/// Move the cursor to this node's first child. When this returns
4620
+ /// false, the node has no child, and the cursor has not been moved.
4621
+ firstChild(){return this.enterChild(1,0,4/* DontCare */);}/// Move the cursor to this node's last child.
4622
+ lastChild(){return this.enterChild(-1,0,4/* DontCare */);}/// Move the cursor to the first child that ends after `pos`.
4623
+ childAfter(pos){return this.enterChild(1,pos,2/* After */);}/// Move to the last child that starts before `pos`.
4624
+ childBefore(pos){return this.enterChild(-1,pos,-2/* Before */);}/// Move the cursor to the child around `pos`. If side is -1 the
4625
+ /// child may end at that position, when 1 it may start there. This
4626
+ /// will also enter [overlaid](#common.MountedTree.overlay)
4627
+ /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is
4628
+ /// set to false.
4629
+ enter(pos,side,mode=this.mode){if(!this.buffer)return this.yield(this._tree.enter(pos,side,mode));return mode&IterMode.ExcludeBuffers?false:this.enterChild(1,pos,side);}/// Move to the node's parent node, if this isn't the top node.
4630
+ parent(){if(!this.buffer)return this.yieldNode(this.mode&IterMode.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let parent=this.mode&IterMode.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();this.buffer=null;return this.yieldNode(parent);}/// @internal
4631
+ sibling(dir){if(!this.buffer)return !this._tree._parent?false:this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+dir,dir,0,4/* DontCare */,this.mode));let{buffer}=this.buffer,d=this.stack.length-1;if(dir<0){let parentStart=d<0?0:this.stack[d]+4;if(this.index!=parentStart)return this.yieldBuf(buffer.findChild(parentStart,this.index,-1,0,4/* DontCare */));}else {let after=buffer.buffer[this.index+3];if(after<(d<0?buffer.buffer.length:buffer.buffer[this.stack[d]+3]))return this.yieldBuf(after);}return d<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+dir,dir,0,4/* DontCare */,this.mode)):false;}/// Move to this node's next sibling, if any.
4632
+ nextSibling(){return this.sibling(1);}/// Move to this node's previous sibling, if any.
4633
+ prevSibling(){return this.sibling(-1);}atLastNode(dir){let index,parent,{buffer}=this;if(buffer){if(dir>0){if(this.index<buffer.buffer.buffer.length)return false;}else {for(let i=0;i<this.index;i++)if(buffer.buffer.buffer[i+3]<this.index)return false;}({index,parent}=buffer);}else {({index,_parent:parent}=this._tree);}for(;parent;({index,_parent:parent}=parent)){if(index>-1)for(let i=index+dir,e=dir<0?-1:parent._tree.children.length;i!=e;i+=dir){let child=parent._tree.children[i];if(this.mode&IterMode.IncludeAnonymous||child instanceof TreeBuffer||!child.type.isAnonymous||hasChild(child))return false;}}return true;}move(dir,enter){if(enter&&this.enterChild(dir,0,4/* DontCare */))return true;for(;;){if(this.sibling(dir))return true;if(this.atLastNode(dir)||!this.parent())return false;}}/// Move to the next node in a
4634
+ /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR))
4635
+ /// traversal, going from a node to its first child or, if the
4636
+ /// current node is empty or `enter` is false, its next sibling or
4637
+ /// the next sibling of the first parent node that has one.
4638
+ next(enter=true){return this.move(1,enter);}/// Move to the next node in a last-to-first pre-order traveral. A
4639
+ /// node is followed by its last child or, if it has none, its
4640
+ /// previous sibling or the previous sibling of the first parent
4641
+ /// node that has one.
4642
+ prev(enter=true){return this.move(-1,enter);}/// Move the cursor to the innermost node that covers `pos`. If
4643
+ /// `side` is -1, it will enter nodes that end at `pos`. If it is 1,
4644
+ /// it will enter nodes that start at `pos`.
4645
+ moveTo(pos,side=0){// Move up to a node that actually holds the position, if possible
4646
+ while(this.from==this.to||(side<1?this.from>=pos:this.from>pos)||(side>-1?this.to<=pos:this.to<pos))if(!this.parent())break;// Then scan down into child nodes as far as possible
4647
+ while(this.enterChild(1,pos,side)){}return this;}/// Get a [syntax node](#common.SyntaxNode) at the cursor's current
4648
+ /// position.
4649
+ get node(){if(!this.buffer)return this._tree;let cache=this.bufferNode,result=null,depth=0;if(cache&&cache.context==this.buffer){scan:for(let index=this.index,d=this.stack.length;d>=0;){for(let c=cache;c;c=c._parent)if(c.index==index){if(index==this.index)return c;result=c;depth=d+1;break scan;}index=this.stack[--d];}}for(let i=depth;i<this.stack.length;i++)result=new BufferNode(this.buffer,result,this.stack[i]);return this.bufferNode=new BufferNode(this.buffer,result,this.index);}/// Get the [tree](#common.Tree) that represents the current node, if
4650
+ /// any. Will return null when the node is in a [tree
4651
+ /// buffer](#common.TreeBuffer).
4652
+ get tree(){return this.buffer?null:this._tree._tree;}/// Iterate over the current node and all its descendants, calling
4653
+ /// `enter` when entering a node and `leave`, if given, when leaving
4654
+ /// one. When `enter` returns `false`, any children of that node are
4655
+ /// skipped, and `leave` isn't called for it.
4656
+ iterate(enter,leave){for(let depth=0;;){let mustLeave=false;if(this.type.isAnonymous||enter(this)!==false){if(this.firstChild()){depth++;continue;}if(!this.type.isAnonymous)mustLeave=true;}for(;;){if(mustLeave&&leave)leave(this);mustLeave=this.type.isAnonymous;if(this.nextSibling())break;if(!depth)return;this.parent();depth--;mustLeave=true;}}}/// Test whether the current node matches a given context—a sequence
4657
+ /// of direct parent node names. Empty strings in the context array
4658
+ /// are treated as wildcards.
4659
+ matchContext(context){if(!this.buffer)return matchNodeContext(this.node,context);let{buffer}=this.buffer,{types}=buffer.set;for(let i=context.length-1,d=this.stack.length-1;i>=0;d--){if(d<0)return matchNodeContext(this.node,context,i);let type=types[buffer.buffer[this.stack[d]]];if(!type.isAnonymous){if(context[i]&&context[i]!=type.name)return false;i--;}}return true;}}function hasChild(tree){return tree.children.some(ch=>ch instanceof TreeBuffer||!ch.type.isAnonymous||hasChild(ch));}function buildTree(data){var _a;let{buffer,nodeSet,maxBufferLength=DefaultBufferLength,reused=[],minRepeatType=nodeSet.types.length}=data;let cursor=Array.isArray(buffer)?new FlatBufferCursor(buffer,buffer.length):buffer;let types=nodeSet.types;let contextHash=0,lookAhead=0;function takeNode(parentStart,minPos,children,positions,inRepeat){let{id,start,end,size}=cursor;let lookAheadAtStart=lookAhead;while(size<0){cursor.next();if(size==-1/* Reuse */){let node=reused[id];children.push(node);positions.push(start-parentStart);return;}else if(size==-3/* ContextChange */){// Context change
4660
+ contextHash=id;return;}else if(size==-4/* LookAhead */){lookAhead=id;return;}else {throw new RangeError(`Unrecognized record size: ${size}`);}}let type=types[id],node,buffer;let startPos=start-parentStart;if(end-start<=maxBufferLength&&(buffer=findBufferSize(cursor.pos-minPos,inRepeat))){// Small enough for a buffer, and no reused nodes inside
4661
+ let data=new Uint16Array(buffer.size-buffer.skip);let endPos=cursor.pos-buffer.size,index=data.length;while(cursor.pos>endPos)index=copyToBuffer(buffer.start,data,index);node=new TreeBuffer(data,end-buffer.start,nodeSet);startPos=buffer.start-parentStart;}else {// Make it a node
4662
+ let endPos=cursor.pos-size;cursor.next();let localChildren=[],localPositions=[];let localInRepeat=id>=minRepeatType?id:-1;let lastGroup=0,lastEnd=end;while(cursor.pos>endPos){if(localInRepeat>=0&&cursor.id==localInRepeat&&cursor.size>=0){if(cursor.end<=lastEnd-maxBufferLength){makeRepeatLeaf(localChildren,localPositions,start,lastGroup,cursor.end,lastEnd,localInRepeat,lookAheadAtStart);lastGroup=localChildren.length;lastEnd=cursor.end;}cursor.next();}else {takeNode(start,endPos,localChildren,localPositions,localInRepeat);}}if(localInRepeat>=0&&lastGroup>0&&lastGroup<localChildren.length)makeRepeatLeaf(localChildren,localPositions,start,lastGroup,start,lastEnd,localInRepeat,lookAheadAtStart);localChildren.reverse();localPositions.reverse();if(localInRepeat>-1&&lastGroup>0){let make=makeBalanced(type);node=balanceRange(type,localChildren,localPositions,0,localChildren.length,0,end-start,make,make);}else {node=makeTree(type,localChildren,localPositions,end-start,lookAheadAtStart-end);}}children.push(node);positions.push(startPos);}function makeBalanced(type){return (children,positions,length)=>{let lookAhead=0,lastI=children.length-1,last,lookAheadProp;if(lastI>=0&&(last=children[lastI])instanceof Tree){if(!lastI&&last.type==type&&last.length==length)return last;if(lookAheadProp=last.prop(NodeProp.lookAhead))lookAhead=positions[lastI]+last.length+lookAheadProp;}return makeTree(type,children,positions,length,lookAhead);};}function makeRepeatLeaf(children,positions,base,i,from,to,type,lookAhead){let localChildren=[],localPositions=[];while(children.length>i){localChildren.push(children.pop());localPositions.push(positions.pop()+base-from);}children.push(makeTree(nodeSet.types[type],localChildren,localPositions,to-from,lookAhead-to));positions.push(from-base);}function makeTree(type,children,positions,length,lookAhead=0,props){if(contextHash){let pair=[NodeProp.contextHash,contextHash];props=props?[pair].concat(props):[pair];}if(lookAhead>25){let pair=[NodeProp.lookAhead,lookAhead];props=props?[pair].concat(props):[pair];}return new Tree(type,children,positions,length,props);}function findBufferSize(maxSize,inRepeat){// Scan through the buffer to find previous siblings that fit
4663
+ // together in a TreeBuffer, and don't contain any reused nodes
4664
+ // (which can't be stored in a buffer).
4665
+ // If `inRepeat` is > -1, ignore node boundaries of that type for
4666
+ // nesting, but make sure the end falls either at the start
4667
+ // (`maxSize`) or before such a node.
4668
+ let fork=cursor.fork();let size=0,start=0,skip=0,minStart=fork.end-maxBufferLength;let result={size:0,start:0,skip:0};scan:for(let minPos=fork.pos-maxSize;fork.pos>minPos;){let nodeSize=fork.size;// Pretend nested repeat nodes of the same type don't exist
4669
+ if(fork.id==inRepeat&&nodeSize>=0){// Except that we store the current state as a valid return
4670
+ // value.
4671
+ result.size=size;result.start=start;result.skip=skip;skip+=4;size+=4;fork.next();continue;}let startPos=fork.pos-nodeSize;if(nodeSize<0||startPos<minPos||fork.start<minStart)break;let localSkipped=fork.id>=minRepeatType?4:0;let nodeStart=fork.start;fork.next();while(fork.pos>startPos){if(fork.size<0){if(fork.size==-3/* ContextChange */)localSkipped+=4;else break scan;}else if(fork.id>=minRepeatType){localSkipped+=4;}fork.next();}start=nodeStart;size+=nodeSize;skip+=localSkipped;}if(inRepeat<0||size==maxSize){result.size=size;result.start=start;result.skip=skip;}return result.size>4?result:undefined;}function copyToBuffer(bufferStart,buffer,index){let{id,start,end,size}=cursor;cursor.next();if(size>=0&&id<minRepeatType){let startIndex=index;if(size>4){let endPos=cursor.pos-(size-4);while(cursor.pos>endPos)index=copyToBuffer(bufferStart,buffer,index);}buffer[--index]=startIndex;buffer[--index]=end-bufferStart;buffer[--index]=start-bufferStart;buffer[--index]=id;}else if(size==-3/* ContextChange */){contextHash=id;}else if(size==-4/* LookAhead */){lookAhead=id;}return index;}let children=[],positions=[];while(cursor.pos>0)takeNode(data.start||0,data.bufferStart||0,children,positions,-1);let length=(_a=data.length)!==null&&_a!==void 0?_a:children.length?positions[0]+children[0].length:0;return new Tree(types[data.topID],children.reverse(),positions.reverse(),length);}const nodeSizeCache=new WeakMap();function nodeSize(balanceType,node){if(!balanceType.isAnonymous||node instanceof TreeBuffer||node.type!=balanceType)return 1;let size=nodeSizeCache.get(node);if(size==null){size=1;for(let child of node.children){if(child.type!=balanceType||!(child instanceof Tree)){size=1;break;}size+=nodeSize(balanceType,child);}nodeSizeCache.set(node,size);}return size;}function balanceRange(// The type the balanced tree's inner nodes.
4672
+ balanceType,// The direct children and their positions
4673
+ children,positions,// The index range in children/positions to use
4674
+ from,to,// The start position of the nodes, relative to their parent.
4675
+ start,// Length of the outer node
4676
+ length,// Function to build the top node of the balanced tree
4677
+ mkTop,// Function to build internal nodes for the balanced tree
4678
+ mkTree){let total=0;for(let i=from;i<to;i++)total+=nodeSize(balanceType,children[i]);let maxChild=Math.ceil(total*1.5/8/* BranchFactor */);let localChildren=[],localPositions=[];function divide(children,positions,from,to,offset){for(let i=from;i<to;){let groupFrom=i,groupStart=positions[i],groupSize=nodeSize(balanceType,children[i]);i++;for(;i<to;i++){let nextSize=nodeSize(balanceType,children[i]);if(groupSize+nextSize>=maxChild)break;groupSize+=nextSize;}if(i==groupFrom+1){if(groupSize>maxChild){let only=children[groupFrom];// Only trees can have a size > 1
4679
+ divide(only.children,only.positions,0,only.children.length,positions[groupFrom]+offset);continue;}localChildren.push(children[groupFrom]);}else {let length=positions[i-1]+children[i-1].length-groupStart;localChildren.push(balanceRange(balanceType,children,positions,groupFrom,i,groupStart,length,null,mkTree));}localPositions.push(groupStart+offset-start);}}divide(children,positions,from,to,0);return (mkTop||mkTree)(localChildren,localPositions,length);}/// A superclass that parsers should extend.
4680
+ class Parser{/// Start a parse, returning a [partial parse](#common.PartialParse)
4681
+ /// object. [`fragments`](#common.TreeFragment) can be passed in to
4682
+ /// make the parse incremental.
4683
+ ///
4684
+ /// By default, the entire input is parsed. You can pass `ranges`,
4685
+ /// which should be a sorted array of non-empty, non-overlapping
4686
+ /// ranges, to parse only those ranges. The tree returned in that
4687
+ /// case will start at `ranges[0].from`.
4688
+ startParse(input,fragments,ranges){if(typeof input=="string")input=new StringInput(input);ranges=!ranges?[new Range(0,input.length)]:ranges.length?ranges.map(r=>new Range(r.from,r.to)):[new Range(0,0)];return this.createParse(input,fragments||[],ranges);}/// Run a full parse, returning the resulting tree.
4689
+ parse(input,fragments,ranges){let parse=this.startParse(input,fragments,ranges);for(;;){let done=parse.advance();if(done)return done;}}}class StringInput{constructor(string){this.string=string;}get length(){return this.string.length;}chunk(from){return this.string.slice(from);}get lineChunks(){return false;}read(from,to){return this.string.slice(from,to);}}new NodeProp({perNode:true});/// A parse stack. These are used internally by the parser to track
4690
+ /// parsing progress. They also provide some properties and methods
4691
+ /// that external code such as a tokenizer can use to get information
4692
+ /// about the parse state.
4693
+ class Stack{/// @internal
4694
+ constructor(/// The parse that this stack is part of @internal
4695
+ p,/// Holds state, input pos, buffer index triplets for all but the
4696
+ /// top state @internal
4697
+ stack,/// The current parse state @internal
4698
+ state,// The position at which the next reduce should take place. This
4699
+ // can be less than `this.pos` when skipped expressions have been
4700
+ // added to the stack (which should be moved outside of the next
4701
+ // reduction)
4702
+ /// @internal
4703
+ reducePos,/// The input position up to which this stack has parsed.
4704
+ pos,/// The dynamic score of the stack, including dynamic precedence
4705
+ /// and error-recovery penalties
4706
+ /// @internal
4707
+ score,// The output buffer. Holds (type, start, end, size) quads
4708
+ // representing nodes created by the parser, where `size` is
4709
+ // amount of buffer array entries covered by this node.
4710
+ /// @internal
4711
+ buffer,// The base offset of the buffer. When stacks are split, the split
4712
+ // instance shared the buffer history with its parent up to
4713
+ // `bufferBase`, which is the absolute offset (including the
4714
+ // offset of previous splits) into the buffer at which this stack
4715
+ // starts writing.
4716
+ /// @internal
4717
+ bufferBase,/// @internal
4718
+ curContext,/// @internal
4719
+ lookAhead=0,// A parent stack from which this was split off, if any. This is
4720
+ // set up so that it always points to a stack that has some
4721
+ // additional buffer content, never to a stack with an equal
4722
+ // `bufferBase`.
4723
+ /// @internal
4724
+ parent){this.p=p;this.stack=stack;this.state=state;this.reducePos=reducePos;this.pos=pos;this.score=score;this.buffer=buffer;this.bufferBase=bufferBase;this.curContext=curContext;this.lookAhead=lookAhead;this.parent=parent;}/// @internal
4725
+ toString(){return `[${this.stack.filter((_,i)=>i%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`;}// Start an empty stack
4726
+ /// @internal
4727
+ static start(p,state,pos=0){let cx=p.parser.context;return new Stack(p,[],state,pos,pos,0,[],0,cx?new StackContext(cx,cx.start):null,0,null);}/// The stack's current [context](#lr.ContextTracker) value, if
4728
+ /// any. Its type will depend on the context tracker's type
4729
+ /// parameter, or it will be `null` if there is no context
4730
+ /// tracker.
4731
+ get context(){return this.curContext?this.curContext.context:null;}// Push a state onto the stack, tracking its start position as well
4732
+ // as the buffer base at that point.
4733
+ /// @internal
4734
+ pushState(state,start){this.stack.push(this.state,start,this.bufferBase+this.buffer.length);this.state=state;}// Apply a reduce action
4735
+ /// @internal
4736
+ reduce(action){let depth=action>>19/* ReduceDepthShift */,type=action&65535/* ValueMask */;let{parser}=this.p;let dPrec=parser.dynamicPrecedence(type);if(dPrec)this.score+=dPrec;if(depth==0){this.pushState(parser.getGoto(this.state,type,true),this.reducePos);// Zero-depth reductions are a special case—they add stuff to
4737
+ // the stack without popping anything off.
4738
+ if(type<parser.minRepeatTerm)this.storeNode(type,this.reducePos,this.reducePos,4,true);this.reduceContext(type,this.reducePos);return;}// Find the base index into `this.stack`, content after which will
4739
+ // be dropped. Note that with `StayFlag` reductions we need to
4740
+ // consume two extra frames (the dummy parent node for the skipped
4741
+ // expression and the state that we'll be staying in, which should
4742
+ // be moved to `this.state`).
4743
+ let base=this.stack.length-(depth-1)*3-(action&262144/* StayFlag */?6:0);let start=this.stack[base-2];let bufferBase=this.stack[base-1],count=this.bufferBase+this.buffer.length-bufferBase;// Store normal terms or `R -> R R` repeat reductions
4744
+ if(type<parser.minRepeatTerm||action&131072/* RepeatFlag */){let pos=parser.stateFlag(this.state,1/* Skipped */)?this.pos:this.reducePos;this.storeNode(type,start,pos,count+4,true);}if(action&262144/* StayFlag */){this.state=this.stack[base];}else {let baseStateID=this.stack[base-3];this.state=parser.getGoto(baseStateID,type,true);}while(this.stack.length>base)this.stack.pop();this.reduceContext(type,start);}// Shift a value into the buffer
4745
+ /// @internal
4746
+ storeNode(term,start,end,size=4,isReduce=false){if(term==0/* Err */&&(!this.stack.length||this.stack[this.stack.length-1]<this.buffer.length+this.bufferBase)){// Try to omit/merge adjacent error nodes
4747
+ let cur=this,top=this.buffer.length;if(top==0&&cur.parent){top=cur.bufferBase-cur.parent.bufferBase;cur=cur.parent;}if(top>0&&cur.buffer[top-4]==0/* Err */&&cur.buffer[top-1]>-1){if(start==end)return;if(cur.buffer[top-2]>=start){cur.buffer[top-2]=end;return;}}}if(!isReduce||this.pos==end){// Simple case, just append
4748
+ this.buffer.push(term,start,end,size);}else {// There may be skipped nodes that have to be moved forward
4749
+ let index=this.buffer.length;if(index>0&&this.buffer[index-4]!=0/* Err */)while(index>0&&this.buffer[index-2]>end){// Move this record forward
4750
+ this.buffer[index]=this.buffer[index-4];this.buffer[index+1]=this.buffer[index-3];this.buffer[index+2]=this.buffer[index-2];this.buffer[index+3]=this.buffer[index-1];index-=4;if(size>4)size-=4;}this.buffer[index]=term;this.buffer[index+1]=start;this.buffer[index+2]=end;this.buffer[index+3]=size;}}// Apply a shift action
4751
+ /// @internal
4752
+ shift(action,next,nextEnd){let start=this.pos;if(action&131072/* GotoFlag */){this.pushState(action&65535/* ValueMask */,this.pos);}else if((action&262144/* StayFlag */)==0){// Regular shift
4753
+ let nextState=action,{parser}=this.p;if(nextEnd>this.pos||next<=parser.maxNode){this.pos=nextEnd;if(!parser.stateFlag(nextState,1/* Skipped */))this.reducePos=nextEnd;}this.pushState(nextState,start);this.shiftContext(next,start);if(next<=parser.maxNode)this.buffer.push(next,start,nextEnd,4);}else {// Shift-and-stay, which means this is a skipped token
4754
+ this.pos=nextEnd;this.shiftContext(next,start);if(next<=this.p.parser.maxNode)this.buffer.push(next,start,nextEnd,4);}}// Apply an action
4755
+ /// @internal
4756
+ apply(action,next,nextEnd){if(action&65536/* ReduceFlag */)this.reduce(action);else this.shift(action,next,nextEnd);}// Add a prebuilt (reused) node into the buffer.
4757
+ /// @internal
4758
+ useNode(value,next){let index=this.p.reused.length-1;if(index<0||this.p.reused[index]!=value){this.p.reused.push(value);index++;}let start=this.pos;this.reducePos=this.pos=start+value.length;this.pushState(next,start);this.buffer.push(index,start,this.reducePos,-1/* size == -1 means this is a reused value */);if(this.curContext)this.updateContext(this.curContext.tracker.reuse(this.curContext.context,value,this,this.p.stream.reset(this.pos-value.length)));}// Split the stack. Due to the buffer sharing and the fact
4759
+ // that `this.stack` tends to stay quite shallow, this isn't very
4760
+ // expensive.
4761
+ /// @internal
4762
+ split(){let parent=this;let off=parent.buffer.length;// Because the top of the buffer (after this.pos) may be mutated
4763
+ // to reorder reductions and skipped tokens, and shared buffers
4764
+ // should be immutable, this copies any outstanding skipped tokens
4765
+ // to the new buffer, and puts the base pointer before them.
4766
+ while(off>0&&parent.buffer[off-2]>parent.reducePos)off-=4;let buffer=parent.buffer.slice(off),base=parent.bufferBase+off;// Make sure parent points to an actual parent with content, if there is such a parent.
4767
+ while(parent&&base==parent.bufferBase)parent=parent.parent;return new Stack(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,buffer,base,this.curContext,this.lookAhead,parent);}// Try to recover from an error by 'deleting' (ignoring) one token.
4768
+ /// @internal
4769
+ recoverByDelete(next,nextEnd){let isNode=next<=this.p.parser.maxNode;if(isNode)this.storeNode(next,this.pos,nextEnd,4);this.storeNode(0/* Err */,this.pos,nextEnd,isNode?8:4);this.pos=this.reducePos=nextEnd;this.score-=190/* Delete */;}/// Check if the given term would be able to be shifted (optionally
4770
+ /// after some reductions) on this stack. This can be useful for
4771
+ /// external tokenizers that want to make sure they only provide a
4772
+ /// given token when it applies.
4773
+ canShift(term){for(let sim=new SimulatedStack(this);;){let action=this.p.parser.stateSlot(sim.state,4/* DefaultReduce */)||this.p.parser.hasAction(sim.state,term);if((action&65536/* ReduceFlag */)==0)return true;if(action==0)return false;sim.reduce(action);}}// Apply up to Recover.MaxNext recovery actions that conceptually
4774
+ // inserts some missing token or rule.
4775
+ /// @internal
4776
+ recoverByInsert(next){if(this.stack.length>=300/* MaxInsertStackDepth */)return [];let nextStates=this.p.parser.nextStates(this.state);if(nextStates.length>4/* MaxNext */<<1||this.stack.length>=120/* DampenInsertStackDepth */){let best=[];for(let i=0,s;i<nextStates.length;i+=2){if((s=nextStates[i+1])!=this.state&&this.p.parser.hasAction(s,next))best.push(nextStates[i],s);}if(this.stack.length<120/* DampenInsertStackDepth */)for(let i=0;best.length<4/* MaxNext */<<1&&i<nextStates.length;i+=2){let s=nextStates[i+1];if(!best.some((v,i)=>i&1&&v==s))best.push(nextStates[i],s);}nextStates=best;}let result=[];for(let i=0;i<nextStates.length&&result.length<4/* MaxNext */;i+=2){let s=nextStates[i+1];if(s==this.state)continue;let stack=this.split();stack.pushState(s,this.pos);stack.storeNode(0/* Err */,stack.pos,stack.pos,4,true);stack.shiftContext(nextStates[i],this.pos);stack.score-=200/* Insert */;result.push(stack);}return result;}// Force a reduce, if possible. Return false if that can't
4777
+ // be done.
4778
+ /// @internal
4779
+ forceReduce(){let reduce=this.p.parser.stateSlot(this.state,5/* ForcedReduce */);if((reduce&65536/* ReduceFlag */)==0)return false;let{parser}=this.p;if(!parser.validAction(this.state,reduce)){let depth=reduce>>19/* ReduceDepthShift */,term=reduce&65535/* ValueMask */;let target=this.stack.length-depth*3;if(target<0||parser.getGoto(this.stack[target],term,false)<0)return false;this.storeNode(0/* Err */,this.reducePos,this.reducePos,4,true);this.score-=100/* Reduce */;}this.reducePos=this.pos;this.reduce(reduce);return true;}/// @internal
4780
+ forceAll(){while(!this.p.parser.stateFlag(this.state,2/* Accepting */)){if(!this.forceReduce()){this.storeNode(0/* Err */,this.pos,this.pos,4,true);break;}}return this;}/// Check whether this state has no further actions (assumed to be a direct descendant of the
4781
+ /// top state, since any other states must be able to continue
4782
+ /// somehow). @internal
4783
+ get deadEnd(){if(this.stack.length!=3)return false;let{parser}=this.p;return parser.data[parser.stateSlot(this.state,1/* Actions */)]==65535/* End */&&!parser.stateSlot(this.state,4/* DefaultReduce */);}/// Restart the stack (put it back in its start state). Only safe
4784
+ /// when this.stack.length == 3 (state is directly below the top
4785
+ /// state). @internal
4786
+ restart(){this.state=this.stack[0];this.stack.length=0;}/// @internal
4787
+ sameState(other){if(this.state!=other.state||this.stack.length!=other.stack.length)return false;for(let i=0;i<this.stack.length;i+=3)if(this.stack[i]!=other.stack[i])return false;return true;}/// Get the parser used by this stack.
4788
+ get parser(){return this.p.parser;}/// Test whether a given dialect (by numeric ID, as exported from
4789
+ /// the terms file) is enabled.
4790
+ dialectEnabled(dialectID){return this.p.parser.dialect.flags[dialectID];}shiftContext(term,start){if(this.curContext)this.updateContext(this.curContext.tracker.shift(this.curContext.context,term,this,this.p.stream.reset(start)));}reduceContext(term,start){if(this.curContext)this.updateContext(this.curContext.tracker.reduce(this.curContext.context,term,this,this.p.stream.reset(start)));}/// @internal
4791
+ emitContext(){let last=this.buffer.length-1;if(last<0||this.buffer[last]!=-3)this.buffer.push(this.curContext.hash,this.reducePos,this.reducePos,-3);}/// @internal
4792
+ emitLookAhead(){let last=this.buffer.length-1;if(last<0||this.buffer[last]!=-4)this.buffer.push(this.lookAhead,this.reducePos,this.reducePos,-4);}updateContext(context){if(context!=this.curContext.context){let newCx=new StackContext(this.curContext.tracker,context);if(newCx.hash!=this.curContext.hash)this.emitContext();this.curContext=newCx;}}/// @internal
4793
+ setLookAhead(lookAhead){if(lookAhead>this.lookAhead){this.emitLookAhead();this.lookAhead=lookAhead;}}/// @internal
4794
+ close(){if(this.curContext&&this.curContext.tracker.strict)this.emitContext();if(this.lookAhead>0)this.emitLookAhead();}}class StackContext{constructor(tracker,context){this.tracker=tracker;this.context=context;this.hash=tracker.strict?tracker.hash(context):0;}}var Recover;(function(Recover){Recover[Recover["Insert"]=200]="Insert";Recover[Recover["Delete"]=190]="Delete";Recover[Recover["Reduce"]=100]="Reduce";Recover[Recover["MaxNext"]=4]="MaxNext";Recover[Recover["MaxInsertStackDepth"]=300]="MaxInsertStackDepth";Recover[Recover["DampenInsertStackDepth"]=120]="DampenInsertStackDepth";})(Recover||(Recover={}));// Used to cheaply run some reductions to scan ahead without mutating
4795
+ // an entire stack
4796
+ class SimulatedStack{constructor(start){this.start=start;this.state=start.state;this.stack=start.stack;this.base=this.stack.length;}reduce(action){let term=action&65535/* ValueMask */,depth=action>>19/* ReduceDepthShift */;if(depth==0){if(this.stack==this.start.stack)this.stack=this.stack.slice();this.stack.push(this.state,0,0);this.base+=3;}else {this.base-=(depth-1)*3;}let goto=this.start.p.parser.getGoto(this.stack[this.base-3],term,true);this.state=goto;}}// This is given to `Tree.build` to build a buffer, and encapsulates
4797
+ // the parent-stack-walking necessary to read the nodes.
4798
+ class StackBufferCursor{constructor(stack,pos,index){this.stack=stack;this.pos=pos;this.index=index;this.buffer=stack.buffer;if(this.index==0)this.maybeNext();}static create(stack,pos=stack.bufferBase+stack.buffer.length){return new StackBufferCursor(stack,pos,pos-stack.bufferBase);}maybeNext(){let next=this.stack.parent;if(next!=null){this.index=this.stack.bufferBase-next.bufferBase;this.stack=next;this.buffer=next.buffer;}}get id(){return this.buffer[this.index-4];}get start(){return this.buffer[this.index-3];}get end(){return this.buffer[this.index-2];}get size(){return this.buffer[this.index-1];}next(){this.index-=4;this.pos-=4;if(this.index==0)this.maybeNext();}fork(){return new StackBufferCursor(this.stack,this.pos,this.index);}}class CachedToken{constructor(){this.start=-1;this.value=-1;this.end=-1;this.extended=-1;this.lookAhead=0;this.mask=0;this.context=0;}}const nullToken=new CachedToken();/// [Tokenizers](#lr.ExternalTokenizer) interact with the input
4799
+ /// through this interface. It presents the input as a stream of
4800
+ /// characters, tracking lookahead and hiding the complexity of
4801
+ /// [ranges](#common.Parser.parse^ranges) from tokenizer code.
4802
+ class InputStream{/// @internal
4803
+ constructor(/// @internal
4804
+ input,/// @internal
4805
+ ranges){this.input=input;this.ranges=ranges;/// @internal
4806
+ this.chunk="";/// @internal
4807
+ this.chunkOff=0;/// Backup chunk
4808
+ this.chunk2="";this.chunk2Pos=0;/// The character code of the next code unit in the input, or -1
4809
+ /// when the stream is at the end of the input.
4810
+ this.next=-1;/// @internal
4811
+ this.token=nullToken;this.rangeIndex=0;this.pos=this.chunkPos=ranges[0].from;this.range=ranges[0];this.end=ranges[ranges.length-1].to;this.readNext();}resolveOffset(offset,assoc){let range=this.range,index=this.rangeIndex;let pos=this.pos+offset;while(pos<range.from){if(!index)return null;let next=this.ranges[--index];pos-=range.from-next.to;range=next;}while(assoc<0?pos>range.to:pos>=range.to){if(index==this.ranges.length-1)return null;let next=this.ranges[++index];pos+=next.from-range.to;range=next;}return pos;}/// Look at a code unit near the stream position. `.peek(0)` equals
4812
+ /// `.next`, `.peek(-1)` gives you the previous character, and so
4813
+ /// on.
4814
+ ///
4815
+ /// Note that looking around during tokenizing creates dependencies
4816
+ /// on potentially far-away content, which may reduce the
4817
+ /// effectiveness incremental parsing—when looking forward—or even
4818
+ /// cause invalid reparses when looking backward more than 25 code
4819
+ /// units, since the library does not track lookbehind.
4820
+ peek(offset){let idx=this.chunkOff+offset,pos,result;if(idx>=0&&idx<this.chunk.length){pos=this.pos+offset;result=this.chunk.charCodeAt(idx);}else {let resolved=this.resolveOffset(offset,1);if(resolved==null)return -1;pos=resolved;if(pos>=this.chunk2Pos&&pos<this.chunk2Pos+this.chunk2.length){result=this.chunk2.charCodeAt(pos-this.chunk2Pos);}else {let i=this.rangeIndex,range=this.range;while(range.to<=pos)range=this.ranges[++i];this.chunk2=this.input.chunk(this.chunk2Pos=pos);if(pos+this.chunk2.length>range.to)this.chunk2=this.chunk2.slice(0,range.to-pos);result=this.chunk2.charCodeAt(0);}}if(pos>=this.token.lookAhead)this.token.lookAhead=pos+1;return result;}/// Accept a token. By default, the end of the token is set to the
4821
+ /// current stream position, but you can pass an offset (relative to
4822
+ /// the stream position) to change that.
4823
+ acceptToken(token,endOffset=0){let end=endOffset?this.resolveOffset(endOffset,-1):this.pos;if(end==null||end<this.token.start)throw new RangeError("Token end out of bounds");this.token.value=token;this.token.end=end;}getChunk(){if(this.pos>=this.chunk2Pos&&this.pos<this.chunk2Pos+this.chunk2.length){let{chunk,chunkPos}=this;this.chunk=this.chunk2;this.chunkPos=this.chunk2Pos;this.chunk2=chunk;this.chunk2Pos=chunkPos;this.chunkOff=this.pos-this.chunkPos;}else {this.chunk2=this.chunk;this.chunk2Pos=this.chunkPos;let nextChunk=this.input.chunk(this.pos);let end=this.pos+nextChunk.length;this.chunk=end>this.range.to?nextChunk.slice(0,this.range.to-this.pos):nextChunk;this.chunkPos=this.pos;this.chunkOff=0;}}readNext(){if(this.chunkOff>=this.chunk.length){this.getChunk();if(this.chunkOff==this.chunk.length)return this.next=-1;}return this.next=this.chunk.charCodeAt(this.chunkOff);}/// Move the stream forward N (defaults to 1) code units. Returns
4824
+ /// the new value of [`next`](#lr.InputStream.next).
4825
+ advance(n=1){this.chunkOff+=n;while(this.pos+n>=this.range.to){if(this.rangeIndex==this.ranges.length-1)return this.setDone();n-=this.range.to-this.pos;this.range=this.ranges[++this.rangeIndex];this.pos=this.range.from;}this.pos+=n;if(this.pos>=this.token.lookAhead)this.token.lookAhead=this.pos+1;return this.readNext();}setDone(){this.pos=this.chunkPos=this.end;this.range=this.ranges[this.rangeIndex=this.ranges.length-1];this.chunk="";return this.next=-1;}/// @internal
4826
+ reset(pos,token){if(token){this.token=token;token.start=pos;token.lookAhead=pos+1;token.value=token.extended=-1;}else {this.token=nullToken;}if(this.pos!=pos){this.pos=pos;if(pos==this.end){this.setDone();return this;}while(pos<this.range.from)this.range=this.ranges[--this.rangeIndex];while(pos>=this.range.to)this.range=this.ranges[++this.rangeIndex];if(pos>=this.chunkPos&&pos<this.chunkPos+this.chunk.length){this.chunkOff=pos-this.chunkPos;}else {this.chunk="";this.chunkOff=0;}this.readNext();}return this;}/// @internal
4827
+ read(from,to){if(from>=this.chunkPos&&to<=this.chunkPos+this.chunk.length)return this.chunk.slice(from-this.chunkPos,to-this.chunkPos);if(from>=this.chunk2Pos&&to<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(from-this.chunk2Pos,to-this.chunk2Pos);if(from>=this.range.from&&to<=this.range.to)return this.input.read(from,to);let result="";for(let r of this.ranges){if(r.from>=to)break;if(r.to>from)result+=this.input.read(Math.max(r.from,from),Math.min(r.to,to));}return result;}}/// @internal
4828
+ class TokenGroup{constructor(data,id){this.data=data;this.id=id;}token(input,stack){readToken(this.data,input,stack,this.id);}}TokenGroup.prototype.contextual=TokenGroup.prototype.fallback=TokenGroup.prototype.extend=false;// Tokenizer data is stored a big uint16 array containing, for each
4829
+ // state:
4830
+ //
4831
+ // - A group bitmask, indicating what token groups are reachable from
4832
+ // this state, so that paths that can only lead to tokens not in
4833
+ // any of the current groups can be cut off early.
4834
+ //
4835
+ // - The position of the end of the state's sequence of accepting
4836
+ // tokens
4837
+ //
4838
+ // - The number of outgoing edges for the state
4839
+ //
4840
+ // - The accepting tokens, as (token id, group mask) pairs
4841
+ //
4842
+ // - The outgoing edges, as (start character, end character, state
4843
+ // index) triples, with end character being exclusive
4844
+ //
4845
+ // This function interprets that data, running through a stream as
4846
+ // long as new states with the a matching group mask can be reached,
4847
+ // and updating `token` when it matches a token.
4848
+ function readToken(data,input,stack,group){let state=0,groupMask=1<<group,{parser}=stack.p,{dialect}=parser;scan:for(;;){if((groupMask&data[state])==0)break;let accEnd=data[state+1];// Check whether this state can lead to a token in the current group
4849
+ // Accept tokens in this state, possibly overwriting
4850
+ // lower-precedence / shorter tokens
4851
+ for(let i=state+3;i<accEnd;i+=2)if((data[i+1]&groupMask)>0){let term=data[i];if(dialect.allows(term)&&(input.token.value==-1||input.token.value==term||parser.overrides(term,input.token.value))){input.acceptToken(term);break;}}// Do a binary search on the state's edges
4852
+ for(let next=input.next,low=0,high=data[state+2];low<high;){let mid=low+high>>1;let index=accEnd+mid+(mid<<1);let from=data[index],to=data[index+1];if(next<from)high=mid;else if(next>=to)low=mid+1;else {state=data[index+2];input.advance();continue scan;}}break;}}// See lezer-generator/src/encode.ts for comments about the encoding
4853
+ // used here
4854
+ function decodeArray(input,Type=Uint16Array){if(typeof input!="string")return input;let array=null;for(let pos=0,out=0;pos<input.length;){let value=0;for(;;){let next=input.charCodeAt(pos++),stop=false;if(next==126/* BigValCode */){value=65535/* BigVal */;break;}if(next>=92/* Gap2 */)next--;if(next>=34/* Gap1 */)next--;let digit=next-32/* Start */;if(digit>=46/* Base */){digit-=46/* Base */;stop=true;}value+=digit;if(stop)break;value*=46/* Base */;}if(array)array[out++]=value;else array=new Type(value);}return array;}// Environment variable used to control console output
4855
+ const verbose=typeof process!="undefined"&&process.env&&/\bparse\b/.test(process.env.LOG);let stackIDs=null;var Safety;(function(Safety){Safety[Safety["Margin"]=25]="Margin";})(Safety||(Safety={}));function cutAt(tree,pos,side){let cursor=tree.cursor(IterMode.IncludeAnonymous);cursor.moveTo(pos);for(;;){if(!(side<0?cursor.childBefore(pos):cursor.childAfter(pos)))for(;;){if((side<0?cursor.to<pos:cursor.from>pos)&&!cursor.type.isError)return side<0?Math.max(0,Math.min(cursor.to-1,pos-25/* Margin */)):Math.min(tree.length,Math.max(cursor.from+1,pos+25/* Margin */));if(side<0?cursor.prevSibling():cursor.nextSibling())break;if(!cursor.parent())return side<0?0:tree.length;}}}class FragmentCursor{constructor(fragments,nodeSet){this.fragments=fragments;this.nodeSet=nodeSet;this.i=0;this.fragment=null;this.safeFrom=-1;this.safeTo=-1;this.trees=[];this.start=[];this.index=[];this.nextFragment();}nextFragment(){let fr=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(fr){this.safeFrom=fr.openStart?cutAt(fr.tree,fr.from+fr.offset,1)-fr.offset:fr.from;this.safeTo=fr.openEnd?cutAt(fr.tree,fr.to+fr.offset,-1)-fr.offset:fr.to;while(this.trees.length){this.trees.pop();this.start.pop();this.index.pop();}this.trees.push(fr.tree);this.start.push(-fr.offset);this.index.push(0);this.nextStart=this.safeFrom;}else {this.nextStart=1e9;}}// `pos` must be >= any previously given `pos` for this cursor
4856
+ nodeAt(pos){if(pos<this.nextStart)return null;while(this.fragment&&this.safeTo<=pos)this.nextFragment();if(!this.fragment)return null;for(;;){let last=this.trees.length-1;if(last<0){// End of tree
4857
+ this.nextFragment();return null;}let top=this.trees[last],index=this.index[last];if(index==top.children.length){this.trees.pop();this.start.pop();this.index.pop();continue;}let next=top.children[index];let start=this.start[last]+top.positions[index];if(start>pos){this.nextStart=start;return null;}if(next instanceof Tree){if(start==pos){if(start<this.safeFrom)return null;let end=start+next.length;if(end<=this.safeTo){let lookAhead=next.prop(NodeProp.lookAhead);if(!lookAhead||end+lookAhead<this.fragment.to)return next;}}this.index[last]++;if(start+next.length>=Math.max(this.safeFrom,pos)){// Enter this node
4858
+ this.trees.push(next);this.start.push(start);this.index.push(0);}}else {this.index[last]++;this.nextStart=start+next.length;}}}}class TokenCache{constructor(parser,stream){this.stream=stream;this.tokens=[];this.mainToken=null;this.actions=[];this.tokens=parser.tokenizers.map(_=>new CachedToken());}getActions(stack){let actionIndex=0;let main=null;let{parser}=stack.p,{tokenizers}=parser;let mask=parser.stateSlot(stack.state,3/* TokenizerMask */);let context=stack.curContext?stack.curContext.hash:0;let lookAhead=0;for(let i=0;i<tokenizers.length;i++){if((1<<i&mask)==0)continue;let tokenizer=tokenizers[i],token=this.tokens[i];if(main&&!tokenizer.fallback)continue;if(tokenizer.contextual||token.start!=stack.pos||token.mask!=mask||token.context!=context){this.updateCachedToken(token,tokenizer,stack);token.mask=mask;token.context=context;}if(token.lookAhead>token.end+25/* Margin */)lookAhead=Math.max(token.lookAhead,lookAhead);if(token.value!=0/* Err */){let startIndex=actionIndex;if(token.extended>-1)actionIndex=this.addActions(stack,token.extended,token.end,actionIndex);actionIndex=this.addActions(stack,token.value,token.end,actionIndex);if(!tokenizer.extend){main=token;if(actionIndex>startIndex)break;}}}while(this.actions.length>actionIndex)this.actions.pop();if(lookAhead)stack.setLookAhead(lookAhead);if(!main&&stack.pos==this.stream.end){main=new CachedToken();main.value=stack.p.parser.eofTerm;main.start=main.end=stack.pos;actionIndex=this.addActions(stack,main.value,main.end,actionIndex);}this.mainToken=main;return this.actions;}getMainToken(stack){if(this.mainToken)return this.mainToken;let main=new CachedToken(),{pos,p}=stack;main.start=pos;main.end=Math.min(pos+1,p.stream.end);main.value=pos==p.stream.end?p.parser.eofTerm:0/* Err */;return main;}updateCachedToken(token,tokenizer,stack){tokenizer.token(this.stream.reset(stack.pos,token),stack);if(token.value>-1){let{parser}=stack.p;for(let i=0;i<parser.specialized.length;i++)if(parser.specialized[i]==token.value){let result=parser.specializers[i](this.stream.read(token.start,token.end),stack);if(result>=0&&stack.p.parser.dialect.allows(result>>1)){if((result&1)==0/* Specialize */)token.value=result>>1;else token.extended=result>>1;break;}}}else {token.value=0/* Err */;token.end=Math.min(stack.p.stream.end,stack.pos+1);}}putAction(action,token,end,index){// Don't add duplicate actions
4859
+ for(let i=0;i<index;i+=3)if(this.actions[i]==action)return index;this.actions[index++]=action;this.actions[index++]=token;this.actions[index++]=end;return index;}addActions(stack,token,end,index){let{state}=stack,{parser}=stack.p,{data}=parser;for(let set=0;set<2;set++){for(let i=parser.stateSlot(state,set?2/* Skip */:1/* Actions */);;i+=3){if(data[i]==65535/* End */){if(data[i+1]==1/* Next */){i=pair(data,i+2);}else {if(index==0&&data[i+1]==2/* Other */)index=this.putAction(pair(data,i+2),token,end,index);break;}}if(data[i]==token)index=this.putAction(pair(data,i+1),token,end,index);}}return index;}}var Rec;(function(Rec){Rec[Rec["Distance"]=5]="Distance";Rec[Rec["MaxRemainingPerStep"]=3]="MaxRemainingPerStep";// When two stacks have been running independently long enough to
4860
+ // add this many elements to their buffers, prune one.
4861
+ Rec[Rec["MinBufferLengthPrune"]=500]="MinBufferLengthPrune";Rec[Rec["ForceReduceLimit"]=10]="ForceReduceLimit";// Once a stack reaches this depth (in .stack.length) force-reduce
4862
+ // it back to CutTo to avoid creating trees that overflow the stack
4863
+ // on recursive traversal.
4864
+ Rec[Rec["CutDepth"]=15000]="CutDepth";Rec[Rec["CutTo"]=9000]="CutTo";})(Rec||(Rec={}));class Parse{constructor(parser,input,fragments,ranges){this.parser=parser;this.input=input;this.ranges=ranges;this.recovering=0;this.nextStackID=0x2654;// ♔, ♕, ♖, ♗, ♘, ♙, ♠, ♡, ♢, ♣, ♤, ♥, ♦, ♧
4865
+ this.minStackPos=0;this.reused=[];this.stoppedAt=null;this.stream=new InputStream(input,ranges);this.tokens=new TokenCache(parser,this.stream);this.topTerm=parser.top[1];let{from}=ranges[0];this.stacks=[Stack.start(this,parser.top[0],from)];this.fragments=fragments.length&&this.stream.end-from>parser.bufferLength*4?new FragmentCursor(fragments,parser.nodeSet):null;}get parsedPos(){return this.minStackPos;}// Move the parser forward. This will process all parse stacks at
4866
+ // `this.pos` and try to advance them to a further position. If no
4867
+ // stack for such a position is found, it'll start error-recovery.
4868
+ //
4869
+ // When the parse is finished, this will return a syntax tree. When
4870
+ // not, it returns `null`.
4871
+ advance(){let stacks=this.stacks,pos=this.minStackPos;// This will hold stacks beyond `pos`.
4872
+ let newStacks=this.stacks=[];let stopped,stoppedTokens;// Keep advancing any stacks at `pos` until they either move
4873
+ // forward or can't be advanced. Gather stacks that can't be
4874
+ // advanced further in `stopped`.
4875
+ for(let i=0;i<stacks.length;i++){let stack=stacks[i];for(;;){this.tokens.mainToken=null;if(stack.pos>pos){newStacks.push(stack);}else if(this.advanceStack(stack,newStacks,stacks)){continue;}else {if(!stopped){stopped=[];stoppedTokens=[];}stopped.push(stack);let tok=this.tokens.getMainToken(stack);stoppedTokens.push(tok.value,tok.end);}break;}}if(!newStacks.length){let finished=stopped&&findFinished(stopped);if(finished)return this.stackToTree(finished);if(this.parser.strict){if(verbose&&stopped)console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none"));throw new SyntaxError("No parse at "+pos);}if(!this.recovering)this.recovering=5/* Distance */;}if(this.recovering&&stopped){let finished=this.stoppedAt!=null&&stopped[0].pos>this.stoppedAt?stopped[0]:this.runRecovery(stopped,stoppedTokens,newStacks);if(finished)return this.stackToTree(finished.forceAll());}if(this.recovering){let maxRemaining=this.recovering==1?1:this.recovering*3/* MaxRemainingPerStep */;if(newStacks.length>maxRemaining){newStacks.sort((a,b)=>b.score-a.score);while(newStacks.length>maxRemaining)newStacks.pop();}if(newStacks.some(s=>s.reducePos>pos))this.recovering--;}else if(newStacks.length>1){// Prune stacks that are in the same state, or that have been
4876
+ // running without splitting for a while, to avoid getting stuck
4877
+ // with multiple successful stacks running endlessly on.
4878
+ outer:for(let i=0;i<newStacks.length-1;i++){let stack=newStacks[i];for(let j=i+1;j<newStacks.length;j++){let other=newStacks[j];if(stack.sameState(other)||stack.buffer.length>500/* MinBufferLengthPrune */&&other.buffer.length>500/* MinBufferLengthPrune */){if((stack.score-other.score||stack.buffer.length-other.buffer.length)>0){newStacks.splice(j--,1);}else {newStacks.splice(i--,1);continue outer;}}}}}this.minStackPos=newStacks[0].pos;for(let i=1;i<newStacks.length;i++)if(newStacks[i].pos<this.minStackPos)this.minStackPos=newStacks[i].pos;return null;}stopAt(pos){if(this.stoppedAt!=null&&this.stoppedAt<pos)throw new RangeError("Can't move stoppedAt forward");this.stoppedAt=pos;}// Returns an updated version of the given stack, or null if the
4879
+ // stack can't advance normally. When `split` and `stacks` are
4880
+ // given, stacks split off by ambiguous operations will be pushed to
4881
+ // `split`, or added to `stacks` if they move `pos` forward.
4882
+ advanceStack(stack,stacks,split){let start=stack.pos,{parser}=this;let base=verbose?this.stackID(stack)+" -> ":"";if(this.stoppedAt!=null&&start>this.stoppedAt)return stack.forceReduce()?stack:null;if(this.fragments){let strictCx=stack.curContext&&stack.curContext.tracker.strict,cxHash=strictCx?stack.curContext.hash:0;for(let cached=this.fragments.nodeAt(start);cached;){let match=this.parser.nodeSet.types[cached.type.id]==cached.type?parser.getGoto(stack.state,cached.type.id):-1;if(match>-1&&cached.length&&(!strictCx||(cached.prop(NodeProp.contextHash)||0)==cxHash)){stack.useNode(cached,match);if(verbose)console.log(base+this.stackID(stack)+` (via reuse of ${parser.getName(cached.type.id)})`);return true;}if(!(cached instanceof Tree)||cached.children.length==0||cached.positions[0]>0)break;let inner=cached.children[0];if(inner instanceof Tree&&cached.positions[0]==0)cached=inner;else break;}}let defaultReduce=parser.stateSlot(stack.state,4/* DefaultReduce */);if(defaultReduce>0){stack.reduce(defaultReduce);if(verbose)console.log(base+this.stackID(stack)+` (via always-reduce ${parser.getName(defaultReduce&65535/* ValueMask */)})`);return true;}if(stack.stack.length>=15000/* CutDepth */){while(stack.stack.length>9000/* CutTo */&&stack.forceReduce()){}}let actions=this.tokens.getActions(stack);for(let i=0;i<actions.length;){let action=actions[i++],term=actions[i++],end=actions[i++];let last=i==actions.length||!split;let localStack=last?stack:stack.split();localStack.apply(action,term,end);if(verbose)console.log(base+this.stackID(localStack)+` (via ${(action&65536/* ReduceFlag */)==0?"shift":`reduce of ${parser.getName(action&65535/* ValueMask */)}`} for ${parser.getName(term)} @ ${start}${localStack==stack?"":", split"})`);if(last)return true;else if(localStack.pos>start)stacks.push(localStack);else split.push(localStack);}return false;}// Advance a given stack forward as far as it will go. Returns the
4883
+ // (possibly updated) stack if it got stuck, or null if it moved
4884
+ // forward and was given to `pushStackDedup`.
4885
+ advanceFully(stack,newStacks){let pos=stack.pos;for(;;){if(!this.advanceStack(stack,null,null))return false;if(stack.pos>pos){pushStackDedup(stack,newStacks);return true;}}}runRecovery(stacks,tokens,newStacks){let finished=null,restarted=false;for(let i=0;i<stacks.length;i++){let stack=stacks[i],token=tokens[i<<1],tokenEnd=tokens[(i<<1)+1];let base=verbose?this.stackID(stack)+" -> ":"";if(stack.deadEnd){if(restarted)continue;restarted=true;stack.restart();if(verbose)console.log(base+this.stackID(stack)+" (restarted)");let done=this.advanceFully(stack,newStacks);if(done)continue;}let force=stack.split(),forceBase=base;for(let j=0;force.forceReduce()&&j<10/* ForceReduceLimit */;j++){if(verbose)console.log(forceBase+this.stackID(force)+" (via force-reduce)");let done=this.advanceFully(force,newStacks);if(done)break;if(verbose)forceBase=this.stackID(force)+" -> ";}for(let insert of stack.recoverByInsert(token)){if(verbose)console.log(base+this.stackID(insert)+" (via recover-insert)");this.advanceFully(insert,newStacks);}if(this.stream.end>stack.pos){if(tokenEnd==stack.pos){tokenEnd++;token=0/* Err */;}stack.recoverByDelete(token,tokenEnd);if(verbose)console.log(base+this.stackID(stack)+` (via recover-delete ${this.parser.getName(token)})`);pushStackDedup(stack,newStacks);}else if(!finished||finished.score<stack.score){finished=stack;}}return finished;}// Convert the stack's buffer to a syntax tree.
4886
+ stackToTree(stack){stack.close();return Tree.build({buffer:StackBufferCursor.create(stack),nodeSet:this.parser.nodeSet,topID:this.topTerm,maxBufferLength:this.parser.bufferLength,reused:this.reused,start:this.ranges[0].from,length:stack.pos-this.ranges[0].from,minRepeatType:this.parser.minRepeatTerm});}stackID(stack){let id=(stackIDs||(stackIDs=new WeakMap())).get(stack);if(!id)stackIDs.set(stack,id=String.fromCodePoint(this.nextStackID++));return id+stack;}}function pushStackDedup(stack,newStacks){for(let i=0;i<newStacks.length;i++){let other=newStacks[i];if(other.pos==stack.pos&&other.sameState(stack)){if(newStacks[i].score<stack.score)newStacks[i]=stack;return;}}newStacks.push(stack);}class Dialect{constructor(source,flags,disabled){this.source=source;this.flags=flags;this.disabled=disabled;}allows(term){return !this.disabled||this.disabled[term]==0;}}/// A parser holds the parse tables for a given grammar, as generated
4887
+ /// by `lezer-generator`.
4888
+ class LRParser extends Parser{/// @internal
4889
+ constructor(spec){super();/// @internal
4890
+ this.wrappers=[];if(spec.version!=14/* Version */)throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14/* Version */})`);let nodeNames=spec.nodeNames.split(" ");this.minRepeatTerm=nodeNames.length;for(let i=0;i<spec.repeatNodeCount;i++)nodeNames.push("");let topTerms=Object.keys(spec.topRules).map(r=>spec.topRules[r][1]);let nodeProps=[];for(let i=0;i<nodeNames.length;i++)nodeProps.push([]);function setProp(nodeID,prop,value){nodeProps[nodeID].push([prop,prop.deserialize(String(value))]);}if(spec.nodeProps)for(let propSpec of spec.nodeProps){let prop=propSpec[0];if(typeof prop=="string")prop=NodeProp[prop];for(let i=1;i<propSpec.length;){let next=propSpec[i++];if(next>=0){setProp(next,prop,propSpec[i++]);}else {let value=propSpec[i+-next];for(let j=-next;j>0;j--)setProp(propSpec[i++],prop,value);i++;}}}this.nodeSet=new NodeSet(nodeNames.map((name,i)=>NodeType.define({name:i>=this.minRepeatTerm?undefined:name,id:i,props:nodeProps[i],top:topTerms.indexOf(i)>-1,error:i==0,skipped:spec.skippedNodes&&spec.skippedNodes.indexOf(i)>-1})));if(spec.propSources)this.nodeSet=this.nodeSet.extend(...spec.propSources);this.strict=false;this.bufferLength=DefaultBufferLength;let tokenArray=decodeArray(spec.tokenData);this.context=spec.context;this.specialized=new Uint16Array(spec.specialized?spec.specialized.length:0);this.specializers=[];if(spec.specialized)for(let i=0;i<spec.specialized.length;i++){this.specialized[i]=spec.specialized[i].term;this.specializers[i]=spec.specialized[i].get;}this.states=decodeArray(spec.states,Uint32Array);this.data=decodeArray(spec.stateData);this.goto=decodeArray(spec.goto);this.maxTerm=spec.maxTerm;this.tokenizers=spec.tokenizers.map(value=>typeof value=="number"?new TokenGroup(tokenArray,value):value);this.topRules=spec.topRules;this.dialects=spec.dialects||{};this.dynamicPrecedences=spec.dynamicPrecedences||null;this.tokenPrecTable=spec.tokenPrec;this.termNames=spec.termNames||null;this.maxNode=this.nodeSet.types.length-1;this.dialect=this.parseDialect();this.top=this.topRules[Object.keys(this.topRules)[0]];}createParse(input,fragments,ranges){let parse=new Parse(this,input,fragments,ranges);for(let w of this.wrappers)parse=w(parse,input,fragments,ranges);return parse;}/// Get a goto table entry @internal
4891
+ getGoto(state,term,loose=false){let table=this.goto;if(term>=table[0])return -1;for(let pos=table[term+1];;){let groupTag=table[pos++],last=groupTag&1;let target=table[pos++];if(last&&loose)return target;for(let end=pos+(groupTag>>1);pos<end;pos++)if(table[pos]==state)return target;if(last)return -1;}}/// Check if this state has an action for a given terminal @internal
4892
+ hasAction(state,terminal){let data=this.data;for(let set=0;set<2;set++){for(let i=this.stateSlot(state,set?2/* Skip */:1/* Actions */),next;;i+=3){if((next=data[i])==65535/* End */){if(data[i+1]==1/* Next */)next=data[i=pair(data,i+2)];else if(data[i+1]==2/* Other */)return pair(data,i+2);else break;}if(next==terminal||next==0/* Err */)return pair(data,i+1);}}return 0;}/// @internal
4893
+ stateSlot(state,slot){return this.states[state*6/* Size */+slot];}/// @internal
4894
+ stateFlag(state,flag){return (this.stateSlot(state,0/* Flags */)&flag)>0;}/// @internal
4895
+ validAction(state,action){if(action==this.stateSlot(state,4/* DefaultReduce */))return true;for(let i=this.stateSlot(state,1/* Actions */);;i+=3){if(this.data[i]==65535/* End */){if(this.data[i+1]==1/* Next */)i=pair(this.data,i+2);else return false;}if(action==pair(this.data,i+1))return true;}}/// Get the states that can follow this one through shift actions or
4896
+ /// goto jumps. @internal
4897
+ nextStates(state){let result=[];for(let i=this.stateSlot(state,1/* Actions */);;i+=3){if(this.data[i]==65535/* End */){if(this.data[i+1]==1/* Next */)i=pair(this.data,i+2);else break;}if((this.data[i+2]&65536/* ReduceFlag */>>16)==0){let value=this.data[i+1];if(!result.some((v,i)=>i&1&&v==value))result.push(this.data[i],value);}}return result;}/// @internal
4898
+ overrides(token,prev){let iPrev=findOffset(this.data,this.tokenPrecTable,prev);return iPrev<0||findOffset(this.data,this.tokenPrecTable,token)<iPrev;}/// Configure the parser. Returns a new parser instance that has the
4899
+ /// given settings modified. Settings not provided in `config` are
4900
+ /// kept from the original parser.
4901
+ configure(config){// Hideous reflection-based kludge to make it easy to create a
4902
+ // slightly modified copy of a parser.
4903
+ let copy=Object.assign(Object.create(LRParser.prototype),this);if(config.props)copy.nodeSet=this.nodeSet.extend(...config.props);if(config.top){let info=this.topRules[config.top];if(!info)throw new RangeError(`Invalid top rule name ${config.top}`);copy.top=info;}if(config.tokenizers)copy.tokenizers=this.tokenizers.map(t=>{let found=config.tokenizers.find(r=>r.from==t);return found?found.to:t;});if(config.contextTracker)copy.context=config.contextTracker;if(config.dialect)copy.dialect=this.parseDialect(config.dialect);if(config.strict!=null)copy.strict=config.strict;if(config.wrap)copy.wrappers=copy.wrappers.concat(config.wrap);if(config.bufferLength!=null)copy.bufferLength=config.bufferLength;return copy;}/// Tells you whether any [parse wrappers](#lr.ParserConfig.wrap)
4904
+ /// are registered for this parser.
4905
+ hasWrappers(){return this.wrappers.length>0;}/// Returns the name associated with a given term. This will only
4906
+ /// work for all terms when the parser was generated with the
4907
+ /// `--names` option. By default, only the names of tagged terms are
4908
+ /// stored.
4909
+ getName(term){return this.termNames?this.termNames[term]:String(term<=this.maxNode&&this.nodeSet.types[term].name||term);}/// The eof term id is always allocated directly after the node
4910
+ /// types. @internal
4911
+ get eofTerm(){return this.maxNode+1;}/// The type of top node produced by the parser.
4912
+ get topNode(){return this.nodeSet.types[this.top[1]];}/// @internal
4913
+ dynamicPrecedence(term){let prec=this.dynamicPrecedences;return prec==null?0:prec[term]||0;}/// @internal
4914
+ parseDialect(dialect){let values=Object.keys(this.dialects),flags=values.map(()=>false);if(dialect)for(let part of dialect.split(" ")){let id=values.indexOf(part);if(id>=0)flags[id]=true;}let disabled=null;for(let i=0;i<values.length;i++)if(!flags[i]){for(let j=this.dialects[values[i]],id;(id=this.data[j++])!=65535/* End */;)(disabled||(disabled=new Uint8Array(this.maxTerm+1)))[id]=1;}return new Dialect(dialect,flags,disabled);}/// (used by the output of the parser generator) @internal
4915
+ static deserialize(spec){return new LRParser(spec);}}function pair(data,off){return data[off]|data[off+1]<<16;}function findOffset(data,start,term){for(let i=start,next;(next=data[i])!=65535/* End */;i++)if(next==term)return i-start;return -1;}function findFinished(stacks){let best=null;for(let stack of stacks){let stopped=stack.p.stoppedAt;if((stack.pos==stack.p.stream.end||stopped!=null&&stack.pos>stopped)&&stack.p.parser.stateFlag(stack.state,2/* Accepting */)&&(!best||best.score<stack.score))best=stack;}return best;}// This file was generated by lezer-generator. You probably shouldn't edit it.
4916
+ const spec_identifier={__proto__:null,for:10,in:18,return:23,if:26,then:28,else:30,some:34,every:36,satisfies:43,or:46,and:50,between:58,instance:82,of:85,days:93,time:95,duration:97,years:99,months:101,date:103,list:109,context:115,function:122,string:141,length:143,upper:145,case:147,lower:149,substring:151,before:153,after:155,starts:157,with:159,ends:161,contains:163,insert:165,index:167,distinct:169,values:171,met:173,by:175,overlaps:177,finished:179,started:181,day:183,year:185,week:187,month:189,get:191,value:193,entries:195,start:205,position:207,decimal:209,sep:211,separator:213,grouping:215,null:218,true:344,false:344,"?":232,external:248,method:265,signature:267,not:273};const parser=LRParser.deserialize({version:14,states:"!#UO]QPOOO&hQPOOO'sQPO'#FiO]QPO'#DOO*[QPO'#DOO,zQPO'#DrOOQO'#En'#EnOOQO'#Eo'#EoOOQO'#Ep'#EpO,zQPO'#EqOOQO'#F{'#F{OOQO'#Fz'#FzOOQO'#Es'#EsO-PQPO'#EvO-kQPO'#EwO0ZQPO'#ExO-PQPO'#EuOOQO'#Eu'#EuOOQO'#Fk'#FkO0bQPO'#FQOOQO'#GQ'#GQOOQO'#Fj'#FjOOQO'#FZ'#FZQ]QPOOO0pQPO'#C`O]QPO'#ChO0pQPO'#ClO0uQPO'#DsO0zQPO'#DsO1PQPO'#DsO1UQPO'#DsO1^QPO'#DsO1cQPO'#DsO1hQPO'#DsO1mQPO'#DsO1rQPO'#DsO1wQPO'#DsO1|QPO'#DsO2RQPO'#DsO2WQPO'#DsO2`QPO'#ErOOQO'#Er'#ErO2hQPO'#EyO2mQPO'#CzO5hQPO'#FqOOQO'#C|'#C|O5sQPO'#FXQOQPOOO5zQPOOO]QPO,59bO]QPO,59jO]QPO,59jO]QPO,59jO0pQPO,5:YO]QPO,5:[O8lQPO'#FwOOQO,5:^,5:^OOQO,5<T,5<TO]QPO,59^O]QPO,59`O]QPO,59bO;lQPO,59bO;sQPO,59pO;xQPO,59jOB]QPO,5;YOOQO,5;],5;]OOQO'#Cd'#CdOGqQPO'#DYOKoQPO'#EnOOQO'#GP'#GPOKtQPO,5;bOMQQPO'#CdOM_QPO,5;cOMfQPO'#FzONsQPO'#FyO! QQPO,5;dOOQO,5;a,5;aOOQO'#FS'#FSO! VQPO'#FRO! [QPO'#GSO! dQPO,5;lO! iQPO'#FTOOQO-E9X-E9XO! nQPO'#FmOOQO'#Cb'#CbO! vQPO'#CcO! {QPO,58zO!!QQPO,59SO!!XQPO'#FpOOQO'#Co'#CoO!!aQPO'#CpO!!fQPO,59WO!!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%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
4804
4917
  if(editorView.state.doc.length===0){return messages;}const tree=syntaxTree(editorView.state);tree.iterate({enter:node=>{if(node.type.isError){const error=node.toString();/* The error has the pattern [⚠ || ⚠(NodeType)]. The regex extracts the node type from inside the brackets */const match=/\((.*?)\)/.exec(error);const nodeType=match&&match[1];let message;if(nodeType){message='unexpected '+nodeType;}else {message='expression expected';}messages.push({from:node.from,to:node.to,severity:'error',message:message,source:'syntaxError'});}}});return messages;};var syntaxLinter=linter$1(FeelLinter);var linter=[syntaxLinter];const baseTheme=EditorView.theme({'& .cm-content':{padding:'0px'},'& .cm-line':{padding:'0px'},'&.cm-editor.cm-focused':{outline:'none'}});const highlightTheme=EditorView.baseTheme({'& .variableName':{color:'#10f'},'& .number':{color:'#164'},'& .string':{color:'#a11'},'& .function':{color:'#aa3731',fontWeight:'bold'},'& .atom':{color:'#708'}});const syntaxClasses=syntaxHighlighting(HighlightStyle.define([{tag:tags.variableName,class:'variableName'},{tag:tags.name,class:'variableName'},{tag:tags.number,class:'number'},{tag:tags.string,class:'string'},{tag:tags.function(tags.variableName),class:'function'},{tag:tags.atom,class:'atom'}]));var theme=[baseTheme,highlightTheme,syntaxClasses];/**
4805
4918
  * Creates a FEEL editor in the supplied container
4806
4919
  *
@@ -4808,16 +4921,19 @@ if(editorView.state.doc.length===0){return messages;}const tree=syntaxTree(edito
4808
4921
  * @param {DOMNode} config.container
4809
4922
  * @param {Function} [config.onChange]
4810
4923
  * @param {Function} [config.onKeyDown]
4924
+ * @param {Function} [config.onLint]
4925
+ * @param {Boolean} [config.readOnly]
4811
4926
  * @param {String} [config.value]
4927
+ * @param {Array} [config.variables]
4812
4928
  *
4813
4929
  * @returns {Object} editor
4814
- */function FeelEditor({container,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(),theme,linter];if(readOnly){extensions.push(EditorView.editable.of(false));}this._cmEditor=new EditorView({state:EditorState.create({doc:value,extensions:extensions}),parent:container});return this;}/**
4930
+ */function FeelEditor({container,onChange=()=>{},onKeyDown=()=>{},onLint=()=>{},readOnly=false,value='',variables=[]}){const changeHandler=EditorView.updateListener.of(update=>{if(update.docChanged){onChange(update.state.doc.toString());}});const lintHandler=EditorView.updateListener.of(update=>{const diagnosticEffects=update.transactions.flatMap(t=>t.effects).filter(effect=>effect.is(setDiagnosticsEffect));if(!diagnosticEffects.length){return;}const messages=diagnosticEffects.flatMap(effect=>effect.value);onLint(messages);});const keyHandler=EditorView.domEventHandlers({keydown:onKeyDown});const extensions=[keymap.of([...defaultKeymap]),changeHandler,keyHandler,language(),autocompletion(variables),theme,linter,lintHandler];if(readOnly){extensions.push(EditorView.editable.of(false));}this._cmEditor=new EditorView({state:EditorState.create({doc:value,extensions:extensions}),parent:container});return this;}/**
4815
4931
  * Replaces the content of the Editor
4816
4932
  *
4817
4933
  * @param {String} value
4818
4934
  */FeelEditor.prototype.setValue=function(value){this._cmEditor.dispatch({changes:{from:0,to:this._cmEditor.state.doc.length,insert:value}});};/**
4819
4935
  * Sets the focus in the editor.
4820
- */FeelEditor.prototype.focus=function(){this._cmEditor.focus();};/**
4936
+ */FeelEditor.prototype.focus=function(position){const cmEditor=this._cmEditor;cmEditor.focus();if(typeof position==='number'){const end=cmEditor.state.doc.length;cmEditor.dispatch({selection:{anchor:position<=end?position:end}});}};/**
4821
4937
  * Returns the current selection ranges. If no text is selected, a single
4822
4938
  * range with the start and end index at the cursor position will be returned.
4823
4939
  *
@@ -4826,19 +4942,19 @@ if(editorView.state.doc.length===0){return messages;}const tree=syntaxTree(edito
4826
4942
  */FeelEditor.prototype.getSelection=function(){return this._cmEditor.state.selection;};
4827
4943
 
4828
4944
  const useBufferedFocus = function (editor, ref) {
4829
- const [buffer, setBuffer] = useState(false);
4945
+ const [buffer, setBuffer] = useState(undefined);
4830
4946
  ref.current = useMemo(() => ({
4831
- focus: () => {
4947
+ focus: argument => {
4832
4948
  if (editor) {
4833
- editor.focus();
4949
+ editor.focus(argument);
4834
4950
  } else {
4835
- setBuffer(true);
4951
+ setBuffer(argument);
4836
4952
  }
4837
4953
  }
4838
4954
  }), [editor]);
4839
4955
  useEffect(() => {
4840
- if (buffer && editor) {
4841
- editor.focus();
4956
+ if (typeof buffer !== 'undefined' && editor) {
4957
+ editor.focus(buffer);
4842
4958
  setBuffer(false);
4843
4959
  }
4844
4960
  }, [editor, buffer]);
@@ -4849,7 +4965,8 @@ const CodeEditor = forwardRef((props, ref) => {
4849
4965
  value,
4850
4966
  onInput,
4851
4967
  onFeelToggle,
4852
- disabled
4968
+ disabled,
4969
+ variables
4853
4970
  } = props;
4854
4971
  const inputRef = useRef();
4855
4972
  const [editor, setEditor] = useState();
@@ -4884,10 +5001,15 @@ const CodeEditor = forwardRef((props, ref) => {
4884
5001
  container: inputRef.current,
4885
5002
  onChange: handleInput,
4886
5003
  onKeyDown: onKeyDown,
4887
- value: localValue
5004
+ value: localValue,
5005
+ variables: variables
4888
5006
  });
4889
5007
  setEditor(editor);
4890
- }, []);
5008
+ return () => {
5009
+ inputRef.current.innerHTML = '';
5010
+ setEditor(null);
5011
+ };
5012
+ }, [variables]);
4891
5013
  useEffect(() => {
4892
5014
  if (!editor) {
4893
5015
  return;
@@ -4975,10 +5097,20 @@ function FeelTextfield(props) {
4975
5097
  OptionalComponent = OptionalFeelInput
4976
5098
  } = props;
4977
5099
  const [localValue, _setLocalValue] = useState(value);
4978
- const ref = useShowEntryEvent(id);
5100
+ const editorRef = useShowEntryEvent(id);
5101
+ const containerRef = useRef();
4979
5102
  const feelActive = localValue.startsWith('=') || feel === 'required';
4980
5103
  const feelOnlyValue = localValue.substring(1);
4981
- const [focus, setFocus] = useState();
5104
+ const [focus, _setFocus] = useState(undefined);
5105
+
5106
+ const setFocus = (offset = 0) => {
5107
+ const hasFocus = containerRef.current.contains(document.activeElement); // Keep carret position if it is already focused, otherwise focus at the end
5108
+
5109
+ const position = hasFocus ? document.activeElement.selectionStart : Infinity;
5110
+
5111
+ _setFocus(position + offset);
5112
+ };
5113
+
4982
5114
  const handleInputCallback = useMemo(() => {
4983
5115
  return debounce(newValue => {
4984
5116
  onInput(newValue);
@@ -5019,14 +5151,16 @@ function FeelTextfield(props) {
5019
5151
  setLocalValue(newValue);
5020
5152
 
5021
5153
  if (!feelActive && newValue.startsWith('=')) {
5022
- setFocus(true);
5154
+ // focus is behind `=` sign that will be removed
5155
+ setFocus(-1);
5023
5156
  }
5024
5157
  };
5025
5158
 
5026
5159
  useEffect(() => {
5027
- if (focus) {
5028
- ref.current.focus();
5029
- setFocus(false);
5160
+ if (typeof focus !== 'undefined') {
5161
+ editorRef.current.focus(focus);
5162
+
5163
+ _setFocus(undefined);
5030
5164
  }
5031
5165
  }, [focus]);
5032
5166
  useEffect(() => {
@@ -5041,13 +5175,47 @@ function FeelTextfield(props) {
5041
5175
  }
5042
5176
 
5043
5177
  setLocalValue(value);
5044
- }, [value]);
5178
+ }, [value]); // copy-paste integration
5179
+
5180
+ useEffect(() => {
5181
+ const copyHandler = event => {
5182
+ if (!feelActive) {
5183
+ return;
5184
+ }
5185
+
5186
+ event.clipboardData.setData('application/FEEL', event.clipboardData.getData('text'));
5187
+ };
5188
+
5189
+ const pasteHandler = event => {
5190
+ if (feelActive) {
5191
+ return;
5192
+ }
5193
+
5194
+ const data = event.clipboardData.getData('application/FEEL');
5195
+
5196
+ if (data) {
5197
+ setTimeout(() => {
5198
+ handleFeelToggle();
5199
+ setFocus();
5200
+ });
5201
+ }
5202
+ };
5203
+
5204
+ containerRef.current.addEventListener('copy', copyHandler);
5205
+ containerRef.current.addEventListener('cut', copyHandler);
5206
+ containerRef.current.addEventListener('paste', pasteHandler);
5207
+ return () => {
5208
+ containerRef.current.removeEventListener('copy', copyHandler);
5209
+ containerRef.current.removeEventListener('cut', copyHandler);
5210
+ containerRef.current.removeEventListener('paste', pasteHandler);
5211
+ };
5212
+ }, [containerRef, feelActive, handleFeelToggle, setFocus]);
5045
5213
  return jsxs("div", {
5046
5214
  class: "bio-properties-panel-feel-entry",
5047
5215
  children: [jsxs("label", {
5048
5216
  for: prefixId$6(id),
5049
5217
  class: "bio-properties-panel-label",
5050
- onClick: () => setFocus(true),
5218
+ onClick: () => setFocus(),
5051
5219
  children: [label, jsx(FeelIcon, {
5052
5220
  label: label,
5053
5221
  feel: feel,
@@ -5056,6 +5224,7 @@ function FeelTextfield(props) {
5056
5224
  })]
5057
5225
  }), jsxs("div", {
5058
5226
  class: "bio-properties-panel-feel-container",
5227
+ ref: containerRef,
5059
5228
  children: [jsx(FeelIndicator, {
5060
5229
  active: feelActive,
5061
5230
  disabled: feel !== 'optional' || disabled,
@@ -5067,14 +5236,15 @@ function FeelTextfield(props) {
5067
5236
  disabled: disabled,
5068
5237
  onFeelToggle: () => {
5069
5238
  handleFeelToggle();
5070
- setFocus(true);
5239
+ setFocus();
5071
5240
  },
5072
5241
  value: feelOnlyValue,
5073
- ref: ref
5242
+ variables: props.variables,
5243
+ ref: editorRef
5074
5244
  }) : jsx(OptionalComponent, { ...props,
5075
5245
  onInput: handleLocalInput,
5076
5246
  value: localValue,
5077
- ref: ref
5247
+ ref: editorRef
5078
5248
  })]
5079
5249
  })]
5080
5250
  });
@@ -5091,7 +5261,7 @@ const OptionalFeelInput = forwardRef((props, ref) => {
5091
5261
  // this ensures clean editing experience when switching with the keyboard
5092
5262
 
5093
5263
  ref.current = {
5094
- focus: () => {
5264
+ focus: position => {
5095
5265
  const input = inputRef.current;
5096
5266
 
5097
5267
  if (!input) {
@@ -5099,7 +5269,14 @@ const OptionalFeelInput = forwardRef((props, ref) => {
5099
5269
  }
5100
5270
 
5101
5271
  input.focus();
5102
- input.setSelectionRange(0, 0);
5272
+
5273
+ if (typeof position === 'number') {
5274
+ if (position > value.length) {
5275
+ position = value.length;
5276
+ }
5277
+
5278
+ input.setSelectionRange(position, position);
5279
+ }
5103
5280
  }
5104
5281
  };
5105
5282
  return jsx("input", {
@@ -5229,8 +5406,9 @@ function FeelEntry(props) {
5229
5406
  example: props.example,
5230
5407
  show: show,
5231
5408
  value: value,
5409
+ variables: props.variables,
5232
5410
  OptionalComponent: props.OptionalComponent
5233
- }), error && jsx("div", {
5411
+ }, element), error && jsx("div", {
5234
5412
  class: "bio-properties-panel-error",
5235
5413
  children: error
5236
5414
  }), jsx(Description, {
@@ -5560,7 +5738,7 @@ function NumberFieldEntry(props) {
5560
5738
  min: min,
5561
5739
  step: step,
5562
5740
  value: value
5563
- }), jsx(Description, {
5741
+ }, element), jsx(Description, {
5564
5742
  forId: id,
5565
5743
  element: element,
5566
5744
  value: description
@@ -5666,7 +5844,7 @@ function SelectEntry(props) {
5666
5844
  onChange: setValue,
5667
5845
  options: options,
5668
5846
  disabled: disabled
5669
- }), error && jsx("div", {
5847
+ }, element), error && jsx("div", {
5670
5848
  class: "bio-properties-panel-error",
5671
5849
  children: error
5672
5850
  }), jsx(Description, {
@@ -5730,7 +5908,7 @@ function Simple(props) {
5730
5908
  onFocus: onFocus,
5731
5909
  onBlur: onBlur,
5732
5910
  value: localValue
5733
- })
5911
+ }, element)
5734
5912
  });
5735
5913
  }
5736
5914
  function isEdited$3(node) {
@@ -5824,7 +6002,7 @@ function TextAreaEntry(props) {
5824
6002
  const value = getValue(element);
5825
6003
  const error = useError(id);
5826
6004
  return jsxs("div", {
5827
- class: "bio-properties-panel-entry",
6005
+ class: classnames('bio-properties-panel-entry', error ? 'has-error' : ''),
5828
6006
  "data-entry-id": id,
5829
6007
  children: [jsx(TextArea, {
5830
6008
  id: id,
@@ -5835,7 +6013,7 @@ function TextAreaEntry(props) {
5835
6013
  debounce: debounce,
5836
6014
  monospace: monospace,
5837
6015
  disabled: disabled
5838
- }), error && jsx("div", {
6016
+ }, element), error && jsx("div", {
5839
6017
  class: "bio-properties-panel-error",
5840
6018
  children: error
5841
6019
  }), jsx(Description, {
@@ -5973,7 +6151,7 @@ function TextfieldEntry(props) {
5973
6151
  label: label,
5974
6152
  onInput: onInput,
5975
6153
  value: value
5976
- }), error && jsx("div", {
6154
+ }, element), error && jsx("div", {
5977
6155
  class: "bio-properties-panel-error",
5978
6156
  children: error
5979
6157
  }), jsx(Description, {