@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.js CHANGED
@@ -468,8 +468,9 @@ function useShowEntryEvent(id) {
468
468
 
469
469
  function useStickyIntersectionObserver(ref, scrollContainerSelector, setSticky) {
470
470
  hooks.useEffect(() => {
471
- // return early if IntersectionObserver is not available
472
- if (!IntersectionObserver) {
471
+ const Observer = IntersectionObserver; // return early if IntersectionObserver is not available
472
+
473
+ if (!Observer) {
473
474
  return;
474
475
  }
475
476
 
@@ -477,12 +478,14 @@ function useStickyIntersectionObserver(ref, scrollContainerSelector, setSticky)
477
478
 
478
479
  if (ref.current) {
479
480
  const scrollContainer = minDom.query(scrollContainerSelector);
480
- observer = new IntersectionObserver(entries => {
481
- if (entries[0].intersectionRatio < 1) {
482
- setSticky(true);
483
- } else if (entries[0].intersectionRatio === 1) {
484
- setSticky(false);
485
- }
481
+ observer = new Observer(entries => {
482
+ entries.forEach(entry => {
483
+ if (entry.intersectionRatio < 1) {
484
+ setSticky(true);
485
+ } else if (entry.intersectionRatio === 1) {
486
+ setSticky(false);
487
+ }
488
+ });
486
489
  }, {
487
490
  root: scrollContainer,
488
491
  rootMargin: '0px 0px 999999% 0px',
@@ -498,7 +501,7 @@ function useStickyIntersectionObserver(ref, scrollContainerSelector, setSticky)
498
501
  observer.unobserve(ref.current);
499
502
  }
500
503
  };
501
- }, [ref]);
504
+ }, [ref, scrollContainerSelector, setSticky]);
502
505
  }
503
506
 
504
507
  /**
@@ -1316,7 +1319,7 @@ function CheckboxEntry(props) {
1316
1319
  label: label,
1317
1320
  onChange: setValue,
1318
1321
  value: value
1319
- }), error && jsxRuntime.jsx("div", {
1322
+ }, element), error && jsxRuntime.jsx("div", {
1320
1323
  class: "bio-properties-panel-error",
1321
1324
  children: error
1322
1325
  }), jsxRuntime.jsx(Description, {
@@ -1417,6 +1420,10 @@ Find the code point at the given position in a string (like the
1417
1420
  [`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt)
1418
1421
  string method).
1419
1422
  */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;}/**
1423
+ Given a Unicode codepoint, return the JavaScript string that
1424
+ respresents it (like
1425
+ [`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)).
1426
+ */function fromCodePoint(code){if(code<=0xffff)return String.fromCharCode(code);code-=0x10000;return String.fromCharCode((code>>10)+0xd800,(code&1023)+0xdc00);}/**
1420
1427
  The amount of positions a character takes up a JavaScript string.
1421
1428
  */function codePointSize(code){return code<0x10000?1:2;}const DefaultSplit=/\r\n?|\n/;/**
1422
1429
  Distinguishes different ways in which positions can be mapped.
@@ -1888,7 +1895,7 @@ collaborative editing.
1888
1895
  */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.
1889
1896
  function filterTransaction(tr){let state=tr.startState;// Change filters
1890
1897
  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
1891
- 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];}/**
1898
+ 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];}/**
1892
1899
  The categories produced by a [character
1893
1900
  categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used
1894
1901
  do things like selecting by word.
@@ -2442,7 +2449,7 @@ merge(from,to,source,hasStart,openStart,openEnd){if(source){if(!(source instance
2442
2449
  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
2443
2450
  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
2444
2451
  this.getLine().addLineDeco(deco);}if(len){// Advance the iterator past the replaced content
2445
- 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)});/**
2452
+ 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)});/**
2446
2453
  Log or report an unhandled exception in client code. Should
2447
2454
  probably only be used by extension code that allows client code to
2448
2455
  provide functions, and calls those functions in a context where an
@@ -2960,7 +2967,7 @@ transactions for editing actions.
2960
2967
  [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead, which uses this
2961
2968
  as a primitive.
2962
2969
  */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
2963
- 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);}/**
2970
+ 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);}/**
2964
2971
  Reset the view to the given state. (This will cause the entire
2965
2972
  document to be redrawn and all view plugins to be reinitialized,
2966
2973
  so you should probably only use it when the new state isn't
@@ -3116,7 +3123,7 @@ return (document.hasFocus()||browser.safari&&((_a=this.inputState)===null||_a===
3116
3123
  Returns an effect that can be
3117
3124
  [added](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) to a transaction to
3118
3125
  cause it to scroll the given position or range into view.
3119
- */static scrollIntoView(pos,options={}){return scrollIntoView.of(new ScrollTarget(typeof pos=="number"?EditorSelection.cursor(pos):pos,options.y,options.x,options.yMargin,options.xMargin));}/**
3126
+ */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));}/**
3120
3127
  Returns an extension that can be used to add DOM event handlers.
3121
3128
  The value should be an object mapping event names to handler
3122
3129
  functions. For any given event, such functions are ordered by
@@ -3259,9 +3266,9 @@ for a given key, no further handlers are called.
3259
3266
  */const keymap=/*@__PURE__*/Facet.define({enables:handleKeyEvents});const Keymaps=/*@__PURE__*/new WeakMap();// This is hidden behind an indirection, rather than directly computed
3260
3267
  // by the facet, to keep internal types out of the facet's type.
3261
3268
  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.
3262
- 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};/**
3269
+ 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};/**
3263
3270
  Facet to which an extension can add a value to show a tooltip.
3264
- */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
3271
+ */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
3265
3272
  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;}/**
3266
3273
  Set up a hover tooltip, which shows up when the pointer hovers
3267
3274
  over ranges of text. The callback is called when the mouse hovers
@@ -3274,7 +3281,9 @@ pointer is before the position, 1 if after the position.
3274
3281
  Note that all hover tooltips are hosted within a single tooltip
3275
3282
  container element. This allows multiple tooltips over the same
3276
3283
  range to be "merged" together without overlapping.
3277
- */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;}/**
3284
+ */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];}/**
3285
+ Get the active tooltip view for a given tooltip, if available.
3286
+ */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;}/**
3278
3287
  Opening a panel is done by providing a constructor function for
3279
3288
  the panel through this facet. (The panel is closed again when its
3280
3289
  constructor is no longer provided.) Values of `null` are ignored.
@@ -4082,476 +4091,7 @@ direction `dir`. Only the `brackets` and `maxScanDistance`
4082
4091
  properties are used from `config`, if given. Returns null if no
4083
4092
  bracket was found at `pos`, or a match result otherwise.
4084
4093
  */function matchBrackets(state,pos,dir,config={}){let maxScanDistance=config.maxScanDistance||DefaultScanDist,brackets=config.brackets||DefaultBrackets;let tree=syntaxTree(state),node=tree.resolveInner(pos,dir);for(let cur=node;cur;cur=cur.parent){let matches=matchingNodes(cur.type,dir,brackets);if(matches&&cur.from<cur.to)return matchMarkedBrackets(state,pos,dir,cur,matches,brackets);}return matchPlainBrackets(state,pos,dir,tree,node.type,maxScanDistance,brackets);}function matchMarkedBrackets(_state,_pos,dir,token,matching,brackets){let parent=token.parent,firstToken={from:token.from,to:token.to};let depth=0,cursor=parent===null||parent===void 0?void 0:parent.cursor();if(cursor&&(dir<0?cursor.childBefore(token.from):cursor.childAfter(token.to)))do{if(dir<0?cursor.to<=token.from:cursor.from>=token.to){if(depth==0&&matching.indexOf(cursor.type.name)>-1&&cursor.from<cursor.to){return {start:firstToken,end:{from:cursor.from,to:cursor.to},matched:true};}else if(matchingNodes(cursor.type,dir,brackets)){depth++;}else if(matchingNodes(cursor.type,-dir,brackets)){depth--;if(depth==0)return {start:firstToken,end:cursor.from==cursor.to?undefined:{from:cursor.from,to:cursor.to},matched:false};}}}while(dir<0?cursor.prevSibling():cursor.nextSibling());return {start:firstToken,matched:false};}function matchPlainBrackets(state,pos,dir,tree,tokenType,maxScanDistance,brackets){let startCh=dir<0?state.sliceDoc(pos-1,pos):state.sliceDoc(pos,pos+1);let bracket=brackets.indexOf(startCh);if(bracket<0||bracket%2==0!=dir>0)return null;let startToken={from:dir<0?pos-1:pos,to:dir>0?pos+1:pos};let iter=state.doc.iterRange(pos,dir>0?state.doc.length:0),depth=0;for(let distance=0;!iter.next().done&&distance<=maxScanDistance;){let text=iter.value;if(dir<0)distance+=text.length;let basePos=pos+distance*dir;for(let pos=dir>0?0:text.length-1,end=dir>0?text.length:-1;pos!=end;pos+=dir){let found=brackets.indexOf(text[pos]);if(found<0||tree.resolve(basePos+pos,1).type!=tokenType)continue;if(found%2==0==dir>0){depth++;}else if(depth==1){// Closing
4085
- 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
4086
- // parent pointer
4087
- /// The default maximum length of a `TreeBuffer` node (1024).
4088
- 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)
4089
- /// can have metadata associated with it in props. Instances of this
4090
- /// class represent prop names.
4091
- class NodeProp{/// Create a new node prop type.
4092
- 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
4093
- /// [`NodeSet.extend`](#common.NodeSet.extend) or
4094
- /// [`LRParser.configure`](#lr.ParserConfig.props) to compute
4095
- /// prop values for each node type in the set. Takes a [match
4096
- /// object](#common.NodeType^match) or function that returns undefined
4097
- /// if the node type doesn't get this prop, and the prop's value if
4098
- /// it does.
4099
- 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
4100
- /// delimiters, this holds an array of node names (written as a
4101
- /// space-separated string when declaring this prop in a grammar)
4102
- /// for the node types of closing delimiters that match it.
4103
- NodeProp.closedBy=new NodeProp({deserialize:str=>str.split(" ")});/// The inverse of [`closedBy`](#common.NodeProp^closedBy). This is
4104
- /// attached to closing delimiters, holding an array of node names
4105
- /// of types of matching opening delimiters.
4106
- NodeProp.openedBy=new NodeProp({deserialize:str=>str.split(" ")});/// Used to assign node types to groups (for example, all node
4107
- /// types that represent an expression could be tagged with an
4108
- /// `"Expression"` group).
4109
- NodeProp.group=new NodeProp({deserialize:str=>str.split(" ")});/// The hash of the [context](#lr.ContextTracker.constructor)
4110
- /// that the node was parsed in, if any. Used to limit reuse of
4111
- /// contextual nodes.
4112
- NodeProp.contextHash=new NodeProp({perNode:true});/// The distance beyond the end of the node that the tokenizer
4113
- /// looked ahead for any of the tokens inside the node. (The LR
4114
- /// parser only stores this when it is larger than 25, for
4115
- /// efficiency reasons.)
4116
- NodeProp.lookAhead=new NodeProp({perNode:true});/// This per-node prop is used to replace a given node, or part of a
4117
- /// node, with another tree. This is useful to include trees from
4118
- /// different languages.
4119
- NodeProp.mounted=new NodeProp({perNode:true});const noProps=Object.create(null);/// Each node in a syntax tree has a node type associated with it.
4120
- class NodeType{/// @internal
4121
- constructor(/// The name of the node type. Not necessarily unique, but if the
4122
- /// grammar was written properly, different node types with the
4123
- /// same name within a node set should play the same semantic
4124
- /// role.
4125
- name,/// @internal
4126
- props,/// The id of this node in its set. Corresponds to the term ids
4127
- /// used in the parser.
4128
- id,/// @internal
4129
- 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
4130
- /// the prop isn't present on this node.
4131
- prop(prop){return this.props[prop.id];}/// True when this is the top node of a grammar.
4132
- get isTop(){return (this.flags&1/* Top */)>0;}/// True when this node is produced by a skip rule.
4133
- get isSkipped(){return (this.flags&2/* Skipped */)>0;}/// Indicates whether this is an error node.
4134
- get isError(){return (this.flags&4/* Error */)>0;}/// When true, this node type doesn't correspond to a user-declared
4135
- /// named node, for example because it is used to cache repetition.
4136
- get isAnonymous(){return (this.flags&8/* Anonymous */)>0;}/// Returns true when this node's name or one of its
4137
- /// [groups](#common.NodeProp^group) matches the given string.
4138
- 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
4139
- /// specifying an object whose property names are node or
4140
- /// [group](#common.NodeProp^group) names. Often useful with
4141
- /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple
4142
- /// names, separated by spaces, in a single property name to map
4143
- /// multiple node names to a single value.
4144
- 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.
4145
- NodeType.none=new NodeType("",Object.create(null),0,8/* Anonymous */);/// A node set holds a collection of node types. It is used to
4146
- /// compactly represent trees by storing their type ids, rather than a
4147
- /// full pointer to the type object, in a numeric array. Each parser
4148
- /// [has](#lr.LRParser.nodeSet) a node set, and [tree
4149
- /// buffers](#common.TreeBuffer) can only store collections of nodes
4150
- /// from the same set. A set can have a maximum of 2**16 (65536) node
4151
- /// types in it, so that the ids fit into 16-bit typed array slots.
4152
- class NodeSet{/// Create a set with the given types. The `id` property of each
4153
- /// type should correspond to its position within the array.
4154
- constructor(/// The node types in this set, by id.
4155
- 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
4156
- /// arguments to this method should be created with
4157
- /// [`NodeProp.add`](#common.NodeProp.add).
4158
- 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 `|`
4159
- /// operator to enable multiple ones.
4160
- var IterMode;(function(IterMode){/// When enabled, iteration will only visit [`Tree`](#common.Tree)
4161
- /// objects, not nodes packed into
4162
- /// [`TreeBuffer`](#common.TreeBuffer)s.
4163
- IterMode[IterMode["ExcludeBuffers"]=1]="ExcludeBuffers";/// Enable this to make iteration include anonymous nodes (such as
4164
- /// the nodes that wrap repeated grammar constructs into a balanced
4165
- /// tree).
4166
- IterMode[IterMode["IncludeAnonymous"]=2]="IncludeAnonymous";/// By default, regular [mounted](#common.NodeProp^mounted) nodes
4167
- /// replace their base node in iteration. Enable this to ignore them
4168
- /// instead.
4169
- IterMode[IterMode["IgnoreMounts"]=4]="IgnoreMounts";/// This option only applies in
4170
- /// [`enter`](#common.SyntaxNode.enter)-style methods. It tells the
4171
- /// library to not enter mounted overlays if one covers the given
4172
- /// position.
4173
- IterMode[IterMode["IgnoreOverlays"]=8]="IgnoreOverlays";})(IterMode||(IterMode={}));/// A piece of syntax tree. There are two ways to approach these
4174
- /// trees: the way they are actually stored in memory, and the
4175
- /// convenient way.
4176
- ///
4177
- /// Syntax trees are stored as a tree of `Tree` and `TreeBuffer`
4178
- /// objects. By packing detail information into `TreeBuffer` leaf
4179
- /// nodes, the representation is made a lot more memory-efficient.
4180
- ///
4181
- /// However, when you want to actually work with tree nodes, this
4182
- /// representation is very awkward, so most client code will want to
4183
- /// use the [`TreeCursor`](#common.TreeCursor) or
4184
- /// [`SyntaxNode`](#common.SyntaxNode) interface instead, which provides
4185
- /// a view on some part of this data structure, and can be used to
4186
- /// move around to adjacent nodes.
4187
- class Tree{/// Construct a new tree. See also [`Tree.build`](#common.Tree^build).
4188
- constructor(/// The type of the top node.
4189
- type,/// This node's child nodes.
4190
- children,/// The positions (offsets relative to the start of this tree) of
4191
- /// the children.
4192
- positions,/// The total length of this tree
4193
- length,/// Per-node [node props](#common.NodeProp) to associate with this node.
4194
- props){this.type=type;this.children=children;this.positions=positions;this.length=length;/// @internal
4195
- 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
4196
- 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
4197
- /// the tree. Mode can be used to [control](#common.IterMode) which
4198
- /// nodes the cursor visits.
4199
- cursor(mode=0){return new TreeCursor(this.topNode,mode);}/// Get a [tree cursor](#common.TreeCursor) pointing into this tree
4200
- /// at the given position and side (see
4201
- /// [`moveTo`](#common.TreeCursor.moveTo).
4202
- 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
4203
- /// tree.
4204
- get topNode(){return new TreeNode(this,0,0,null);}/// Get the [syntax node](#common.SyntaxNode) at the given position.
4205
- /// If `side` is -1, this will move into nodes that end at the
4206
- /// position. If 1, it'll move into nodes that start at the
4207
- /// position. With 0, it'll only enter nodes that cover the position
4208
- /// from both sides.
4209
- 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
4210
- /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
4211
- /// pointing into the innermost overlaid tree at the given position
4212
- /// (with parent links going through all parent structure, including
4213
- /// the host trees).
4214
- 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
4215
- /// node that touches the `from`/`to` region (if given) before
4216
- /// running over such a node's children, and `leave` (if given) when
4217
- /// leaving the node. When `enter` returns `false`, that node will
4218
- /// not have its children iterated over (or `leave` called).
4219
- 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
4220
- /// node. Works with both per-node and per-type props.
4221
- 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
4222
- /// format that can be passed to the [`Tree`](#common.Tree)
4223
- /// constructor.
4224
- 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
4225
- /// which may have children grouped into subtrees with type
4226
- /// [`NodeType.none`](#common.NodeType^none).
4227
- 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,
4228
- /// or a cursor over such a buffer.
4229
- static build(data){return buildTree(data);}}/// The empty tree
4230
- 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
4231
- /// node. In such a buffer, nodes are stored in prefix order (parents
4232
- /// before children, with the endIndex of the parent indicating which
4233
- /// children belong to it)
4234
- class TreeBuffer{/// Create a tree buffer.
4235
- constructor(/// The buffer's content.
4236
- buffer,/// The total length of the group of nodes in the buffer.
4237
- length,/// The node set used in this buffer.
4238
- set){this.buffer=buffer;this.length=length;this.set=set;}/// @internal
4239
- get type(){return NodeType.none;}/// @internal
4240
- 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
4241
- 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
4242
- 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
4243
- 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
4244
- 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
4245
- 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)
4246
- 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
4247
- 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
4248
- 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
4249
- /// allows you to move to adjacent nodes.
4250
- class TreeCursor{/// @internal
4251
- constructor(node,/// @internal
4252
- mode=0){this.mode=mode;/// @internal
4253
- this.buffer=null;this.stack=[];/// @internal
4254
- 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`.
4255
- 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
4256
- toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString();}/// @internal
4257
- 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
4258
- /// false, the node has no child, and the cursor has not been moved.
4259
- firstChild(){return this.enterChild(1,0,4/* DontCare */);}/// Move the cursor to this node's last child.
4260
- lastChild(){return this.enterChild(-1,0,4/* DontCare */);}/// Move the cursor to the first child that ends after `pos`.
4261
- childAfter(pos){return this.enterChild(1,pos,2/* After */);}/// Move to the last child that starts before `pos`.
4262
- childBefore(pos){return this.enterChild(-1,pos,-2/* Before */);}/// Move the cursor to the child around `pos`. If side is -1 the
4263
- /// child may end at that position, when 1 it may start there. This
4264
- /// will also enter [overlaid](#common.MountedTree.overlay)
4265
- /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is
4266
- /// set to false.
4267
- 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.
4268
- 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
4269
- 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.
4270
- nextSibling(){return this.sibling(1);}/// Move to this node's previous sibling, if any.
4271
- 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
4272
- /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR))
4273
- /// traversal, going from a node to its first child or, if the
4274
- /// current node is empty or `enter` is false, its next sibling or
4275
- /// the next sibling of the first parent node that has one.
4276
- next(enter=true){return this.move(1,enter);}/// Move to the next node in a last-to-first pre-order traveral. A
4277
- /// node is followed by its last child or, if it has none, its
4278
- /// previous sibling or the previous sibling of the first parent
4279
- /// node that has one.
4280
- prev(enter=true){return this.move(-1,enter);}/// Move the cursor to the innermost node that covers `pos`. If
4281
- /// `side` is -1, it will enter nodes that end at `pos`. If it is 1,
4282
- /// it will enter nodes that start at `pos`.
4283
- moveTo(pos,side=0){// Move up to a node that actually holds the position, if possible
4284
- 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
4285
- while(this.enterChild(1,pos,side)){}return this;}/// Get a [syntax node](#common.SyntaxNode) at the cursor's current
4286
- /// position.
4287
- 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
4288
- /// any. Will return null when the node is in a [tree
4289
- /// buffer](#common.TreeBuffer).
4290
- get tree(){return this.buffer?null:this._tree._tree;}/// Iterate over the current node and all its descendants, calling
4291
- /// `enter` when entering a node and `leave`, if given, when leaving
4292
- /// one. When `enter` returns `false`, any children of that node are
4293
- /// skipped, and `leave` isn't called for it.
4294
- 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
4295
- /// of direct parent node names. Empty strings in the context array
4296
- /// are treated as wildcards.
4297
- 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
4298
- 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
4299
- 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
4300
- 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
4301
- // together in a TreeBuffer, and don't contain any reused nodes
4302
- // (which can't be stored in a buffer).
4303
- // If `inRepeat` is > -1, ignore node boundaries of that type for
4304
- // nesting, but make sure the end falls either at the start
4305
- // (`maxSize`) or before such a node.
4306
- 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
4307
- if(fork.id==inRepeat&&nodeSize>=0){// Except that we store the current state as a valid return
4308
- // value.
4309
- 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.
4310
- balanceType,// The direct children and their positions
4311
- children,positions,// The index range in children/positions to use
4312
- from,to,// The start position of the nodes, relative to their parent.
4313
- start,// Length of the outer node
4314
- length,// Function to build the top node of the balanced tree
4315
- mkTop,// Function to build internal nodes for the balanced tree
4316
- 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
4317
- 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.
4318
- class Parser{/// Start a parse, returning a [partial parse](#common.PartialParse)
4319
- /// object. [`fragments`](#common.TreeFragment) can be passed in to
4320
- /// make the parse incremental.
4321
- ///
4322
- /// By default, the entire input is parsed. You can pass `ranges`,
4323
- /// which should be a sorted array of non-empty, non-overlapping
4324
- /// ranges, to parse only those ranges. The tree returned in that
4325
- /// case will start at `ranges[0].from`.
4326
- 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.
4327
- 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
4328
- /// parsing progress. They also provide some properties and methods
4329
- /// that external code such as a tokenizer can use to get information
4330
- /// about the parse state.
4331
- class Stack{/// @internal
4332
- constructor(/// The parse that this stack is part of @internal
4333
- p,/// Holds state, input pos, buffer index triplets for all but the
4334
- /// top state @internal
4335
- stack,/// The current parse state @internal
4336
- state,// The position at which the next reduce should take place. This
4337
- // can be less than `this.pos` when skipped expressions have been
4338
- // added to the stack (which should be moved outside of the next
4339
- // reduction)
4340
- /// @internal
4341
- reducePos,/// The input position up to which this stack has parsed.
4342
- pos,/// The dynamic score of the stack, including dynamic precedence
4343
- /// and error-recovery penalties
4344
- /// @internal
4345
- score,// The output buffer. Holds (type, start, end, size) quads
4346
- // representing nodes created by the parser, where `size` is
4347
- // amount of buffer array entries covered by this node.
4348
- /// @internal
4349
- buffer,// The base offset of the buffer. When stacks are split, the split
4350
- // instance shared the buffer history with its parent up to
4351
- // `bufferBase`, which is the absolute offset (including the
4352
- // offset of previous splits) into the buffer at which this stack
4353
- // starts writing.
4354
- /// @internal
4355
- bufferBase,/// @internal
4356
- curContext,/// @internal
4357
- lookAhead=0,// A parent stack from which this was split off, if any. This is
4358
- // set up so that it always points to a stack that has some
4359
- // additional buffer content, never to a stack with an equal
4360
- // `bufferBase`.
4361
- /// @internal
4362
- 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
4363
- toString(){return `[${this.stack.filter((_,i)=>i%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`;}// Start an empty stack
4364
- /// @internal
4365
- 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
4366
- /// any. Its type will depend on the context tracker's type
4367
- /// parameter, or it will be `null` if there is no context
4368
- /// tracker.
4369
- get context(){return this.curContext?this.curContext.context:null;}// Push a state onto the stack, tracking its start position as well
4370
- // as the buffer base at that point.
4371
- /// @internal
4372
- pushState(state,start){this.stack.push(this.state,start,this.bufferBase+this.buffer.length);this.state=state;}// Apply a reduce action
4373
- /// @internal
4374
- 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
4375
- // the stack without popping anything off.
4376
- 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
4377
- // be dropped. Note that with `StayFlag` reductions we need to
4378
- // consume two extra frames (the dummy parent node for the skipped
4379
- // expression and the state that we'll be staying in, which should
4380
- // be moved to `this.state`).
4381
- 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
4382
- 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
4383
- /// @internal
4384
- 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
4385
- 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
4386
- this.buffer.push(term,start,end,size);}else {// There may be skipped nodes that have to be moved forward
4387
- 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
4388
- 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
4389
- /// @internal
4390
- 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
4391
- 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
4392
- this.pos=nextEnd;this.shiftContext(next,start);if(next<=this.p.parser.maxNode)this.buffer.push(next,start,nextEnd,4);}}// Apply an action
4393
- /// @internal
4394
- 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.
4395
- /// @internal
4396
- 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
4397
- // that `this.stack` tends to stay quite shallow, this isn't very
4398
- // expensive.
4399
- /// @internal
4400
- split(){let parent=this;let off=parent.buffer.length;// Because the top of the buffer (after this.pos) may be mutated
4401
- // to reorder reductions and skipped tokens, and shared buffers
4402
- // should be immutable, this copies any outstanding skipped tokens
4403
- // to the new buffer, and puts the base pointer before them.
4404
- 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.
4405
- 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.
4406
- /// @internal
4407
- 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
4408
- /// after some reductions) on this stack. This can be useful for
4409
- /// external tokenizers that want to make sure they only provide a
4410
- /// given token when it applies.
4411
- 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
4412
- // inserts some missing token or rule.
4413
- /// @internal
4414
- 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
4415
- // be done.
4416
- /// @internal
4417
- 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
4418
- 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
4419
- /// top state, since any other states must be able to continue
4420
- /// somehow). @internal
4421
- 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
4422
- /// when this.stack.length == 3 (state is directly below the top
4423
- /// state). @internal
4424
- restart(){this.state=this.stack[0];this.stack.length=0;}/// @internal
4425
- 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.
4426
- get parser(){return this.p.parser;}/// Test whether a given dialect (by numeric ID, as exported from
4427
- /// the terms file) is enabled.
4428
- 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
4429
- 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
4430
- 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
4431
- setLookAhead(lookAhead){if(lookAhead>this.lookAhead){this.emitLookAhead();this.lookAhead=lookAhead;}}/// @internal
4432
- 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
4433
- // an entire stack
4434
- 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
4435
- // the parent-stack-walking necessary to read the nodes.
4436
- 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
4437
- /// through this interface. It presents the input as a stream of
4438
- /// characters, tracking lookahead and hiding the complexity of
4439
- /// [ranges](#common.Parser.parse^ranges) from tokenizer code.
4440
- class InputStream{/// @internal
4441
- constructor(/// @internal
4442
- input,/// @internal
4443
- ranges){this.input=input;this.ranges=ranges;/// @internal
4444
- this.chunk="";/// @internal
4445
- this.chunkOff=0;/// Backup chunk
4446
- this.chunk2="";this.chunk2Pos=0;/// The character code of the next code unit in the input, or -1
4447
- /// when the stream is at the end of the input.
4448
- this.next=-1;/// @internal
4449
- 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
4450
- /// `.next`, `.peek(-1)` gives you the previous character, and so
4451
- /// on.
4452
- ///
4453
- /// Note that looking around during tokenizing creates dependencies
4454
- /// on potentially far-away content, which may reduce the
4455
- /// effectiveness incremental parsing—when looking forward—or even
4456
- /// cause invalid reparses when looking backward more than 25 code
4457
- /// units, since the library does not track lookbehind.
4458
- 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
4459
- /// current stream position, but you can pass an offset (relative to
4460
- /// the stream position) to change that.
4461
- 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
4462
- /// the new value of [`next`](#lr.InputStream.next).
4463
- 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
4464
- 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
4465
- 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
4466
- 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
4467
- // state:
4468
- //
4469
- // - A group bitmask, indicating what token groups are reachable from
4470
- // this state, so that paths that can only lead to tokens not in
4471
- // any of the current groups can be cut off early.
4472
- //
4473
- // - The position of the end of the state's sequence of accepting
4474
- // tokens
4475
- //
4476
- // - The number of outgoing edges for the state
4477
- //
4478
- // - The accepting tokens, as (token id, group mask) pairs
4479
- //
4480
- // - The outgoing edges, as (start character, end character, state
4481
- // index) triples, with end character being exclusive
4482
- //
4483
- // This function interprets that data, running through a stream as
4484
- // long as new states with the a matching group mask can be reached,
4485
- // and updating `token` when it matches a token.
4486
- 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
4487
- // Accept tokens in this state, possibly overwriting
4488
- // lower-precedence / shorter tokens
4489
- 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
4490
- 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
4491
- // used here
4492
- 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
4493
- 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
4494
- 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
4495
- 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
4496
- 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
4497
- 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
4498
- // add this many elements to their buffers, prune one.
4499
- Rec[Rec["MinBufferLengthPrune"]=500]="MinBufferLengthPrune";Rec[Rec["ForceReduceLimit"]=10]="ForceReduceLimit";// Once a stack reaches this depth (in .stack.length) force-reduce
4500
- // it back to CutTo to avoid creating trees that overflow the stack
4501
- // on recursive traversal.
4502
- 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;// ♔, ♕, ♖, ♗, ♘, ♙, ♠, ♡, ♢, ♣, ♤, ♥, ♦, ♧
4503
- 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
4504
- // `this.pos` and try to advance them to a further position. If no
4505
- // stack for such a position is found, it'll start error-recovery.
4506
- //
4507
- // When the parse is finished, this will return a syntax tree. When
4508
- // not, it returns `null`.
4509
- advance(){let stacks=this.stacks,pos=this.minStackPos;// This will hold stacks beyond `pos`.
4510
- let newStacks=this.stacks=[];let stopped,stoppedTokens;// Keep advancing any stacks at `pos` until they either move
4511
- // forward or can't be advanced. Gather stacks that can't be
4512
- // advanced further in `stopped`.
4513
- 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
4514
- // running without splitting for a while, to avoid getting stuck
4515
- // with multiple successful stacks running endlessly on.
4516
- 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
4517
- // stack can't advance normally. When `split` and `stacks` are
4518
- // given, stacks split off by ambiguous operations will be pushed to
4519
- // `split`, or added to `stacks` if they move `pos` forward.
4520
- 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
4521
- // (possibly updated) stack if it got stuck, or null if it moved
4522
- // forward and was given to `pushStackDedup`.
4523
- 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.
4524
- 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
4525
- /// by `lezer-generator`.
4526
- class LRParser extends Parser{/// @internal
4527
- constructor(spec){super();/// @internal
4528
- 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
4529
- 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
4530
- 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
4531
- stateSlot(state,slot){return this.states[state*6/* Size */+slot];}/// @internal
4532
- stateFlag(state,flag){return (this.stateSlot(state,0/* Flags */)&flag)>0;}/// @internal
4533
- 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
4534
- /// goto jumps. @internal
4535
- 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
4536
- 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
4537
- /// given settings modified. Settings not provided in `config` are
4538
- /// kept from the original parser.
4539
- configure(config){// Hideous reflection-based kludge to make it easy to create a
4540
- // slightly modified copy of a parser.
4541
- 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)
4542
- /// are registered for this parser.
4543
- hasWrappers(){return this.wrappers.length>0;}/// Returns the name associated with a given term. This will only
4544
- /// work for all terms when the parser was generated with the
4545
- /// `--names` option. By default, only the names of tagged terms are
4546
- /// stored.
4547
- 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
4548
- /// types. @internal
4549
- get eofTerm(){return this.maxNode+1;}/// The type of top node produced by the parser.
4550
- get topNode(){return this.nodeSet.types[this.top[1]];}/// @internal
4551
- dynamicPrecedence(term){let prec=this.dynamicPrecedences;return prec==null?0:prec[term]||0;}/// @internal
4552
- 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
4553
- 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.
4554
- 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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X!c#gX~PKyOq#qO~P&rOX$nXg$nXi$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!uf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O'Q'S'U'V'W'Y'k'l'm'n'o's't'v'y'{(U(V(W(X(Y(^(_(a(c(e(g(j(o(rR!cXR#b!XQ!m_R#c!X$rZOPRSgi!O!R!S!T!U!W!X![!]!^!_#U#W#r#u#|#}$O$R$S$`$e%W%e%f%l&c&d&e&f&g&h&i&j&p&q&r&s&t&u&y&{&}'R'^'_'`'b'c'd'e'f'g'h'i'p'q'r'u'x'z'|'}(O(P(Q(R(S(T(Z([(](`(b(d(f(l(m(w({U!g]`#pV!k^_#jW!h]^_#jQ!n`R$r#pX$Y#T'j(x(|R!rc",nodeNames:"⚠ LineComment BlockComment Expressions ForExpression for InExpressions InExpression Name in IterationContext return IfExpression if then else QuantifiedExpression some every InExpressions InExpression satisfies Disjunction or Conjunction and Comparison CompareOp CompareOp between PositiveUnaryTest ( PositiveUnaryTests ) ArithmeticExpression ArithOp ArithOp ArithOp ArithOp ArithOp InstanceOf instance of Type QualifiedName SpecialType days time duration years months date > ListType list < ContextType context ContextEntryTypes ContextEntryType FunctionType function ArgumentTypes ArgumentType PathExpression ] FilterExpression [ FunctionInvocation SpecialFunctionName string length upper case lower substring before after starts with ends contains insert index distinct values met by overlaps finished started day year week month get value entries NamedParameters NamedParameter ParameterName SpecialParameterName start position decimal sep separator grouping PositionalParameters null NumericLiteral StringLiteral BooleanLiteral DateTimeLiteral DateTimeConstructor VariableName ? SimplePositiveUnaryTest Interval ParenthesizedExpression List FunctionDefinition FormalParameters FormalParameter external FunctionBody } { Context ContextEntry Key SpecialKey method signature UnaryTests Wildcard not",maxTerm:177,nodeProps:[["group",-18,4,12,16,22,24,26,34,40,64,66,68,115,116,117,119,120,121,128,"Expression",-5,109,110,111,112,113,"Expression Literal"],["closedBy",31,")",67,"]",127,"}"],["openedBy",33,"(",65,"[",126,"{"]],skippedNodes:[0,1,2],repeatNodeCount:11,tokenData:"+Y~R|XY#{Y^#{pq#{qr$prs${tu%oxy&yyz'Oz{'T{|'b|}'g}!O'l!O!P'y!P!Q(c!Q![)n![!]*P!]!^*U!^!_*Z!_!`$v!`!a*j!a!b%o!c!}%o!}#O*t#P#Q*y#Q#R']#R#S%o#T#o%o#o#p+O#q#r+T#y#z#{$f$g#{#BY#BZ#{$IS$I_#{$I`$Ib%o$I|$JO#{$JT$JU#{$KV$KW#{$Kh%#t%o&/x&Et%o&FU&FV#{&FV;'S%o;'S;:j&s?&r?Ah%o?BY?Mn%o~$QY$[~X^#{pq#{#y#z#{$f$g#{#BY#BZ#{$IS$I_#{$I|$JO#{$JT$JU#{$KV$KW#{&FU&FV#{~$sP!_!`$v~${Ok~~%QU$q~OY${Zr${rs%ds#O${#O#P%i#P~${~%iO$q~~%lPO~${~%t_$`~tu%o!Q![%o!a!b%o!c!}%o#R#S%o#T#o%o1p4U%o$I`$Ib%o$Je$Jg%o$Kh%#t%o&/x&Et%o&FV;'S%o;'S;:j&s?&r?Ah%o?BY?Mn%o~&vP;=`<%l%o~'OOo~~'TOq~~'YPu~z{']~'bOw~~'gOs~~'lO$c~R'qPtP!`!a'tQ'yO$jQ~(OQ$f~!O!P(U!Q![(Z~(ZO$b~~(`P$p~!Q![(Z~(hQv~z{(n!P!Q)c~(qROz(nz{(z{~(n~(}TOz(nz{(z{!P(n!P!Q)^!Q~(n~)cOQ~~)hQP~OY)cZ~)c~)sQ$p~!O!P)y!Q![)n~)|P!Q![(Z~*UO$h~~*ZO$w~R*bP!XQlP!_!`*eP*jOlPR*qP!UQlP!_!`*e~*yO!e~~+OO!c~~+TO#s~~+YO#r~",tokenizers:[0,1],topRules:{"Expressions":[0,3],"UnaryTests":[1,134]},dynamicPrecedences:{"24":-1,"68":-1,"151":-1},specialized:[{term:154,get:value=>spec_identifier[value]||-1}],tokenPrec:0});const highlightTags=styleTags({VariableName:tags.variableName,NumericLiteral:tags.number,QualifiedName:tags.name,Name:tags.name,BooleanLiteral:tags.bool,StringLiteral:tags.string,LineComment:tags.lineComment,BlockComment:tags.blockComment,'( )':tags.paren,BuiltInFunctionName:tags.function(tags.variableName),BuiltInType:tags.function(tags.variableName),ListType:tags.function(tags.variableName),ContextType:tags.function(tags.variableName),FunctionType:tags.function(tags.variableName),DateAndTime:tags.function(tags.variableName),'DateTimeConstructor!':tags.function(tags.variableName),'for in return null':tags.atom,List:tags.list,Interval:tags.list});const parserWithMetadata=parser.configure({props:[highlightTags]});const FeelLanguage=LRLanguage.define({parser:parserWithMetadata});function language(){return new LanguageSupport(FeelLanguage,[]);}/**
4094
+ return {start:startToken,end:{from:basePos+pos,to:basePos+pos+1},matched:found>>1==bracket>>1};}else {depth--;}}if(dir>0)distance+=text.length;}return iter.done?{start:startToken,matched:false}:null;}const noTokens=/*@__PURE__*/Object.create(null);const typeArray=[NodeType$1.none];const warned=[];const defaultTable=/*@__PURE__*/Object.create(null);for(let[legacyName,name]of [["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","typeName"],["attribute","propertyName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])defaultTable[legacyName]=/*@__PURE__*/createTokenType(noTokens,name);function warnForPart(part,msg){if(warned.indexOf(part)>-1)return;warned.push(part);console.warn(msg);}function createTokenType(extra,tagStr){let tag=null;for(let part of tagStr.split(".")){let value=extra[part]||tags[part];if(!value){warnForPart(part,`Unknown highlighting tag ${part}`);}else if(typeof value=="function"){if(!tag)warnForPart(part,`Modifier ${part} used at start of tag`);else tag=value(tag);}else {if(tag)warnForPart(part,`Tag ${part} used as modifier`);else tag=value;}}if(!tag)return 0;let name=tagStr.replace(/ /g,"_"),type=NodeType$1.define({id:typeArray.length,name,props:[styleTags({[name]:tag})]});typeArray.push(type);return type.id;}/**
4555
4095
  Comment or uncomment the current selection. Will use line comments
4556
4096
  if available, otherwise falling back to block comments.
4557
4097
  */const toggleComment=target=>{let config=getConfig(target.state);return config.line?toggleLineComment(target):config.block?toggleBlockCommentByLine(target):false;};function command(f,option){return ({state,dispatch})=>{if(state.readOnly)return false;let tr=f(option,state);if(!tr)return false;dispatch(state.update(tr));return true;};}/**
@@ -4788,7 +4328,7 @@ The default keymap. Includes all bindings from
4788
4328
  - Shift-Alt-a: [`toggleBlockComment`](https://codemirror.net/6/docs/ref/#commands.toggleBlockComment).
4789
4329
  */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
4790
4330
  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
4791
- 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]));}/**
4331
+ 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]));}/**
4792
4332
  Returns a transaction spec which updates the current set of
4793
4333
  diagnostics, and enables the lint extension if if wasn't already
4794
4334
  active.
@@ -4808,7 +4348,580 @@ this.moveSelection((this.selectedIndex+1)%this.items.length);}else if(event.keyC
4808
4348
  this.moveSelection(0);}else if(event.keyCode==35){// End
4809
4349
  this.moveSelection(this.items.length-1);}else if(event.keyCode==13){// Enter
4810
4350
  this.view.focus();}else if(event.keyCode>=65&&event.keyCode<=90&&this.selectedIndex>=0){// A-Z
4811
- 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
4351
+ let{diagnostic}=this.items[this.selectedIndex],keys=assignKeys(diagnostic.actions);for(let i=0;i<keys.length;i++)if(keys[i].toUpperCase().charCodeAt(0)==event.keyCode){let found=findDiagnostic(this.view.state.field(lintState).diagnostics,diagnostic);if(found)diagnostic.actions[i].apply(view,found.from,found.to);}}else {return;}event.preventDefault();};let onclick=event=>{for(let i=0;i<this.items.length;i++){if(this.items[i].dom.contains(event.target))this.moveSelection(i);}};this.list=crelt("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown,onclick});this.dom=crelt("div",{class:"cm-panel-lint"},this.list,crelt("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>closeLintPanel(this.view)},"×"));this.update();}get selectedIndex(){let selected=this.view.state.field(lintState).selected;if(!selected)return -1;for(let i=0;i<this.items.length;i++)if(this.items[i].diagnostic==selected.diagnostic)return i;return -1;}update(){let{diagnostics,selected}=this.view.state.field(lintState);let i=0,needsSync=false,newSelectedItem=null;diagnostics.between(0,this.view.state.doc.length,(_start,_end,{spec})=>{let found=-1,item;for(let j=i;j<this.items.length;j++)if(this.items[j].diagnostic==spec.diagnostic){found=j;break;}if(found<0){item=new PanelItem(this.view,spec.diagnostic);this.items.splice(i,0,item);needsSync=true;}else {item=this.items[found];if(found>i){this.items.splice(i,found-i);needsSync=true;}}if(selected&&item.diagnostic==selected.diagnostic){if(!item.dom.hasAttribute("aria-selected")){item.dom.setAttribute("aria-selected","true");newSelectedItem=item;}}else if(item.dom.hasAttribute("aria-selected")){item.dom.removeAttribute("aria-selected");}i++;});while(i<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0)){needsSync=true;this.items.pop();}if(this.items.length==0){this.items.push(new PanelItem(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")}));needsSync=true;}if(newSelectedItem){this.list.setAttribute("aria-activedescendant",newSelectedItem.id);this.view.requestMeasure({key:this,read:()=>({sel:newSelectedItem.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel,panel})=>{if(sel.top<panel.top)this.list.scrollTop-=panel.top-sel.top;else if(sel.bottom>panel.bottom)this.list.scrollTop+=sel.bottom-panel.bottom;}});}else if(this.selectedIndex<0){this.list.removeAttribute("aria-activedescendant");}if(needsSync)this.sync();}sync(){let domPos=this.list.firstChild;function rm(){let prev=domPos;domPos=prev.nextSibling;prev.remove();}for(let item of this.items){if(item.dom.parentNode==this.list){while(domPos!=item.dom)rm();domPos=item.dom.nextSibling;}else {this.list.insertBefore(item.dom,domPos);}}while(domPos)rm();}moveSelection(selectedIndex){if(this.selectedIndex<0)return;let field=this.view.state.field(lintState);let selection=findDiagnostic(field.diagnostics,this.items[selectedIndex].diagnostic);if(!selection)return;this.view.dispatch({selection:{anchor:selection.from,head:selection.to},scrollIntoView:true,effects:movePanelSelection.of(selection)});}static open(view){return new LintPanel(view);}}function svg(content,attrs=`viewBox="0 0 40 40"`){return `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${attrs}>${encodeURIComponent(content)}</svg>')`;}function underline(color){return svg(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${color}" fill="none" stroke-width=".7"/>`,`width="6" height="3"`);}const baseTheme$2=/*@__PURE__*/EditorView.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:/*@__PURE__*/underline("#d11")},".cm-lintRange-warning":{backgroundImage:/*@__PURE__*/underline("orange")},".cm-lintRange-info":{backgroundImage:/*@__PURE__*/underline("#999")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}});/**
4352
+ An instance of this is passed to completion source functions.
4353
+ */class CompletionContext{/**
4354
+ Create a new completion context. (Mostly useful for testing
4355
+ completion sources—in the editor, the extension will create
4356
+ these for you.)
4357
+ */constructor(/**
4358
+ The editor state that the completion happens in.
4359
+ */state,/**
4360
+ The position at which the completion is happening.
4361
+ */pos,/**
4362
+ Indicates whether completion was activated explicitly, or
4363
+ implicitly by typing. The usual way to respond to this is to
4364
+ only return completions when either there is part of a
4365
+ completable entity before the cursor, or `explicit` is true.
4366
+ */explicit){this.state=state;this.pos=pos;this.explicit=explicit;/**
4367
+ @internal
4368
+ */this.abortListeners=[];}/**
4369
+ Get the extent, content, and (if there is a token) type of the
4370
+ token before `this.pos`.
4371
+ */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;}/**
4372
+ Get the match of the given expression directly before the
4373
+ cursor.
4374
+ */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)};}/**
4375
+ Yields true when the query has been aborted. Can be useful in
4376
+ asynchronous queries to avoid doing work that will be ignored.
4377
+ */get aborted(){return this.abortListeners==null;}/**
4378
+ Allows you to register abort handlers, which will be called when
4379
+ the query is
4380
+ [aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted).
4381
+ */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)];}/**
4382
+ Given a a fixed array of options, return an autocompleter that
4383
+ completes them.
4384
+ */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
4385
+ // true, a ^ at its start.
4386
+ 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":"");}/**
4387
+ Helper function that returns a transaction spec which inserts a
4388
+ completion's text in the main selection range, and any other
4389
+ selection range that has the same text in front of it.
4390
+ */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
4391
+ // once for a pattern, and then use that to match any number of
4392
+ // completions.
4393
+ class FuzzyMatcher{constructor(pattern){this.pattern=pattern;this.chars=[];this.folded=[];// Buffers reused by calls to `match` to track matched character
4394
+ // positions.
4395
+ 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).
4396
+ // Will return null for no match, and otherwise an array that starts
4397
+ // with the match score, followed by any number of `from, to` pairs
4398
+ // indicating the matched parts of `word`.
4399
+ //
4400
+ // The score is a number that is more negative the worse the match
4401
+ // is. See `Penalty` above.
4402
+ match(word){if(this.pattern.length==0)return [0];if(word.length<this.pattern.length)return null;let{chars,folded,any,precise,byWord}=this;// For single-character queries, only match when they occur right
4403
+ // at the start
4404
+ if(chars.length==1){let first=codePointAt(word,0);return first==chars[0]?[0,0,codePointSize(first)]:first==folded[0]?[-200/* CaseFold */,0,codePointSize(first)]:null;}let direct=word.indexOf(this.pattern);if(direct==0)return [0,0,this.pattern.length];let len=chars.length,anyTo=0;if(direct<0){for(let i=0,e=Math.min(word.length,200);i<e&&anyTo<len;){let next=codePointAt(word,i);if(next==chars[anyTo]||next==folded[anyTo])any[anyTo++]=i;i+=codePointSize(next);}// No match, exit immediately
4405
+ if(anyTo<len)return null;}// This tracks the extent of the precise (non-folded, not
4406
+ // necessarily adjacent) match
4407
+ let preciseTo=0;// Tracks whether there is a match that hits only characters that
4408
+ // appear to be starting words. `byWordFolded` is set to true when
4409
+ // a case folded character is encountered in such a match
4410
+ let byWordTo=0,byWordFolded=false;// If we've found a partial adjacent match, these track its state
4411
+ let adjacentTo=0,adjacentStart=-1,adjacentEnd=-1;let hasLower=/[a-z]/.test(word),wordAdjacent=true;// Go over the option's text, scanning for the various kinds of matches
4412
+ for(let i=0,e=Math.min(word.length,200),prevType=0/* NonWord */;i<e&&byWordTo<len;){let next=codePointAt(word,i);if(direct<0){if(preciseTo<len&&next==chars[preciseTo])precise[preciseTo++]=i;if(adjacentTo<len){if(next==chars[adjacentTo]||next==folded[adjacentTo]){if(adjacentTo==0)adjacentStart=i;adjacentEnd=i+1;adjacentTo++;}else {adjacentTo=0;}}}let ch,type=next<0xff?next>=48&&next<=57||next>=97&&next<=122?2/* Lower */:next>=65&&next<=90?1/* Upper */:0/* NonWord */:(ch=fromCodePoint(next))!=ch.toLowerCase()?1/* Upper */:ch!=ch.toUpperCase()?2/* Lower */:0/* NonWord */;if(!i||type==1/* Upper */&&hasLower||prevType==0/* NonWord */&&type!=0/* NonWord */){if(chars[byWordTo]==next||folded[byWordTo]==next&&(byWordFolded=true))byWord[byWordTo++]=i;else if(byWord.length)wordAdjacent=false;}prevType=type;i+=codePointSize(next);}if(byWordTo==len&&byWord[0]==0&&wordAdjacent)return this.result(-100/* ByWord */+(byWordFolded?-200/* CaseFold */:0),byWord,word);if(adjacentTo==len&&adjacentStart==0)return [-200/* CaseFold */-word.length,0,adjacentEnd];if(direct>-1)return [-700/* NotStart */-word.length,direct,direct+this.pattern.length];if(adjacentTo==len)return [-200/* CaseFold */+-700/* NotStart */-word.length,adjacentStart,adjacentEnd];if(byWordTo==len)return this.result(-100/* ByWord */+(byWordFolded?-200/* CaseFold */:0)+-700/* NotStart */+(wordAdjacent?0:-1100/* Gap */),byWord,word);return chars.length==2?null:this.result((any[0]?-700/* NotStart */:0)+-200/* CaseFold */+-1100/* Gap */,any,word);}result(score,positions,word){let result=[score-word.length],i=1;for(let pos of positions){let to=pos+(this.astral?codePointSize(codePointAt(word,pos)):1);if(i>1&&result[i-1]==pos)result[i-1]=to;else {result[i++]=pos;result[i++]=to;}}return result;}}const completionConfig=/*@__PURE__*/Facet.define({combine(configs){return combineConfig(configs,{activateOnTyping:true,override:null,closeOnBlur:true,maxRenderedOptions:100,defaultKeymap:true,optionClass:()=>"",aboveCursor:false,icons:true,addToOptions:[]},{defaultKeymap:(a,b)=>a&&b,closeOnBlur:(a,b)=>a&&b,icons:(a,b)=>a&&b,optionClass:(a,b)=>c=>joinClass(a(c),b(c)),addToOptions:(a,b)=>a.concat(b)});}});function joinClass(a,b){return a?b?a+" "+b:a:b;}function optionContent(config){let content=config.addToOptions.slice();if(config.icons)content.push({render(completion){let icon=document.createElement("div");icon.classList.add("cm-completionIcon");if(completion.type)icon.classList.add(...completion.type.split(/\s+/g).map(cls=>"cm-completionIcon-"+cls));icon.setAttribute("aria-hidden","true");return icon;},position:20});content.push({render(completion,_s,match){let labelElt=document.createElement("span");labelElt.className="cm-completionLabel";let{label}=completion,off=0;for(let j=1;j<match.length;){let from=match[j++],to=match[j++];if(from>off)labelElt.appendChild(document.createTextNode(label.slice(off,from)));let span=labelElt.appendChild(document.createElement("span"));span.appendChild(document.createTextNode(label.slice(from,to)));span.className="cm-completionMatchedText";off=to;}if(off<label.length)labelElt.appendChild(document.createTextNode(label.slice(off)));return labelElt;},position:50},{render(completion){if(!completion.detail)return null;let detailElt=document.createElement("span");detailElt.className="cm-completionDetail";detailElt.textContent=completion.detail;return detailElt;},position:80});return content.sort((a,b)=>a.position-b.position).map(a=>a.render);}function rangeAroundSelected(total,selected,max){if(total<=max)return {from:0,to:total};if(selected<=total>>1){let off=Math.floor(selected/max);return {from:off*max,to:(off+1)*max};}let off=Math.floor((total-selected)/max);return {from:total-(off+1)*max,to:total-off*max};}class CompletionTooltip{constructor(view,stateField){this.view=view;this.stateField=stateField;this.info=null;this.placeInfo={read:()=>this.measureInfo(),write:pos=>this.positionInfo(pos),key:this};let cState=view.state.field(stateField);let{options,selected}=cState.open;let config=view.state.facet(completionConfig);this.optionContent=optionContent(config);this.optionClass=config.optionClass;this.range=rangeAroundSelected(options.length,selected,config.maxRenderedOptions);this.dom=document.createElement("div");this.dom.className="cm-tooltip-autocomplete";this.dom.addEventListener("mousedown",e=>{for(let dom=e.target,match;dom&&dom!=this.dom;dom=dom.parentNode){if(dom.nodeName=="LI"&&(match=/-(\d+)$/.exec(dom.id))&&+match[1]<options.length){applyCompletion(view,options[+match[1]]);e.preventDefault();return;}}});this.list=this.dom.appendChild(this.createListBox(options,cState.id,this.range));this.list.addEventListener("scroll",()=>{if(this.info)this.view.requestMeasure(this.placeInfo);});}mount(){this.updateSel();}update(update){if(update.state.field(this.stateField)!=update.startState.field(this.stateField))this.updateSel();}positioned(){if(this.info)this.view.requestMeasure(this.placeInfo);}updateSel(){let cState=this.view.state.field(this.stateField),open=cState.open;if(open.selected<this.range.from||open.selected>=this.range.to){this.range=rangeAroundSelected(open.options.length,open.selected,this.view.state.facet(completionConfig).maxRenderedOptions);this.list.remove();this.list=this.dom.appendChild(this.createListBox(open.options,cState.id,this.range));this.list.addEventListener("scroll",()=>{if(this.info)this.view.requestMeasure(this.placeInfo);});}if(this.updateSelectedOption(open.selected)){if(this.info){this.info.remove();this.info=null;}let{completion}=open.options[open.selected];let{info}=completion;if(!info)return;let infoResult=typeof info==='string'?document.createTextNode(info):info(completion);if(!infoResult)return;if('then'in infoResult){infoResult.then(node=>{if(node&&this.view.state.field(this.stateField,false)==cState)this.addInfoPane(node);}).catch(e=>logException(this.view.state,e,"completion info"));}else {this.addInfoPane(infoResult);}}}addInfoPane(content){let dom=this.info=document.createElement("div");dom.className="cm-tooltip cm-completionInfo";dom.appendChild(content);this.dom.appendChild(dom);this.view.requestMeasure(this.placeInfo);}updateSelectedOption(selected){let set=null;for(let opt=this.list.firstChild,i=this.range.from;opt;opt=opt.nextSibling,i++){if(i==selected){if(!opt.hasAttribute("aria-selected")){opt.setAttribute("aria-selected","true");set=opt;}}else {if(opt.hasAttribute("aria-selected"))opt.removeAttribute("aria-selected");}}if(set)scrollIntoView(this.list,set);return set;}measureInfo(){let sel=this.dom.querySelector("[aria-selected]");if(!sel||!this.info)return null;let listRect=this.dom.getBoundingClientRect();let infoRect=this.info.getBoundingClientRect();let selRect=sel.getBoundingClientRect();if(selRect.top>Math.min(innerHeight,listRect.bottom)-10||selRect.bottom<Math.max(0,listRect.top)+10)return null;let top=Math.max(0,Math.min(selRect.top,innerHeight-infoRect.height))-listRect.top;let left=this.view.textDirection==Direction.RTL;let spaceLeft=listRect.left,spaceRight=innerWidth-listRect.right;if(left&&spaceLeft<Math.min(infoRect.width,spaceRight))left=false;else if(!left&&spaceRight<Math.min(infoRect.width,spaceLeft))left=true;return {top,left};}positionInfo(pos){if(this.info){this.info.style.top=(pos?pos.top:-1e6)+"px";if(pos){this.info.classList.toggle("cm-completionInfo-left",pos.left);this.info.classList.toggle("cm-completionInfo-right",!pos.left);}}}createListBox(options,id,range){const ul=document.createElement("ul");ul.id=id;ul.setAttribute("role","listbox");ul.setAttribute("aria-expanded","true");ul.setAttribute("aria-label",this.view.state.phrase("Completions"));for(let i=range.from;i<range.to;i++){let{completion,match}=options[i];const li=ul.appendChild(document.createElement("li"));li.id=id+"-"+i;li.setAttribute("role","option");let cls=this.optionClass(completion);if(cls)li.className=cls;for(let source of this.optionContent){let node=source(completion,this.view.state,match);if(node)li.appendChild(node);}}if(range.from)ul.classList.add("cm-completionListIncompleteTop");if(range.to<options.length)ul.classList.add("cm-completionListIncompleteBottom");return ul;}}// We allocate a new function instance every time the completion
4413
+ // changes to force redrawing/repositioning of the tooltip
4414
+ function completionTooltip(stateField){return view=>new CompletionTooltip(view,stateField);}function scrollIntoView(container,element){let parent=container.getBoundingClientRect();let self=element.getBoundingClientRect();if(self.top<parent.top)container.scrollTop-=parent.top-self.top;else if(self.bottom>parent.bottom)container.scrollTop+=self.bottom-parent.bottom;}// Used to pick a preferred option when two options with the same
4415
+ // label occur in the result.
4416
+ function score(option){return (option.boost||0)*100+(option.apply?10:0)+(option.info?5:0)+(option.type?1:0);}function sortOptions(active,state){let options=[],i=0;for(let a of active)if(a.hasResult()){if(a.result.filter===false){let getMatch=a.result.getMatch;for(let option of a.result.options){let match=[1e9-i++];if(getMatch)for(let n of getMatch(option))match.push(n);options.push(new Option(option,a,match));}}else {let matcher=new FuzzyMatcher(state.sliceDoc(a.from,a.to)),match;for(let option of a.result.options)if(match=matcher.match(option.label)){if(option.boost!=null)match[0]+=option.boost;options.push(new Option(option,a,match));}}}let result=[],prev=null;for(let opt of options.sort(cmpOption)){if(!prev||prev.label!=opt.completion.label||prev.detail!=opt.completion.detail||prev.type!=null&&opt.completion.type!=null&&prev.type!=opt.completion.type||prev.apply!=opt.completion.apply)result.push(opt);else if(score(opt.completion)>score(prev))result[result.length-1]=opt;prev=opt.completion;}return result;}class CompletionDialog{constructor(options,attrs,tooltip,timestamp,selected){this.options=options;this.attrs=attrs;this.tooltip=tooltip;this.timestamp=timestamp;this.selected=selected;}setSelected(selected,id){return selected==this.selected||selected>=this.options.length?this:new CompletionDialog(this.options,makeAttrs(id,selected),this.tooltip,this.timestamp,selected);}static build(active,state,id,prev,conf){let options=sortOptions(active,state);if(!options.length)return null;let selected=0;if(prev&&prev.selected){let selectedValue=prev.options[prev.selected].completion;for(let i=0;i<options.length;i++)if(options[i].completion==selectedValue){selected=i;break;}}return new CompletionDialog(options,makeAttrs(id,selected),{pos:active.reduce((a,b)=>b.hasResult()?Math.min(a,b.from):a,1e8),create:completionTooltip(completionState),above:conf.aboveCursor},prev?prev.timestamp:Date.now(),selected);}map(changes){return new CompletionDialog(this.options,this.attrs,Object.assign(Object.assign({},this.tooltip),{pos:changes.mapPos(this.tooltip.pos)}),this.timestamp,this.selected);}}class CompletionState{constructor(active,id,open){this.active=active;this.id=id;this.open=open;}static start(){return new CompletionState(none,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null);}update(tr){let{state}=tr,conf=state.facet(completionConfig);let sources=conf.override||state.languageDataAt("autocomplete",cur(state)).map(asSource);let active=sources.map(source=>{let value=this.active.find(s=>s.source==source)||new ActiveSource(source,this.active.some(a=>a.state!=0/* Inactive */)?1/* Pending */:0/* Inactive */);return value.update(tr,conf);});if(active.length==this.active.length&&active.every((a,i)=>a==this.active[i]))active=this.active;let open=tr.selection||active.some(a=>a.hasResult()&&tr.changes.touchesRange(a.from,a.to))||!sameResults(active,this.active)?CompletionDialog.build(active,state,this.id,this.open,conf):this.open&&tr.docChanged?this.open.map(tr.changes):this.open;if(!open&&active.every(a=>a.state!=1/* Pending */)&&active.some(a=>a.hasResult()))active=active.map(a=>a.hasResult()?new ActiveSource(a.source,0/* Inactive */):a);for(let effect of tr.effects)if(effect.is(setSelectedEffect))open=open&&open.setSelected(effect.value,this.id);return active==this.active&&open==this.open?this:new CompletionState(active,this.id,open);}get tooltip(){return this.open?this.open.tooltip:null;}get attrs(){return this.open?this.open.attrs:baseAttrs;}}function sameResults(a,b){if(a==b)return true;for(let iA=0,iB=0;;){while(iA<a.length&&!a[iA].hasResult)iA++;while(iB<b.length&&!b[iB].hasResult)iB++;let endA=iA==a.length,endB=iB==b.length;if(endA||endB)return endA==endB;if(a[iA++].result!=b[iB++].result)return false;}}const baseAttrs={"aria-autocomplete":"list"};function makeAttrs(id,selected){return {"aria-autocomplete":"list","aria-haspopup":"listbox","aria-activedescendant":id+"-"+selected,"aria-controls":id};}const none=[];function cmpOption(a,b){let dScore=b.match[0]-a.match[0];if(dScore)return dScore;return a.completion.label.localeCompare(b.completion.label);}function getUserEvent(tr){return tr.isUserEvent("input.type")?"input":tr.isUserEvent("delete.backward")?"delete":null;}class ActiveSource{constructor(source,state,explicitPos=-1){this.source=source;this.state=state;this.explicitPos=explicitPos;}hasResult(){return false;}update(tr,conf){let event=getUserEvent(tr),value=this;if(event)value=value.handleUserEvent(tr,event,conf);else if(tr.docChanged)value=value.handleChange(tr);else if(tr.selection&&value.state!=0/* Inactive */)value=new ActiveSource(value.source,0/* Inactive */);for(let effect of tr.effects){if(effect.is(startCompletionEffect))value=new ActiveSource(value.source,1/* Pending */,effect.value?cur(tr.state):-1);else if(effect.is(closeCompletionEffect))value=new ActiveSource(value.source,0/* Inactive */);else if(effect.is(setActiveEffect))for(let active of effect.value)if(active.source==value.source)value=active;}return value;}handleUserEvent(tr,type,conf){return type=="delete"||!conf.activateOnTyping?this.map(tr.changes):new ActiveSource(this.source,1/* Pending */);}handleChange(tr){return tr.changes.touchesRange(cur(tr.startState))?new ActiveSource(this.source,0/* Inactive */):this.map(tr.changes);}map(changes){return changes.empty||this.explicitPos<0?this:new ActiveSource(this.source,this.state,changes.mapPos(this.explicitPos));}}class ActiveResult extends ActiveSource{constructor(source,explicitPos,result,from,to){super(source,2/* Result */,explicitPos);this.result=result;this.from=from;this.to=to;}hasResult(){return true;}handleUserEvent(tr,type,conf){var _a;let from=tr.changes.mapPos(this.from),to=tr.changes.mapPos(this.to,1);let pos=cur(tr.state);if((this.explicitPos<0?pos<=from:pos<this.from)||pos>to||type=="delete"&&cur(tr.startState)==this.from)return new ActiveSource(this.source,type=="input"&&conf.activateOnTyping?1/* Pending */:0/* Inactive */);let explicitPos=this.explicitPos<0?-1:tr.changes.mapPos(this.explicitPos),updated;if(checkValid(this.result.validFor,tr.state,from,to))return new ActiveResult(this.source,explicitPos,this.result,from,to);if(this.result.update&&(updated=this.result.update(this.result,from,to,new CompletionContext(tr.state,pos,explicitPos>=0))))return new ActiveResult(this.source,explicitPos,updated,updated.from,(_a=updated.to)!==null&&_a!==void 0?_a:cur(tr.state));return new ActiveSource(this.source,1/* Pending */,explicitPos);}handleChange(tr){return tr.changes.touchesRange(this.from,this.to)?new ActiveSource(this.source,0/* Inactive */):this.map(tr.changes);}map(mapping){return mapping.empty?this:new ActiveResult(this.source,this.explicitPos<0?-1:mapping.mapPos(this.explicitPos),this.result,mapping.mapPos(this.from),mapping.mapPos(this.to,1));}}function checkValid(validFor,state,from,to){if(!validFor)return false;let text=state.sliceDoc(from,to);return typeof validFor=="function"?validFor(text,from,to,state):ensureAnchor(validFor,true).test(text);}const startCompletionEffect=/*@__PURE__*/StateEffect.define();const closeCompletionEffect=/*@__PURE__*/StateEffect.define();const setActiveEffect=/*@__PURE__*/StateEffect.define({map(sources,mapping){return sources.map(s=>s.map(mapping));}});const setSelectedEffect=/*@__PURE__*/StateEffect.define();const completionState=/*@__PURE__*/StateField.define({create(){return CompletionState.start();},update(value,tr){return value.update(tr);},provide:f=>[showTooltip.from(f,val=>val.tooltip),EditorView.contentAttributes.from(f,state=>state.attrs)]});const CompletionInteractMargin=75;/**
4417
+ Returns a command that moves the completion selection forward or
4418
+ backward by the given amount.
4419
+ */function moveCompletionSelection(forward,by="option"){return view=>{let cState=view.state.field(completionState,false);if(!cState||!cState.open||Date.now()-cState.open.timestamp<CompletionInteractMargin)return false;let step=1,tooltip;if(by=="page"&&(tooltip=getTooltip(view,cState.open.tooltip)))step=Math.max(2,Math.floor(tooltip.dom.offsetHeight/tooltip.dom.querySelector("li").offsetHeight)-1);let selected=cState.open.selected+step*(forward?1:-1),{length}=cState.open.options;if(selected<0)selected=by=="page"?0:length-1;else if(selected>=length)selected=by=="page"?length-1:0;view.dispatch({effects:setSelectedEffect.of(selected)});return true;};}/**
4420
+ Accept the current completion.
4421
+ */const acceptCompletion=view=>{let cState=view.state.field(completionState,false);if(view.state.readOnly||!cState||!cState.open||Date.now()-cState.open.timestamp<CompletionInteractMargin)return false;applyCompletion(view,cState.open.options[cState.open.selected]);return true;};/**
4422
+ Explicitly start autocompletion.
4423
+ */const startCompletion=view=>{let cState=view.state.field(completionState,false);if(!cState)return false;view.dispatch({effects:startCompletionEffect.of(true)});return true;};/**
4424
+ Close the currently active completion.
4425
+ */const closeCompletion=view=>{let cState=view.state.field(completionState,false);if(!cState||!cState.active.some(a=>a.state!=0/* Inactive */))return false;view.dispatch({effects:closeCompletionEffect.of(null)});return true;};class RunningQuery{constructor(active,context){this.active=active;this.context=context;this.time=Date.now();this.updates=[];// Note that 'undefined' means 'not done yet', whereas 'null' means
4426
+ // 'query returned null'.
4427
+ this.done=undefined;}}const DebounceTime=50,MaxUpdateCount=50,MinAbortTime=1000;const completionPlugin=/*@__PURE__*/ViewPlugin.fromClass(class{constructor(view){this.view=view;this.debounceUpdate=-1;this.running=[];this.debounceAccept=-1;this.composing=0/* None */;for(let active of view.state.field(completionState).active)if(active.state==1/* Pending */)this.startQuery(active);}update(update){let cState=update.state.field(completionState);if(!update.selectionSet&&!update.docChanged&&update.startState.field(completionState)==cState)return;let doesReset=update.transactions.some(tr=>{return (tr.selection||tr.docChanged)&&!getUserEvent(tr);});for(let i=0;i<this.running.length;i++){let query=this.running[i];if(doesReset||query.updates.length+update.transactions.length>MaxUpdateCount&&Date.now()-query.time>MinAbortTime){for(let handler of query.context.abortListeners){try{handler();}catch(e){logException(this.view.state,e);}}query.context.abortListeners=null;this.running.splice(i--,1);}else {query.updates.push(...update.transactions);}}if(this.debounceUpdate>-1)clearTimeout(this.debounceUpdate);this.debounceUpdate=cState.active.some(a=>a.state==1/* Pending */&&!this.running.some(q=>q.active.source==a.source))?setTimeout(()=>this.startUpdate(),DebounceTime):-1;if(this.composing!=0/* None */)for(let tr of update.transactions){if(getUserEvent(tr)=="input")this.composing=2/* Changed */;else if(this.composing==2/* Changed */&&tr.selection)this.composing=3/* ChangedAndMoved */;}}startUpdate(){this.debounceUpdate=-1;let{state}=this.view,cState=state.field(completionState);for(let active of cState.active){if(active.state==1/* Pending */&&!this.running.some(r=>r.active.source==active.source))this.startQuery(active);}}startQuery(active){let{state}=this.view,pos=cur(state);let context=new CompletionContext(state,pos,active.explicitPos==pos);let pending=new RunningQuery(active,context);this.running.push(pending);Promise.resolve(active.source(context)).then(result=>{if(!pending.context.aborted){pending.done=result||null;this.scheduleAccept();}},err=>{this.view.dispatch({effects:closeCompletionEffect.of(null)});logException(this.view.state,err);});}scheduleAccept(){if(this.running.every(q=>q.done!==undefined))this.accept();else if(this.debounceAccept<0)this.debounceAccept=setTimeout(()=>this.accept(),DebounceTime);}// For each finished query in this.running, try to create a result
4428
+ // or, if appropriate, restart the query.
4429
+ accept(){var _a;if(this.debounceAccept>-1)clearTimeout(this.debounceAccept);this.debounceAccept=-1;let updated=[];let conf=this.view.state.facet(completionConfig);for(let i=0;i<this.running.length;i++){let query=this.running[i];if(query.done===undefined)continue;this.running.splice(i--,1);if(query.done){let active=new ActiveResult(query.active.source,query.active.explicitPos,query.done,query.done.from,(_a=query.done.to)!==null&&_a!==void 0?_a:cur(query.updates.length?query.updates[0].startState:this.view.state));// Replay the transactions that happened since the start of
4430
+ // the request and see if that preserves the result
4431
+ for(let tr of query.updates)active=active.update(tr,conf);if(active.hasResult()){updated.push(active);continue;}}let current=this.view.state.field(completionState).active.find(a=>a.source==query.active.source);if(current&&current.state==1/* Pending */){if(query.done==null){// Explicitly failed. Should clear the pending status if it
4432
+ // hasn't been re-set in the meantime.
4433
+ let active=new ActiveSource(query.active.source,0/* Inactive */);for(let tr of query.updates)active=active.update(tr,conf);if(active.state!=1/* Pending */)updated.push(active);}else {// Cleared by subsequent transactions. Restart.
4434
+ this.startQuery(current);}}}if(updated.length)this.view.dispatch({effects:setActiveEffect.of(updated)});}},{eventHandlers:{blur(){let state=this.view.state.field(completionState,false);if(state&&state.tooltip&&this.view.state.facet(completionConfig).closeOnBlur)this.view.dispatch({effects:closeCompletionEffect.of(null)});},compositionstart(){this.composing=1/* Started */;},compositionend(){if(this.composing==3/* ChangedAndMoved */){// Safari fires compositionend events synchronously, possibly
4435
+ // from inside an update, so dispatch asynchronously to avoid reentrancy
4436
+ setTimeout(()=>this.view.dispatch({effects:startCompletionEffect.of(false)}),20);}this.composing=0/* None */;}}});const baseTheme$1=/*@__PURE__*/EditorView.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",listStyle:"none",margin:0,padding:0,"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer",padding:"1px 3px",lineHeight:1.2}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"···"',opacity:0.5,display:"block",textAlign:"center"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"300px"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'ƒ'"}},".cm-completionIcon-class":{"&:after":{content:"'○'"}},".cm-completionIcon-interface":{"&:after":{content:"'◌'"}},".cm-completionIcon-variable":{"&:after":{content:"'𝑥'"}},".cm-completionIcon-constant":{"&:after":{content:"'𝐶'"}},".cm-completionIcon-type":{"&:after":{content:"'𝑡'"}},".cm-completionIcon-enum":{"&:after":{content:"'∪'"}},".cm-completionIcon-property":{"&:after":{content:"'□'"}},".cm-completionIcon-keyword":{"&:after":{content:"'🔑\uFE0E'"}// Disable emoji rendering
4437
+ },".cm-completionIcon-namespace":{"&:after":{content:"'▢'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}});const closedBracket=/*@__PURE__*/new class extends RangeValue{}();closedBracket.startSide=1;closedBracket.endSide=-1;/**
4438
+ Returns an extension that enables autocompletion.
4439
+ */function autocompletion$1(config={}){return [completionState,completionConfig.of(config),completionPlugin,completionKeymapExt,baseTheme$1];}/**
4440
+ Basic keybindings for autocompletion.
4441
+
4442
+ - Ctrl-Space: [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion)
4443
+ - Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion)
4444
+ - ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)`
4445
+ - ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)`
4446
+ - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
4447
+ - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
4448
+ - Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion)
4449
+ */const completionKeymap=[{key:"Ctrl-Space",run:startCompletion},{key:"Escape",run:closeCompletion},{key:"ArrowDown",run:/*@__PURE__*/moveCompletionSelection(true)},{key:"ArrowUp",run:/*@__PURE__*/moveCompletionSelection(false)},{key:"PageDown",run:/*@__PURE__*/moveCompletionSelection(true,"page")},{key:"PageUp",run:/*@__PURE__*/moveCompletionSelection(false,"page")},{key:"Enter",run:acceptCompletion}];const completionKeymapExt=/*@__PURE__*/Prec.highest(/*@__PURE__*/keymap.computeN([completionConfig],state=>state.facet(completionConfig).defaultKeymap?[completionKeymap]:[]));var variables=variables=>context=>{const options=variables.map(v=>({label:v.name,type:'variable',info:v.info,detail:v.detail}));// In most cases, use what is typed before the cursor
4450
+ let nodeBefore=syntaxTree(context.state).resolve(context.pos,-1);// For the special case of empty nodes, we need to check the current node
4451
+ // as well. The previous node could be part of another token, e.g.
4452
+ // when typing functions "abs(".
4453
+ let nextNode=nodeBefore.nextSibling;const isInEmptyNode=isNodeEmpty(nodeBefore)||nextNode&&nextNode.from===context.pos&&isNodeEmpty(nextNode);if(context.explicit&&isInEmptyNode){return {from:context.pos,options:options};}const result={from:nodeBefore.from,options:options};// Only auto-complete variables
4454
+ if(nodeBefore.name!=='VariableName'){return null;}return result;};// helpers ///////////////////////////////
4455
+ function isNodeEmpty(node){return node.from===node.to;}function autocompletion(context){return [autocompletion$1({override:[variables(context)]})];}// FIXME profile adding a per-Tree TreeNode cache, validating it by
4456
+ // parent pointer
4457
+ /// The default maximum length of a `TreeBuffer` node (1024).
4458
+ const DefaultBufferLength=1024;let nextPropID=0;class Range{constructor(from,to){this.from=from;this.to=to;}}/// Each [node type](#common.NodeType) or [individual tree](#common.Tree)
4459
+ /// can have metadata associated with it in props. Instances of this
4460
+ /// class represent prop names.
4461
+ class NodeProp{/// Create a new node prop type.
4462
+ constructor(config={}){this.id=nextPropID++;this.perNode=!!config.perNode;this.deserialize=config.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function");});}/// This is meant to be used with
4463
+ /// [`NodeSet.extend`](#common.NodeSet.extend) or
4464
+ /// [`LRParser.configure`](#lr.ParserConfig.props) to compute
4465
+ /// prop values for each node type in the set. Takes a [match
4466
+ /// object](#common.NodeType^match) or function that returns undefined
4467
+ /// if the node type doesn't get this prop, and the prop's value if
4468
+ /// it does.
4469
+ add(match){if(this.perNode)throw new RangeError("Can't add per-node props to node types");if(typeof match!="function")match=NodeType.match(match);return type=>{let result=match(type);return result===undefined?null:[this,result];};}}/// Prop that is used to describe matching delimiters. For opening
4470
+ /// delimiters, this holds an array of node names (written as a
4471
+ /// space-separated string when declaring this prop in a grammar)
4472
+ /// for the node types of closing delimiters that match it.
4473
+ NodeProp.closedBy=new NodeProp({deserialize:str=>str.split(" ")});/// The inverse of [`closedBy`](#common.NodeProp^closedBy). This is
4474
+ /// attached to closing delimiters, holding an array of node names
4475
+ /// of types of matching opening delimiters.
4476
+ NodeProp.openedBy=new NodeProp({deserialize:str=>str.split(" ")});/// Used to assign node types to groups (for example, all node
4477
+ /// types that represent an expression could be tagged with an
4478
+ /// `"Expression"` group).
4479
+ NodeProp.group=new NodeProp({deserialize:str=>str.split(" ")});/// The hash of the [context](#lr.ContextTracker.constructor)
4480
+ /// that the node was parsed in, if any. Used to limit reuse of
4481
+ /// contextual nodes.
4482
+ NodeProp.contextHash=new NodeProp({perNode:true});/// The distance beyond the end of the node that the tokenizer
4483
+ /// looked ahead for any of the tokens inside the node. (The LR
4484
+ /// parser only stores this when it is larger than 25, for
4485
+ /// efficiency reasons.)
4486
+ NodeProp.lookAhead=new NodeProp({perNode:true});/// This per-node prop is used to replace a given node, or part of a
4487
+ /// node, with another tree. This is useful to include trees from
4488
+ /// different languages.
4489
+ NodeProp.mounted=new NodeProp({perNode:true});const noProps=Object.create(null);/// Each node in a syntax tree has a node type associated with it.
4490
+ class NodeType{/// @internal
4491
+ constructor(/// The name of the node type. Not necessarily unique, but if the
4492
+ /// grammar was written properly, different node types with the
4493
+ /// same name within a node set should play the same semantic
4494
+ /// role.
4495
+ name,/// @internal
4496
+ props,/// The id of this node in its set. Corresponds to the term ids
4497
+ /// used in the parser.
4498
+ id,/// @internal
4499
+ flags=0){this.name=name;this.props=props;this.id=id;this.flags=flags;}static define(spec){let props=spec.props&&spec.props.length?Object.create(null):noProps;let flags=(spec.top?1/* Top */:0)|(spec.skipped?2/* Skipped */:0)|(spec.error?4/* Error */:0)|(spec.name==null?8/* Anonymous */:0);let type=new NodeType(spec.name||"",props,spec.id,flags);if(spec.props)for(let src of spec.props){if(!Array.isArray(src))src=src(type);if(src){if(src[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");props[src[0].id]=src[1];}}return type;}/// Retrieves a node prop for this type. Will return `undefined` if
4500
+ /// the prop isn't present on this node.
4501
+ prop(prop){return this.props[prop.id];}/// True when this is the top node of a grammar.
4502
+ get isTop(){return (this.flags&1/* Top */)>0;}/// True when this node is produced by a skip rule.
4503
+ get isSkipped(){return (this.flags&2/* Skipped */)>0;}/// Indicates whether this is an error node.
4504
+ get isError(){return (this.flags&4/* Error */)>0;}/// When true, this node type doesn't correspond to a user-declared
4505
+ /// named node, for example because it is used to cache repetition.
4506
+ get isAnonymous(){return (this.flags&8/* Anonymous */)>0;}/// Returns true when this node's name or one of its
4507
+ /// [groups](#common.NodeProp^group) matches the given string.
4508
+ is(name){if(typeof name=='string'){if(this.name==name)return true;let group=this.prop(NodeProp.group);return group?group.indexOf(name)>-1:false;}return this.id==name;}/// Create a function from node types to arbitrary values by
4509
+ /// specifying an object whose property names are node or
4510
+ /// [group](#common.NodeProp^group) names. Often useful with
4511
+ /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple
4512
+ /// names, separated by spaces, in a single property name to map
4513
+ /// multiple node names to a single value.
4514
+ static match(map){let direct=Object.create(null);for(let prop in map)for(let name of prop.split(" "))direct[name]=map[prop];return node=>{for(let groups=node.prop(NodeProp.group),i=-1;i<(groups?groups.length:0);i++){let found=direct[i<0?node.name:groups[i]];if(found)return found;}};}}/// An empty dummy node type to use when no actual type is available.
4515
+ NodeType.none=new NodeType("",Object.create(null),0,8/* Anonymous */);/// A node set holds a collection of node types. It is used to
4516
+ /// compactly represent trees by storing their type ids, rather than a
4517
+ /// full pointer to the type object, in a numeric array. Each parser
4518
+ /// [has](#lr.LRParser.nodeSet) a node set, and [tree
4519
+ /// buffers](#common.TreeBuffer) can only store collections of nodes
4520
+ /// from the same set. A set can have a maximum of 2**16 (65536) node
4521
+ /// types in it, so that the ids fit into 16-bit typed array slots.
4522
+ class NodeSet{/// Create a set with the given types. The `id` property of each
4523
+ /// type should correspond to its position within the array.
4524
+ constructor(/// The node types in this set, by id.
4525
+ types){this.types=types;for(let i=0;i<types.length;i++)if(types[i].id!=i)throw new RangeError("Node type ids should correspond to array positions when creating a node set");}/// Create a copy of this set with some node properties added. The
4526
+ /// arguments to this method should be created with
4527
+ /// [`NodeProp.add`](#common.NodeProp.add).
4528
+ extend(...props){let newTypes=[];for(let type of this.types){let newProps=null;for(let source of props){let add=source(type);if(add){if(!newProps)newProps=Object.assign({},type.props);newProps[add[0].id]=add[1];}}newTypes.push(newProps?new NodeType(type.name,newProps,type.id,type.flags):type);}return new NodeSet(newTypes);}}const CachedNode=new WeakMap(),CachedInnerNode=new WeakMap();/// Options that control iteration. Can be combined with the `|`
4529
+ /// operator to enable multiple ones.
4530
+ var IterMode;(function(IterMode){/// When enabled, iteration will only visit [`Tree`](#common.Tree)
4531
+ /// objects, not nodes packed into
4532
+ /// [`TreeBuffer`](#common.TreeBuffer)s.
4533
+ IterMode[IterMode["ExcludeBuffers"]=1]="ExcludeBuffers";/// Enable this to make iteration include anonymous nodes (such as
4534
+ /// the nodes that wrap repeated grammar constructs into a balanced
4535
+ /// tree).
4536
+ IterMode[IterMode["IncludeAnonymous"]=2]="IncludeAnonymous";/// By default, regular [mounted](#common.NodeProp^mounted) nodes
4537
+ /// replace their base node in iteration. Enable this to ignore them
4538
+ /// instead.
4539
+ IterMode[IterMode["IgnoreMounts"]=4]="IgnoreMounts";/// This option only applies in
4540
+ /// [`enter`](#common.SyntaxNode.enter)-style methods. It tells the
4541
+ /// library to not enter mounted overlays if one covers the given
4542
+ /// position.
4543
+ IterMode[IterMode["IgnoreOverlays"]=8]="IgnoreOverlays";})(IterMode||(IterMode={}));/// A piece of syntax tree. There are two ways to approach these
4544
+ /// trees: the way they are actually stored in memory, and the
4545
+ /// convenient way.
4546
+ ///
4547
+ /// Syntax trees are stored as a tree of `Tree` and `TreeBuffer`
4548
+ /// objects. By packing detail information into `TreeBuffer` leaf
4549
+ /// nodes, the representation is made a lot more memory-efficient.
4550
+ ///
4551
+ /// However, when you want to actually work with tree nodes, this
4552
+ /// representation is very awkward, so most client code will want to
4553
+ /// use the [`TreeCursor`](#common.TreeCursor) or
4554
+ /// [`SyntaxNode`](#common.SyntaxNode) interface instead, which provides
4555
+ /// a view on some part of this data structure, and can be used to
4556
+ /// move around to adjacent nodes.
4557
+ class Tree{/// Construct a new tree. See also [`Tree.build`](#common.Tree^build).
4558
+ constructor(/// The type of the top node.
4559
+ type,/// This node's child nodes.
4560
+ children,/// The positions (offsets relative to the start of this tree) of
4561
+ /// the children.
4562
+ positions,/// The total length of this tree
4563
+ length,/// Per-node [node props](#common.NodeProp) to associate with this node.
4564
+ props){this.type=type;this.children=children;this.positions=positions;this.length=length;/// @internal
4565
+ this.props=null;if(props&&props.length){this.props=Object.create(null);for(let[prop,value]of props)this.props[typeof prop=="number"?prop:prop.id]=value;}}/// @internal
4566
+ toString(){let mounted=this.prop(NodeProp.mounted);if(mounted&&!mounted.overlay)return mounted.tree.toString();let children="";for(let ch of this.children){let str=ch.toString();if(str){if(children)children+=",";children+=str;}}return !this.type.name?children:(/\W/.test(this.type.name)&&!this.type.isError?JSON.stringify(this.type.name):this.type.name)+(children.length?"("+children+")":"");}/// Get a [tree cursor](#common.TreeCursor) positioned at the top of
4567
+ /// the tree. Mode can be used to [control](#common.IterMode) which
4568
+ /// nodes the cursor visits.
4569
+ cursor(mode=0){return new TreeCursor(this.topNode,mode);}/// Get a [tree cursor](#common.TreeCursor) pointing into this tree
4570
+ /// at the given position and side (see
4571
+ /// [`moveTo`](#common.TreeCursor.moveTo).
4572
+ cursorAt(pos,side=0,mode=0){let scope=CachedNode.get(this)||this.topNode;let cursor=new TreeCursor(scope);cursor.moveTo(pos,side);CachedNode.set(this,cursor._tree);return cursor;}/// Get a [syntax node](#common.SyntaxNode) object for the top of the
4573
+ /// tree.
4574
+ get topNode(){return new TreeNode(this,0,0,null);}/// Get the [syntax node](#common.SyntaxNode) at the given position.
4575
+ /// If `side` is -1, this will move into nodes that end at the
4576
+ /// position. If 1, it'll move into nodes that start at the
4577
+ /// position. With 0, it'll only enter nodes that cover the position
4578
+ /// from both sides.
4579
+ resolve(pos,side=0){let node=resolveNode(CachedNode.get(this)||this.topNode,pos,side,false);CachedNode.set(this,node);return node;}/// Like [`resolve`](#common.Tree.resolve), but will enter
4580
+ /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
4581
+ /// pointing into the innermost overlaid tree at the given position
4582
+ /// (with parent links going through all parent structure, including
4583
+ /// the host trees).
4584
+ resolveInner(pos,side=0){let node=resolveNode(CachedInnerNode.get(this)||this.topNode,pos,side,true);CachedInnerNode.set(this,node);return node;}/// Iterate over the tree and its children, calling `enter` for any
4585
+ /// node that touches the `from`/`to` region (if given) before
4586
+ /// running over such a node's children, and `leave` (if given) when
4587
+ /// leaving the node. When `enter` returns `false`, that node will
4588
+ /// not have its children iterated over (or `leave` called).
4589
+ iterate(spec){let{enter,leave,from=0,to=this.length}=spec;for(let c=this.cursor((spec.mode||0)|IterMode.IncludeAnonymous);;){let entered=false;if(c.from<=to&&c.to>=from&&(c.type.isAnonymous||enter(c)!==false)){if(c.firstChild())continue;entered=true;}for(;;){if(entered&&leave&&!c.type.isAnonymous)leave(c);if(c.nextSibling())break;if(!c.parent())return;entered=true;}}}/// Get the value of the given [node prop](#common.NodeProp) for this
4590
+ /// node. Works with both per-node and per-type props.
4591
+ prop(prop){return !prop.perNode?this.type.prop(prop):this.props?this.props[prop.id]:undefined;}/// Returns the node's [per-node props](#common.NodeProp.perNode) in a
4592
+ /// format that can be passed to the [`Tree`](#common.Tree)
4593
+ /// constructor.
4594
+ get propValues(){let result=[];if(this.props)for(let id in this.props)result.push([+id,this.props[id]]);return result;}/// Balance the direct children of this tree, producing a copy of
4595
+ /// which may have children grouped into subtrees with type
4596
+ /// [`NodeType.none`](#common.NodeType^none).
4597
+ balance(config={}){return this.children.length<=8/* BranchFactor */?this:balanceRange(NodeType.none,this.children,this.positions,0,this.children.length,0,this.length,(children,positions,length)=>new Tree(this.type,children,positions,length,this.propValues),config.makeTree||((children,positions,length)=>new Tree(NodeType.none,children,positions,length)));}/// Build a tree from a postfix-ordered buffer of node information,
4598
+ /// or a cursor over such a buffer.
4599
+ static build(data){return buildTree(data);}}/// The empty tree
4600
+ Tree.empty=new Tree(NodeType.none,[],[],0);class FlatBufferCursor{constructor(buffer,index){this.buffer=buffer;this.index=index;}get id(){return this.buffer[this.index-4];}get start(){return this.buffer[this.index-3];}get end(){return this.buffer[this.index-2];}get size(){return this.buffer[this.index-1];}get pos(){return this.index;}next(){this.index-=4;}fork(){return new FlatBufferCursor(this.buffer,this.index);}}/// Tree buffers contain (type, start, end, endIndex) quads for each
4601
+ /// node. In such a buffer, nodes are stored in prefix order (parents
4602
+ /// before children, with the endIndex of the parent indicating which
4603
+ /// children belong to it)
4604
+ class TreeBuffer{/// Create a tree buffer.
4605
+ constructor(/// The buffer's content.
4606
+ buffer,/// The total length of the group of nodes in the buffer.
4607
+ length,/// The node set used in this buffer.
4608
+ set){this.buffer=buffer;this.length=length;this.set=set;}/// @internal
4609
+ get type(){return NodeType.none;}/// @internal
4610
+ toString(){let result=[];for(let index=0;index<this.buffer.length;){result.push(this.childString(index));index=this.buffer[index+3];}return result.join(",");}/// @internal
4611
+ childString(index){let id=this.buffer[index],endIndex=this.buffer[index+3];let type=this.set.types[id],result=type.name;if(/\W/.test(result)&&!type.isError)result=JSON.stringify(result);index+=4;if(endIndex==index)return result;let children=[];while(index<endIndex){children.push(this.childString(index));index=this.buffer[index+3];}return result+"("+children.join(",")+")";}/// @internal
4612
+ findChild(startIndex,endIndex,dir,pos,side){let{buffer}=this,pick=-1;for(let i=startIndex;i!=endIndex;i=buffer[i+3]){if(checkSide(side,pos,buffer[i+1],buffer[i+2])){pick=i;if(dir>0)break;}}return pick;}/// @internal
4613
+ slice(startI,endI,from,to){let b=this.buffer;let copy=new Uint16Array(endI-startI);for(let i=startI,j=0;i<endI;){copy[j++]=b[i++];copy[j++]=b[i++]-from;copy[j++]=b[i++]-from;copy[j++]=b[i++]-startI;}return new TreeBuffer(copy,to-from,this.set);}}function checkSide(side,pos,from,to){switch(side){case-2/* Before */:return from<pos;case-1/* AtOrBefore */:return to>=pos&&from<pos;case 0/* Around */:return from<pos&&to>pos;case 1/* AtOrAfter */:return from<=pos&&to>pos;case 2/* After */:return to>pos;case 4/* DontCare */:return true;}}function enterUnfinishedNodesBefore(node,pos){let scan=node.childBefore(pos);while(scan){let last=scan.lastChild;if(!last||last.to!=scan.to)break;if(last.type.isError&&last.from==last.to){node=scan;scan=last.prevSibling;}else {scan=last;}}return node;}function resolveNode(node,pos,side,overlays){var _a;// Move up to a node that actually holds the position, if possible
4614
+ while(node.from==node.to||(side<1?node.from>=pos:node.from>pos)||(side>-1?node.to<=pos:node.to<pos)){let parent=!overlays&&node instanceof TreeNode&&node.index<0?null:node.parent;if(!parent)return node;node=parent;}let mode=overlays?0:IterMode.IgnoreOverlays;// Must go up out of overlays when those do not overlap with pos
4615
+ if(overlays)for(let scan=node,parent=scan.parent;parent;scan=parent,parent=scan.parent){if(scan instanceof TreeNode&&scan.index<0&&((_a=parent.enter(pos,side,mode))===null||_a===void 0?void 0:_a.from)!=scan.from)node=parent;}for(;;){let inner=node.enter(pos,side,mode);if(!inner)return node;node=inner;}}class TreeNode{constructor(_tree,from,// Index in parent node, set to -1 if the node is not a direct child of _parent.node (overlay)
4616
+ index,_parent){this._tree=_tree;this.from=from;this.index=index;this._parent=_parent;}get type(){return this._tree.type;}get name(){return this._tree.type.name;}get to(){return this.from+this._tree.length;}nextChild(i,dir,pos,side,mode=0){for(let parent=this;;){for(let{children,positions}=parent._tree,e=dir>0?children.length:-1;i!=e;i+=dir){let next=children[i],start=positions[i]+parent.from;if(!checkSide(side,pos,start,start+next.length))continue;if(next instanceof TreeBuffer){if(mode&IterMode.ExcludeBuffers)continue;let index=next.findChild(0,next.buffer.length,dir,pos-start,side);if(index>-1)return new BufferNode(new BufferContext(parent,next,i,start),null,index);}else if(mode&IterMode.IncludeAnonymous||!next.type.isAnonymous||hasChild(next)){let mounted;if(!(mode&IterMode.IgnoreMounts)&&next.props&&(mounted=next.prop(NodeProp.mounted))&&!mounted.overlay)return new TreeNode(mounted.tree,start,i,parent);let inner=new TreeNode(next,start,i,parent);return mode&IterMode.IncludeAnonymous||!inner.type.isAnonymous?inner:inner.nextChild(dir<0?next.children.length-1:0,dir,pos,side);}}if(mode&IterMode.IncludeAnonymous||!parent.type.isAnonymous)return null;if(parent.index>=0)i=parent.index+dir;else i=dir<0?-1:parent._parent._tree.children.length;parent=parent._parent;if(!parent)return null;}}get firstChild(){return this.nextChild(0,1,0,4/* DontCare */);}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4/* DontCare */);}childAfter(pos){return this.nextChild(0,1,pos,2/* After */);}childBefore(pos){return this.nextChild(this._tree.children.length-1,-1,pos,-2/* Before */);}enter(pos,side,mode=0){let mounted;if(!(mode&IterMode.IgnoreOverlays)&&(mounted=this._tree.prop(NodeProp.mounted))&&mounted.overlay){let rPos=pos-this.from;for(let{from,to}of mounted.overlay){if((side>0?from<=rPos:from<rPos)&&(side<0?to>=rPos:to>rPos))return new TreeNode(mounted.tree,mounted.overlay[0].from+this.from,-1,this);}}return this.nextChild(0,1,pos,side,mode);}nextSignificantParent(){let val=this;while(val.type.isAnonymous&&val._parent)val=val._parent;return val;}get parent(){return this._parent?this._parent.nextSignificantParent():null;}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4/* DontCare */):null;}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4/* DontCare */):null;}cursor(mode=0){return new TreeCursor(this,mode);}get tree(){return this._tree;}toTree(){return this._tree;}resolve(pos,side=0){return resolveNode(this,pos,side,false);}resolveInner(pos,side=0){return resolveNode(this,pos,side,true);}enterUnfinishedNodesBefore(pos){return enterUnfinishedNodesBefore(this,pos);}getChild(type,before=null,after=null){let r=getChildren(this,type,before,after);return r.length?r[0]:null;}getChildren(type,before=null,after=null){return getChildren(this,type,before,after);}/// @internal
4617
+ toString(){return this._tree.toString();}get node(){return this;}matchContext(context){return matchNodeContext(this,context);}}function getChildren(node,type,before,after){let cur=node.cursor(),result=[];if(!cur.firstChild())return result;if(before!=null)while(!cur.type.is(before))if(!cur.nextSibling())return result;for(;;){if(after!=null&&cur.type.is(after))return result;if(cur.type.is(type))result.push(cur.node);if(!cur.nextSibling())return after==null?result:[];}}function matchNodeContext(node,context,i=context.length-1){for(let p=node.parent;i>=0;p=p.parent){if(!p)return false;if(!p.type.isAnonymous){if(context[i]&&context[i]!=p.name)return false;i--;}}return true;}class BufferContext{constructor(parent,buffer,index,start){this.parent=parent;this.buffer=buffer;this.index=index;this.start=start;}}class BufferNode{constructor(context,_parent,index){this.context=context;this._parent=_parent;this.index=index;this.type=context.buffer.set.types[context.buffer.buffer[index]];}get name(){return this.type.name;}get from(){return this.context.start+this.context.buffer.buffer[this.index+1];}get to(){return this.context.start+this.context.buffer.buffer[this.index+2];}child(dir,pos,side){let{buffer}=this.context;let index=buffer.findChild(this.index+4,buffer.buffer[this.index+3],dir,pos-this.context.start,side);return index<0?null:new BufferNode(this.context,this,index);}get firstChild(){return this.child(1,0,4/* DontCare */);}get lastChild(){return this.child(-1,0,4/* DontCare */);}childAfter(pos){return this.child(1,pos,2/* After */);}childBefore(pos){return this.child(-1,pos,-2/* Before */);}enter(pos,side,mode=0){if(mode&IterMode.ExcludeBuffers)return null;let{buffer}=this.context;let index=buffer.findChild(this.index+4,buffer.buffer[this.index+3],side>0?1:-1,pos-this.context.start,side);return index<0?null:new BufferNode(this.context,this,index);}get parent(){return this._parent||this.context.parent.nextSignificantParent();}externalSibling(dir){return this._parent?null:this.context.parent.nextChild(this.context.index+dir,dir,0,4/* DontCare */);}get nextSibling(){let{buffer}=this.context;let after=buffer.buffer[this.index+3];if(after<(this._parent?buffer.buffer[this._parent.index+3]:buffer.buffer.length))return new BufferNode(this.context,this._parent,after);return this.externalSibling(1);}get prevSibling(){let{buffer}=this.context;let parentStart=this._parent?this._parent.index+4:0;if(this.index==parentStart)return this.externalSibling(-1);return new BufferNode(this.context,this._parent,buffer.findChild(parentStart,this.index,-1,0,4/* DontCare */));}cursor(mode=0){return new TreeCursor(this,mode);}get tree(){return null;}toTree(){let children=[],positions=[];let{buffer}=this.context;let startI=this.index+4,endI=buffer.buffer[this.index+3];if(endI>startI){let from=buffer.buffer[this.index+1],to=buffer.buffer[this.index+2];children.push(buffer.slice(startI,endI,from,to));positions.push(0);}return new Tree(this.type,children,positions,this.to-this.from);}resolve(pos,side=0){return resolveNode(this,pos,side,false);}resolveInner(pos,side=0){return resolveNode(this,pos,side,true);}enterUnfinishedNodesBefore(pos){return enterUnfinishedNodesBefore(this,pos);}/// @internal
4618
+ toString(){return this.context.buffer.childString(this.index);}getChild(type,before=null,after=null){let r=getChildren(this,type,before,after);return r.length?r[0]:null;}getChildren(type,before=null,after=null){return getChildren(this,type,before,after);}get node(){return this;}matchContext(context){return matchNodeContext(this,context);}}/// A tree cursor object focuses on a given node in a syntax tree, and
4619
+ /// allows you to move to adjacent nodes.
4620
+ class TreeCursor{/// @internal
4621
+ constructor(node,/// @internal
4622
+ mode=0){this.mode=mode;/// @internal
4623
+ this.buffer=null;this.stack=[];/// @internal
4624
+ this.index=0;this.bufferNode=null;if(node instanceof TreeNode){this.yieldNode(node);}else {this._tree=node.context.parent;this.buffer=node.context;for(let n=node._parent;n;n=n._parent)this.stack.unshift(n.index);this.bufferNode=node;this.yieldBuf(node.index);}}/// Shorthand for `.type.name`.
4625
+ get name(){return this.type.name;}yieldNode(node){if(!node)return false;this._tree=node;this.type=node.type;this.from=node.from;this.to=node.to;return true;}yieldBuf(index,type){this.index=index;let{start,buffer}=this.buffer;this.type=type||buffer.set.types[buffer.buffer[index]];this.from=start+buffer.buffer[index+1];this.to=start+buffer.buffer[index+2];return true;}yield(node){if(!node)return false;if(node instanceof TreeNode){this.buffer=null;return this.yieldNode(node);}this.buffer=node.context;return this.yieldBuf(node.index,node.type);}/// @internal
4626
+ toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString();}/// @internal
4627
+ enterChild(dir,pos,side){if(!this.buffer)return this.yield(this._tree.nextChild(dir<0?this._tree._tree.children.length-1:0,dir,pos,side,this.mode));let{buffer}=this.buffer;let index=buffer.findChild(this.index+4,buffer.buffer[this.index+3],dir,pos-this.buffer.start,side);if(index<0)return false;this.stack.push(this.index);return this.yieldBuf(index);}/// Move the cursor to this node's first child. When this returns
4628
+ /// false, the node has no child, and the cursor has not been moved.
4629
+ firstChild(){return this.enterChild(1,0,4/* DontCare */);}/// Move the cursor to this node's last child.
4630
+ lastChild(){return this.enterChild(-1,0,4/* DontCare */);}/// Move the cursor to the first child that ends after `pos`.
4631
+ childAfter(pos){return this.enterChild(1,pos,2/* After */);}/// Move to the last child that starts before `pos`.
4632
+ childBefore(pos){return this.enterChild(-1,pos,-2/* Before */);}/// Move the cursor to the child around `pos`. If side is -1 the
4633
+ /// child may end at that position, when 1 it may start there. This
4634
+ /// will also enter [overlaid](#common.MountedTree.overlay)
4635
+ /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is
4636
+ /// set to false.
4637
+ enter(pos,side,mode=this.mode){if(!this.buffer)return this.yield(this._tree.enter(pos,side,mode));return mode&IterMode.ExcludeBuffers?false:this.enterChild(1,pos,side);}/// Move to the node's parent node, if this isn't the top node.
4638
+ parent(){if(!this.buffer)return this.yieldNode(this.mode&IterMode.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let parent=this.mode&IterMode.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();this.buffer=null;return this.yieldNode(parent);}/// @internal
4639
+ sibling(dir){if(!this.buffer)return !this._tree._parent?false:this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+dir,dir,0,4/* DontCare */,this.mode));let{buffer}=this.buffer,d=this.stack.length-1;if(dir<0){let parentStart=d<0?0:this.stack[d]+4;if(this.index!=parentStart)return this.yieldBuf(buffer.findChild(parentStart,this.index,-1,0,4/* DontCare */));}else {let after=buffer.buffer[this.index+3];if(after<(d<0?buffer.buffer.length:buffer.buffer[this.stack[d]+3]))return this.yieldBuf(after);}return d<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+dir,dir,0,4/* DontCare */,this.mode)):false;}/// Move to this node's next sibling, if any.
4640
+ nextSibling(){return this.sibling(1);}/// Move to this node's previous sibling, if any.
4641
+ prevSibling(){return this.sibling(-1);}atLastNode(dir){let index,parent,{buffer}=this;if(buffer){if(dir>0){if(this.index<buffer.buffer.buffer.length)return false;}else {for(let i=0;i<this.index;i++)if(buffer.buffer.buffer[i+3]<this.index)return false;}({index,parent}=buffer);}else {({index,_parent:parent}=this._tree);}for(;parent;({index,_parent:parent}=parent)){if(index>-1)for(let i=index+dir,e=dir<0?-1:parent._tree.children.length;i!=e;i+=dir){let child=parent._tree.children[i];if(this.mode&IterMode.IncludeAnonymous||child instanceof TreeBuffer||!child.type.isAnonymous||hasChild(child))return false;}}return true;}move(dir,enter){if(enter&&this.enterChild(dir,0,4/* DontCare */))return true;for(;;){if(this.sibling(dir))return true;if(this.atLastNode(dir)||!this.parent())return false;}}/// Move to the next node in a
4642
+ /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR))
4643
+ /// traversal, going from a node to its first child or, if the
4644
+ /// current node is empty or `enter` is false, its next sibling or
4645
+ /// the next sibling of the first parent node that has one.
4646
+ next(enter=true){return this.move(1,enter);}/// Move to the next node in a last-to-first pre-order traveral. A
4647
+ /// node is followed by its last child or, if it has none, its
4648
+ /// previous sibling or the previous sibling of the first parent
4649
+ /// node that has one.
4650
+ prev(enter=true){return this.move(-1,enter);}/// Move the cursor to the innermost node that covers `pos`. If
4651
+ /// `side` is -1, it will enter nodes that end at `pos`. If it is 1,
4652
+ /// it will enter nodes that start at `pos`.
4653
+ moveTo(pos,side=0){// Move up to a node that actually holds the position, if possible
4654
+ while(this.from==this.to||(side<1?this.from>=pos:this.from>pos)||(side>-1?this.to<=pos:this.to<pos))if(!this.parent())break;// Then scan down into child nodes as far as possible
4655
+ while(this.enterChild(1,pos,side)){}return this;}/// Get a [syntax node](#common.SyntaxNode) at the cursor's current
4656
+ /// position.
4657
+ get node(){if(!this.buffer)return this._tree;let cache=this.bufferNode,result=null,depth=0;if(cache&&cache.context==this.buffer){scan:for(let index=this.index,d=this.stack.length;d>=0;){for(let c=cache;c;c=c._parent)if(c.index==index){if(index==this.index)return c;result=c;depth=d+1;break scan;}index=this.stack[--d];}}for(let i=depth;i<this.stack.length;i++)result=new BufferNode(this.buffer,result,this.stack[i]);return this.bufferNode=new BufferNode(this.buffer,result,this.index);}/// Get the [tree](#common.Tree) that represents the current node, if
4658
+ /// any. Will return null when the node is in a [tree
4659
+ /// buffer](#common.TreeBuffer).
4660
+ get tree(){return this.buffer?null:this._tree._tree;}/// Iterate over the current node and all its descendants, calling
4661
+ /// `enter` when entering a node and `leave`, if given, when leaving
4662
+ /// one. When `enter` returns `false`, any children of that node are
4663
+ /// skipped, and `leave` isn't called for it.
4664
+ iterate(enter,leave){for(let depth=0;;){let mustLeave=false;if(this.type.isAnonymous||enter(this)!==false){if(this.firstChild()){depth++;continue;}if(!this.type.isAnonymous)mustLeave=true;}for(;;){if(mustLeave&&leave)leave(this);mustLeave=this.type.isAnonymous;if(this.nextSibling())break;if(!depth)return;this.parent();depth--;mustLeave=true;}}}/// Test whether the current node matches a given context—a sequence
4665
+ /// of direct parent node names. Empty strings in the context array
4666
+ /// are treated as wildcards.
4667
+ matchContext(context){if(!this.buffer)return matchNodeContext(this.node,context);let{buffer}=this.buffer,{types}=buffer.set;for(let i=context.length-1,d=this.stack.length-1;i>=0;d--){if(d<0)return matchNodeContext(this.node,context,i);let type=types[buffer.buffer[this.stack[d]]];if(!type.isAnonymous){if(context[i]&&context[i]!=type.name)return false;i--;}}return true;}}function hasChild(tree){return tree.children.some(ch=>ch instanceof TreeBuffer||!ch.type.isAnonymous||hasChild(ch));}function buildTree(data){var _a;let{buffer,nodeSet,maxBufferLength=DefaultBufferLength,reused=[],minRepeatType=nodeSet.types.length}=data;let cursor=Array.isArray(buffer)?new FlatBufferCursor(buffer,buffer.length):buffer;let types=nodeSet.types;let contextHash=0,lookAhead=0;function takeNode(parentStart,minPos,children,positions,inRepeat){let{id,start,end,size}=cursor;let lookAheadAtStart=lookAhead;while(size<0){cursor.next();if(size==-1/* Reuse */){let node=reused[id];children.push(node);positions.push(start-parentStart);return;}else if(size==-3/* ContextChange */){// Context change
4668
+ contextHash=id;return;}else if(size==-4/* LookAhead */){lookAhead=id;return;}else {throw new RangeError(`Unrecognized record size: ${size}`);}}let type=types[id],node,buffer;let startPos=start-parentStart;if(end-start<=maxBufferLength&&(buffer=findBufferSize(cursor.pos-minPos,inRepeat))){// Small enough for a buffer, and no reused nodes inside
4669
+ let data=new Uint16Array(buffer.size-buffer.skip);let endPos=cursor.pos-buffer.size,index=data.length;while(cursor.pos>endPos)index=copyToBuffer(buffer.start,data,index);node=new TreeBuffer(data,end-buffer.start,nodeSet);startPos=buffer.start-parentStart;}else {// Make it a node
4670
+ let endPos=cursor.pos-size;cursor.next();let localChildren=[],localPositions=[];let localInRepeat=id>=minRepeatType?id:-1;let lastGroup=0,lastEnd=end;while(cursor.pos>endPos){if(localInRepeat>=0&&cursor.id==localInRepeat&&cursor.size>=0){if(cursor.end<=lastEnd-maxBufferLength){makeRepeatLeaf(localChildren,localPositions,start,lastGroup,cursor.end,lastEnd,localInRepeat,lookAheadAtStart);lastGroup=localChildren.length;lastEnd=cursor.end;}cursor.next();}else {takeNode(start,endPos,localChildren,localPositions,localInRepeat);}}if(localInRepeat>=0&&lastGroup>0&&lastGroup<localChildren.length)makeRepeatLeaf(localChildren,localPositions,start,lastGroup,start,lastEnd,localInRepeat,lookAheadAtStart);localChildren.reverse();localPositions.reverse();if(localInRepeat>-1&&lastGroup>0){let make=makeBalanced(type);node=balanceRange(type,localChildren,localPositions,0,localChildren.length,0,end-start,make,make);}else {node=makeTree(type,localChildren,localPositions,end-start,lookAheadAtStart-end);}}children.push(node);positions.push(startPos);}function makeBalanced(type){return (children,positions,length)=>{let lookAhead=0,lastI=children.length-1,last,lookAheadProp;if(lastI>=0&&(last=children[lastI])instanceof Tree){if(!lastI&&last.type==type&&last.length==length)return last;if(lookAheadProp=last.prop(NodeProp.lookAhead))lookAhead=positions[lastI]+last.length+lookAheadProp;}return makeTree(type,children,positions,length,lookAhead);};}function makeRepeatLeaf(children,positions,base,i,from,to,type,lookAhead){let localChildren=[],localPositions=[];while(children.length>i){localChildren.push(children.pop());localPositions.push(positions.pop()+base-from);}children.push(makeTree(nodeSet.types[type],localChildren,localPositions,to-from,lookAhead-to));positions.push(from-base);}function makeTree(type,children,positions,length,lookAhead=0,props){if(contextHash){let pair=[NodeProp.contextHash,contextHash];props=props?[pair].concat(props):[pair];}if(lookAhead>25){let pair=[NodeProp.lookAhead,lookAhead];props=props?[pair].concat(props):[pair];}return new Tree(type,children,positions,length,props);}function findBufferSize(maxSize,inRepeat){// Scan through the buffer to find previous siblings that fit
4671
+ // together in a TreeBuffer, and don't contain any reused nodes
4672
+ // (which can't be stored in a buffer).
4673
+ // If `inRepeat` is > -1, ignore node boundaries of that type for
4674
+ // nesting, but make sure the end falls either at the start
4675
+ // (`maxSize`) or before such a node.
4676
+ let fork=cursor.fork();let size=0,start=0,skip=0,minStart=fork.end-maxBufferLength;let result={size:0,start:0,skip:0};scan:for(let minPos=fork.pos-maxSize;fork.pos>minPos;){let nodeSize=fork.size;// Pretend nested repeat nodes of the same type don't exist
4677
+ if(fork.id==inRepeat&&nodeSize>=0){// Except that we store the current state as a valid return
4678
+ // value.
4679
+ result.size=size;result.start=start;result.skip=skip;skip+=4;size+=4;fork.next();continue;}let startPos=fork.pos-nodeSize;if(nodeSize<0||startPos<minPos||fork.start<minStart)break;let localSkipped=fork.id>=minRepeatType?4:0;let nodeStart=fork.start;fork.next();while(fork.pos>startPos){if(fork.size<0){if(fork.size==-3/* ContextChange */)localSkipped+=4;else break scan;}else if(fork.id>=minRepeatType){localSkipped+=4;}fork.next();}start=nodeStart;size+=nodeSize;skip+=localSkipped;}if(inRepeat<0||size==maxSize){result.size=size;result.start=start;result.skip=skip;}return result.size>4?result:undefined;}function copyToBuffer(bufferStart,buffer,index){let{id,start,end,size}=cursor;cursor.next();if(size>=0&&id<minRepeatType){let startIndex=index;if(size>4){let endPos=cursor.pos-(size-4);while(cursor.pos>endPos)index=copyToBuffer(bufferStart,buffer,index);}buffer[--index]=startIndex;buffer[--index]=end-bufferStart;buffer[--index]=start-bufferStart;buffer[--index]=id;}else if(size==-3/* ContextChange */){contextHash=id;}else if(size==-4/* LookAhead */){lookAhead=id;}return index;}let children=[],positions=[];while(cursor.pos>0)takeNode(data.start||0,data.bufferStart||0,children,positions,-1);let length=(_a=data.length)!==null&&_a!==void 0?_a:children.length?positions[0]+children[0].length:0;return new Tree(types[data.topID],children.reverse(),positions.reverse(),length);}const nodeSizeCache=new WeakMap();function nodeSize(balanceType,node){if(!balanceType.isAnonymous||node instanceof TreeBuffer||node.type!=balanceType)return 1;let size=nodeSizeCache.get(node);if(size==null){size=1;for(let child of node.children){if(child.type!=balanceType||!(child instanceof Tree)){size=1;break;}size+=nodeSize(balanceType,child);}nodeSizeCache.set(node,size);}return size;}function balanceRange(// The type the balanced tree's inner nodes.
4680
+ balanceType,// The direct children and their positions
4681
+ children,positions,// The index range in children/positions to use
4682
+ from,to,// The start position of the nodes, relative to their parent.
4683
+ start,// Length of the outer node
4684
+ length,// Function to build the top node of the balanced tree
4685
+ mkTop,// Function to build internal nodes for the balanced tree
4686
+ mkTree){let total=0;for(let i=from;i<to;i++)total+=nodeSize(balanceType,children[i]);let maxChild=Math.ceil(total*1.5/8/* BranchFactor */);let localChildren=[],localPositions=[];function divide(children,positions,from,to,offset){for(let i=from;i<to;){let groupFrom=i,groupStart=positions[i],groupSize=nodeSize(balanceType,children[i]);i++;for(;i<to;i++){let nextSize=nodeSize(balanceType,children[i]);if(groupSize+nextSize>=maxChild)break;groupSize+=nextSize;}if(i==groupFrom+1){if(groupSize>maxChild){let only=children[groupFrom];// Only trees can have a size > 1
4687
+ divide(only.children,only.positions,0,only.children.length,positions[groupFrom]+offset);continue;}localChildren.push(children[groupFrom]);}else {let length=positions[i-1]+children[i-1].length-groupStart;localChildren.push(balanceRange(balanceType,children,positions,groupFrom,i,groupStart,length,null,mkTree));}localPositions.push(groupStart+offset-start);}}divide(children,positions,from,to,0);return (mkTop||mkTree)(localChildren,localPositions,length);}/// A superclass that parsers should extend.
4688
+ class Parser{/// Start a parse, returning a [partial parse](#common.PartialParse)
4689
+ /// object. [`fragments`](#common.TreeFragment) can be passed in to
4690
+ /// make the parse incremental.
4691
+ ///
4692
+ /// By default, the entire input is parsed. You can pass `ranges`,
4693
+ /// which should be a sorted array of non-empty, non-overlapping
4694
+ /// ranges, to parse only those ranges. The tree returned in that
4695
+ /// case will start at `ranges[0].from`.
4696
+ startParse(input,fragments,ranges){if(typeof input=="string")input=new StringInput(input);ranges=!ranges?[new Range(0,input.length)]:ranges.length?ranges.map(r=>new Range(r.from,r.to)):[new Range(0,0)];return this.createParse(input,fragments||[],ranges);}/// Run a full parse, returning the resulting tree.
4697
+ parse(input,fragments,ranges){let parse=this.startParse(input,fragments,ranges);for(;;){let done=parse.advance();if(done)return done;}}}class StringInput{constructor(string){this.string=string;}get length(){return this.string.length;}chunk(from){return this.string.slice(from);}get lineChunks(){return false;}read(from,to){return this.string.slice(from,to);}}new NodeProp({perNode:true});/// A parse stack. These are used internally by the parser to track
4698
+ /// parsing progress. They also provide some properties and methods
4699
+ /// that external code such as a tokenizer can use to get information
4700
+ /// about the parse state.
4701
+ class Stack{/// @internal
4702
+ constructor(/// The parse that this stack is part of @internal
4703
+ p,/// Holds state, input pos, buffer index triplets for all but the
4704
+ /// top state @internal
4705
+ stack,/// The current parse state @internal
4706
+ state,// The position at which the next reduce should take place. This
4707
+ // can be less than `this.pos` when skipped expressions have been
4708
+ // added to the stack (which should be moved outside of the next
4709
+ // reduction)
4710
+ /// @internal
4711
+ reducePos,/// The input position up to which this stack has parsed.
4712
+ pos,/// The dynamic score of the stack, including dynamic precedence
4713
+ /// and error-recovery penalties
4714
+ /// @internal
4715
+ score,// The output buffer. Holds (type, start, end, size) quads
4716
+ // representing nodes created by the parser, where `size` is
4717
+ // amount of buffer array entries covered by this node.
4718
+ /// @internal
4719
+ buffer,// The base offset of the buffer. When stacks are split, the split
4720
+ // instance shared the buffer history with its parent up to
4721
+ // `bufferBase`, which is the absolute offset (including the
4722
+ // offset of previous splits) into the buffer at which this stack
4723
+ // starts writing.
4724
+ /// @internal
4725
+ bufferBase,/// @internal
4726
+ curContext,/// @internal
4727
+ lookAhead=0,// A parent stack from which this was split off, if any. This is
4728
+ // set up so that it always points to a stack that has some
4729
+ // additional buffer content, never to a stack with an equal
4730
+ // `bufferBase`.
4731
+ /// @internal
4732
+ parent){this.p=p;this.stack=stack;this.state=state;this.reducePos=reducePos;this.pos=pos;this.score=score;this.buffer=buffer;this.bufferBase=bufferBase;this.curContext=curContext;this.lookAhead=lookAhead;this.parent=parent;}/// @internal
4733
+ toString(){return `[${this.stack.filter((_,i)=>i%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`;}// Start an empty stack
4734
+ /// @internal
4735
+ static start(p,state,pos=0){let cx=p.parser.context;return new Stack(p,[],state,pos,pos,0,[],0,cx?new StackContext(cx,cx.start):null,0,null);}/// The stack's current [context](#lr.ContextTracker) value, if
4736
+ /// any. Its type will depend on the context tracker's type
4737
+ /// parameter, or it will be `null` if there is no context
4738
+ /// tracker.
4739
+ get context(){return this.curContext?this.curContext.context:null;}// Push a state onto the stack, tracking its start position as well
4740
+ // as the buffer base at that point.
4741
+ /// @internal
4742
+ pushState(state,start){this.stack.push(this.state,start,this.bufferBase+this.buffer.length);this.state=state;}// Apply a reduce action
4743
+ /// @internal
4744
+ reduce(action){let depth=action>>19/* ReduceDepthShift */,type=action&65535/* ValueMask */;let{parser}=this.p;let dPrec=parser.dynamicPrecedence(type);if(dPrec)this.score+=dPrec;if(depth==0){this.pushState(parser.getGoto(this.state,type,true),this.reducePos);// Zero-depth reductions are a special case—they add stuff to
4745
+ // the stack without popping anything off.
4746
+ if(type<parser.minRepeatTerm)this.storeNode(type,this.reducePos,this.reducePos,4,true);this.reduceContext(type,this.reducePos);return;}// Find the base index into `this.stack`, content after which will
4747
+ // be dropped. Note that with `StayFlag` reductions we need to
4748
+ // consume two extra frames (the dummy parent node for the skipped
4749
+ // expression and the state that we'll be staying in, which should
4750
+ // be moved to `this.state`).
4751
+ let base=this.stack.length-(depth-1)*3-(action&262144/* StayFlag */?6:0);let start=this.stack[base-2];let bufferBase=this.stack[base-1],count=this.bufferBase+this.buffer.length-bufferBase;// Store normal terms or `R -> R R` repeat reductions
4752
+ if(type<parser.minRepeatTerm||action&131072/* RepeatFlag */){let pos=parser.stateFlag(this.state,1/* Skipped */)?this.pos:this.reducePos;this.storeNode(type,start,pos,count+4,true);}if(action&262144/* StayFlag */){this.state=this.stack[base];}else {let baseStateID=this.stack[base-3];this.state=parser.getGoto(baseStateID,type,true);}while(this.stack.length>base)this.stack.pop();this.reduceContext(type,start);}// Shift a value into the buffer
4753
+ /// @internal
4754
+ storeNode(term,start,end,size=4,isReduce=false){if(term==0/* Err */&&(!this.stack.length||this.stack[this.stack.length-1]<this.buffer.length+this.bufferBase)){// Try to omit/merge adjacent error nodes
4755
+ let cur=this,top=this.buffer.length;if(top==0&&cur.parent){top=cur.bufferBase-cur.parent.bufferBase;cur=cur.parent;}if(top>0&&cur.buffer[top-4]==0/* Err */&&cur.buffer[top-1]>-1){if(start==end)return;if(cur.buffer[top-2]>=start){cur.buffer[top-2]=end;return;}}}if(!isReduce||this.pos==end){// Simple case, just append
4756
+ this.buffer.push(term,start,end,size);}else {// There may be skipped nodes that have to be moved forward
4757
+ let index=this.buffer.length;if(index>0&&this.buffer[index-4]!=0/* Err */)while(index>0&&this.buffer[index-2]>end){// Move this record forward
4758
+ this.buffer[index]=this.buffer[index-4];this.buffer[index+1]=this.buffer[index-3];this.buffer[index+2]=this.buffer[index-2];this.buffer[index+3]=this.buffer[index-1];index-=4;if(size>4)size-=4;}this.buffer[index]=term;this.buffer[index+1]=start;this.buffer[index+2]=end;this.buffer[index+3]=size;}}// Apply a shift action
4759
+ /// @internal
4760
+ shift(action,next,nextEnd){let start=this.pos;if(action&131072/* GotoFlag */){this.pushState(action&65535/* ValueMask */,this.pos);}else if((action&262144/* StayFlag */)==0){// Regular shift
4761
+ let nextState=action,{parser}=this.p;if(nextEnd>this.pos||next<=parser.maxNode){this.pos=nextEnd;if(!parser.stateFlag(nextState,1/* Skipped */))this.reducePos=nextEnd;}this.pushState(nextState,start);this.shiftContext(next,start);if(next<=parser.maxNode)this.buffer.push(next,start,nextEnd,4);}else {// Shift-and-stay, which means this is a skipped token
4762
+ this.pos=nextEnd;this.shiftContext(next,start);if(next<=this.p.parser.maxNode)this.buffer.push(next,start,nextEnd,4);}}// Apply an action
4763
+ /// @internal
4764
+ apply(action,next,nextEnd){if(action&65536/* ReduceFlag */)this.reduce(action);else this.shift(action,next,nextEnd);}// Add a prebuilt (reused) node into the buffer.
4765
+ /// @internal
4766
+ useNode(value,next){let index=this.p.reused.length-1;if(index<0||this.p.reused[index]!=value){this.p.reused.push(value);index++;}let start=this.pos;this.reducePos=this.pos=start+value.length;this.pushState(next,start);this.buffer.push(index,start,this.reducePos,-1/* size == -1 means this is a reused value */);if(this.curContext)this.updateContext(this.curContext.tracker.reuse(this.curContext.context,value,this,this.p.stream.reset(this.pos-value.length)));}// Split the stack. Due to the buffer sharing and the fact
4767
+ // that `this.stack` tends to stay quite shallow, this isn't very
4768
+ // expensive.
4769
+ /// @internal
4770
+ split(){let parent=this;let off=parent.buffer.length;// Because the top of the buffer (after this.pos) may be mutated
4771
+ // to reorder reductions and skipped tokens, and shared buffers
4772
+ // should be immutable, this copies any outstanding skipped tokens
4773
+ // to the new buffer, and puts the base pointer before them.
4774
+ while(off>0&&parent.buffer[off-2]>parent.reducePos)off-=4;let buffer=parent.buffer.slice(off),base=parent.bufferBase+off;// Make sure parent points to an actual parent with content, if there is such a parent.
4775
+ while(parent&&base==parent.bufferBase)parent=parent.parent;return new Stack(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,buffer,base,this.curContext,this.lookAhead,parent);}// Try to recover from an error by 'deleting' (ignoring) one token.
4776
+ /// @internal
4777
+ recoverByDelete(next,nextEnd){let isNode=next<=this.p.parser.maxNode;if(isNode)this.storeNode(next,this.pos,nextEnd,4);this.storeNode(0/* Err */,this.pos,nextEnd,isNode?8:4);this.pos=this.reducePos=nextEnd;this.score-=190/* Delete */;}/// Check if the given term would be able to be shifted (optionally
4778
+ /// after some reductions) on this stack. This can be useful for
4779
+ /// external tokenizers that want to make sure they only provide a
4780
+ /// given token when it applies.
4781
+ canShift(term){for(let sim=new SimulatedStack(this);;){let action=this.p.parser.stateSlot(sim.state,4/* DefaultReduce */)||this.p.parser.hasAction(sim.state,term);if((action&65536/* ReduceFlag */)==0)return true;if(action==0)return false;sim.reduce(action);}}// Apply up to Recover.MaxNext recovery actions that conceptually
4782
+ // inserts some missing token or rule.
4783
+ /// @internal
4784
+ recoverByInsert(next){if(this.stack.length>=300/* MaxInsertStackDepth */)return [];let nextStates=this.p.parser.nextStates(this.state);if(nextStates.length>4/* MaxNext */<<1||this.stack.length>=120/* DampenInsertStackDepth */){let best=[];for(let i=0,s;i<nextStates.length;i+=2){if((s=nextStates[i+1])!=this.state&&this.p.parser.hasAction(s,next))best.push(nextStates[i],s);}if(this.stack.length<120/* DampenInsertStackDepth */)for(let i=0;best.length<4/* MaxNext */<<1&&i<nextStates.length;i+=2){let s=nextStates[i+1];if(!best.some((v,i)=>i&1&&v==s))best.push(nextStates[i],s);}nextStates=best;}let result=[];for(let i=0;i<nextStates.length&&result.length<4/* MaxNext */;i+=2){let s=nextStates[i+1];if(s==this.state)continue;let stack=this.split();stack.pushState(s,this.pos);stack.storeNode(0/* Err */,stack.pos,stack.pos,4,true);stack.shiftContext(nextStates[i],this.pos);stack.score-=200/* Insert */;result.push(stack);}return result;}// Force a reduce, if possible. Return false if that can't
4785
+ // be done.
4786
+ /// @internal
4787
+ forceReduce(){let reduce=this.p.parser.stateSlot(this.state,5/* ForcedReduce */);if((reduce&65536/* ReduceFlag */)==0)return false;let{parser}=this.p;if(!parser.validAction(this.state,reduce)){let depth=reduce>>19/* ReduceDepthShift */,term=reduce&65535/* ValueMask */;let target=this.stack.length-depth*3;if(target<0||parser.getGoto(this.stack[target],term,false)<0)return false;this.storeNode(0/* Err */,this.reducePos,this.reducePos,4,true);this.score-=100/* Reduce */;}this.reducePos=this.pos;this.reduce(reduce);return true;}/// @internal
4788
+ forceAll(){while(!this.p.parser.stateFlag(this.state,2/* Accepting */)){if(!this.forceReduce()){this.storeNode(0/* Err */,this.pos,this.pos,4,true);break;}}return this;}/// Check whether this state has no further actions (assumed to be a direct descendant of the
4789
+ /// top state, since any other states must be able to continue
4790
+ /// somehow). @internal
4791
+ get deadEnd(){if(this.stack.length!=3)return false;let{parser}=this.p;return parser.data[parser.stateSlot(this.state,1/* Actions */)]==65535/* End */&&!parser.stateSlot(this.state,4/* DefaultReduce */);}/// Restart the stack (put it back in its start state). Only safe
4792
+ /// when this.stack.length == 3 (state is directly below the top
4793
+ /// state). @internal
4794
+ restart(){this.state=this.stack[0];this.stack.length=0;}/// @internal
4795
+ sameState(other){if(this.state!=other.state||this.stack.length!=other.stack.length)return false;for(let i=0;i<this.stack.length;i+=3)if(this.stack[i]!=other.stack[i])return false;return true;}/// Get the parser used by this stack.
4796
+ get parser(){return this.p.parser;}/// Test whether a given dialect (by numeric ID, as exported from
4797
+ /// the terms file) is enabled.
4798
+ dialectEnabled(dialectID){return this.p.parser.dialect.flags[dialectID];}shiftContext(term,start){if(this.curContext)this.updateContext(this.curContext.tracker.shift(this.curContext.context,term,this,this.p.stream.reset(start)));}reduceContext(term,start){if(this.curContext)this.updateContext(this.curContext.tracker.reduce(this.curContext.context,term,this,this.p.stream.reset(start)));}/// @internal
4799
+ emitContext(){let last=this.buffer.length-1;if(last<0||this.buffer[last]!=-3)this.buffer.push(this.curContext.hash,this.reducePos,this.reducePos,-3);}/// @internal
4800
+ emitLookAhead(){let last=this.buffer.length-1;if(last<0||this.buffer[last]!=-4)this.buffer.push(this.lookAhead,this.reducePos,this.reducePos,-4);}updateContext(context){if(context!=this.curContext.context){let newCx=new StackContext(this.curContext.tracker,context);if(newCx.hash!=this.curContext.hash)this.emitContext();this.curContext=newCx;}}/// @internal
4801
+ setLookAhead(lookAhead){if(lookAhead>this.lookAhead){this.emitLookAhead();this.lookAhead=lookAhead;}}/// @internal
4802
+ close(){if(this.curContext&&this.curContext.tracker.strict)this.emitContext();if(this.lookAhead>0)this.emitLookAhead();}}class StackContext{constructor(tracker,context){this.tracker=tracker;this.context=context;this.hash=tracker.strict?tracker.hash(context):0;}}var Recover;(function(Recover){Recover[Recover["Insert"]=200]="Insert";Recover[Recover["Delete"]=190]="Delete";Recover[Recover["Reduce"]=100]="Reduce";Recover[Recover["MaxNext"]=4]="MaxNext";Recover[Recover["MaxInsertStackDepth"]=300]="MaxInsertStackDepth";Recover[Recover["DampenInsertStackDepth"]=120]="DampenInsertStackDepth";})(Recover||(Recover={}));// Used to cheaply run some reductions to scan ahead without mutating
4803
+ // an entire stack
4804
+ class SimulatedStack{constructor(start){this.start=start;this.state=start.state;this.stack=start.stack;this.base=this.stack.length;}reduce(action){let term=action&65535/* ValueMask */,depth=action>>19/* ReduceDepthShift */;if(depth==0){if(this.stack==this.start.stack)this.stack=this.stack.slice();this.stack.push(this.state,0,0);this.base+=3;}else {this.base-=(depth-1)*3;}let goto=this.start.p.parser.getGoto(this.stack[this.base-3],term,true);this.state=goto;}}// This is given to `Tree.build` to build a buffer, and encapsulates
4805
+ // the parent-stack-walking necessary to read the nodes.
4806
+ class StackBufferCursor{constructor(stack,pos,index){this.stack=stack;this.pos=pos;this.index=index;this.buffer=stack.buffer;if(this.index==0)this.maybeNext();}static create(stack,pos=stack.bufferBase+stack.buffer.length){return new StackBufferCursor(stack,pos,pos-stack.bufferBase);}maybeNext(){let next=this.stack.parent;if(next!=null){this.index=this.stack.bufferBase-next.bufferBase;this.stack=next;this.buffer=next.buffer;}}get id(){return this.buffer[this.index-4];}get start(){return this.buffer[this.index-3];}get end(){return this.buffer[this.index-2];}get size(){return this.buffer[this.index-1];}next(){this.index-=4;this.pos-=4;if(this.index==0)this.maybeNext();}fork(){return new StackBufferCursor(this.stack,this.pos,this.index);}}class CachedToken{constructor(){this.start=-1;this.value=-1;this.end=-1;this.extended=-1;this.lookAhead=0;this.mask=0;this.context=0;}}const nullToken=new CachedToken();/// [Tokenizers](#lr.ExternalTokenizer) interact with the input
4807
+ /// through this interface. It presents the input as a stream of
4808
+ /// characters, tracking lookahead and hiding the complexity of
4809
+ /// [ranges](#common.Parser.parse^ranges) from tokenizer code.
4810
+ class InputStream{/// @internal
4811
+ constructor(/// @internal
4812
+ input,/// @internal
4813
+ ranges){this.input=input;this.ranges=ranges;/// @internal
4814
+ this.chunk="";/// @internal
4815
+ this.chunkOff=0;/// Backup chunk
4816
+ this.chunk2="";this.chunk2Pos=0;/// The character code of the next code unit in the input, or -1
4817
+ /// when the stream is at the end of the input.
4818
+ this.next=-1;/// @internal
4819
+ this.token=nullToken;this.rangeIndex=0;this.pos=this.chunkPos=ranges[0].from;this.range=ranges[0];this.end=ranges[ranges.length-1].to;this.readNext();}resolveOffset(offset,assoc){let range=this.range,index=this.rangeIndex;let pos=this.pos+offset;while(pos<range.from){if(!index)return null;let next=this.ranges[--index];pos-=range.from-next.to;range=next;}while(assoc<0?pos>range.to:pos>=range.to){if(index==this.ranges.length-1)return null;let next=this.ranges[++index];pos+=next.from-range.to;range=next;}return pos;}/// Look at a code unit near the stream position. `.peek(0)` equals
4820
+ /// `.next`, `.peek(-1)` gives you the previous character, and so
4821
+ /// on.
4822
+ ///
4823
+ /// Note that looking around during tokenizing creates dependencies
4824
+ /// on potentially far-away content, which may reduce the
4825
+ /// effectiveness incremental parsing—when looking forward—or even
4826
+ /// cause invalid reparses when looking backward more than 25 code
4827
+ /// units, since the library does not track lookbehind.
4828
+ peek(offset){let idx=this.chunkOff+offset,pos,result;if(idx>=0&&idx<this.chunk.length){pos=this.pos+offset;result=this.chunk.charCodeAt(idx);}else {let resolved=this.resolveOffset(offset,1);if(resolved==null)return -1;pos=resolved;if(pos>=this.chunk2Pos&&pos<this.chunk2Pos+this.chunk2.length){result=this.chunk2.charCodeAt(pos-this.chunk2Pos);}else {let i=this.rangeIndex,range=this.range;while(range.to<=pos)range=this.ranges[++i];this.chunk2=this.input.chunk(this.chunk2Pos=pos);if(pos+this.chunk2.length>range.to)this.chunk2=this.chunk2.slice(0,range.to-pos);result=this.chunk2.charCodeAt(0);}}if(pos>=this.token.lookAhead)this.token.lookAhead=pos+1;return result;}/// Accept a token. By default, the end of the token is set to the
4829
+ /// current stream position, but you can pass an offset (relative to
4830
+ /// the stream position) to change that.
4831
+ acceptToken(token,endOffset=0){let end=endOffset?this.resolveOffset(endOffset,-1):this.pos;if(end==null||end<this.token.start)throw new RangeError("Token end out of bounds");this.token.value=token;this.token.end=end;}getChunk(){if(this.pos>=this.chunk2Pos&&this.pos<this.chunk2Pos+this.chunk2.length){let{chunk,chunkPos}=this;this.chunk=this.chunk2;this.chunkPos=this.chunk2Pos;this.chunk2=chunk;this.chunk2Pos=chunkPos;this.chunkOff=this.pos-this.chunkPos;}else {this.chunk2=this.chunk;this.chunk2Pos=this.chunkPos;let nextChunk=this.input.chunk(this.pos);let end=this.pos+nextChunk.length;this.chunk=end>this.range.to?nextChunk.slice(0,this.range.to-this.pos):nextChunk;this.chunkPos=this.pos;this.chunkOff=0;}}readNext(){if(this.chunkOff>=this.chunk.length){this.getChunk();if(this.chunkOff==this.chunk.length)return this.next=-1;}return this.next=this.chunk.charCodeAt(this.chunkOff);}/// Move the stream forward N (defaults to 1) code units. Returns
4832
+ /// the new value of [`next`](#lr.InputStream.next).
4833
+ advance(n=1){this.chunkOff+=n;while(this.pos+n>=this.range.to){if(this.rangeIndex==this.ranges.length-1)return this.setDone();n-=this.range.to-this.pos;this.range=this.ranges[++this.rangeIndex];this.pos=this.range.from;}this.pos+=n;if(this.pos>=this.token.lookAhead)this.token.lookAhead=this.pos+1;return this.readNext();}setDone(){this.pos=this.chunkPos=this.end;this.range=this.ranges[this.rangeIndex=this.ranges.length-1];this.chunk="";return this.next=-1;}/// @internal
4834
+ reset(pos,token){if(token){this.token=token;token.start=pos;token.lookAhead=pos+1;token.value=token.extended=-1;}else {this.token=nullToken;}if(this.pos!=pos){this.pos=pos;if(pos==this.end){this.setDone();return this;}while(pos<this.range.from)this.range=this.ranges[--this.rangeIndex];while(pos>=this.range.to)this.range=this.ranges[++this.rangeIndex];if(pos>=this.chunkPos&&pos<this.chunkPos+this.chunk.length){this.chunkOff=pos-this.chunkPos;}else {this.chunk="";this.chunkOff=0;}this.readNext();}return this;}/// @internal
4835
+ read(from,to){if(from>=this.chunkPos&&to<=this.chunkPos+this.chunk.length)return this.chunk.slice(from-this.chunkPos,to-this.chunkPos);if(from>=this.chunk2Pos&&to<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(from-this.chunk2Pos,to-this.chunk2Pos);if(from>=this.range.from&&to<=this.range.to)return this.input.read(from,to);let result="";for(let r of this.ranges){if(r.from>=to)break;if(r.to>from)result+=this.input.read(Math.max(r.from,from),Math.min(r.to,to));}return result;}}/// @internal
4836
+ class TokenGroup{constructor(data,id){this.data=data;this.id=id;}token(input,stack){readToken(this.data,input,stack,this.id);}}TokenGroup.prototype.contextual=TokenGroup.prototype.fallback=TokenGroup.prototype.extend=false;// Tokenizer data is stored a big uint16 array containing, for each
4837
+ // state:
4838
+ //
4839
+ // - A group bitmask, indicating what token groups are reachable from
4840
+ // this state, so that paths that can only lead to tokens not in
4841
+ // any of the current groups can be cut off early.
4842
+ //
4843
+ // - The position of the end of the state's sequence of accepting
4844
+ // tokens
4845
+ //
4846
+ // - The number of outgoing edges for the state
4847
+ //
4848
+ // - The accepting tokens, as (token id, group mask) pairs
4849
+ //
4850
+ // - The outgoing edges, as (start character, end character, state
4851
+ // index) triples, with end character being exclusive
4852
+ //
4853
+ // This function interprets that data, running through a stream as
4854
+ // long as new states with the a matching group mask can be reached,
4855
+ // and updating `token` when it matches a token.
4856
+ function readToken(data,input,stack,group){let state=0,groupMask=1<<group,{parser}=stack.p,{dialect}=parser;scan:for(;;){if((groupMask&data[state])==0)break;let accEnd=data[state+1];// Check whether this state can lead to a token in the current group
4857
+ // Accept tokens in this state, possibly overwriting
4858
+ // lower-precedence / shorter tokens
4859
+ for(let i=state+3;i<accEnd;i+=2)if((data[i+1]&groupMask)>0){let term=data[i];if(dialect.allows(term)&&(input.token.value==-1||input.token.value==term||parser.overrides(term,input.token.value))){input.acceptToken(term);break;}}// Do a binary search on the state's edges
4860
+ for(let next=input.next,low=0,high=data[state+2];low<high;){let mid=low+high>>1;let index=accEnd+mid+(mid<<1);let from=data[index],to=data[index+1];if(next<from)high=mid;else if(next>=to)low=mid+1;else {state=data[index+2];input.advance();continue scan;}}break;}}// See lezer-generator/src/encode.ts for comments about the encoding
4861
+ // used here
4862
+ function decodeArray(input,Type=Uint16Array){if(typeof input!="string")return input;let array=null;for(let pos=0,out=0;pos<input.length;){let value=0;for(;;){let next=input.charCodeAt(pos++),stop=false;if(next==126/* BigValCode */){value=65535/* BigVal */;break;}if(next>=92/* Gap2 */)next--;if(next>=34/* Gap1 */)next--;let digit=next-32/* Start */;if(digit>=46/* Base */){digit-=46/* Base */;stop=true;}value+=digit;if(stop)break;value*=46/* Base */;}if(array)array[out++]=value;else array=new Type(value);}return array;}// Environment variable used to control console output
4863
+ const verbose=typeof process!="undefined"&&process.env&&/\bparse\b/.test(process.env.LOG);let stackIDs=null;var Safety;(function(Safety){Safety[Safety["Margin"]=25]="Margin";})(Safety||(Safety={}));function cutAt(tree,pos,side){let cursor=tree.cursor(IterMode.IncludeAnonymous);cursor.moveTo(pos);for(;;){if(!(side<0?cursor.childBefore(pos):cursor.childAfter(pos)))for(;;){if((side<0?cursor.to<pos:cursor.from>pos)&&!cursor.type.isError)return side<0?Math.max(0,Math.min(cursor.to-1,pos-25/* Margin */)):Math.min(tree.length,Math.max(cursor.from+1,pos+25/* Margin */));if(side<0?cursor.prevSibling():cursor.nextSibling())break;if(!cursor.parent())return side<0?0:tree.length;}}}class FragmentCursor{constructor(fragments,nodeSet){this.fragments=fragments;this.nodeSet=nodeSet;this.i=0;this.fragment=null;this.safeFrom=-1;this.safeTo=-1;this.trees=[];this.start=[];this.index=[];this.nextFragment();}nextFragment(){let fr=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(fr){this.safeFrom=fr.openStart?cutAt(fr.tree,fr.from+fr.offset,1)-fr.offset:fr.from;this.safeTo=fr.openEnd?cutAt(fr.tree,fr.to+fr.offset,-1)-fr.offset:fr.to;while(this.trees.length){this.trees.pop();this.start.pop();this.index.pop();}this.trees.push(fr.tree);this.start.push(-fr.offset);this.index.push(0);this.nextStart=this.safeFrom;}else {this.nextStart=1e9;}}// `pos` must be >= any previously given `pos` for this cursor
4864
+ nodeAt(pos){if(pos<this.nextStart)return null;while(this.fragment&&this.safeTo<=pos)this.nextFragment();if(!this.fragment)return null;for(;;){let last=this.trees.length-1;if(last<0){// End of tree
4865
+ this.nextFragment();return null;}let top=this.trees[last],index=this.index[last];if(index==top.children.length){this.trees.pop();this.start.pop();this.index.pop();continue;}let next=top.children[index];let start=this.start[last]+top.positions[index];if(start>pos){this.nextStart=start;return null;}if(next instanceof Tree){if(start==pos){if(start<this.safeFrom)return null;let end=start+next.length;if(end<=this.safeTo){let lookAhead=next.prop(NodeProp.lookAhead);if(!lookAhead||end+lookAhead<this.fragment.to)return next;}}this.index[last]++;if(start+next.length>=Math.max(this.safeFrom,pos)){// Enter this node
4866
+ this.trees.push(next);this.start.push(start);this.index.push(0);}}else {this.index[last]++;this.nextStart=start+next.length;}}}}class TokenCache{constructor(parser,stream){this.stream=stream;this.tokens=[];this.mainToken=null;this.actions=[];this.tokens=parser.tokenizers.map(_=>new CachedToken());}getActions(stack){let actionIndex=0;let main=null;let{parser}=stack.p,{tokenizers}=parser;let mask=parser.stateSlot(stack.state,3/* TokenizerMask */);let context=stack.curContext?stack.curContext.hash:0;let lookAhead=0;for(let i=0;i<tokenizers.length;i++){if((1<<i&mask)==0)continue;let tokenizer=tokenizers[i],token=this.tokens[i];if(main&&!tokenizer.fallback)continue;if(tokenizer.contextual||token.start!=stack.pos||token.mask!=mask||token.context!=context){this.updateCachedToken(token,tokenizer,stack);token.mask=mask;token.context=context;}if(token.lookAhead>token.end+25/* Margin */)lookAhead=Math.max(token.lookAhead,lookAhead);if(token.value!=0/* Err */){let startIndex=actionIndex;if(token.extended>-1)actionIndex=this.addActions(stack,token.extended,token.end,actionIndex);actionIndex=this.addActions(stack,token.value,token.end,actionIndex);if(!tokenizer.extend){main=token;if(actionIndex>startIndex)break;}}}while(this.actions.length>actionIndex)this.actions.pop();if(lookAhead)stack.setLookAhead(lookAhead);if(!main&&stack.pos==this.stream.end){main=new CachedToken();main.value=stack.p.parser.eofTerm;main.start=main.end=stack.pos;actionIndex=this.addActions(stack,main.value,main.end,actionIndex);}this.mainToken=main;return this.actions;}getMainToken(stack){if(this.mainToken)return this.mainToken;let main=new CachedToken(),{pos,p}=stack;main.start=pos;main.end=Math.min(pos+1,p.stream.end);main.value=pos==p.stream.end?p.parser.eofTerm:0/* Err */;return main;}updateCachedToken(token,tokenizer,stack){tokenizer.token(this.stream.reset(stack.pos,token),stack);if(token.value>-1){let{parser}=stack.p;for(let i=0;i<parser.specialized.length;i++)if(parser.specialized[i]==token.value){let result=parser.specializers[i](this.stream.read(token.start,token.end),stack);if(result>=0&&stack.p.parser.dialect.allows(result>>1)){if((result&1)==0/* Specialize */)token.value=result>>1;else token.extended=result>>1;break;}}}else {token.value=0/* Err */;token.end=Math.min(stack.p.stream.end,stack.pos+1);}}putAction(action,token,end,index){// Don't add duplicate actions
4867
+ for(let i=0;i<index;i+=3)if(this.actions[i]==action)return index;this.actions[index++]=action;this.actions[index++]=token;this.actions[index++]=end;return index;}addActions(stack,token,end,index){let{state}=stack,{parser}=stack.p,{data}=parser;for(let set=0;set<2;set++){for(let i=parser.stateSlot(state,set?2/* Skip */:1/* Actions */);;i+=3){if(data[i]==65535/* End */){if(data[i+1]==1/* Next */){i=pair(data,i+2);}else {if(index==0&&data[i+1]==2/* Other */)index=this.putAction(pair(data,i+2),token,end,index);break;}}if(data[i]==token)index=this.putAction(pair(data,i+1),token,end,index);}}return index;}}var Rec;(function(Rec){Rec[Rec["Distance"]=5]="Distance";Rec[Rec["MaxRemainingPerStep"]=3]="MaxRemainingPerStep";// When two stacks have been running independently long enough to
4868
+ // add this many elements to their buffers, prune one.
4869
+ Rec[Rec["MinBufferLengthPrune"]=500]="MinBufferLengthPrune";Rec[Rec["ForceReduceLimit"]=10]="ForceReduceLimit";// Once a stack reaches this depth (in .stack.length) force-reduce
4870
+ // it back to CutTo to avoid creating trees that overflow the stack
4871
+ // on recursive traversal.
4872
+ Rec[Rec["CutDepth"]=15000]="CutDepth";Rec[Rec["CutTo"]=9000]="CutTo";})(Rec||(Rec={}));class Parse{constructor(parser,input,fragments,ranges){this.parser=parser;this.input=input;this.ranges=ranges;this.recovering=0;this.nextStackID=0x2654;// ♔, ♕, ♖, ♗, ♘, ♙, ♠, ♡, ♢, ♣, ♤, ♥, ♦, ♧
4873
+ this.minStackPos=0;this.reused=[];this.stoppedAt=null;this.stream=new InputStream(input,ranges);this.tokens=new TokenCache(parser,this.stream);this.topTerm=parser.top[1];let{from}=ranges[0];this.stacks=[Stack.start(this,parser.top[0],from)];this.fragments=fragments.length&&this.stream.end-from>parser.bufferLength*4?new FragmentCursor(fragments,parser.nodeSet):null;}get parsedPos(){return this.minStackPos;}// Move the parser forward. This will process all parse stacks at
4874
+ // `this.pos` and try to advance them to a further position. If no
4875
+ // stack for such a position is found, it'll start error-recovery.
4876
+ //
4877
+ // When the parse is finished, this will return a syntax tree. When
4878
+ // not, it returns `null`.
4879
+ advance(){let stacks=this.stacks,pos=this.minStackPos;// This will hold stacks beyond `pos`.
4880
+ let newStacks=this.stacks=[];let stopped,stoppedTokens;// Keep advancing any stacks at `pos` until they either move
4881
+ // forward or can't be advanced. Gather stacks that can't be
4882
+ // advanced further in `stopped`.
4883
+ for(let i=0;i<stacks.length;i++){let stack=stacks[i];for(;;){this.tokens.mainToken=null;if(stack.pos>pos){newStacks.push(stack);}else if(this.advanceStack(stack,newStacks,stacks)){continue;}else {if(!stopped){stopped=[];stoppedTokens=[];}stopped.push(stack);let tok=this.tokens.getMainToken(stack);stoppedTokens.push(tok.value,tok.end);}break;}}if(!newStacks.length){let finished=stopped&&findFinished(stopped);if(finished)return this.stackToTree(finished);if(this.parser.strict){if(verbose&&stopped)console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none"));throw new SyntaxError("No parse at "+pos);}if(!this.recovering)this.recovering=5/* Distance */;}if(this.recovering&&stopped){let finished=this.stoppedAt!=null&&stopped[0].pos>this.stoppedAt?stopped[0]:this.runRecovery(stopped,stoppedTokens,newStacks);if(finished)return this.stackToTree(finished.forceAll());}if(this.recovering){let maxRemaining=this.recovering==1?1:this.recovering*3/* MaxRemainingPerStep */;if(newStacks.length>maxRemaining){newStacks.sort((a,b)=>b.score-a.score);while(newStacks.length>maxRemaining)newStacks.pop();}if(newStacks.some(s=>s.reducePos>pos))this.recovering--;}else if(newStacks.length>1){// Prune stacks that are in the same state, or that have been
4884
+ // running without splitting for a while, to avoid getting stuck
4885
+ // with multiple successful stacks running endlessly on.
4886
+ outer:for(let i=0;i<newStacks.length-1;i++){let stack=newStacks[i];for(let j=i+1;j<newStacks.length;j++){let other=newStacks[j];if(stack.sameState(other)||stack.buffer.length>500/* MinBufferLengthPrune */&&other.buffer.length>500/* MinBufferLengthPrune */){if((stack.score-other.score||stack.buffer.length-other.buffer.length)>0){newStacks.splice(j--,1);}else {newStacks.splice(i--,1);continue outer;}}}}}this.minStackPos=newStacks[0].pos;for(let i=1;i<newStacks.length;i++)if(newStacks[i].pos<this.minStackPos)this.minStackPos=newStacks[i].pos;return null;}stopAt(pos){if(this.stoppedAt!=null&&this.stoppedAt<pos)throw new RangeError("Can't move stoppedAt forward");this.stoppedAt=pos;}// Returns an updated version of the given stack, or null if the
4887
+ // stack can't advance normally. When `split` and `stacks` are
4888
+ // given, stacks split off by ambiguous operations will be pushed to
4889
+ // `split`, or added to `stacks` if they move `pos` forward.
4890
+ advanceStack(stack,stacks,split){let start=stack.pos,{parser}=this;let base=verbose?this.stackID(stack)+" -> ":"";if(this.stoppedAt!=null&&start>this.stoppedAt)return stack.forceReduce()?stack:null;if(this.fragments){let strictCx=stack.curContext&&stack.curContext.tracker.strict,cxHash=strictCx?stack.curContext.hash:0;for(let cached=this.fragments.nodeAt(start);cached;){let match=this.parser.nodeSet.types[cached.type.id]==cached.type?parser.getGoto(stack.state,cached.type.id):-1;if(match>-1&&cached.length&&(!strictCx||(cached.prop(NodeProp.contextHash)||0)==cxHash)){stack.useNode(cached,match);if(verbose)console.log(base+this.stackID(stack)+` (via reuse of ${parser.getName(cached.type.id)})`);return true;}if(!(cached instanceof Tree)||cached.children.length==0||cached.positions[0]>0)break;let inner=cached.children[0];if(inner instanceof Tree&&cached.positions[0]==0)cached=inner;else break;}}let defaultReduce=parser.stateSlot(stack.state,4/* DefaultReduce */);if(defaultReduce>0){stack.reduce(defaultReduce);if(verbose)console.log(base+this.stackID(stack)+` (via always-reduce ${parser.getName(defaultReduce&65535/* ValueMask */)})`);return true;}if(stack.stack.length>=15000/* CutDepth */){while(stack.stack.length>9000/* CutTo */&&stack.forceReduce()){}}let actions=this.tokens.getActions(stack);for(let i=0;i<actions.length;){let action=actions[i++],term=actions[i++],end=actions[i++];let last=i==actions.length||!split;let localStack=last?stack:stack.split();localStack.apply(action,term,end);if(verbose)console.log(base+this.stackID(localStack)+` (via ${(action&65536/* ReduceFlag */)==0?"shift":`reduce of ${parser.getName(action&65535/* ValueMask */)}`} for ${parser.getName(term)} @ ${start}${localStack==stack?"":", split"})`);if(last)return true;else if(localStack.pos>start)stacks.push(localStack);else split.push(localStack);}return false;}// Advance a given stack forward as far as it will go. Returns the
4891
+ // (possibly updated) stack if it got stuck, or null if it moved
4892
+ // forward and was given to `pushStackDedup`.
4893
+ advanceFully(stack,newStacks){let pos=stack.pos;for(;;){if(!this.advanceStack(stack,null,null))return false;if(stack.pos>pos){pushStackDedup(stack,newStacks);return true;}}}runRecovery(stacks,tokens,newStacks){let finished=null,restarted=false;for(let i=0;i<stacks.length;i++){let stack=stacks[i],token=tokens[i<<1],tokenEnd=tokens[(i<<1)+1];let base=verbose?this.stackID(stack)+" -> ":"";if(stack.deadEnd){if(restarted)continue;restarted=true;stack.restart();if(verbose)console.log(base+this.stackID(stack)+" (restarted)");let done=this.advanceFully(stack,newStacks);if(done)continue;}let force=stack.split(),forceBase=base;for(let j=0;force.forceReduce()&&j<10/* ForceReduceLimit */;j++){if(verbose)console.log(forceBase+this.stackID(force)+" (via force-reduce)");let done=this.advanceFully(force,newStacks);if(done)break;if(verbose)forceBase=this.stackID(force)+" -> ";}for(let insert of stack.recoverByInsert(token)){if(verbose)console.log(base+this.stackID(insert)+" (via recover-insert)");this.advanceFully(insert,newStacks);}if(this.stream.end>stack.pos){if(tokenEnd==stack.pos){tokenEnd++;token=0/* Err */;}stack.recoverByDelete(token,tokenEnd);if(verbose)console.log(base+this.stackID(stack)+` (via recover-delete ${this.parser.getName(token)})`);pushStackDedup(stack,newStacks);}else if(!finished||finished.score<stack.score){finished=stack;}}return finished;}// Convert the stack's buffer to a syntax tree.
4894
+ stackToTree(stack){stack.close();return Tree.build({buffer:StackBufferCursor.create(stack),nodeSet:this.parser.nodeSet,topID:this.topTerm,maxBufferLength:this.parser.bufferLength,reused:this.reused,start:this.ranges[0].from,length:stack.pos-this.ranges[0].from,minRepeatType:this.parser.minRepeatTerm});}stackID(stack){let id=(stackIDs||(stackIDs=new WeakMap())).get(stack);if(!id)stackIDs.set(stack,id=String.fromCodePoint(this.nextStackID++));return id+stack;}}function pushStackDedup(stack,newStacks){for(let i=0;i<newStacks.length;i++){let other=newStacks[i];if(other.pos==stack.pos&&other.sameState(stack)){if(newStacks[i].score<stack.score)newStacks[i]=stack;return;}}newStacks.push(stack);}class Dialect{constructor(source,flags,disabled){this.source=source;this.flags=flags;this.disabled=disabled;}allows(term){return !this.disabled||this.disabled[term]==0;}}/// A parser holds the parse tables for a given grammar, as generated
4895
+ /// by `lezer-generator`.
4896
+ class LRParser extends Parser{/// @internal
4897
+ constructor(spec){super();/// @internal
4898
+ this.wrappers=[];if(spec.version!=14/* Version */)throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14/* Version */})`);let nodeNames=spec.nodeNames.split(" ");this.minRepeatTerm=nodeNames.length;for(let i=0;i<spec.repeatNodeCount;i++)nodeNames.push("");let topTerms=Object.keys(spec.topRules).map(r=>spec.topRules[r][1]);let nodeProps=[];for(let i=0;i<nodeNames.length;i++)nodeProps.push([]);function setProp(nodeID,prop,value){nodeProps[nodeID].push([prop,prop.deserialize(String(value))]);}if(spec.nodeProps)for(let propSpec of spec.nodeProps){let prop=propSpec[0];if(typeof prop=="string")prop=NodeProp[prop];for(let i=1;i<propSpec.length;){let next=propSpec[i++];if(next>=0){setProp(next,prop,propSpec[i++]);}else {let value=propSpec[i+-next];for(let j=-next;j>0;j--)setProp(propSpec[i++],prop,value);i++;}}}this.nodeSet=new NodeSet(nodeNames.map((name,i)=>NodeType.define({name:i>=this.minRepeatTerm?undefined:name,id:i,props:nodeProps[i],top:topTerms.indexOf(i)>-1,error:i==0,skipped:spec.skippedNodes&&spec.skippedNodes.indexOf(i)>-1})));if(spec.propSources)this.nodeSet=this.nodeSet.extend(...spec.propSources);this.strict=false;this.bufferLength=DefaultBufferLength;let tokenArray=decodeArray(spec.tokenData);this.context=spec.context;this.specialized=new Uint16Array(spec.specialized?spec.specialized.length:0);this.specializers=[];if(spec.specialized)for(let i=0;i<spec.specialized.length;i++){this.specialized[i]=spec.specialized[i].term;this.specializers[i]=spec.specialized[i].get;}this.states=decodeArray(spec.states,Uint32Array);this.data=decodeArray(spec.stateData);this.goto=decodeArray(spec.goto);this.maxTerm=spec.maxTerm;this.tokenizers=spec.tokenizers.map(value=>typeof value=="number"?new TokenGroup(tokenArray,value):value);this.topRules=spec.topRules;this.dialects=spec.dialects||{};this.dynamicPrecedences=spec.dynamicPrecedences||null;this.tokenPrecTable=spec.tokenPrec;this.termNames=spec.termNames||null;this.maxNode=this.nodeSet.types.length-1;this.dialect=this.parseDialect();this.top=this.topRules[Object.keys(this.topRules)[0]];}createParse(input,fragments,ranges){let parse=new Parse(this,input,fragments,ranges);for(let w of this.wrappers)parse=w(parse,input,fragments,ranges);return parse;}/// Get a goto table entry @internal
4899
+ getGoto(state,term,loose=false){let table=this.goto;if(term>=table[0])return -1;for(let pos=table[term+1];;){let groupTag=table[pos++],last=groupTag&1;let target=table[pos++];if(last&&loose)return target;for(let end=pos+(groupTag>>1);pos<end;pos++)if(table[pos]==state)return target;if(last)return -1;}}/// Check if this state has an action for a given terminal @internal
4900
+ hasAction(state,terminal){let data=this.data;for(let set=0;set<2;set++){for(let i=this.stateSlot(state,set?2/* Skip */:1/* Actions */),next;;i+=3){if((next=data[i])==65535/* End */){if(data[i+1]==1/* Next */)next=data[i=pair(data,i+2)];else if(data[i+1]==2/* Other */)return pair(data,i+2);else break;}if(next==terminal||next==0/* Err */)return pair(data,i+1);}}return 0;}/// @internal
4901
+ stateSlot(state,slot){return this.states[state*6/* Size */+slot];}/// @internal
4902
+ stateFlag(state,flag){return (this.stateSlot(state,0/* Flags */)&flag)>0;}/// @internal
4903
+ validAction(state,action){if(action==this.stateSlot(state,4/* DefaultReduce */))return true;for(let i=this.stateSlot(state,1/* Actions */);;i+=3){if(this.data[i]==65535/* End */){if(this.data[i+1]==1/* Next */)i=pair(this.data,i+2);else return false;}if(action==pair(this.data,i+1))return true;}}/// Get the states that can follow this one through shift actions or
4904
+ /// goto jumps. @internal
4905
+ nextStates(state){let result=[];for(let i=this.stateSlot(state,1/* Actions */);;i+=3){if(this.data[i]==65535/* End */){if(this.data[i+1]==1/* Next */)i=pair(this.data,i+2);else break;}if((this.data[i+2]&65536/* ReduceFlag */>>16)==0){let value=this.data[i+1];if(!result.some((v,i)=>i&1&&v==value))result.push(this.data[i],value);}}return result;}/// @internal
4906
+ overrides(token,prev){let iPrev=findOffset(this.data,this.tokenPrecTable,prev);return iPrev<0||findOffset(this.data,this.tokenPrecTable,token)<iPrev;}/// Configure the parser. Returns a new parser instance that has the
4907
+ /// given settings modified. Settings not provided in `config` are
4908
+ /// kept from the original parser.
4909
+ configure(config){// Hideous reflection-based kludge to make it easy to create a
4910
+ // slightly modified copy of a parser.
4911
+ let copy=Object.assign(Object.create(LRParser.prototype),this);if(config.props)copy.nodeSet=this.nodeSet.extend(...config.props);if(config.top){let info=this.topRules[config.top];if(!info)throw new RangeError(`Invalid top rule name ${config.top}`);copy.top=info;}if(config.tokenizers)copy.tokenizers=this.tokenizers.map(t=>{let found=config.tokenizers.find(r=>r.from==t);return found?found.to:t;});if(config.contextTracker)copy.context=config.contextTracker;if(config.dialect)copy.dialect=this.parseDialect(config.dialect);if(config.strict!=null)copy.strict=config.strict;if(config.wrap)copy.wrappers=copy.wrappers.concat(config.wrap);if(config.bufferLength!=null)copy.bufferLength=config.bufferLength;return copy;}/// Tells you whether any [parse wrappers](#lr.ParserConfig.wrap)
4912
+ /// are registered for this parser.
4913
+ hasWrappers(){return this.wrappers.length>0;}/// Returns the name associated with a given term. This will only
4914
+ /// work for all terms when the parser was generated with the
4915
+ /// `--names` option. By default, only the names of tagged terms are
4916
+ /// stored.
4917
+ getName(term){return this.termNames?this.termNames[term]:String(term<=this.maxNode&&this.nodeSet.types[term].name||term);}/// The eof term id is always allocated directly after the node
4918
+ /// types. @internal
4919
+ get eofTerm(){return this.maxNode+1;}/// The type of top node produced by the parser.
4920
+ get topNode(){return this.nodeSet.types[this.top[1]];}/// @internal
4921
+ dynamicPrecedence(term){let prec=this.dynamicPrecedences;return prec==null?0:prec[term]||0;}/// @internal
4922
+ parseDialect(dialect){let values=Object.keys(this.dialects),flags=values.map(()=>false);if(dialect)for(let part of dialect.split(" ")){let id=values.indexOf(part);if(id>=0)flags[id]=true;}let disabled=null;for(let i=0;i<values.length;i++)if(!flags[i]){for(let j=this.dialects[values[i]],id;(id=this.data[j++])!=65535/* End */;)(disabled||(disabled=new Uint8Array(this.maxTerm+1)))[id]=1;}return new Dialect(dialect,flags,disabled);}/// (used by the output of the parser generator) @internal
4923
+ static deserialize(spec){return new LRParser(spec);}}function pair(data,off){return data[off]|data[off+1]<<16;}function findOffset(data,start,term){for(let i=start,next;(next=data[i])!=65535/* End */;i++)if(next==term)return i-start;return -1;}function findFinished(stacks){let best=null;for(let stack of stacks){let stopped=stack.p.stoppedAt;if((stack.pos==stack.p.stream.end||stopped!=null&&stack.pos>stopped)&&stack.p.parser.stateFlag(stack.state,2/* Accepting */)&&(!best||best.score<stack.score))best=stack;}return best;}// This file was generated by lezer-generator. You probably shouldn't edit it.
4924
+ const spec_identifier={__proto__:null,for:10,in:18,return:23,if:26,then:28,else:30,some:34,every:36,satisfies:43,or:46,and:50,between:58,instance:82,of:85,days:93,time:95,duration:97,years:99,months:101,date:103,list:109,context:115,function:122,string:141,length:143,upper:145,case:147,lower:149,substring:151,before:153,after:155,starts:157,with:159,ends:161,contains:163,insert:165,index:167,distinct:169,values:171,met:173,by:175,overlaps:177,finished:179,started:181,day:183,year:185,week:187,month:189,get:191,value:193,entries:195,start:205,position:207,decimal:209,sep:211,separator:213,grouping:215,null:218,true:344,false:344,"?":232,external:248,method:265,signature:267,not:273};const parser=LRParser.deserialize({version:14,states:"!#UO]QPOOO&hQPOOO'sQPO'#FiO]QPO'#DOO*[QPO'#DOO,zQPO'#DrOOQO'#En'#EnOOQO'#Eo'#EoOOQO'#Ep'#EpO,zQPO'#EqOOQO'#F{'#F{OOQO'#Fz'#FzOOQO'#Es'#EsO-PQPO'#EvO-kQPO'#EwO0ZQPO'#ExO-PQPO'#EuOOQO'#Eu'#EuOOQO'#Fk'#FkO0bQPO'#FQOOQO'#GQ'#GQOOQO'#Fj'#FjOOQO'#FZ'#FZQ]QPOOO0pQPO'#C`O]QPO'#ChO0pQPO'#ClO0uQPO'#DsO0zQPO'#DsO1PQPO'#DsO1UQPO'#DsO1^QPO'#DsO1cQPO'#DsO1hQPO'#DsO1mQPO'#DsO1rQPO'#DsO1wQPO'#DsO1|QPO'#DsO2RQPO'#DsO2WQPO'#DsO2`QPO'#ErOOQO'#Er'#ErO2hQPO'#EyO2mQPO'#CzO5hQPO'#FqOOQO'#C|'#C|O5sQPO'#FXQOQPOOO5zQPOOO]QPO,59bO]QPO,59jO]QPO,59jO]QPO,59jO0pQPO,5:YO]QPO,5:[O8lQPO'#FwOOQO,5:^,5:^OOQO,5<T,5<TO]QPO,59^O]QPO,59`O]QPO,59bO;lQPO,59bO;sQPO,59pO;xQPO,59jOB]QPO,5;YOOQO,5;],5;]OOQO'#Cd'#CdOGqQPO'#DYOKoQPO'#EnOOQO'#GP'#GPOKtQPO,5;bOMQQPO'#CdOM_QPO,5;cOMfQPO'#FzONsQPO'#FyO! QQPO,5;dOOQO,5;a,5;aOOQO'#FS'#FSO! VQPO'#FRO! [QPO'#GSO! dQPO,5;lO! iQPO'#FTOOQO-E9X-E9XO! nQPO'#FmOOQO'#Cb'#CbO! vQPO'#CcO! {QPO,58zO!!QQPO,59SO!!XQPO'#FpOOQO'#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Q%X$`Q%[$eS%j%W%lQ%y%eQ%z%fQ&a&rQ&k&dQ&l&eQ&m&fQ&n&hQ&o&iQ&v&pQ&w&qQ&x&tQ&z&uS&|&y&}Q'O&{Q'Q&sQ'S&jQ'U'^Q'V'_Q'W'`Q'Y'hQ'k'bQ'l'cQ'm'dQ'n'fQ'o'gQ's'pQ't'qQ'v'rS'y'u'zQ'{'xQ(U'}Q(V(OQ(W(PQ(X(RQ(Y(SQ(^(ZQ(_([Q(a(]S(c(`(dQ(e(bQ(g(TQ(j(wQ(o'iR(r({$yeOPRS^_gi!O!R!S!T!U!W!X![!]!^!_#U#W#j#r#u#|#}$O$R$S$`$e%W%e%f%l&c&d&e&f&g&h&i&j&p&q&r&s&t&u&y&{&}'R'^'_'`'b'c'd'e'f'g'h'i'p'q'r'u'x'z'|'}(O(P(Q(R(S(T(Z([(](`(b(d(f(l(m(w({X!vh'](u(yX!{j'a(v(zV}P#W#jR%s%bT%w%c'w$Q!YQT{!a!j!l!y#X#Y#Z#[#^#g#h#i$f$s$u$z$|$}%Q%R%X%[%j%y%z&a&k&l&m&n&o&v&w&x&z&|'O'Q'S'U'V'W'Y'k'l'm'n'o's't'v'y'{(U(V(W(X(Y(^(_(a(c(e(g(j(o(rR!cXR#b!XQ!m_R#c!X$rZOPRSgi!O!R!S!T!U!W!X![!]!^!_#U#W#r#u#|#}$O$R$S$`$e%W%e%f%l&c&d&e&f&g&h&i&j&p&q&r&s&t&u&y&{&}'R'^'_'`'b'c'd'e'f'g'h'i'p'q'r'u'x'z'|'}(O(P(Q(R(S(T(Z([(](`(b(d(f(l(m(w({U!g]`#pV!k^_#jW!h]^_#jQ!n`R$r#pX$Y#T'j(x(|R!rc",nodeNames:"⚠ LineComment BlockComment Expressions ForExpression for InExpressions InExpression Name in IterationContext return IfExpression if then else QuantifiedExpression some every InExpressions InExpression satisfies Disjunction or Conjunction and Comparison CompareOp CompareOp between PositiveUnaryTest ( PositiveUnaryTests ) ArithmeticExpression ArithOp ArithOp ArithOp ArithOp ArithOp InstanceOf instance of Type QualifiedName SpecialType days time duration years months date > ListType list < ContextType context ContextEntryTypes ContextEntryType FunctionType function ArgumentTypes ArgumentType PathExpression ] FilterExpression [ FunctionInvocation SpecialFunctionName string length upper case lower substring before after starts with ends contains insert index distinct values met by overlaps finished started day year week month get value entries NamedParameters NamedParameter ParameterName SpecialParameterName start position decimal sep separator grouping PositionalParameters null NumericLiteral StringLiteral BooleanLiteral DateTimeLiteral DateTimeConstructor VariableName ? SimplePositiveUnaryTest Interval ParenthesizedExpression List FunctionDefinition FormalParameters FormalParameter external FunctionBody } { Context ContextEntry Key SpecialKey method signature UnaryTests Wildcard not",maxTerm:177,nodeProps:[["group",-18,4,12,16,22,24,26,34,40,64,66,68,115,116,117,119,120,121,128,"Expression",-5,109,110,111,112,113,"Expression Literal"],["closedBy",31,")",67,"]",127,"}"],["openedBy",33,"(",65,"[",126,"{"]],skippedNodes:[0,1,2],repeatNodeCount:11,tokenData:"+Y~R|XY#{Y^#{pq#{qr$prs${tu%oxy&yyz'Oz{'T{|'b|}'g}!O'l!O!P'y!P!Q(c!Q![)n![!]*P!]!^*U!^!_*Z!_!`$v!`!a*j!a!b%o!c!}%o!}#O*t#P#Q*y#Q#R']#R#S%o#T#o%o#o#p+O#q#r+T#y#z#{$f$g#{#BY#BZ#{$IS$I_#{$I`$Ib%o$I|$JO#{$JT$JU#{$KV$KW#{$Kh%#t%o&/x&Et%o&FU&FV#{&FV;'S%o;'S;:j&s?&r?Ah%o?BY?Mn%o~$QY$[~X^#{pq#{#y#z#{$f$g#{#BY#BZ#{$IS$I_#{$I|$JO#{$JT$JU#{$KV$KW#{&FU&FV#{~$sP!_!`$v~${Ok~~%QU$q~OY${Zr${rs%ds#O${#O#P%i#P~${~%iO$q~~%lPO~${~%t_$`~tu%o!Q![%o!a!b%o!c!}%o#R#S%o#T#o%o1p4U%o$I`$Ib%o$Je$Jg%o$Kh%#t%o&/x&Et%o&FV;'S%o;'S;:j&s?&r?Ah%o?BY?Mn%o~&vP;=`<%l%o~'OOo~~'TOq~~'YPu~z{']~'bOw~~'gOs~~'lO$c~R'qPtP!`!a'tQ'yO$jQ~(OQ$f~!O!P(U!Q![(Z~(ZO$b~~(`P$p~!Q![(Z~(hQv~z{(n!P!Q)c~(qROz(nz{(z{~(n~(}TOz(nz{(z{!P(n!P!Q)^!Q~(n~)cOQ~~)hQP~OY)cZ~)c~)sQ$p~!O!P)y!Q![)n~)|P!Q![(Z~*UO$h~~*ZO$w~R*bP!XQlP!_!`*eP*jOlPR*qP!UQlP!_!`*e~*yO!e~~+OO!c~~+TO#s~~+YO#r~",tokenizers:[0,1],topRules:{"Expressions":[0,3],"UnaryTests":[1,134]},dynamicPrecedences:{"24":-1,"68":-1,"151":-1},specialized:[{term:154,get:value=>spec_identifier[value]||-1}],tokenPrec:0});const highlightTags=styleTags({VariableName:tags.variableName,NumericLiteral:tags.number,QualifiedName:tags.name,Name:tags.name,BooleanLiteral:tags.bool,StringLiteral:tags.string,LineComment:tags.lineComment,BlockComment:tags.blockComment,'( )':tags.paren,BuiltInFunctionName:tags.function(tags.variableName),BuiltInType:tags.function(tags.variableName),ListType:tags.function(tags.variableName),ContextType:tags.function(tags.variableName),FunctionType:tags.function(tags.variableName),DateAndTime:tags.function(tags.variableName),'DateTimeConstructor!':tags.function(tags.variableName),'for in return null':tags.atom,List:tags.list,Interval:tags.list});const parserWithMetadata=parser.configure({props:[highlightTags]});const FeelLanguage=LRLanguage.define({parser:parserWithMetadata});function language(){return new LanguageSupport(FeelLanguage,[]);}const FeelLinter=function(editorView){const messages=[];// don't lint if the Editor is empty
4812
4925
  if(editorView.state.doc.length===0){return messages;}const tree=syntaxTree(editorView.state);tree.iterate({enter:node=>{if(node.type.isError){const error=node.toString();/* The error has the pattern [⚠ || ⚠(NodeType)]. The regex extracts the node type from inside the brackets */const match=/\((.*?)\)/.exec(error);const nodeType=match&&match[1];let message;if(nodeType){message='unexpected '+nodeType;}else {message='expression expected';}messages.push({from:node.from,to:node.to,severity:'error',message:message,source:'syntaxError'});}}});return messages;};var syntaxLinter=linter$1(FeelLinter);var linter=[syntaxLinter];const baseTheme=EditorView.theme({'& .cm-content':{padding:'0px'},'& .cm-line':{padding:'0px'},'&.cm-editor.cm-focused':{outline:'none'}});const highlightTheme=EditorView.baseTheme({'& .variableName':{color:'#10f'},'& .number':{color:'#164'},'& .string':{color:'#a11'},'& .function':{color:'#aa3731',fontWeight:'bold'},'& .atom':{color:'#708'}});const syntaxClasses=syntaxHighlighting(HighlightStyle.define([{tag:tags.variableName,class:'variableName'},{tag:tags.name,class:'variableName'},{tag:tags.number,class:'number'},{tag:tags.string,class:'string'},{tag:tags.function(tags.variableName),class:'function'},{tag:tags.atom,class:'atom'}]));var theme=[baseTheme,highlightTheme,syntaxClasses];/**
4813
4926
  * Creates a FEEL editor in the supplied container
4814
4927
  *
@@ -4816,16 +4929,19 @@ if(editorView.state.doc.length===0){return messages;}const tree=syntaxTree(edito
4816
4929
  * @param {DOMNode} config.container
4817
4930
  * @param {Function} [config.onChange]
4818
4931
  * @param {Function} [config.onKeyDown]
4932
+ * @param {Function} [config.onLint]
4933
+ * @param {Boolean} [config.readOnly]
4819
4934
  * @param {String} [config.value]
4935
+ * @param {Array} [config.variables]
4820
4936
  *
4821
4937
  * @returns {Object} editor
4822
- */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;}/**
4938
+ */function FeelEditor({container,onChange=()=>{},onKeyDown=()=>{},onLint=()=>{},readOnly=false,value='',variables=[]}){const changeHandler=EditorView.updateListener.of(update=>{if(update.docChanged){onChange(update.state.doc.toString());}});const lintHandler=EditorView.updateListener.of(update=>{const diagnosticEffects=update.transactions.flatMap(t=>t.effects).filter(effect=>effect.is(setDiagnosticsEffect));if(!diagnosticEffects.length){return;}const messages=diagnosticEffects.flatMap(effect=>effect.value);onLint(messages);});const keyHandler=EditorView.domEventHandlers({keydown:onKeyDown});const extensions=[keymap.of([...defaultKeymap]),changeHandler,keyHandler,language(),autocompletion(variables),theme,linter,lintHandler];if(readOnly){extensions.push(EditorView.editable.of(false));}this._cmEditor=new EditorView({state:EditorState.create({doc:value,extensions:extensions}),parent:container});return this;}/**
4823
4939
  * Replaces the content of the Editor
4824
4940
  *
4825
4941
  * @param {String} value
4826
4942
  */FeelEditor.prototype.setValue=function(value){this._cmEditor.dispatch({changes:{from:0,to:this._cmEditor.state.doc.length,insert:value}});};/**
4827
4943
  * Sets the focus in the editor.
4828
- */FeelEditor.prototype.focus=function(){this._cmEditor.focus();};/**
4944
+ */FeelEditor.prototype.focus=function(position){const cmEditor=this._cmEditor;cmEditor.focus();if(typeof position==='number'){const end=cmEditor.state.doc.length;cmEditor.dispatch({selection:{anchor:position<=end?position:end}});}};/**
4829
4945
  * Returns the current selection ranges. If no text is selected, a single
4830
4946
  * range with the start and end index at the cursor position will be returned.
4831
4947
  *
@@ -4834,19 +4950,19 @@ if(editorView.state.doc.length===0){return messages;}const tree=syntaxTree(edito
4834
4950
  */FeelEditor.prototype.getSelection=function(){return this._cmEditor.state.selection;};
4835
4951
 
4836
4952
  const useBufferedFocus = function (editor, ref) {
4837
- const [buffer, setBuffer] = hooks.useState(false);
4953
+ const [buffer, setBuffer] = hooks.useState(undefined);
4838
4954
  ref.current = hooks.useMemo(() => ({
4839
- focus: () => {
4955
+ focus: argument => {
4840
4956
  if (editor) {
4841
- editor.focus();
4957
+ editor.focus(argument);
4842
4958
  } else {
4843
- setBuffer(true);
4959
+ setBuffer(argument);
4844
4960
  }
4845
4961
  }
4846
4962
  }), [editor]);
4847
4963
  hooks.useEffect(() => {
4848
- if (buffer && editor) {
4849
- editor.focus();
4964
+ if (typeof buffer !== 'undefined' && editor) {
4965
+ editor.focus(buffer);
4850
4966
  setBuffer(false);
4851
4967
  }
4852
4968
  }, [editor, buffer]);
@@ -4857,7 +4973,8 @@ const CodeEditor = compat.forwardRef((props, ref) => {
4857
4973
  value,
4858
4974
  onInput,
4859
4975
  onFeelToggle,
4860
- disabled
4976
+ disabled,
4977
+ variables
4861
4978
  } = props;
4862
4979
  const inputRef = hooks.useRef();
4863
4980
  const [editor, setEditor] = hooks.useState();
@@ -4892,10 +5009,15 @@ const CodeEditor = compat.forwardRef((props, ref) => {
4892
5009
  container: inputRef.current,
4893
5010
  onChange: handleInput,
4894
5011
  onKeyDown: onKeyDown,
4895
- value: localValue
5012
+ value: localValue,
5013
+ variables: variables
4896
5014
  });
4897
5015
  setEditor(editor);
4898
- }, []);
5016
+ return () => {
5017
+ inputRef.current.innerHTML = '';
5018
+ setEditor(null);
5019
+ };
5020
+ }, [variables]);
4899
5021
  hooks.useEffect(() => {
4900
5022
  if (!editor) {
4901
5023
  return;
@@ -4983,10 +5105,20 @@ function FeelTextfield(props) {
4983
5105
  OptionalComponent = OptionalFeelInput
4984
5106
  } = props;
4985
5107
  const [localValue, _setLocalValue] = hooks.useState(value);
4986
- const ref = useShowEntryEvent(id);
5108
+ const editorRef = useShowEntryEvent(id);
5109
+ const containerRef = hooks.useRef();
4987
5110
  const feelActive = localValue.startsWith('=') || feel === 'required';
4988
5111
  const feelOnlyValue = localValue.substring(1);
4989
- const [focus, setFocus] = hooks.useState();
5112
+ const [focus, _setFocus] = hooks.useState(undefined);
5113
+
5114
+ const setFocus = (offset = 0) => {
5115
+ const hasFocus = containerRef.current.contains(document.activeElement); // Keep carret position if it is already focused, otherwise focus at the end
5116
+
5117
+ const position = hasFocus ? document.activeElement.selectionStart : Infinity;
5118
+
5119
+ _setFocus(position + offset);
5120
+ };
5121
+
4990
5122
  const handleInputCallback = hooks.useMemo(() => {
4991
5123
  return debounce(newValue => {
4992
5124
  onInput(newValue);
@@ -5027,14 +5159,16 @@ function FeelTextfield(props) {
5027
5159
  setLocalValue(newValue);
5028
5160
 
5029
5161
  if (!feelActive && newValue.startsWith('=')) {
5030
- setFocus(true);
5162
+ // focus is behind `=` sign that will be removed
5163
+ setFocus(-1);
5031
5164
  }
5032
5165
  };
5033
5166
 
5034
5167
  hooks.useEffect(() => {
5035
- if (focus) {
5036
- ref.current.focus();
5037
- setFocus(false);
5168
+ if (typeof focus !== 'undefined') {
5169
+ editorRef.current.focus(focus);
5170
+
5171
+ _setFocus(undefined);
5038
5172
  }
5039
5173
  }, [focus]);
5040
5174
  hooks.useEffect(() => {
@@ -5049,13 +5183,47 @@ function FeelTextfield(props) {
5049
5183
  }
5050
5184
 
5051
5185
  setLocalValue(value);
5052
- }, [value]);
5186
+ }, [value]); // copy-paste integration
5187
+
5188
+ hooks.useEffect(() => {
5189
+ const copyHandler = event => {
5190
+ if (!feelActive) {
5191
+ return;
5192
+ }
5193
+
5194
+ event.clipboardData.setData('application/FEEL', event.clipboardData.getData('text'));
5195
+ };
5196
+
5197
+ const pasteHandler = event => {
5198
+ if (feelActive) {
5199
+ return;
5200
+ }
5201
+
5202
+ const data = event.clipboardData.getData('application/FEEL');
5203
+
5204
+ if (data) {
5205
+ setTimeout(() => {
5206
+ handleFeelToggle();
5207
+ setFocus();
5208
+ });
5209
+ }
5210
+ };
5211
+
5212
+ containerRef.current.addEventListener('copy', copyHandler);
5213
+ containerRef.current.addEventListener('cut', copyHandler);
5214
+ containerRef.current.addEventListener('paste', pasteHandler);
5215
+ return () => {
5216
+ containerRef.current.removeEventListener('copy', copyHandler);
5217
+ containerRef.current.removeEventListener('cut', copyHandler);
5218
+ containerRef.current.removeEventListener('paste', pasteHandler);
5219
+ };
5220
+ }, [containerRef, feelActive, handleFeelToggle, setFocus]);
5053
5221
  return jsxRuntime.jsxs("div", {
5054
5222
  class: "bio-properties-panel-feel-entry",
5055
5223
  children: [jsxRuntime.jsxs("label", {
5056
5224
  for: prefixId$6(id),
5057
5225
  class: "bio-properties-panel-label",
5058
- onClick: () => setFocus(true),
5226
+ onClick: () => setFocus(),
5059
5227
  children: [label, jsxRuntime.jsx(FeelIcon, {
5060
5228
  label: label,
5061
5229
  feel: feel,
@@ -5064,6 +5232,7 @@ function FeelTextfield(props) {
5064
5232
  })]
5065
5233
  }), jsxRuntime.jsxs("div", {
5066
5234
  class: "bio-properties-panel-feel-container",
5235
+ ref: containerRef,
5067
5236
  children: [jsxRuntime.jsx(FeelIndicator, {
5068
5237
  active: feelActive,
5069
5238
  disabled: feel !== 'optional' || disabled,
@@ -5075,14 +5244,15 @@ function FeelTextfield(props) {
5075
5244
  disabled: disabled,
5076
5245
  onFeelToggle: () => {
5077
5246
  handleFeelToggle();
5078
- setFocus(true);
5247
+ setFocus();
5079
5248
  },
5080
5249
  value: feelOnlyValue,
5081
- ref: ref
5250
+ variables: props.variables,
5251
+ ref: editorRef
5082
5252
  }) : jsxRuntime.jsx(OptionalComponent, { ...props,
5083
5253
  onInput: handleLocalInput,
5084
5254
  value: localValue,
5085
- ref: ref
5255
+ ref: editorRef
5086
5256
  })]
5087
5257
  })]
5088
5258
  });
@@ -5099,7 +5269,7 @@ const OptionalFeelInput = compat.forwardRef((props, ref) => {
5099
5269
  // this ensures clean editing experience when switching with the keyboard
5100
5270
 
5101
5271
  ref.current = {
5102
- focus: () => {
5272
+ focus: position => {
5103
5273
  const input = inputRef.current;
5104
5274
 
5105
5275
  if (!input) {
@@ -5107,7 +5277,14 @@ const OptionalFeelInput = compat.forwardRef((props, ref) => {
5107
5277
  }
5108
5278
 
5109
5279
  input.focus();
5110
- input.setSelectionRange(0, 0);
5280
+
5281
+ if (typeof position === 'number') {
5282
+ if (position > value.length) {
5283
+ position = value.length;
5284
+ }
5285
+
5286
+ input.setSelectionRange(position, position);
5287
+ }
5111
5288
  }
5112
5289
  };
5113
5290
  return jsxRuntime.jsx("input", {
@@ -5237,8 +5414,9 @@ function FeelEntry(props) {
5237
5414
  example: props.example,
5238
5415
  show: show,
5239
5416
  value: value,
5417
+ variables: props.variables,
5240
5418
  OptionalComponent: props.OptionalComponent
5241
- }), error && jsxRuntime.jsx("div", {
5419
+ }, element), error && jsxRuntime.jsx("div", {
5242
5420
  class: "bio-properties-panel-error",
5243
5421
  children: error
5244
5422
  }), jsxRuntime.jsx(Description, {
@@ -5568,7 +5746,7 @@ function NumberFieldEntry(props) {
5568
5746
  min: min,
5569
5747
  step: step,
5570
5748
  value: value
5571
- }), jsxRuntime.jsx(Description, {
5749
+ }, element), jsxRuntime.jsx(Description, {
5572
5750
  forId: id,
5573
5751
  element: element,
5574
5752
  value: description
@@ -5674,7 +5852,7 @@ function SelectEntry(props) {
5674
5852
  onChange: setValue,
5675
5853
  options: options,
5676
5854
  disabled: disabled
5677
- }), error && jsxRuntime.jsx("div", {
5855
+ }, element), error && jsxRuntime.jsx("div", {
5678
5856
  class: "bio-properties-panel-error",
5679
5857
  children: error
5680
5858
  }), jsxRuntime.jsx(Description, {
@@ -5738,7 +5916,7 @@ function Simple(props) {
5738
5916
  onFocus: onFocus,
5739
5917
  onBlur: onBlur,
5740
5918
  value: localValue
5741
- })
5919
+ }, element)
5742
5920
  });
5743
5921
  }
5744
5922
  function isEdited$3(node) {
@@ -5832,7 +6010,7 @@ function TextAreaEntry(props) {
5832
6010
  const value = getValue(element);
5833
6011
  const error = useError(id);
5834
6012
  return jsxRuntime.jsxs("div", {
5835
- class: "bio-properties-panel-entry",
6013
+ class: classnames__default["default"]('bio-properties-panel-entry', error ? 'has-error' : ''),
5836
6014
  "data-entry-id": id,
5837
6015
  children: [jsxRuntime.jsx(TextArea, {
5838
6016
  id: id,
@@ -5843,7 +6021,7 @@ function TextAreaEntry(props) {
5843
6021
  debounce: debounce,
5844
6022
  monospace: monospace,
5845
6023
  disabled: disabled
5846
- }), error && jsxRuntime.jsx("div", {
6024
+ }, element), error && jsxRuntime.jsx("div", {
5847
6025
  class: "bio-properties-panel-error",
5848
6026
  children: error
5849
6027
  }), jsxRuntime.jsx(Description, {
@@ -5981,7 +6159,7 @@ function TextfieldEntry(props) {
5981
6159
  label: label,
5982
6160
  onInput: onInput,
5983
6161
  value: value
5984
- }), error && jsxRuntime.jsx("div", {
6162
+ }, element), error && jsxRuntime.jsx("div", {
5985
6163
  class: "bio-properties-panel-error",
5986
6164
  children: error
5987
6165
  }), jsxRuntime.jsx(Description, {