@malloydata/render 0.0.265-dev250416204239 → 0.0.265-dev250417230458

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.
@@ -1042,15 +1042,15 @@ Use (?: … ) instead`);if(!oe.lineBreaks&&j.test(`
1042
1042
  `))throw new Error("Rule should declare lineBreaks: "+j);fe.push(l(L))}}var z=q&&q.fallback,F=i&&!z?"ym":"gm",M=i||z?"":"|";X===!0&&(F+="u");var U=new RegExp(c(fe)+M,F);return{regexp:U,groups:ce,fast:Y,error:q||E}}function _(D){var k=A(y(D));return new S({start:k},"start")}function v(D,k,q){var Y=D&&(D.push||D.next);if(Y&&!q[Y])throw new Error("Missing state '"+Y+"' (in token '"+D.defaultType+"' of state '"+k+"')");if(D&&D.pop&&+D.pop!=1)throw new Error("pop must be 1 (in token '"+D.defaultType+"' of state '"+k+"')")}function C(D,k){var q=D.$all?y(D.$all):[];delete D.$all;var Y=Object.getOwnPropertyNames(D);k||(k=Y[0]);for(var Q=Object.create(null),X=0;X<Y.length;X++){var ce=Y[X];Q[ce]=y(D[ce]).concat(q)}for(var X=0;X<Y.length;X++)for(var ce=Y[X],fe=Q[ce],te=Object.create(null),oe=0;oe<fe.length;oe++){var xe=fe[oe];if(xe.include){var be=[oe,1];if(xe.include!==ce&&!te[xe.include]){te[xe.include]=!0;var I=Q[xe.include];if(!I)throw new Error("Cannot include nonexistent state '"+xe.include+"' (in state '"+ce+"')");for(var N=0;N<I.length;N++){var L=I[N];fe.indexOf(L)===-1&&be.push(L)}}fe.splice.apply(fe,be),oe--}}for(var j=Object.create(null),X=0;X<Y.length;X++){var ce=Y[X];j[ce]=A(Q[ce],!0)}for(var X=0;X<Y.length;X++){for(var V=Y[X],z=j[V],F=z.groups,oe=0;oe<F.length;oe++)v(F[oe],V,j);for(var M=Object.getOwnPropertyNames(z.fast),oe=0;oe<M.length;oe++)v(z.fast[M[oe]],V,j)}return new S(j,k)}function b(D){for(var k=typeof Map<"u",q=k?new Map:Object.create(null),Y=Object.getOwnPropertyNames(D),Q=0;Q<Y.length;Q++){var X=Y[Q],ce=D[X],fe=Array.isArray(ce)?ce:[ce];fe.forEach(function(te){if(typeof te!="string")throw new Error("keyword must be string (in keyword '"+X+"')");k?q.set(te,X):q[te]=X})}return function(te){return k?q.get(te):q[te]}}var S=function(D,k){this.startState=k,this.states=D,this.buffer="",this.stack=[],this.reset()};S.prototype.reset=function(D,k){return this.buffer=D||"",this.index=0,this.line=k?k.line:1,this.col=k?k.col:1,this.queuedToken=k?k.queuedToken:null,this.queuedText=k?k.queuedText:"",this.queuedThrow=k?k.queuedThrow:null,this.setState(k?k.state:this.startState),this.stack=k&&k.stack?k.stack.slice():[],this},S.prototype.save=function(){return{line:this.line,col:this.col,state:this.state,stack:this.stack.slice(),queuedToken:this.queuedToken,queuedText:this.queuedText,queuedThrow:this.queuedThrow}},S.prototype.setState=function(D){if(!(!D||this.state===D)){this.state=D;var k=this.states[D];this.groups=k.groups,this.error=k.error,this.re=k.regexp,this.fast=k.fast}},S.prototype.popState=function(){this.setState(this.stack.pop())},S.prototype.pushState=function(D){this.stack.push(this.state),this.setState(D)};var R=i?function(D,k){return D.exec(k)}:function(D,k){var q=D.exec(k);return q[0].length===0?null:q};S.prototype._getGroup=function(D){for(var k=this.groups.length,q=0;q<k;q++)if(D[q+1]!==void 0)return this.groups[q];throw new Error("Cannot find token type for matched text")};function O(){return this.value}if(S.prototype.next=function(){var D=this.index;if(this.queuedGroup){var k=this._token(this.queuedGroup,this.queuedText,D);return this.queuedGroup=null,this.queuedText="",k}var q=this.buffer;if(D!==q.length){var ce=this.fast[q.charCodeAt(D)];if(ce)return this._token(ce,q.charAt(D),D);var Y=this.re;Y.lastIndex=D;var Q=R(Y,q),X=this.error;if(Q==null)return this._token(X,q.slice(D,q.length),D);var ce=this._getGroup(Q),fe=Q[0];return X.fallback&&Q.index!==D?(this.queuedGroup=ce,this.queuedText=fe,this._token(X,q.slice(D,Q.index),D)):this._token(ce,fe,D)}},S.prototype._token=function(D,k,q){var Y=0;if(D.lineBreaks){var Q=/\n/g,X=1;if(k===`
1043
1043
  `)Y=1;else for(;Q.exec(k);)Y++,X=Q.lastIndex}var ce={type:typeof D.type=="function"&&D.type(k)||D.defaultType,value:typeof D.value=="function"?D.value(k):k,text:k,toString:O,offset:q,lineBreaks:Y,line:this.line,col:this.col},fe=k.length;if(this.index+=fe,this.line+=Y,Y!==0?this.col=fe-X+1:this.col+=fe,D.shouldThrow){var te=new Error(this.formatError(ce,"invalid syntax"));throw te}return D.pop?this.popState():D.push?this.pushState(D.push):D.next&&this.setState(D.next),ce},typeof Symbol<"u"&&Symbol.iterator){var B=function(D){this.lexer=D};B.prototype.next=function(){var D=this.lexer.next();return{value:D,done:!D}},B.prototype[Symbol.iterator]=function(){return this},S.prototype[Symbol.iterator]=function(){return new B(this)}}return S.prototype.formatError=function(D,k){if(D==null)var q=this.buffer.slice(this.index),D={text:q,offset:this.index,lineBreaks:q.indexOf(`
1044
1044
  `)===-1?0:1,line:this.line,col:this.col};var Y=2,Q=Math.max(D.line-Y,1),X=D.line+Y,ce=String(X).length,fe=h(this.buffer,this.line-D.line+Y+1).slice(0,5),te=[];te.push(k+" at line "+D.line+" col "+D.col+":"),te.push("");for(var oe=0;oe<fe.length;oe++){var xe=fe[oe],be=Q+oe;te.push(x(String(be),ce)+" "+xe),be===D.line&&te.push(x("",ce+D.col+1)+"^")}return te.join(`
1045
- `)},S.prototype.clone=function(){return new S(this.states,this.state)},S.prototype.has=function(D){return!0},{compile:_,states:C,error:Object.freeze({error:!0}),fallback:Object.freeze({fallback:!0}),keywords:b}})})(dae);var ZB=dae.exports,qt={};Object.defineProperty(qt,"__esModule",{value:!0}),qt.mkUnits=qt.timeLiteral=qt.joinTemporal=qt.temporalNot=qt.numNot=qt.mkValues=qt.mkRange=qt.joinNumbers=qt.conjoin=qt.matchOp=qt.escape=qt.unescape=qt.maybeNot=void 0;const Ca=bn;function LJe(t){const[e,r]=t;return e&&r&&(0,Ca.isStringFilter)(r)?{...r,not:!0}:r}qt.maybeNot=LJe;function Sy(t){return t.replace(/\\(.)/g,"$1")}qt.unescape=Sy;function IJe(t){const e=t.toLowerCase();return e==="null"||e==="empty"?"\\"+t:t.replace(/([,; |()\\%_-])/g,"\\$1")}qt.escape=IJe;function M4(t){let e=!1,r=!1,i=0,s=!1;const o=t.length;for(let u=0;u<o;u+=1){const a=t[u];if(a===" "||a===" "){i+=1;continue}i=0,a==="%"?(s=!0,u===0&&(e=!0),r=!0):(r=!1,a==="\\"?u+=1:a==="_"&&(s=!0))}return{hasLike:s,percentEnd:r&&o>1,percentStart:e&&o>1,endSpace:i}}function BJe(t){let e=t.trimStart();const{hasLike:r,percentEnd:i,percentStart:s,endSpace:o}=M4(e);if(o>0&&(e=e.slice(0,-o)),r){if(s&&i){const u=e.slice(1,-1);if(!M4(u).hasLike&&u.length>0)return{operator:"contains",values:[Sy(u)]}}else if(i){const u=e.slice(0,-1);if(!M4(u).hasLike)return{operator:"starts",values:[Sy(u)]}}else if(s){const u=e.slice(1);if(!M4(u).hasLike)return{operator:"ends",values:[Sy(u)]}}return{operator:"~",escaped_values:[e]}}return e.toLowerCase()==="null"||e==="NULL"?{operator:"null"}:e==="empty"||e==="EMPTY"?{operator:"empty"}:{operator:"=",values:[Sy(e)]}}qt.matchOp=BJe;function e$(t,e){var r,i;return t.operator===e.operator&&((r=t.not)!==null&&r!==void 0?r:!1)===((i=e.not)!==null&&i!==void 0?i:!1)}function $Je(t,e,r){if((0,Ca.isStringFilter)(t)&&(0,Ca.isStringFilter)(r)){if(e===","){if(t.operator==="~"&&e$(t,r))return{...t,escaped_values:[...t.escaped_values,...r.escaped_values]};if((0,Ca.isStringCondition)(t)&&e$(t,r))return{...t,values:[...t.values,...r.values]}}const i=e===","?",":e==="|"?"or":e===";"?"and":void 0;if(i)return t.operator===i?{...t,members:[...t.members,r]}:{operator:i,members:[t,r]}}return null}qt.conjoin=$Je;function kJe(t,e,r){if((0,Ca.isNumberFilter)(t)&&(0,Ca.isNumberFilter)(r)){if(e==="or"&&t.operator==="="&&e$(t,r)){const i={operator:"=",values:[...t.values,...r.values]};return t.not&&(i.not=!0),i}if(e==="and"||e==="or")return t.operator===e?{...t,members:[...t.members,r]}:{operator:e,members:[t,r]}}return null}qt.joinNumbers=kJe;function MJe(t,e,r,i){return{operator:"range",startValue:e,startOperator:t==="("?">":">=",endValue:r,endOperator:i===")"?"<":"<="}}qt.mkRange=MJe;function PJe(t,e){return{values:[t,...e]}}qt.mkValues=PJe;function UJe(t,e){return(0,Ca.isNumberFilter)(t)&&e?t.operator==="="?{operator:"!=",values:t.values}:t.operator==="!="?{operator:"=",values:t.values}:{...t,not:!0}:t}qt.numNot=UJe;function jJe(t,e){return(0,Ca.isTemporalFilter)(t)&&e?{...t,not:!0}:t}qt.temporalNot=jJe;function qJe(t,e,r){return(0,Ca.isTemporalFilter)(t)&&(0,Ca.isTemporalFilter)(r)&&(e==="and"||e==="or")?t.operator===e?{...t,members:[...t.members,r]}:{operator:e,members:[t,r]}:null}qt.joinTemporal=qJe;function HJe(t,e){const r={moment:"literal",literal:t};return e&&(r.units=e),r}qt.timeLiteral=HJe;function QJe(t){switch(t.toLowerCase()){case"second":case"seconds":return"second";case"minute":case"minutes":return"minute";case"hour":case"hours":return"hour";case"day":case"days":return"day";case"week":case"weeks":return"week";case"month":case"months":return"month";case"quarter":case"quarters":return"quarter";case"year":case"years":return"year"}}qt.mkUnits=QJe;var zJe=T&&T.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(XB,"__esModule",{value:!0});function GJe(t){return t[0]}const hae=zJe(ZB),Hp=qt,Ln=hae.default.compile({WS:/[ \t]+/,id:{match:/[a-zA-Z]+/,type:hae.default.keywords({AND:"and",OR:"or",NOT:"not",NULL_KW:"null",TO:"to"})},oparen:"(",cparen:")",obrack:"[",cbrack:"]",comma:",",op:/<=|>=|<|>/,ne:"!=",eq:"=",float:/-?(?:\d+)?\.\d+(?:[Ee][+-]?\d+)?/,numberE:/-?\d+[Ee][+-]?\d+/,integer:/-?\d+/}),WJe=Ln.next;Ln.next=(t=>()=>{for(;;){const e=t.call(Ln);if(e===void 0||e.type!=="WS")return e}})(WJe);const VJe={Lexer:Ln,ParserRules:[{name:"numberFilter",symbols:["numberFilter","conjunction","numberUnary"],postprocess:([t,e,r])=>(0,Hp.joinNumbers)(t,e[0].text,r)},{name:"numberFilter",symbols:["numberUnary"],postprocess:t=>t[0]},{name:"numberUnary$ebnf$1",symbols:[Ln.has("NOT")?{type:"NOT"}:NOT],postprocess:GJe},{name:"numberUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"numberUnary",symbols:["numberUnary$ebnf$1","clause"],postprocess:([t,e])=>(0,Hp.numNot)(e,t)},{name:"clause",symbols:[Ln.has("NULL_KW")?{type:"NULL_KW"}:NULL_KW],postprocess:()=>({operator:"null"})},{name:"clause$ebnf$1",symbols:[]},{name:"clause$ebnf$1",symbols:["clause$ebnf$1","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:["N","clause$ebnf$1"],postprocess:([t,e])=>({operator:"=",...(0,Hp.mkValues)(t,e)})},{name:"clause$ebnf$2",symbols:[]},{name:"clause$ebnf$2",symbols:["clause$ebnf$2","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:[Ln.has("eq")?{type:"eq"}:eq,"N","clause$ebnf$2"],postprocess:([t,e,r])=>({operator:"=",...(0,Hp.mkValues)(e,r)})},{name:"clause$ebnf$3",symbols:[]},{name:"clause$ebnf$3",symbols:["clause$ebnf$3","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:[Ln.has("ne")?{type:"ne"}:ne,"N","clause$ebnf$3"],postprocess:([t,e,r])=>({operator:"!=",...(0,Hp.mkValues)(e,r)})},{name:"clause",symbols:[Ln.has("op")?{type:"op"}:op,"N"],postprocess:([t,e])=>({operator:t.text,values:[e]})},{name:"clause",symbols:[Ln.has("oparen")?{type:"oparen"}:oparen,"numberFilter",Ln.has("cparen")?{type:"cparen"}:cparen],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"clause",symbols:["openInterval","N",Ln.has("TO")?{type:"TO"}:TO,"N","closeInterval"],postprocess:([t,e,r,i,s])=>(0,Hp.mkRange)(t[0].text,e,i,s[0].text)},{name:"numberList",symbols:[Ln.has("comma")?{type:"comma"}:comma,"N"],postprocess:([t,e])=>e},{name:"closeInterval",symbols:[Ln.has("cbrack")?{type:"cbrack"}:cbrack]},{name:"closeInterval",symbols:[Ln.has("cparen")?{type:"cparen"}:cparen]},{name:"openInterval",symbols:[Ln.has("obrack")?{type:"obrack"}:obrack]},{name:"openInterval",symbols:[Ln.has("oparen")?{type:"oparen"}:oparen]},{name:"N$subexpression$1",symbols:[Ln.has("float")?{type:"float"}:float]},{name:"N$subexpression$1",symbols:[Ln.has("numberE")?{type:"numberE"}:numberE]},{name:"N$subexpression$1",symbols:[Ln.has("integer")?{type:"integer"}:integer]},{name:"N",symbols:["N$subexpression$1"],postprocess:([t])=>t[0].text},{name:"conjunction",symbols:[Ln.has("OR")?{type:"OR"}:OR]},{name:"conjunction",symbols:[Ln.has("AND")?{type:"AND"}:AND]}],ParserStart:"numberFilter"};XB.default=VJe;var Qp={};Object.defineProperty(Qp,"__esModule",{value:!0}),Qp.run_parser=void 0;const YJe=bn;function KJe(t,e){try{e.feed(t);const i=e.finish()[0];return(0,YJe.isFilterExpression)(i)?{parsed:i,log:[]}:{parsed:null,log:[]}}catch(r){let i=r.message,s=1,o=t.length;if(r.token){const u=r.token;s=u.col,o=u.text.length;const l=r.message.match(new RegExp("(?<=A ).*(?= based on:)","g")).map(c=>c.replace(/\s+token/i,""));i=`Unexpected ${u.type} token "${u.value}"`,l&&l.length&&(i+=` Tokens expected: ${[...new Set(l)]}`)}return{parsed:null,log:[{message:i,startIndex:s-1,endIndex:s-1+o-1,severity:"error"}]}}}Qp.run_parser=KJe,function(t){var e=T&&T.__createBinding||(Object.create?function(c,f,x,h){h===void 0&&(h=x);var p=Object.getOwnPropertyDescriptor(f,x);(!p||("get"in p?!f.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return f[x]}}),Object.defineProperty(c,h,p)}:function(c,f,x,h){h===void 0&&(h=x),c[h]=f[x]}),r=T&&T.__setModuleDefault||(Object.create?function(c,f){Object.defineProperty(c,"default",{enumerable:!0,value:f})}:function(c,f){c.default=f}),i=T&&T.__importStar||function(c){if(c&&c.__esModule)return c;var f={};if(c!=null)for(var x in c)x!=="default"&&Object.prototype.hasOwnProperty.call(c,x)&&e(f,c,x);return r(f,c),f},s=T&&T.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(t,"__esModule",{value:!0}),t.NumberFilterExpression=void 0;const o=bn,u=i(JB),a=s(XB),l=Qp;t.NumberFilterExpression={parse(c){if(c.match(/^\s*$/))return{parsed:null,log:[]};const f=new u.Parser(u.Grammar.fromCompiled(a.default)),x=(0,l.run_parser)(c,f);return x.parsed&&(0,o.isNumberFilter)(x.parsed)?{parsed:x.parsed,log:[]}:{parsed:null,log:x.log}},unparse(c){if(c===null)return"";switch(c.operator){case"=":return c.values.join(", ");case"!=":return"!= "+c.values.join(", ");case">":case"<":case"<=":case">=":return c.not?c.values.map(f=>c.operator==="="?`not ${f}`:`not ${c.operator} ${f}`).join(", "):c.values.map(f=>`${c.operator} ${f}`).join(", ");case"range":{const f=c.startOperator===">"?"(":"[",x=c.endOperator==="<"?")":"]",h=`${f}${c.startValue} to ${c.endValue}${x}`;return c.not?`not ${h}`:h}case"null":return c.not?"not null":"null";case"and":case"or":return c.members.map(f=>t.NumberFilterExpression.unparse(f)).join(` ${c.operator} `);case"()":{const f="("+t.NumberFilterExpression.unparse(c.expr)+")";return c.not?"not "+f:f}}return`no unparse for ${JSON.stringify(c)}`}}}(fae);var pae={},t$={},JJe=T&&T.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(t$,"__esModule",{value:!0});function XJe(t){return t[0]}const ZJe=JJe(ZB),n$=qt,fu=ZJe.default.compile({WS:/[ \t]+/,comma:",",semi:";",or:"|",open:"(",close:")",minus:"-",matchStr:/(?:\\[^\n]|[^\n,;()|])+/}),eXe=fu.next;fu.next=(t=>()=>{for(;;){const e=t.call(fu);if(e==null||e.type!=="WS")return e}})(eXe);const tXe={Lexer:fu,ParserRules:[{name:"stringFilter",symbols:["stringFilter","conjunction","sfUnary"],postprocess:([t,e,r])=>(0,n$.conjoin)(t,e[0].text,r)},{name:"stringFilter",symbols:["sfUnary"],postprocess:t=>t[0]},{name:"sfUnary$ebnf$1",symbols:[fu.has("minus")?{type:"minus"}:minus],postprocess:XJe},{name:"sfUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"sfUnary",symbols:["sfUnary$ebnf$1","clause"],postprocess:t=>(0,n$.maybeNot)(t)},{name:"parens",symbols:[fu.has("open")?{type:"open"}:open,"stringFilter",fu.has("close")?{type:"close"}:close],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"clause",symbols:[fu.has("matchStr")?{type:"matchStr"}:matchStr],postprocess:([t])=>(0,n$.matchOp)(t.text)},{name:"clause",symbols:["parens"],postprocess:t=>t[0]},{name:"conjunction",symbols:[fu.has("comma")?{type:"comma"}:comma]},{name:"conjunction",symbols:[fu.has("semi")?{type:"semi"}:semi]},{name:"conjunction",symbols:[fu.has("or")?{type:"or"}:or]}],ParserStart:"stringFilter"};t$.default=tXe,function(t){var e=T&&T.__createBinding||(Object.create?function(f,x,h,p){p===void 0&&(p=h);var m=Object.getOwnPropertyDescriptor(x,h);(!m||("get"in m?!x.__esModule:m.writable||m.configurable))&&(m={enumerable:!0,get:function(){return x[h]}}),Object.defineProperty(f,p,m)}:function(f,x,h,p){p===void 0&&(p=h),f[p]=x[h]}),r=T&&T.__setModuleDefault||(Object.create?function(f,x){Object.defineProperty(f,"default",{enumerable:!0,value:x})}:function(f,x){f.default=x}),i=T&&T.__importStar||function(f){if(f&&f.__esModule)return f;var x={};if(f!=null)for(var h in f)h!=="default"&&Object.prototype.hasOwnProperty.call(f,h)&&e(x,f,h);return r(x,f),x},s=T&&T.__importDefault||function(f){return f&&f.__esModule?f:{default:f}};Object.defineProperty(t,"__esModule",{value:!0}),t.StringFilterExpression=void 0;const o=bn,u=i(JB),a=s(t$),l=qt,c=Qp;t.StringFilterExpression={parse(f){if(f.match(/^\s*$/))return{parsed:null,log:[]};const x=new u.Parser(u.Grammar.fromCompiled(a.default)),h=(0,c.run_parser)(f,x);return h.parsed&&(0,o.isStringFilter)(h.parsed)?{parsed:h.parsed,log:[]}:{parsed:null,log:h.log}},unparse(f){if(f===null)return"";switch(f.operator){case"=":return f.not?f.values.map(x=>"-"+(0,l.escape)(x)).join(", "):f.values.map(x=>(0,l.escape)(x)).join(", ");case"~":return f.not?f.escaped_values.map(x=>"-"+x).join(", "):f.escaped_values.join(", ");case"starts":return f.not?f.values.map(x=>"-"+(0,l.escape)(x)+"%").join(", "):f.values.map(x=>(0,l.escape)(x)+"%").join(", ");case"ends":return f.not?f.values.map(x=>"-%"+(0,l.escape)(x)).join(", "):f.values.map(x=>"%"+(0,l.escape)(x)).join(", ");case"contains":return f.not?f.values.map(x=>"-%"+(0,l.escape)(x)+"%").join(", "):f.values.map(x=>"%"+(0,l.escape)(x)+"%").join(", ");case"or":return f.members.map(x=>t.StringFilterExpression.unparse(x)).join(" | ");case"and":return f.members.map(x=>t.StringFilterExpression.unparse(x)).join("; ");case",":return f.members.map(x=>t.StringFilterExpression.unparse(x)).join(", ");case"()":{const x="("+t.StringFilterExpression.unparse(f.expr)+")";return f.not?"-"+x:x}case"null":return f.not?"-null":"null";case"empty":return f.not?"-empty":"empty"}}}}(pae);var mae={},r$={},nXe=T&&T.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(r$,"__esModule",{value:!0});function rXe(t){return t[0]}const gae=nXe(ZB),xu=qt,Ke=gae.default.compile({WS:/[ \t]+/,id:{match:/[a-zA-Z]+/,type:gae.default.keywords({AND:"and",OR:"or",NOT:"not",NULL_KW:"null",TO:"to",NOW:"now",LAST:"last",THIS:"this",NEXT:"next",AGO:"ago",FROM:"from",BEFORE:"before",AFTER:"after",FOR:"for",TODAY:"today",YESTERDAY:"yesterday",TOMORROW:"tomorrow",SECOND:"second",MINUTE:"minute",HOUR:"hour",DAY:"day",WEEK:"week",MONTH:"month",QUARTER:"quarter",YEAR:"year",SECONDS:"seconds",MINUTES:"minutes",HOURS:"hours",DAYS:"days",WEEKS:"weeks",MONTHS:"months",QUARTERS:"quarters",YEARS:"years",MONDAY:"monday",TUESDAY:"tuesday",WEDNESDAY:"wednesday",THURSDAY:"thursday",FRIDAY:"friday",SATURDAY:"saturday",SUNDAY:"sunday"})},oparen:"(",cparen:")",comma:",",literal:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d:\d\d(?::\d\d(?:[.,]\d*)?)/,lit_week:/\d\d\d\d-\d\d-\d\d-[Ww][Kk]/,lit_quarter:/\d\d\d\d-[qQ][1234]/,lit_min:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d:\d\d/,lit_hour:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d/,lit_day:/\d\d\d\d-\d\d-\d\d/,lit_month:/\d\d\d\d-\d\d/,lit_year:/\d\d\d\d/,n:/\d+/}),iXe=Ke.next;Ke.next=(t=>()=>{for(;;){const e=t.call(Ke);if(e===void 0||e.type!=="WS")return e}})(iXe);const sXe={Lexer:Ke,ParserRules:[{name:"temporalFilter",symbols:["temporalFilter","conjunction","temporalUnary"],postprocess:([t,e,r])=>(0,xu.joinTemporal)(t,e[0].text,r)},{name:"temporalFilter",symbols:["temporalUnary"],postprocess:t=>t[0]},{name:"temporalUnary$ebnf$1",symbols:[Ke.has("NOT")?{type:"NOT"}:NOT],postprocess:rXe},{name:"temporalUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"temporalUnary",symbols:["temporalUnary$ebnf$1","clause"],postprocess:([t,e])=>(0,xu.temporalNot)(e,t)},{name:"duration",symbols:["number","unit"],postprocess:([t,e])=>({units:e,n:t})},{name:"number",symbols:[Ke.has("n")?{type:"n"}:n],postprocess:([t])=>t.text},{name:"number",symbols:[Ke.has("lityear")?{type:"lityear"}:lityear],postprocess:([t])=>t.text},{name:"unit$subexpression$1",symbols:[Ke.has("SECOND")?{type:"SECOND"}:SECOND]},{name:"unit$subexpression$1",symbols:[Ke.has("MINUTE")?{type:"MINUTE"}:MINUTE]},{name:"unit$subexpression$1",symbols:[Ke.has("HOUR")?{type:"HOUR"}:HOUR]},{name:"unit$subexpression$1",symbols:[Ke.has("DAY")?{type:"DAY"}:DAY]},{name:"unit$subexpression$1",symbols:[Ke.has("WEEK")?{type:"WEEK"}:WEEK]},{name:"unit$subexpression$1",symbols:[Ke.has("MONTH")?{type:"MONTH"}:MONTH]},{name:"unit$subexpression$1",symbols:[Ke.has("QUARTER")?{type:"QUARTER"}:QUARTER]},{name:"unit$subexpression$1",symbols:[Ke.has("YEAR")?{type:"YEAR"}:YEAR]},{name:"unit$subexpression$1",symbols:[Ke.has("SECONDS")?{type:"SECONDS"}:SECONDS]},{name:"unit$subexpression$1",symbols:[Ke.has("MINUTES")?{type:"MINUTES"}:MINUTES]},{name:"unit$subexpression$1",symbols:[Ke.has("HOURS")?{type:"HOURS"}:HOURS]},{name:"unit$subexpression$1",symbols:[Ke.has("DAYS")?{type:"DAYS"}:DAYS]},{name:"unit$subexpression$1",symbols:[Ke.has("WEEKS")?{type:"WEEKS"}:WEEKS]},{name:"unit$subexpression$1",symbols:[Ke.has("MONTHS")?{type:"MONTHS"}:MONTHS]},{name:"unit$subexpression$1",symbols:[Ke.has("QUARTERS")?{type:"QUARTERS"}:QUARTERS]},{name:"unit$subexpression$1",symbols:[Ke.has("YEARS")?{type:"YEARS"}:YEARS]},{name:"unit",symbols:["unit$subexpression$1"],postprocess:([t])=>(0,xu.mkUnits)(t[0].text)},{name:"clause",symbols:[Ke.has("NULL_KW")?{type:"NULL_KW"}:NULL_KW],postprocess:()=>({operator:"null"})},{name:"clause",symbols:["parens"],postprocess:t=>t[0]},{name:"clause",symbols:["duration"],postprocess:([t])=>({operator:"in_last",...t})},{name:"clause",symbols:[Ke.has("BEFORE")?{type:"BEFORE"}:BEFORE,"moment"],postprocess:([t,e])=>({operator:"before",before:e})},{name:"clause",symbols:[Ke.has("AFTER")?{type:"AFTER"}:AFTER,"moment"],postprocess:([t,e])=>({operator:"after",after:e})},{name:"clause",symbols:["moment",Ke.has("TO")?{type:"TO"}:TO,"moment"],postprocess:([t,e,r])=>({operator:"to",fromMoment:t,toMoment:r})},{name:"clause",symbols:["moment",Ke.has("FOR")?{type:"FOR"}:FOR,"duration"],postprocess:([t,e,r])=>({...r,operator:"for",begin:t})},{name:"clause$subexpression$1",symbols:[Ke.has("LAST")?{type:"LAST"}:LAST]},{name:"clause$subexpression$1",symbols:[Ke.has("NEXT")?{type:"NEXT"}:NEXT]},{name:"clause",symbols:["clause$subexpression$1","duration"],postprocess:([t,e])=>({operator:t[0].text,...e})},{name:"clause",symbols:["moment"],postprocess:([t])=>({operator:"in",in:t})},{name:"lastNextThis",symbols:[Ke.has("THIS")?{type:"THIS"}:THIS],postprocess:([t])=>t.text.toLowerCase()},{name:"lastNextThis",symbols:[Ke.has("NEXT")?{type:"NEXT"}:NEXT],postprocess:([t])=>t.text.toLowerCase()},{name:"lastNextThis",symbols:[Ke.has("LAST")?{type:"LAST"}:LAST],postprocess:([t])=>t.text.toLowerCase()},{name:"moment",symbols:[Ke.has("NOW")?{type:"NOW"}:NOW],postprocess:()=>({moment:"now"})},{name:"moment",symbols:["lastNextThis","unit"],postprocess:([t,e])=>({moment:t,units:e})},{name:"moment",symbols:[Ke.has("TODAY")?{type:"TODAY"}:TODAY],postprocess:()=>({moment:"today"})},{name:"moment",symbols:[Ke.has("YESTERDAY")?{type:"YESTERDAY"}:YESTERDAY],postprocess:()=>({moment:"yesterday"})},{name:"moment",symbols:[Ke.has("TOMORROW")?{type:"TOMORROW"}:TOMORROW],postprocess:()=>({moment:"tomorrow"})},{name:"moment",symbols:["duration",Ke.has("AGO")?{type:"AGO"}:AGO],postprocess:([t,e])=>({moment:"ago",...t})},{name:"moment",symbols:["duration",Ke.has("FROM")?{type:"FROM"}:FROM,Ke.has("NOW")?{type:"NOW"}:NOW],postprocess:([t,e])=>({moment:"from_now",...t})},{name:"moment",symbols:[Ke.has("NEXT")?{type:"NEXT"}:NEXT,"weekday"],postprocess:([t,e])=>({moment:e.toLowerCase(),which:"next"})},{name:"moment",symbols:[Ke.has("LAST")?{type:"LAST"}:LAST,"weekday"],postprocess:([t,e])=>({moment:e.toLowerCase(),which:"last"})},{name:"moment",symbols:["weekday"],postprocess:([t])=>({moment:t.toLowerCase(),which:"last"})},{name:"moment",symbols:["timeLiteral"],postprocess:t=>t[0]},{name:"timeLiteral",symbols:[Ke.has("literal")?{type:"literal"}:literal],postprocess:([t])=>(0,xu.timeLiteral)(t.text)},{name:"timeLiteral",symbols:[Ke.has("lit_day")?{type:"lit_day"}:lit_day],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"day")},{name:"timeLiteral",symbols:[Ke.has("lit_min")?{type:"lit_min"}:lit_min],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"minute")},{name:"timeLiteral",symbols:[Ke.has("lit_hour")?{type:"lit_hour"}:lit_hour],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"hour")},{name:"timeLiteral",symbols:[Ke.has("lit_month")?{type:"lit_month"}:lit_month],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"month")},{name:"timeLiteral",symbols:[Ke.has("lit_quarter")?{type:"lit_quarter"}:lit_quarter],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"quarter")},{name:"timeLiteral",symbols:[Ke.has("lit_week")?{type:"lit_week"}:lit_week],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"week")},{name:"timeLiteral",symbols:[Ke.has("lit_year")?{type:"lit_year"}:lit_year],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"year")},{name:"weekday$subexpression$1",symbols:[Ke.has("MONDAY")?{type:"MONDAY"}:MONDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("TUESDAY")?{type:"TUESDAY"}:TUESDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("WEDNESDAY")?{type:"WEDNESDAY"}:WEDNESDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("THURSDAY")?{type:"THURSDAY"}:THURSDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("FRIDAY")?{type:"FRIDAY"}:FRIDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("SATURDAY")?{type:"SATURDAY"}:SATURDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("SUNDAY")?{type:"SUNDAY"}:SUNDAY]},{name:"weekday",symbols:["weekday$subexpression$1"],postprocess:([t])=>t[0].text},{name:"parens",symbols:[Ke.has("oparen")?{type:"oparen"}:oparen,"temporalFilter",Ke.has("cparen")?{type:"cparen"}:cparen],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"conjunction",symbols:[Ke.has("OR")?{type:"OR"}:OR]},{name:"conjunction",symbols:[Ke.has("AND")?{type:"AND"}:AND]}],ParserStart:"temporalFilter"};r$.default=sXe,function(t){var e=T&&T.__createBinding||(Object.create?function(h,p,m,g){g===void 0&&(g=m);var y=Object.getOwnPropertyDescriptor(p,m);(!y||("get"in y?!p.__esModule:y.writable||y.configurable))&&(y={enumerable:!0,get:function(){return p[m]}}),Object.defineProperty(h,g,y)}:function(h,p,m,g){g===void 0&&(g=m),h[g]=p[m]}),r=T&&T.__setModuleDefault||(Object.create?function(h,p){Object.defineProperty(h,"default",{enumerable:!0,value:p})}:function(h,p){h.default=p}),i=T&&T.__importStar||function(h){if(h&&h.__esModule)return h;var p={};if(h!=null)for(var m in h)m!=="default"&&Object.prototype.hasOwnProperty.call(h,m)&&e(p,h,m);return r(p,h),p},s=T&&T.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterExpression=void 0;const o=bn,u=s(r$),a=i(JB),l=Qp;t.TemporalFilterExpression={parse(h){if(h.match(/^\s*$/))return{parsed:null,log:[]};const p=new a.Parser(a.Grammar.fromCompiled(u.default)),m=(0,l.run_parser)(h,p);return m.parsed&&(0,o.isTemporalFilter)(m.parsed)?{parsed:m.parsed,log:[]}:{parsed:null,log:m.log}},unparse(h){if(h===null)return"";switch(h.operator){case"null":return c(h,"null");case"in":return c(h,x(h.in));case"()":return"("+t.TemporalFilterExpression.unparse(h.expr)+")";case"in_last":return c(h,f(h));case"last":case"next":return c(h,`${h.operator} ${f(h)}`);case"before":return c(h,`before ${x(h.before)}`);case"after":return c(h,`after ${x(h.after)}`);case"to":return c(h,`${x(h.fromMoment)} to ${x(h.toMoment)}`);case"for":return c(h,`${x(h.begin)} for ${f(h)}`);case"or":return h.members.map(p=>t.TemporalFilterExpression.unparse(p)).join(" or ");case"and":return h.members.map(p=>t.TemporalFilterExpression.unparse(p)).join(" and ")}}};function c(h,p){return"not"in h&&h.not?"not "+p:p}function f(h){return h.n==="1"?`1 ${h.units}`:`${h.n} ${h.units}s`}function x(h){switch(h.moment){case"literal":return h.literal;case"now":case"today":case"yesterday":case"tomorrow":return h.moment;case"monday":case"tuesday":case"wednesday":case"thursday":case"friday":case"saturday":case"sunday":return h.which==="next"?"next "+h.moment:h.moment;case"this":case"next":case"last":return`${h.moment} ${h.units}`;case"ago":return`${f(h)} ago`;case"from_now":return`${f(h)} from now`}}}(mae),function(t){var e=T&&T.__createBinding||(Object.create?function(a,l,c,f){f===void 0&&(f=c);var x=Object.getOwnPropertyDescriptor(l,c);(!x||("get"in x?!l.__esModule:x.writable||x.configurable))&&(x={enumerable:!0,get:function(){return l[c]}}),Object.defineProperty(a,f,x)}:function(a,l,c,f){f===void 0&&(f=c),a[f]=l[c]}),r=T&&T.__exportStar||function(a,l){for(var c in a)c!=="default"&&!Object.prototype.hasOwnProperty.call(l,c)&&e(l,a,c)};Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterExpression=t.StringFilterExpression=t.NumberFilterExpression=t.BooleanFilterExpression=void 0,r(bn,t);var i=k4;Object.defineProperty(t,"BooleanFilterExpression",{enumerable:!0,get:function(){return i.BooleanFilterExpression}});var s=fae;Object.defineProperty(t,"NumberFilterExpression",{enumerable:!0,get:function(){return s.NumberFilterExpression}});var o=pae;Object.defineProperty(t,"StringFilterExpression",{enumerable:!0,get:function(){return o.StringFilterExpression}});var u=mae;Object.defineProperty(t,"TemporalFilterExpression",{enumerable:!0,get:function(){return u.TemporalFilterExpression}})}(Cy);const by=gP(Q1e);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterCompiler=t.FilterCompilers=void 0;const e=Cy,r=Xe,i=by;function s(m){return m.replace(/([%_\\])/g,"\\$1")}function o(m){return m===">"?"<=":m==="<"?">=":m===">="?"<":">"}function u(m,g){const y=` OR ${g} IS NULL`;return m.length===1?`${m[0]}${y}`:`(${m.join(" AND ")})${y}`}t.FilterCompilers={compile(m,g,y,E){if(g===null)return"true";if(m==="string"&&(0,e.isStringFilter)(g))return t.FilterCompilers.stringCompile(g,y,E);if(m==="number"&&(0,e.isNumberFilter)(g))return t.FilterCompilers.numberCompile(g,y,E);if(m==="boolean"&&(0,e.isBooleanFilter)(g))return t.FilterCompilers.booleanCompile(g,y,E);if((m==="date"||m==="timestamp")&&(0,e.isTemporalFilter)(g))return t.FilterCompilers.temporalCompile(g,y,E,m);throw new Error("INTERNAL ERROR: No filter compiler for "+m)},numberCompile(m,g,y){switch(m.operator){case"!=":case"=":{const E=m.operator==="="&&m.not||m.operator==="!="&&!m.not,A=m.values.join(", ");return m.values.length===1?E?`${g} != ${A} OR ${g} IS NULL`:`${g} = ${A}`:E?`${g} NOT IN (${A}) OR ${g} IS NULL`:`${g} IN (${A})`}case">":case"<":case">=":case"<=":return m.values.map(E=>`${g} ${m.operator} ${E}`).join(m.not?" AND ":" OR ");case"range":{let E=m.startOperator,A=m.endOperator,_=" AND ";return m.not&&(E=o(E),A=o(A),_=" OR "),`${g} ${E} ${m.startValue} ${_} ${g} ${A} ${m.endValue}`}case"null":return m.not?`${g} IS NOT NULL`:`${g} IS NULL`;case"()":{const E="("+t.FilterCompilers.numberCompile(m.expr,g,y)+")";return m.not?`NOT ${E}`:E}case"and":case"or":return m.members.map(E=>t.FilterCompilers.numberCompile(E,g,y)).join(` ${m.operator.toUpperCase()} `)}},booleanCompile(m,g,y){switch(m.operator){case"false":return`${g} = false`;case"false_or_null":return`${g} IS NULL OR ${g} = false`;case"null":return m.not?`${g} IS NOT NULL`:`${g} IS NULL`;case"true":return g}},stringCompile(m,g,y){switch(m.operator){case"null":return m.not?`${g} IS NOT NULL`:`${g} IS NULL`;case"empty":return m.not?`COALESCE(${g},'') != ''`:`COALESCE(${g},'') = ''`;case"=":{if(m.values.length===1){const A=m.not?"!=":"=",_=`${g} ${A} ${y.sqlLiteralString(m.values[0])}`;return m.not?`(${_} OR ${g} IS NULL)`:_}const E="("+m.values.map(A=>y.sqlLiteralString(A)).join(", ")+")";return m.not?`(${g} NOT IN ${E} OR ${g} IS NULL)`:`${g} IN ${E}`}case"()":{const E="("+t.FilterCompilers.stringCompile(m.expr,g,y)+")";return m.not?`not ${E}`:E}case"contains":{const E=m.values.map(A=>"%"+s(A)+"%");return m.not?u(E.map(A=>y.sqlLike("NOT LIKE",g,A)),g):E.map(A=>y.sqlLike("LIKE",g,A)).join(" OR ")}case"starts":{const E=m.values.map(A=>s(A)+"%");return m.not?u(E.map(A=>y.sqlLike("NOT LIKE",g,A)),g):E.map(A=>y.sqlLike("LIKE",g,A)).join(" OR ")}case"ends":{const E=m.values.map(A=>"%"+s(A));return m.not?u(E.map(A=>y.sqlLike("NOT LIKE",g,A)),g):E.map(A=>y.sqlLike("LIKE",g,A)).join(" OR ")}case"~":return m.not?u(m.escaped_values.map(E=>y.sqlLike("NOT LIKE",g,E)),g):m.escaped_values.map(E=>y.sqlLike("LIKE",g,E)).join(" OR ");case"and":return m.members.map(A=>t.FilterCompilers.stringCompile(A,g,y)).join(" AND ");case"or":return m.members.map(A=>t.FilterCompilers.stringCompile(A,g,y)).join(" AND ");case",":{const E=[],A=[];let _=!1,v=!1,C=!1,b=!1;for(const O of m.members)switch(O.operator){case"or":case"and":case",":E.push(O);break;case"null":O.not?v=!0:_=!0;break;case"empty":O.not?(b=!0,v=!0):(C=!0,_=!0);break;default:(O.not?A:E).push(O)}if(C&&b||_&&v)return"false";let S="";if(E.length>0||_||C){b=!1,v=!1;const O=E.map(B=>t.FilterCompilers.stringCompile(B,g,y));C&&O.push(`${g} = ''`),_&&O.push(`${g} IS NULL`),S=O.join(" OR ")}let R="";if(A.length>0||b||v){const O=A.map(B=>t.FilterCompilers.stringCompile(B,g,y));b&&O.push(`${g} != ''`),v&&O.push(`${g} IS NOT NULL`),R=O.join(" AND ")}return S?R!==""?`(${S}) AND (${R})`:S:R!==""?R:"true"}}},temporalCompile(m,g,y,E){return new p(g,y,E).compile(m)}};const a="yyyy",l=`${a}-LL`,c=`${l}-dd`,f=`${c} HH`,x=`${f}:mm`,h=`${x}:ss`;class p{constructor(g,y,E="timestamp"){this.expr=g,this.timetype=E,this.d=y}time(g){return this.timetype==="timestamp"?g:this.d.sqlCast({},{node:"cast",e:{node:"genericSQLExpr",src:["",g],kids:{args:[]},sql:g},srcType:{type:"timestamp"},dstType:{type:"date"},safe:!1})}compile(g){const y=this.expr;switch(g.operator){case"after":return`${y} ${g.not?"<":">="} ${this.time(this.moment(g.after).end)}`;case"before":return`${y} ${g.not?">=":"<"} ${this.time(this.moment(g.before).begin.sql)}`;case"in":{const E=this.moment(g.in);return E.begin.sql===E.end?g.not?`${y} != ${this.time(E.end)} OR ${y} IS NULL`:`${y} = ${this.time(E.end)}`:this.isIn(g.not,E.begin.sql,E.end)}case"for":{const E=this.moment(g.begin),A=this.delta(E.begin,"+",g.n,g.units);return this.isIn(g.not,E.begin.sql,A.sql)}case"in_last":{const E=Number(g.n)-1,A=this.nowDot(g.units),_=E>0?this.delta(A,"-",E.toString(),g.units):A,v=this.delta(A,"+","1",g.units);return this.isIn(g.not,_.sql,v.sql)}case"to":{const E=this.moment(g.fromMoment),A=this.moment(g.toMoment);return this.isIn(g.not,E.begin.sql,A.begin.sql)}case"last":{const E=this.nowDot(g.units),A=this.delta(E,"-",g.n,g.units);return this.isIn(g.not,A.sql,E.sql)}case"next":{const E=this.nowDot(g.units),A=this.delta(E,"+","1",g.units),_=this.delta(E,"+",(Number(g.n)+1).toString(),g.units);return this.isIn(g.not,A.sql,_.sql)}case"null":return g.not?`${y} IS NOT NULL`:`${y} IS NULL`;case"()":{const E="("+this.compile(g.expr)+")";return g.not?`NOT ${E}`:E}case"and":case"or":return g.members.map(E=>this.compile(E)).join(` ${g.operator.toUpperCase()} `)}}expandLiteral(g){let y=g.literal;switch(g.units){case"year":{const E=i.DateTime.fromFormat(y,a),A=this.literalNode(E.toFormat(h)),_=E.plus({year:1});return{begin:A,end:this.literalNode(_.toFormat(h)).sql}}case"month":{const E=i.DateTime.fromFormat(y,l),A=this.literalNode(E.toFormat(h)),_=E.plus({month:1});return{begin:A,end:this.literalNode(_.toFormat(h)).sql}}case"day":{const E=i.DateTime.fromFormat(y,c),A=this.literalNode(E.toFormat(h)),_=E.plus({day:1});return{begin:A,end:this.literalNode(_.toFormat(h)).sql}}case"hour":{const E=i.DateTime.fromFormat(y,f),A=this.literalNode(E.toFormat(h)),_=E.plus({hour:1});return{begin:A,end:this.literalNode(_.toFormat(h)).sql}}case"minute":{const E=i.DateTime.fromFormat(y,x),A=this.literalNode(E.toFormat(h)),_=E.plus({minute:1});return{begin:A,end:this.literalNode(_.toFormat(h)).sql}}case"week":{const _=i.DateTime.fromFormat(y.slice(0,10),c).plus({day:1}).startOf("week").minus({day:1}),v=this.literalNode(_.toFormat(h)),C=_.plus({days:7});return{begin:v,end:this.literalNode(C.toFormat(h)).sql}}case"quarter":{const E=y.slice(0,4),A=y.slice(6);A==="1"?y=`${E}-01-01 00:00:00`:A==="2"?y=`${E}-03-01 00:00:00`:A==="3"?y=`${E}-06-01 00:00:00`:y=`${E}-09-01 00:00:00`;const _=this.literalNode(y),C=i.DateTime.fromFormat(y,h).plus({months:3});return{begin:_,end:this.literalNode(C.toFormat(h)).sql}}case void 0:case"second":{const E=this.literalNode(y);return{begin:E,end:E.sql}}}}literalNode(g){const y={node:"timeLiteral",typeDef:{type:"timestamp"},literal:g};return{...y,sql:this.d.sqlLiteralTime({},y)}}nowExpr(){return{node:"now",typeDef:{type:"timestamp"},sql:this.d.sqlNowExpr()}}n(g){return{node:"numberLiteral",literal:g,sql:g}}delta(g,y,E,A){const _={node:"delta",op:y,units:A,kids:{base:(0,r.mkTemporal)(g,"timestamp"),delta:this.n(E)}};return{..._,sql:this.d.sqlAlterTimeExpr(_)}}dayofWeek(g){const y={node:"extract",e:(0,r.mkTemporal)(g,"timestamp"),units:"day_of_week"};return{...y,sql:this.d.sqlTimeExtractExpr({},y)}}nowDot(g){const y={node:"trunc",e:this.nowExpr(),units:g};return{...y,sql:this.d.sqlTruncExpr({},y)}}thisUnit(g){const y=this.nowDot(g),E=this.delta(y,"+","1",g);return{begin:y,end:E.sql}}lastUnit(g){const y=this.nowDot(g);return{begin:this.delta(y,"-","1",g),end:y.sql}}nextUnit(g){const y=this.nowDot(g),E=this.delta(y,"+","1",g),A=this.delta(y,"+","2",g);return{begin:E,end:A.sql}}mod7(g){return this.d.hasModOperator?`(${g})%7`:`MOD(${g},7)`}moment(g){switch(g.moment){case"now":{const y=this.nowExpr();return{begin:y,end:y.sql}}case"literal":return this.expandLiteral(g);case"ago":case"from_now":{const y=this.nowDot(g.units),E=(0,r.mkTemporal)(y,"timestamp"),A=this.delta(E,g.moment==="ago"?"-":"+",g.n,g.units);if(g.moment==="ago"&&g.n==="1")return{begin:A,end:y.sql};const _=Number(g.n)+(g.moment==="ago"?-1:1),v={...A,kids:{base:E,delta:this.n(_.toString())}};return{begin:A,end:this.d.sqlAlterTimeExpr(v)}}case"today":return this.thisUnit("day");case"yesterday":return this.lastUnit("day");case"tomorrow":return this.nextUnit("day");case"this":return this.thisUnit(g.units);case"last":return this.lastUnit(g.units);case"next":return this.nextUnit(g.units);case"monday":case"tuesday":case"wednesday":case"thursday":case"friday":case"saturday":case"sunday":{const y=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].indexOf(g.moment),E=this.dayofWeek(this.nowExpr()).sql;if(g.which==="next"){const C=`${this.mod7(`${y}-(${E}-1)+6`)}+1`,b=this.delta(this.thisUnit("day").begin,"+",C,"day"),S=this.delta(this.thisUnit("day").begin,"+",`${C}+1`,"day");return{begin:b,end:S.sql}}const A=`${this.mod7(`(${E}-1)-${y}+6`)}+1`,_=this.delta(this.thisUnit("day").begin,"-",A,"day"),v=this.delta(this.thisUnit("day").begin,"-",`(${A})-1`,"day");return{begin:_,end:v.sql}}}}isIn(g,y,E){let A=">=",_="<",v="AND";return g&&(v="OR",A="<",_=">="),y=this.time(y),E=this.time(E),`${this.expr} ${A} ${y} ${v} ${this.expr} ${_} ${E}`}}t.TemporalFilterCompiler=p})(cae),Object.defineProperty(Ls,"__esModule",{value:!0}),Ls.QueryModel=Ls.getResultStructDefForQuery=Ls.getResultStructDefForView=Ls.Segment=void 0;const oXe=Pp,uXe=kp,aXe=Ay,Be=Xe,Tn=Bt,P4=qp,lXe=ui,cXe=cae,U4=Cy;function yae(t){return t.map(e=>encodeURIComponent(e)).join("/")}function i$(t){return`'${t}'`}function fXe(t){return t.replace(/[^a-zA-Z0-9_]/g,"_o_")}function zp(t){const e=[];for(const r of t.fields.filter(Be.fieldIsIntrinsic))e.push({typeDef:r,sqlExpression:(0,Be.getIdentifier)(r),rawName:(0,Be.getIdentifier)(r),sqlOutputName:(0,Be.getIdentifier)(r)});return e}function Eae(t,e){const{sqlExpression:r,sqlOutputName:i,rawName:s}=e;(0,Be.isAtomic)(e.fieldDef)&&t.push({typeDef:e.fieldDef,sqlExpression:r,sqlOutputName:i,rawName:s})}class xXe extends Set{add_use(e){if(e!==void 0)return this.add(e)}hasAsymetricFunctions(){return this.has("sum")||this.has("avg")||this.has("count")||this.has("generic_asymmetric_aggregate")}}class Gp{constructor(e=!0,r){this.parent=r,this.withs=[],this.udfs=[],this.pdts=[],this.dependenciesToMaterialize={},this.stagePrefix="__stage",this.useCTE=e}getName(e){return`${this.stagePrefix}${e}`}root(){return this.parent===void 0?this:this.parent.root()}addStage(e){return this.useCTE?(this.withs.push(e),this.getName(this.withs.length-1)):(this.withs[0]=e,(0,Tn.indent)(`
1045
+ `)},S.prototype.clone=function(){return new S(this.states,this.state)},S.prototype.has=function(D){return!0},{compile:_,states:C,error:Object.freeze({error:!0}),fallback:Object.freeze({fallback:!0}),keywords:b}})})(dae);var ZB=dae.exports,qt={};Object.defineProperty(qt,"__esModule",{value:!0}),qt.mkUnits=qt.timeLiteral=qt.joinTemporal=qt.temporalNot=qt.numNot=qt.mkValues=qt.mkRange=qt.joinNumbers=qt.conjoin=qt.matchOp=qt.escape=qt.unescape=qt.maybeNot=void 0;const Ca=bn;function LJe(t){const[e,r]=t;return e&&r&&(0,Ca.isStringFilter)(r)?{...r,not:!0}:r}qt.maybeNot=LJe;function Sy(t){return t.replace(/\\(.)/g,"$1")}qt.unescape=Sy;function IJe(t){const e=t.toLowerCase();return e==="null"||e==="empty"?"\\"+t:t.replace(/([,; |()\\%_-])/g,"\\$1")}qt.escape=IJe;function M4(t){let e=!1,r=!1,i=0,s=!1;const o=t.length;for(let u=0;u<o;u+=1){const a=t[u];if(a===" "||a===" "){i+=1;continue}i=0,a==="%"?(s=!0,u===0&&(e=!0),r=!0):(r=!1,a==="\\"?u+=1:a==="_"&&(s=!0))}return{hasLike:s,percentEnd:r&&o>1,percentStart:e&&o>1,endSpace:i}}function BJe(t){let e=t.trimStart();const{hasLike:r,percentEnd:i,percentStart:s,endSpace:o}=M4(e);if(o>0&&(e=e.slice(0,-o)),r){if(s&&i){const u=e.slice(1,-1);if(!M4(u).hasLike&&u.length>0)return{operator:"contains",values:[Sy(u)]}}else if(i){const u=e.slice(0,-1);if(!M4(u).hasLike)return{operator:"starts",values:[Sy(u)]}}else if(s){const u=e.slice(1);if(!M4(u).hasLike)return{operator:"ends",values:[Sy(u)]}}return{operator:"~",escaped_values:[e]}}return e.toLowerCase()==="null"?{operator:"null"}:e.toLowerCase()==="empty"?{operator:"empty"}:{operator:"=",values:[Sy(e)]}}qt.matchOp=BJe;function e$(t,e){var r,i;return t.operator===e.operator&&((r=t.not)!==null&&r!==void 0?r:!1)===((i=e.not)!==null&&i!==void 0?i:!1)}function $Je(t,e,r){if(e=e.toLowerCase(),(0,Ca.isStringFilter)(t)&&(0,Ca.isStringFilter)(r)){if(e===","){if(t.operator==="~"&&e$(t,r))return{...t,escaped_values:[...t.escaped_values,...r.escaped_values]};if((0,Ca.isStringCondition)(t)&&e$(t,r))return{...t,values:[...t.values,...r.values]}}const i=e===","?",":e==="|"?"or":e===";"?"and":void 0;if(i)return t.operator===i?{...t,members:[...t.members,r]}:{operator:i,members:[t,r]}}return null}qt.conjoin=$Je;function kJe(t,e,r){if(e=e.toLowerCase(),(0,Ca.isNumberFilter)(t)&&(0,Ca.isNumberFilter)(r)){if(e==="or"&&t.operator==="="&&e$(t,r)){const i={operator:"=",values:[...t.values,...r.values]};return t.not&&(i.not=!0),i}if(e==="and"||e==="or")return t.operator===e?{...t,members:[...t.members,r]}:{operator:e,members:[t,r]}}return null}qt.joinNumbers=kJe;function MJe(t,e,r,i){return{operator:"range",startValue:e,startOperator:t==="("?">":">=",endValue:r,endOperator:i===")"?"<":"<="}}qt.mkRange=MJe;function PJe(t,e){return{values:[t,...e]}}qt.mkValues=PJe;function UJe(t,e){return(0,Ca.isNumberFilter)(t)&&e?t.operator==="="?{operator:"!=",values:t.values}:t.operator==="!="?{operator:"=",values:t.values}:{...t,not:!0}:t}qt.numNot=UJe;function jJe(t,e){return(0,Ca.isTemporalFilter)(t)&&e?{...t,not:!0}:t}qt.temporalNot=jJe;function qJe(t,e,r){return e=e.toLowerCase(),(0,Ca.isTemporalFilter)(t)&&(0,Ca.isTemporalFilter)(r)&&(e==="and"||e==="or")?t.operator===e?{...t,members:[...t.members,r]}:{operator:e,members:[t,r]}:null}qt.joinTemporal=qJe;function HJe(t,e){const r={moment:"literal",literal:t};return e&&(r.units=e),r}qt.timeLiteral=HJe;function QJe(t){switch(t.toLowerCase()){case"second":case"seconds":return"second";case"minute":case"minutes":return"minute";case"hour":case"hours":return"hour";case"day":case"days":return"day";case"week":case"weeks":return"week";case"month":case"months":return"month";case"quarter":case"quarters":return"quarter";case"year":case"years":return"year"}}qt.mkUnits=QJe;var zJe=T&&T.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(XB,"__esModule",{value:!0});function GJe(t){return t[0]}const hae=zJe(ZB),Hp=qt,WJe=hae.default.keywords({AND:"and",OR:"or",NOT:"not",NULL_KW:"null",TO:"to"}),Ln=hae.default.compile({WS:/[ \t]+/,id:{match:/[a-zA-Z]+/,type:t=>WJe(t.toLowerCase())},oparen:"(",cparen:")",obrack:"[",cbrack:"]",comma:",",op:/<=|>=|<|>/,ne:"!=",eq:"=",float:/-?(?:\d+)?\.\d+(?:[Ee][+-]?\d+)?/,numberE:/-?\d+[Ee][+-]?\d+/,integer:/-?\d+/}),VJe=Ln.next;Ln.next=(t=>()=>{for(;;){const e=t.call(Ln);if(e===void 0||e.type!=="WS")return e}})(VJe);const YJe={Lexer:Ln,ParserRules:[{name:"numberFilter",symbols:["numberFilter","conjunction","numberUnary"],postprocess:([t,e,r])=>(0,Hp.joinNumbers)(t,e[0].text,r)},{name:"numberFilter",symbols:["numberUnary"],postprocess:t=>t[0]},{name:"numberUnary$ebnf$1",symbols:[Ln.has("NOT")?{type:"NOT"}:NOT],postprocess:GJe},{name:"numberUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"numberUnary",symbols:["numberUnary$ebnf$1","clause"],postprocess:([t,e])=>(0,Hp.numNot)(e,t)},{name:"clause",symbols:[Ln.has("NULL_KW")?{type:"NULL_KW"}:NULL_KW],postprocess:()=>({operator:"null"})},{name:"clause$ebnf$1",symbols:[]},{name:"clause$ebnf$1",symbols:["clause$ebnf$1","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:["N","clause$ebnf$1"],postprocess:([t,e])=>({operator:"=",...(0,Hp.mkValues)(t,e)})},{name:"clause$ebnf$2",symbols:[]},{name:"clause$ebnf$2",symbols:["clause$ebnf$2","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:[Ln.has("eq")?{type:"eq"}:eq,"N","clause$ebnf$2"],postprocess:([t,e,r])=>({operator:"=",...(0,Hp.mkValues)(e,r)})},{name:"clause$ebnf$3",symbols:[]},{name:"clause$ebnf$3",symbols:["clause$ebnf$3","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:[Ln.has("ne")?{type:"ne"}:ne,"N","clause$ebnf$3"],postprocess:([t,e,r])=>({operator:"!=",...(0,Hp.mkValues)(e,r)})},{name:"clause",symbols:[Ln.has("op")?{type:"op"}:op,"N"],postprocess:([t,e])=>({operator:t.text,values:[e]})},{name:"clause",symbols:[Ln.has("oparen")?{type:"oparen"}:oparen,"numberFilter",Ln.has("cparen")?{type:"cparen"}:cparen],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"clause",symbols:["openInterval","N",Ln.has("TO")?{type:"TO"}:TO,"N","closeInterval"],postprocess:([t,e,r,i,s])=>(0,Hp.mkRange)(t[0].text,e,i,s[0].text)},{name:"numberList",symbols:[Ln.has("comma")?{type:"comma"}:comma,"N"],postprocess:([t,e])=>e},{name:"closeInterval",symbols:[Ln.has("cbrack")?{type:"cbrack"}:cbrack]},{name:"closeInterval",symbols:[Ln.has("cparen")?{type:"cparen"}:cparen]},{name:"openInterval",symbols:[Ln.has("obrack")?{type:"obrack"}:obrack]},{name:"openInterval",symbols:[Ln.has("oparen")?{type:"oparen"}:oparen]},{name:"N$subexpression$1",symbols:[Ln.has("float")?{type:"float"}:float]},{name:"N$subexpression$1",symbols:[Ln.has("numberE")?{type:"numberE"}:numberE]},{name:"N$subexpression$1",symbols:[Ln.has("integer")?{type:"integer"}:integer]},{name:"N",symbols:["N$subexpression$1"],postprocess:([t])=>t[0].text},{name:"conjunction",symbols:[Ln.has("OR")?{type:"OR"}:OR]},{name:"conjunction",symbols:[Ln.has("AND")?{type:"AND"}:AND]}],ParserStart:"numberFilter"};XB.default=YJe;var Qp={};Object.defineProperty(Qp,"__esModule",{value:!0}),Qp.run_parser=void 0;const KJe=bn;function JJe(t,e){try{e.feed(t);const i=e.finish()[0];return(0,KJe.isFilterExpression)(i)?{parsed:i,log:[]}:{parsed:null,log:[]}}catch(r){let i=r.message,s=1,o=t.length;if(r.token){const u=r.token;s=u.col,o=u.text.length;const l=r.message.match(new RegExp("(?<=A ).*(?= based on:)","g")).map(c=>c.replace(/\s+token/i,""));i=`Unexpected ${u.type} token "${u.value}"`,l&&l.length&&(i+=` Tokens expected: ${[...new Set(l)]}`)}return{parsed:null,log:[{message:i,startIndex:s-1,endIndex:s-1+o-1,severity:"error"}]}}}Qp.run_parser=JJe,function(t){var e=T&&T.__createBinding||(Object.create?function(c,f,x,h){h===void 0&&(h=x);var p=Object.getOwnPropertyDescriptor(f,x);(!p||("get"in p?!f.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return f[x]}}),Object.defineProperty(c,h,p)}:function(c,f,x,h){h===void 0&&(h=x),c[h]=f[x]}),r=T&&T.__setModuleDefault||(Object.create?function(c,f){Object.defineProperty(c,"default",{enumerable:!0,value:f})}:function(c,f){c.default=f}),i=T&&T.__importStar||function(c){if(c&&c.__esModule)return c;var f={};if(c!=null)for(var x in c)x!=="default"&&Object.prototype.hasOwnProperty.call(c,x)&&e(f,c,x);return r(f,c),f},s=T&&T.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(t,"__esModule",{value:!0}),t.NumberFilterExpression=void 0;const o=bn,u=i(JB),a=s(XB),l=Qp;t.NumberFilterExpression={parse(c){if(c.match(/^\s*$/))return{parsed:null,log:[]};const f=new u.Parser(u.Grammar.fromCompiled(a.default)),x=(0,l.run_parser)(c,f);return x.parsed&&(0,o.isNumberFilter)(x.parsed)?{parsed:x.parsed,log:[]}:{parsed:null,log:x.log}},unparse(c){if(c===null)return"";switch(c.operator){case"=":return c.values.join(", ");case"!=":return"!= "+c.values.join(", ");case">":case"<":case"<=":case">=":return c.not?c.values.map(f=>c.operator==="="?`not ${f}`:`not ${c.operator} ${f}`).join(", "):c.values.map(f=>`${c.operator} ${f}`).join(", ");case"range":{const f=c.startOperator===">"?"(":"[",x=c.endOperator==="<"?")":"]",h=`${f}${c.startValue} to ${c.endValue}${x}`;return c.not?`not ${h}`:h}case"null":return c.not?"not null":"null";case"and":case"or":return c.members.map(f=>t.NumberFilterExpression.unparse(f)).join(` ${c.operator} `);case"()":{const f="("+t.NumberFilterExpression.unparse(c.expr)+")";return c.not?"not "+f:f}}return`no unparse for ${JSON.stringify(c)}`}}}(fae);var pae={},t$={},XJe=T&&T.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(t$,"__esModule",{value:!0});function ZJe(t){return t[0]}const eXe=XJe(ZB),n$=qt,fu=eXe.default.compile({WS:/[ \t]+/,comma:",",semi:";",or:"|",open:"(",close:")",minus:"-",matchStr:/(?:\\[^\n]|[^\n,;()|])+/}),tXe=fu.next;fu.next=(t=>()=>{for(;;){const e=t.call(fu);if(e==null||e.type!=="WS")return e}})(tXe);const nXe={Lexer:fu,ParserRules:[{name:"stringFilter",symbols:["stringFilter","conjunction","sfUnary"],postprocess:([t,e,r])=>(0,n$.conjoin)(t,e[0].text,r)},{name:"stringFilter",symbols:["sfUnary"],postprocess:t=>t[0]},{name:"sfUnary$ebnf$1",symbols:[fu.has("minus")?{type:"minus"}:minus],postprocess:ZJe},{name:"sfUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"sfUnary",symbols:["sfUnary$ebnf$1","clause"],postprocess:t=>(0,n$.maybeNot)(t)},{name:"parens",symbols:[fu.has("open")?{type:"open"}:open,"stringFilter",fu.has("close")?{type:"close"}:close],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"clause",symbols:[fu.has("matchStr")?{type:"matchStr"}:matchStr],postprocess:([t])=>(0,n$.matchOp)(t.text)},{name:"clause",symbols:["parens"],postprocess:t=>t[0]},{name:"conjunction",symbols:[fu.has("comma")?{type:"comma"}:comma]},{name:"conjunction",symbols:[fu.has("semi")?{type:"semi"}:semi]},{name:"conjunction",symbols:[fu.has("or")?{type:"or"}:or]}],ParserStart:"stringFilter"};t$.default=nXe,function(t){var e=T&&T.__createBinding||(Object.create?function(f,x,h,p){p===void 0&&(p=h);var m=Object.getOwnPropertyDescriptor(x,h);(!m||("get"in m?!x.__esModule:m.writable||m.configurable))&&(m={enumerable:!0,get:function(){return x[h]}}),Object.defineProperty(f,p,m)}:function(f,x,h,p){p===void 0&&(p=h),f[p]=x[h]}),r=T&&T.__setModuleDefault||(Object.create?function(f,x){Object.defineProperty(f,"default",{enumerable:!0,value:x})}:function(f,x){f.default=x}),i=T&&T.__importStar||function(f){if(f&&f.__esModule)return f;var x={};if(f!=null)for(var h in f)h!=="default"&&Object.prototype.hasOwnProperty.call(f,h)&&e(x,f,h);return r(x,f),x},s=T&&T.__importDefault||function(f){return f&&f.__esModule?f:{default:f}};Object.defineProperty(t,"__esModule",{value:!0}),t.StringFilterExpression=void 0;const o=bn,u=i(JB),a=s(t$),l=qt,c=Qp;t.StringFilterExpression={parse(f){if(f.match(/^\s*$/))return{parsed:null,log:[]};const x=new u.Parser(u.Grammar.fromCompiled(a.default)),h=(0,c.run_parser)(f,x);return h.parsed&&(0,o.isStringFilter)(h.parsed)?{parsed:h.parsed,log:[]}:{parsed:null,log:h.log}},unparse(f){if(f===null)return"";switch(f.operator){case"=":return f.not?f.values.map(x=>"-"+(0,l.escape)(x)).join(", "):f.values.map(x=>(0,l.escape)(x)).join(", ");case"~":return f.not?f.escaped_values.map(x=>"-"+x).join(", "):f.escaped_values.join(", ");case"starts":return f.not?f.values.map(x=>"-"+(0,l.escape)(x)+"%").join(", "):f.values.map(x=>(0,l.escape)(x)+"%").join(", ");case"ends":return f.not?f.values.map(x=>"-%"+(0,l.escape)(x)).join(", "):f.values.map(x=>"%"+(0,l.escape)(x)).join(", ");case"contains":return f.not?f.values.map(x=>"-%"+(0,l.escape)(x)+"%").join(", "):f.values.map(x=>"%"+(0,l.escape)(x)+"%").join(", ");case"or":return f.members.map(x=>t.StringFilterExpression.unparse(x)).join(" | ");case"and":return f.members.map(x=>t.StringFilterExpression.unparse(x)).join("; ");case",":return f.members.map(x=>t.StringFilterExpression.unparse(x)).join(", ");case"()":{const x="("+t.StringFilterExpression.unparse(f.expr)+")";return f.not?"-"+x:x}case"null":return f.not?"-null":"null";case"empty":return f.not?"-empty":"empty"}}}}(pae);var mae={},r$={},rXe=T&&T.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(r$,"__esModule",{value:!0});function iXe(t){return t[0]}const gae=rXe(ZB),xu=qt,sXe=gae.default.keywords({AND:"and",OR:"or",NOT:"not",NULL_KW:"null",TO:"to",NOW:"now",LAST:"last",THIS:"this",NEXT:"next",AGO:"ago",FROM:"from",BEFORE:"before",AFTER:"after",FOR:"for",TODAY:"today",YESTERDAY:"yesterday",TOMORROW:"tomorrow",SECOND:"second",MINUTE:"minute",HOUR:"hour",DAY:"day",WEEK:"week",MONTH:"month",QUARTER:"quarter",YEAR:"year",SECONDS:"seconds",MINUTES:"minutes",HOURS:"hours",DAYS:"days",WEEKS:"weeks",MONTHS:"months",QUARTERS:"quarters",YEARS:"years",MONDAY:"monday",TUESDAY:"tuesday",WEDNESDAY:"wednesday",THURSDAY:"thursday",FRIDAY:"friday",SATURDAY:"saturday",SUNDAY:"sunday"}),Ke=gae.default.compile({WS:/[ \t]+/,id:{match:/[a-zA-Z]+/,type:t=>sXe(t.toLowerCase())},oparen:"(",cparen:")",comma:",",literal:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d:\d\d(?::\d\d(?:[.,]\d*)?)/,lit_week:/\d\d\d\d-\d\d-\d\d-[Ww][Kk]/,lit_quarter:/\d\d\d\d-[qQ][1234]/,lit_min:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d:\d\d/,lit_hour:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d/,lit_day:/\d\d\d\d-\d\d-\d\d/,lit_month:/\d\d\d\d-\d\d/,lit_year:/\d\d\d\d/,n:/\d+/}),oXe=Ke.next;Ke.next=(t=>()=>{for(;;){const e=t.call(Ke);if(e===void 0||e.type!=="WS")return e}})(oXe);const uXe={Lexer:Ke,ParserRules:[{name:"temporalFilter",symbols:["temporalFilter","conjunction","temporalUnary"],postprocess:([t,e,r])=>(0,xu.joinTemporal)(t,e[0].text,r)},{name:"temporalFilter",symbols:["temporalUnary"],postprocess:t=>t[0]},{name:"temporalUnary$ebnf$1",symbols:[Ke.has("NOT")?{type:"NOT"}:NOT],postprocess:iXe},{name:"temporalUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"temporalUnary",symbols:["temporalUnary$ebnf$1","clause"],postprocess:([t,e])=>(0,xu.temporalNot)(e,t)},{name:"duration",symbols:["number","unit"],postprocess:([t,e])=>({units:e,n:t})},{name:"number",symbols:[Ke.has("n")?{type:"n"}:n],postprocess:([t])=>t.text},{name:"number",symbols:[Ke.has("lityear")?{type:"lityear"}:lityear],postprocess:([t])=>t.text},{name:"unit$subexpression$1",symbols:[Ke.has("SECOND")?{type:"SECOND"}:SECOND]},{name:"unit$subexpression$1",symbols:[Ke.has("MINUTE")?{type:"MINUTE"}:MINUTE]},{name:"unit$subexpression$1",symbols:[Ke.has("HOUR")?{type:"HOUR"}:HOUR]},{name:"unit$subexpression$1",symbols:[Ke.has("DAY")?{type:"DAY"}:DAY]},{name:"unit$subexpression$1",symbols:[Ke.has("WEEK")?{type:"WEEK"}:WEEK]},{name:"unit$subexpression$1",symbols:[Ke.has("MONTH")?{type:"MONTH"}:MONTH]},{name:"unit$subexpression$1",symbols:[Ke.has("QUARTER")?{type:"QUARTER"}:QUARTER]},{name:"unit$subexpression$1",symbols:[Ke.has("YEAR")?{type:"YEAR"}:YEAR]},{name:"unit$subexpression$1",symbols:[Ke.has("SECONDS")?{type:"SECONDS"}:SECONDS]},{name:"unit$subexpression$1",symbols:[Ke.has("MINUTES")?{type:"MINUTES"}:MINUTES]},{name:"unit$subexpression$1",symbols:[Ke.has("HOURS")?{type:"HOURS"}:HOURS]},{name:"unit$subexpression$1",symbols:[Ke.has("DAYS")?{type:"DAYS"}:DAYS]},{name:"unit$subexpression$1",symbols:[Ke.has("WEEKS")?{type:"WEEKS"}:WEEKS]},{name:"unit$subexpression$1",symbols:[Ke.has("MONTHS")?{type:"MONTHS"}:MONTHS]},{name:"unit$subexpression$1",symbols:[Ke.has("QUARTERS")?{type:"QUARTERS"}:QUARTERS]},{name:"unit$subexpression$1",symbols:[Ke.has("YEARS")?{type:"YEARS"}:YEARS]},{name:"unit",symbols:["unit$subexpression$1"],postprocess:([t])=>(0,xu.mkUnits)(t[0].text)},{name:"clause",symbols:[Ke.has("NULL_KW")?{type:"NULL_KW"}:NULL_KW],postprocess:()=>({operator:"null"})},{name:"clause",symbols:["parens"],postprocess:t=>t[0]},{name:"clause",symbols:["duration"],postprocess:([t])=>({operator:"in_last",...t})},{name:"clause",symbols:[Ke.has("BEFORE")?{type:"BEFORE"}:BEFORE,"moment"],postprocess:([t,e])=>({operator:"before",before:e})},{name:"clause",symbols:[Ke.has("AFTER")?{type:"AFTER"}:AFTER,"moment"],postprocess:([t,e])=>({operator:"after",after:e})},{name:"clause",symbols:["moment",Ke.has("TO")?{type:"TO"}:TO,"moment"],postprocess:([t,e,r])=>({operator:"to",fromMoment:t,toMoment:r})},{name:"clause",symbols:["moment",Ke.has("FOR")?{type:"FOR"}:FOR,"duration"],postprocess:([t,e,r])=>({...r,operator:"for",begin:t})},{name:"clause$subexpression$1",symbols:[Ke.has("LAST")?{type:"LAST"}:LAST]},{name:"clause$subexpression$1",symbols:[Ke.has("NEXT")?{type:"NEXT"}:NEXT]},{name:"clause",symbols:["clause$subexpression$1","duration"],postprocess:([t,e])=>({operator:t[0].text,...e})},{name:"clause",symbols:["moment"],postprocess:([t])=>({operator:"in",in:t})},{name:"lastNextThis",symbols:[Ke.has("THIS")?{type:"THIS"}:THIS],postprocess:([t])=>t.text.toLowerCase()},{name:"lastNextThis",symbols:[Ke.has("NEXT")?{type:"NEXT"}:NEXT],postprocess:([t])=>t.text.toLowerCase()},{name:"lastNextThis",symbols:[Ke.has("LAST")?{type:"LAST"}:LAST],postprocess:([t])=>t.text.toLowerCase()},{name:"moment",symbols:[Ke.has("NOW")?{type:"NOW"}:NOW],postprocess:()=>({moment:"now"})},{name:"moment",symbols:["lastNextThis","unit"],postprocess:([t,e])=>({moment:t,units:e})},{name:"moment",symbols:[Ke.has("TODAY")?{type:"TODAY"}:TODAY],postprocess:()=>({moment:"today"})},{name:"moment",symbols:[Ke.has("YESTERDAY")?{type:"YESTERDAY"}:YESTERDAY],postprocess:()=>({moment:"yesterday"})},{name:"moment",symbols:[Ke.has("TOMORROW")?{type:"TOMORROW"}:TOMORROW],postprocess:()=>({moment:"tomorrow"})},{name:"moment",symbols:["duration",Ke.has("AGO")?{type:"AGO"}:AGO],postprocess:([t,e])=>({moment:"ago",...t})},{name:"moment",symbols:["duration",Ke.has("FROM")?{type:"FROM"}:FROM,Ke.has("NOW")?{type:"NOW"}:NOW],postprocess:([t,e])=>({moment:"from_now",...t})},{name:"moment",symbols:[Ke.has("NEXT")?{type:"NEXT"}:NEXT,"weekday"],postprocess:([t,e])=>({moment:e.toLowerCase(),which:"next"})},{name:"moment",symbols:[Ke.has("LAST")?{type:"LAST"}:LAST,"weekday"],postprocess:([t,e])=>({moment:e.toLowerCase(),which:"last"})},{name:"moment",symbols:["weekday"],postprocess:([t])=>({moment:t.toLowerCase(),which:"last"})},{name:"moment",symbols:["timeLiteral"],postprocess:t=>t[0]},{name:"timeLiteral",symbols:[Ke.has("literal")?{type:"literal"}:literal],postprocess:([t])=>(0,xu.timeLiteral)(t.text)},{name:"timeLiteral",symbols:[Ke.has("lit_day")?{type:"lit_day"}:lit_day],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"day")},{name:"timeLiteral",symbols:[Ke.has("lit_min")?{type:"lit_min"}:lit_min],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"minute")},{name:"timeLiteral",symbols:[Ke.has("lit_hour")?{type:"lit_hour"}:lit_hour],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"hour")},{name:"timeLiteral",symbols:[Ke.has("lit_month")?{type:"lit_month"}:lit_month],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"month")},{name:"timeLiteral",symbols:[Ke.has("lit_quarter")?{type:"lit_quarter"}:lit_quarter],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"quarter")},{name:"timeLiteral",symbols:[Ke.has("lit_week")?{type:"lit_week"}:lit_week],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"week")},{name:"timeLiteral",symbols:[Ke.has("lit_year")?{type:"lit_year"}:lit_year],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"year")},{name:"weekday$subexpression$1",symbols:[Ke.has("MONDAY")?{type:"MONDAY"}:MONDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("TUESDAY")?{type:"TUESDAY"}:TUESDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("WEDNESDAY")?{type:"WEDNESDAY"}:WEDNESDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("THURSDAY")?{type:"THURSDAY"}:THURSDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("FRIDAY")?{type:"FRIDAY"}:FRIDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("SATURDAY")?{type:"SATURDAY"}:SATURDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("SUNDAY")?{type:"SUNDAY"}:SUNDAY]},{name:"weekday",symbols:["weekday$subexpression$1"],postprocess:([t])=>t[0].text},{name:"parens",symbols:[Ke.has("oparen")?{type:"oparen"}:oparen,"temporalFilter",Ke.has("cparen")?{type:"cparen"}:cparen],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"conjunction",symbols:[Ke.has("OR")?{type:"OR"}:OR]},{name:"conjunction",symbols:[Ke.has("AND")?{type:"AND"}:AND]}],ParserStart:"temporalFilter"};r$.default=uXe,function(t){var e=T&&T.__createBinding||(Object.create?function(h,p,m,g){g===void 0&&(g=m);var y=Object.getOwnPropertyDescriptor(p,m);(!y||("get"in y?!p.__esModule:y.writable||y.configurable))&&(y={enumerable:!0,get:function(){return p[m]}}),Object.defineProperty(h,g,y)}:function(h,p,m,g){g===void 0&&(g=m),h[g]=p[m]}),r=T&&T.__setModuleDefault||(Object.create?function(h,p){Object.defineProperty(h,"default",{enumerable:!0,value:p})}:function(h,p){h.default=p}),i=T&&T.__importStar||function(h){if(h&&h.__esModule)return h;var p={};if(h!=null)for(var m in h)m!=="default"&&Object.prototype.hasOwnProperty.call(h,m)&&e(p,h,m);return r(p,h),p},s=T&&T.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterExpression=void 0;const o=bn,u=s(r$),a=i(JB),l=Qp;t.TemporalFilterExpression={parse(h){if(h.match(/^\s*$/))return{parsed:null,log:[]};const p=new a.Parser(a.Grammar.fromCompiled(u.default)),m=(0,l.run_parser)(h,p);return m.parsed&&(0,o.isTemporalFilter)(m.parsed)?{parsed:m.parsed,log:[]}:{parsed:null,log:m.log}},unparse(h){if(h===null)return"";switch(h.operator){case"null":return c(h,"null");case"in":return c(h,x(h.in));case"()":return"("+t.TemporalFilterExpression.unparse(h.expr)+")";case"in_last":return c(h,f(h));case"last":case"next":return c(h,`${h.operator} ${f(h)}`);case"before":return c(h,`before ${x(h.before)}`);case"after":return c(h,`after ${x(h.after)}`);case"to":return c(h,`${x(h.fromMoment)} to ${x(h.toMoment)}`);case"for":return c(h,`${x(h.begin)} for ${f(h)}`);case"or":return h.members.map(p=>t.TemporalFilterExpression.unparse(p)).join(" or ");case"and":return h.members.map(p=>t.TemporalFilterExpression.unparse(p)).join(" and ")}}};function c(h,p){return"not"in h&&h.not?"not "+p:p}function f(h){return h.n==="1"?`1 ${h.units}`:`${h.n} ${h.units}s`}function x(h){switch(h.moment){case"literal":return h.literal;case"now":case"today":case"yesterday":case"tomorrow":return h.moment;case"monday":case"tuesday":case"wednesday":case"thursday":case"friday":case"saturday":case"sunday":return h.which==="next"?"next "+h.moment:h.moment;case"this":case"next":case"last":return`${h.moment} ${h.units}`;case"ago":return`${f(h)} ago`;case"from_now":return`${f(h)} from now`}}}(mae),function(t){var e=T&&T.__createBinding||(Object.create?function(a,l,c,f){f===void 0&&(f=c);var x=Object.getOwnPropertyDescriptor(l,c);(!x||("get"in x?!l.__esModule:x.writable||x.configurable))&&(x={enumerable:!0,get:function(){return l[c]}}),Object.defineProperty(a,f,x)}:function(a,l,c,f){f===void 0&&(f=c),a[f]=l[c]}),r=T&&T.__exportStar||function(a,l){for(var c in a)c!=="default"&&!Object.prototype.hasOwnProperty.call(l,c)&&e(l,a,c)};Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterExpression=t.StringFilterExpression=t.NumberFilterExpression=t.BooleanFilterExpression=void 0,r(bn,t);var i=k4;Object.defineProperty(t,"BooleanFilterExpression",{enumerable:!0,get:function(){return i.BooleanFilterExpression}});var s=fae;Object.defineProperty(t,"NumberFilterExpression",{enumerable:!0,get:function(){return s.NumberFilterExpression}});var o=pae;Object.defineProperty(t,"StringFilterExpression",{enumerable:!0,get:function(){return o.StringFilterExpression}});var u=mae;Object.defineProperty(t,"TemporalFilterExpression",{enumerable:!0,get:function(){return u.TemporalFilterExpression}})}(Cy);const by=gP(Q1e);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterCompiler=t.FilterCompilers=void 0;const e=Cy,r=Xe,i=by;function s(m){return m.replace(/([%_\\])/g,"\\$1")}function o(m){return m===">"?"<=":m==="<"?">=":m===">="?"<":">"}function u(m,g){const y=` OR ${g} IS NULL`;return m.length===1?`${m[0]}${y}`:`(${m.join(" AND ")})${y}`}t.FilterCompilers={compile(m,g,y,E){if(g===null)return"true";if(m==="string"&&(0,e.isStringFilter)(g))return t.FilterCompilers.stringCompile(g,y,E);if(m==="number"&&(0,e.isNumberFilter)(g))return t.FilterCompilers.numberCompile(g,y,E);if(m==="boolean"&&(0,e.isBooleanFilter)(g))return t.FilterCompilers.booleanCompile(g,y,E);if((m==="date"||m==="timestamp")&&(0,e.isTemporalFilter)(g))return t.FilterCompilers.temporalCompile(g,y,E,m);throw new Error("INTERNAL ERROR: No filter compiler for "+m)},numberCompile(m,g,y){switch(m.operator){case"!=":case"=":{const E=m.operator==="="&&m.not||m.operator==="!="&&!m.not,A=m.values.join(", ");return m.values.length===1?E?`${g} != ${A} OR ${g} IS NULL`:`${g} = ${A}`:E?`${g} NOT IN (${A}) OR ${g} IS NULL`:`${g} IN (${A})`}case">":case"<":case">=":case"<=":return m.values.map(E=>`${g} ${m.operator} ${E}`).join(m.not?" AND ":" OR ");case"range":{let E=m.startOperator,A=m.endOperator,_=" AND ";return m.not&&(E=o(E),A=o(A),_=" OR "),`${g} ${E} ${m.startValue} ${_} ${g} ${A} ${m.endValue}`}case"null":return m.not?`${g} IS NOT NULL`:`${g} IS NULL`;case"()":{const E="("+t.FilterCompilers.numberCompile(m.expr,g,y)+")";return m.not?`NOT ${E}`:E}case"and":case"or":return m.members.map(E=>t.FilterCompilers.numberCompile(E,g,y)).join(` ${m.operator.toUpperCase()} `)}},booleanCompile(m,g,y){switch(m.operator){case"false":return`${g} = false`;case"false_or_null":return`${g} IS NULL OR ${g} = false`;case"null":return m.not?`${g} IS NOT NULL`:`${g} IS NULL`;case"true":return g}},stringCompile(m,g,y){switch(m.operator){case"null":return m.not?`${g} IS NOT NULL`:`${g} IS NULL`;case"empty":return m.not?`COALESCE(${g},'') != ''`:`COALESCE(${g},'') = ''`;case"=":{if(m.values.length===1){const A=m.not?"!=":"=",_=`${g} ${A} ${y.sqlLiteralString(m.values[0])}`;return m.not?`(${_} OR ${g} IS NULL)`:_}const E="("+m.values.map(A=>y.sqlLiteralString(A)).join(", ")+")";return m.not?`(${g} NOT IN ${E} OR ${g} IS NULL)`:`${g} IN ${E}`}case"()":{const E="("+t.FilterCompilers.stringCompile(m.expr,g,y)+")";return m.not?`not ${E}`:E}case"contains":{const E=m.values.map(A=>"%"+s(A)+"%");return m.not?u(E.map(A=>y.sqlLike("NOT LIKE",g,A)),g):E.map(A=>y.sqlLike("LIKE",g,A)).join(" OR ")}case"starts":{const E=m.values.map(A=>s(A)+"%");return m.not?u(E.map(A=>y.sqlLike("NOT LIKE",g,A)),g):E.map(A=>y.sqlLike("LIKE",g,A)).join(" OR ")}case"ends":{const E=m.values.map(A=>"%"+s(A));return m.not?u(E.map(A=>y.sqlLike("NOT LIKE",g,A)),g):E.map(A=>y.sqlLike("LIKE",g,A)).join(" OR ")}case"~":return m.not?u(m.escaped_values.map(E=>y.sqlLike("NOT LIKE",g,E)),g):m.escaped_values.map(E=>y.sqlLike("LIKE",g,E)).join(" OR ");case"and":return m.members.map(A=>t.FilterCompilers.stringCompile(A,g,y)).join(" AND ");case"or":return m.members.map(A=>t.FilterCompilers.stringCompile(A,g,y)).join(" AND ");case",":{const E=[],A=[];let _=!1,v=!1,C=!1,b=!1;for(const O of m.members)switch(O.operator){case"or":case"and":case",":E.push(O);break;case"null":O.not?v=!0:_=!0;break;case"empty":O.not?(b=!0,v=!0):(C=!0,_=!0);break;default:(O.not?A:E).push(O)}if(C&&b||_&&v)return"false";let S="";if(E.length>0||_||C){b=!1,v=!1;const O=E.map(B=>t.FilterCompilers.stringCompile(B,g,y));C&&O.push(`${g} = ''`),_&&O.push(`${g} IS NULL`),S=O.join(" OR ")}let R="";if(A.length>0||b||v){const O=A.map(B=>t.FilterCompilers.stringCompile(B,g,y));b&&O.push(`${g} != ''`),v&&O.push(`${g} IS NOT NULL`),R=O.join(" AND ")}return S?R!==""?`(${S}) AND (${R})`:S:R!==""?R:"true"}}},temporalCompile(m,g,y,E){return new p(g,y,E).compile(m)}};const a="yyyy",l=`${a}-LL`,c=`${l}-dd`,f=`${c} HH`,x=`${f}:mm`,h=`${x}:ss`;class p{constructor(g,y,E="timestamp"){this.expr=g,this.timetype=E,this.d=y}time(g){return this.timetype==="timestamp"?g:this.d.sqlCast({},{node:"cast",e:{node:"genericSQLExpr",src:["",g],kids:{args:[]},sql:g},srcType:{type:"timestamp"},dstType:{type:"date"},safe:!1})}compile(g){const y=this.expr;switch(g.operator){case"after":return`${y} ${g.not?"<":">="} ${this.time(this.moment(g.after).end)}`;case"before":return`${y} ${g.not?">=":"<"} ${this.time(this.moment(g.before).begin.sql)}`;case"in":{const E=this.moment(g.in);return E.begin.sql===E.end?g.not?`${y} != ${this.time(E.end)} OR ${y} IS NULL`:`${y} = ${this.time(E.end)}`:this.isIn(g.not,E.begin.sql,E.end)}case"for":{const E=this.moment(g.begin),A=this.delta(E.begin,"+",g.n,g.units);return this.isIn(g.not,E.begin.sql,A.sql)}case"in_last":{const E=Number(g.n)-1,A=this.nowDot(g.units),_=E>0?this.delta(A,"-",E.toString(),g.units):A,v=this.delta(A,"+","1",g.units);return this.isIn(g.not,_.sql,v.sql)}case"to":{const E=this.moment(g.fromMoment),A=this.moment(g.toMoment);return this.isIn(g.not,E.begin.sql,A.begin.sql)}case"last":{const E=this.nowDot(g.units),A=this.delta(E,"-",g.n,g.units);return this.isIn(g.not,A.sql,E.sql)}case"next":{const E=this.nowDot(g.units),A=this.delta(E,"+","1",g.units),_=this.delta(E,"+",(Number(g.n)+1).toString(),g.units);return this.isIn(g.not,A.sql,_.sql)}case"null":return g.not?`${y} IS NOT NULL`:`${y} IS NULL`;case"()":{const E="("+this.compile(g.expr)+")";return g.not?`NOT ${E}`:E}case"and":case"or":return g.members.map(E=>this.compile(E)).join(` ${g.operator.toUpperCase()} `)}}expandLiteral(g){let y=g.literal;switch(g.units){case"year":{const E=i.DateTime.fromFormat(y,a),A=this.literalNode(E.toFormat(h)),_=E.plus({year:1});return{begin:A,end:this.literalNode(_.toFormat(h)).sql}}case"month":{const E=i.DateTime.fromFormat(y,l),A=this.literalNode(E.toFormat(h)),_=E.plus({month:1});return{begin:A,end:this.literalNode(_.toFormat(h)).sql}}case"day":{const E=i.DateTime.fromFormat(y,c),A=this.literalNode(E.toFormat(h)),_=E.plus({day:1});return{begin:A,end:this.literalNode(_.toFormat(h)).sql}}case"hour":{const E=i.DateTime.fromFormat(y,f),A=this.literalNode(E.toFormat(h)),_=E.plus({hour:1});return{begin:A,end:this.literalNode(_.toFormat(h)).sql}}case"minute":{const E=i.DateTime.fromFormat(y,x),A=this.literalNode(E.toFormat(h)),_=E.plus({minute:1});return{begin:A,end:this.literalNode(_.toFormat(h)).sql}}case"week":{const _=i.DateTime.fromFormat(y.slice(0,10),c).plus({day:1}).startOf("week").minus({day:1}),v=this.literalNode(_.toFormat(h)),C=_.plus({days:7});return{begin:v,end:this.literalNode(C.toFormat(h)).sql}}case"quarter":{const E=y.slice(0,4),A=y.slice(6);A==="1"?y=`${E}-01-01 00:00:00`:A==="2"?y=`${E}-03-01 00:00:00`:A==="3"?y=`${E}-06-01 00:00:00`:y=`${E}-09-01 00:00:00`;const _=this.literalNode(y),C=i.DateTime.fromFormat(y,h).plus({months:3});return{begin:_,end:this.literalNode(C.toFormat(h)).sql}}case void 0:case"second":{const E=this.literalNode(y);return{begin:E,end:E.sql}}}}literalNode(g){const y={node:"timeLiteral",typeDef:{type:"timestamp"},literal:g};return{...y,sql:this.d.sqlLiteralTime({},y)}}nowExpr(){return{node:"now",typeDef:{type:"timestamp"},sql:this.d.sqlNowExpr()}}n(g){return{node:"numberLiteral",literal:g,sql:g}}delta(g,y,E,A){const _={node:"delta",op:y,units:A,kids:{base:(0,r.mkTemporal)(g,"timestamp"),delta:this.n(E)}};return{..._,sql:this.d.sqlAlterTimeExpr(_)}}dayofWeek(g){const y={node:"extract",e:(0,r.mkTemporal)(g,"timestamp"),units:"day_of_week"};return{...y,sql:this.d.sqlTimeExtractExpr({},y)}}nowDot(g){const y={node:"trunc",e:this.nowExpr(),units:g};return{...y,sql:this.d.sqlTruncExpr({},y)}}thisUnit(g){const y=this.nowDot(g),E=this.delta(y,"+","1",g);return{begin:y,end:E.sql}}lastUnit(g){const y=this.nowDot(g);return{begin:this.delta(y,"-","1",g),end:y.sql}}nextUnit(g){const y=this.nowDot(g),E=this.delta(y,"+","1",g),A=this.delta(y,"+","2",g);return{begin:E,end:A.sql}}mod7(g){return this.d.hasModOperator?`(${g})%7`:`MOD(${g},7)`}moment(g){switch(g.moment){case"now":{const y=this.nowExpr();return{begin:y,end:y.sql}}case"literal":return this.expandLiteral(g);case"ago":case"from_now":{const y=this.nowDot(g.units),E=(0,r.mkTemporal)(y,"timestamp"),A=this.delta(E,g.moment==="ago"?"-":"+",g.n,g.units);if(g.moment==="ago"&&g.n==="1")return{begin:A,end:y.sql};const _=Number(g.n)+(g.moment==="ago"?-1:1),v={...A,kids:{base:E,delta:this.n(_.toString())}};return{begin:A,end:this.d.sqlAlterTimeExpr(v)}}case"today":return this.thisUnit("day");case"yesterday":return this.lastUnit("day");case"tomorrow":return this.nextUnit("day");case"this":return this.thisUnit(g.units);case"last":return this.lastUnit(g.units);case"next":return this.nextUnit(g.units);case"monday":case"tuesday":case"wednesday":case"thursday":case"friday":case"saturday":case"sunday":{const y=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].indexOf(g.moment),E=this.dayofWeek(this.nowExpr()).sql;if(g.which==="next"){const C=`${this.mod7(`${y}-(${E}-1)+6`)}+1`,b=this.delta(this.thisUnit("day").begin,"+",C,"day"),S=this.delta(this.thisUnit("day").begin,"+",`${C}+1`,"day");return{begin:b,end:S.sql}}const A=`${this.mod7(`(${E}-1)-${y}+6`)}+1`,_=this.delta(this.thisUnit("day").begin,"-",A,"day"),v=this.delta(this.thisUnit("day").begin,"-",`(${A})-1`,"day");return{begin:_,end:v.sql}}}}isIn(g,y,E){let A=">=",_="<",v="AND";return g&&(v="OR",A="<",_=">="),y=this.time(y),E=this.time(E),`${this.expr} ${A} ${y} ${v} ${this.expr} ${_} ${E}`}}t.TemporalFilterCompiler=p})(cae),Object.defineProperty(Ls,"__esModule",{value:!0}),Ls.QueryModel=Ls.getResultStructDefForQuery=Ls.getResultStructDefForView=Ls.Segment=void 0;const aXe=Pp,lXe=kp,cXe=Ay,Be=Xe,Tn=Bt,P4=qp,fXe=ui,xXe=cae,U4=Cy;function yae(t){return t.map(e=>encodeURIComponent(e)).join("/")}function i$(t){return`'${t}'`}function dXe(t){return t.replace(/[^a-zA-Z0-9_]/g,"_o_")}function zp(t){const e=[];for(const r of t.fields.filter(Be.fieldIsIntrinsic))e.push({typeDef:r,sqlExpression:(0,Be.getIdentifier)(r),rawName:(0,Be.getIdentifier)(r),sqlOutputName:(0,Be.getIdentifier)(r)});return e}function Eae(t,e){const{sqlExpression:r,sqlOutputName:i,rawName:s}=e;(0,Be.isAtomic)(e.fieldDef)&&t.push({typeDef:e.fieldDef,sqlExpression:r,sqlOutputName:i,rawName:s})}class hXe extends Set{add_use(e){if(e!==void 0)return this.add(e)}hasAsymetricFunctions(){return this.has("sum")||this.has("avg")||this.has("count")||this.has("generic_asymmetric_aggregate")}}class Gp{constructor(e=!0,r){this.parent=r,this.withs=[],this.udfs=[],this.pdts=[],this.dependenciesToMaterialize={},this.stagePrefix="__stage",this.useCTE=e}getName(e){return`${this.stagePrefix}${e}`}root(){return this.parent===void 0?this:this.parent.root()}addStage(e){return this.useCTE?(this.withs.push(e),this.getName(this.withs.length-1)):(this.withs[0]=e,(0,Tn.indent)(`
1046
1046
  (${e})
1047
1047
  `))}addUDF(e,r,i){var s;let{sql:o,lastStageName:u}=e.combineStages(!0);if(u===void 0)throw new Error("Internal Error: no stage to combine");o+=r.sqlCreateFunctionCombineLastStage(u,zp(i),(s=i.resultMetadata)===null||s===void 0?void 0:s.orderBy);const a=`${r.udfPrefix}${this.root().udfs.length}`;return o=r.sqlCreateFunction(a,o),this.root().udfs.push(o),a}addMaterializedQuery(e,r,i){var s;const o=r.name;if(!o)throw new Error(`Source ${e} on a unnamed query that is tagged as materialize, only named queries can be materialized.`);const u=(s=r.location)===null||s===void 0?void 0:s.url;if(!u)throw new Error(`Trying to materialize query ${o}, but its path is not set.`);const a=(0,P4.buildQueryMaterializationSpec)(u,o,i);return this.root().dependenciesToMaterialize[a.id]=a,a.id}addPDT(e,r){const i=this.combineStages(!1).sql+this.withs[this.withs.length-1],o=`scratch.${e+(0,Tn.generateHash)(i)}`;return this.root().pdts.push(r.sqlCreateTableAsSelect(o,i)),o}combineStages(e){if(!this.useCTE)return{sql:this.withs[0],lastStageName:this.withs[0]};let r=this.getName(0),i="WITH ",s="";for(let o=0;o<this.withs.length-(e?0:1);o++){const u=this.withs[o];if(r=this.getName(o),u===void 0)throw new Error(`Expected sql WITH to be present for stage ${r}.`);s+=`${i}${r} AS (
1048
1048
  ${(0,Tn.indent)(u)})
1049
1049
  `,i=", "}return{sql:s,lastStageName:r}}generateSQLStages(){const e=this.withs.length-1;if(e<0)throw new Error("No SQL generated");const r=this.udfs.join(`
1050
1050
  `),i=this.pdts.join(`
1051
- `),s=this.combineStages(!1).sql;return r+i+s+this.withs[e]}generateCoorelatedSubQuery(e,r){var i,s;return this.useCTE?this.combineStages(!0).sql+e.sqlCreateFunctionCombineLastStage(this.getName(this.withs.length-1),zp(r),(s=r.resultMetadata)===null||s===void 0?void 0:s.orderBy):e.sqlCreateFunctionCombineLastStage(`(${this.withs[0]})`,zp(r),(i=r.resultMetadata)===null||i===void 0?void 0:i.orderBy)}}class Ty{constructor(){this.totalGroupSet=-1}withWhere(e){const r=new Ty;return r.whereSQL=e,r.applyValue=this.applyValue,r.totalGroupSet=this.totalGroupSet,r}withApply(e){const r=new Ty;return r.whereSQL=this.whereSQL,r.applyValue=e,r.totalGroupSet=this.totalGroupSet,r}withTotal(e){const r=new Ty;return r.whereSQL=this.whereSQL,r.applyValue=this.applyValue,r.totalGroupSet=e,r}}class dXe{constructor(e){this.referenceId=e??(0,oXe.v4)()}getChildByName(e){}}let s$=class extends dXe{constructor(e,r,i){super(i),this.fieldDef=e,this.parent=r,this.fieldDef=e}getIdentifier(){return(0,Be.getIdentifier)(this.fieldDef)}uniqueKeyPossibleUse(){}getJoinableParent(){const e=this.parent;return e.structDef.type==="record"?e.getJoinableParent():e}isAtomic(){return(0,Be.isAtomic)(this.fieldDef)}caseGroup(e,r){return e.length===0?r:`CASE WHEN group_set${e.length===1?`=${e[0]}`:` IN (${e.join(",")})`} THEN
1051
+ `),s=this.combineStages(!1).sql;return r+i+s+this.withs[e]}generateCoorelatedSubQuery(e,r){var i,s;return this.useCTE?this.combineStages(!0).sql+e.sqlCreateFunctionCombineLastStage(this.getName(this.withs.length-1),zp(r),(s=r.resultMetadata)===null||s===void 0?void 0:s.orderBy):e.sqlCreateFunctionCombineLastStage(`(${this.withs[0]})`,zp(r),(i=r.resultMetadata)===null||i===void 0?void 0:i.orderBy)}}class Ty{constructor(){this.totalGroupSet=-1}withWhere(e){const r=new Ty;return r.whereSQL=e,r.applyValue=this.applyValue,r.totalGroupSet=this.totalGroupSet,r}withApply(e){const r=new Ty;return r.whereSQL=this.whereSQL,r.applyValue=e,r.totalGroupSet=this.totalGroupSet,r}withTotal(e){const r=new Ty;return r.whereSQL=this.whereSQL,r.applyValue=this.applyValue,r.totalGroupSet=e,r}}class pXe{constructor(e){this.referenceId=e??(0,aXe.v4)()}getChildByName(e){}}let s$=class extends pXe{constructor(e,r,i){super(i),this.fieldDef=e,this.parent=r,this.fieldDef=e}getIdentifier(){return(0,Be.getIdentifier)(this.fieldDef)}uniqueKeyPossibleUse(){}getJoinableParent(){const e=this.parent;return e.structDef.type==="record"?e.getJoinableParent():e}isAtomic(){return(0,Be.isAtomic)(this.fieldDef)}caseGroup(e,r){return e.length===0?r:`CASE WHEN group_set${e.length===1?`=${e[0]}`:` IN (${e.join(",")})`} THEN
1052
1052
  ${r}
1053
- END`}getFullOutputName(){return this.parent.getFullOutputName()+this.getIdentifier()}generateFieldFragment(e,r,i,s){const o=r.getFieldByName(i.path);return(0,Be.hasExpression)(o.fieldDef)?`(${this.exprToSQL(e,o.parent,o.fieldDef.e,s)})`:o.generateExpression(e)}generateOutputFieldFragment(e,r,i,s){return`(${e.getField(i.name).getAnalyticalSQL(!1)})`}*stringsFromSQLExpression(e,r,i,s){const o=[...i.kids.args];for(const u of i.src){yield u;const a=o.shift();a&&(yield this.exprToSQL(e,r,a,s))}}getParameterMap(e,r){return new Map(e.params.map((i,s)=>{const o=i.isVariadic?(0,Tn.range)(s,r):[s];return[i.name,{param:i,argIndexes:o}]}))}expandFunctionCall(e,r,i,s,o){function u(c){const f=[];for(let x=0;x<c.length;)f.push(c[x]),x+=1,x<c.length&&f.push(",");return f}const a=this.getParameterMap(r,i.length);if(r.dialect[e]===void 0)throw new Error(`Function is not defined for '${e}' dialect`);return(0,Tn.exprMap)(r.dialect[e].e,c=>{var f,x;if(c.node==="spread"){const h=c.e;if(h.node!=="function_parameter")throw new Error("Invalid function definition. Argument to spread must be a function parameter.");const p=a.get(h.name);if(p===void 0)return c;const m=p.argIndexes.map(g=>i[g]);return(0,Tn.composeSQLExpr)(u(m))}else if(c.node==="function_parameter"){const h=a.get(c.name);if(h===void 0)return c;if(h.param.isVariadic){const p=h.argIndexes.map(m=>i[m]);return(0,Tn.composeSQLExpr)(u(p))}else return i[h.argIndexes[0]]}else{if(c.node==="aggregate_order_by")return s?(0,Tn.composeSQLExpr)([` ${(f=c.prefix)!==null&&f!==void 0?f:""}${s}${(x=c.suffix)!==null&&x!==void 0?x:""}`]):{node:""};if(c.node==="aggregate_limit")return o?(0,Tn.composeSQLExpr)([` ${o}`]):{node:""}}return c})}getFunctionOrderBy(e,r,i,s,o,u){if(s.length!==0)return"ORDER BY "+s.map(a=>{var l;const c=(l=u.dialect[r.dialect.name].defaultOrderByArgIndex)!==null&&l!==void 0?l:0,f=a.node==="functionOrderBy"?a.e:o[c],x=this.generateDimFragment(e,r,f,i),h=a.dir==="asc"?" ASC":a.dir==="desc"?" DESC":"";return`${x}${h}`}).join(", ")}generateAsymmetricStringAggExpression(e,r,i,s,o,u,a,l){if(u)throw new Error(`Function \`string_agg\` does not support fanning out with an order by in ${a}`);const c=this.generateDimFragment(e,r,i,l),f=s?this.generateDimFragment(e,r,s,l):"";return this.parent.dialect.sqlStringAggDistinct(o,c,f)}getParamForArgIndex(e,r){const i=e.slice(0,r).find(s=>s.isVariadic);return i??e[r]}generateFunctionCallExpression(e,r,i,s){var o,u,a;const l=i.overload,c=i.kids.args,f=(o=i.overload.isSymmetric)!==null&&o!==void 0?o:!1,x=(0,Be.expressionIsAggregate)(l.returnType.expressionType)&&!f&&this.generateDistinctKeyIfNecessary(e,r,i.structPath),h=i.limit?`LIMIT ${i.limit}`:void 0;if(i.name==="string_agg"&&x&&!r.dialect.supportsAggDistinct&&r.dialect.name!=="snowflake")return this.generateAsymmetricStringAggExpression(e,r,c[0],c[1],x,i.kids.orderBy,r.dialect.name,s);if(x){if(!r.dialect.supportsAggDistinct)throw new Error(`Function \`${i.name}\` does not support fanning out in ${r.dialect.name}`);const p=c.map(y=>this.generateDimFragment(e,r,y,s)),m=(u=i.kids.orderBy)!==null&&u!==void 0?u:[],g=m.map(y=>{var E;const A=(E=l.dialect[r.dialect.name].defaultOrderByArgIndex)!==null&&E!==void 0?E:0,_=y.node==="functionOrderBy"?y.e:c[A];return this.generateDimFragment(e,r,_,s)});return r.dialect.sqlAggDistinct(x,[...p,...g],y=>{const E=y.map((b,S)=>S<c.length&&this.getParamForArgIndex(l.params,S).allowedTypes.every(O=>(0,Be.isLiteral)(O.evalSpace))?c[S]:(0,Tn.composeSQLExpr)([b])),A=E.slice(0,p.length),_=E.slice(p.length).map((b,S)=>({node:"functionOrderBy",e:b,dir:m[S].dir})),v=this.getFunctionOrderBy(e,r,s,_,A,l),C=this.expandFunctionCall(r.dialect.name,l,A,v,h);return this.exprToSQL(e,r,C,s)})}else{const p=(0,Be.expressionIsAggregate)(l.returnType.expressionType)?c.map((y,E)=>this.getParamForArgIndex(l.params,E).allowedTypes.every(_=>(0,Be.isLiteral)(_.evalSpace))?y:(0,Tn.composeSQLExpr)([this.generateDimFragment(e,r,y,s)])):c,m=i.kids.orderBy?this.getFunctionOrderBy(e,r,s,i.kids.orderBy,c,l):"",g=this.expandFunctionCall(r.dialect.name,l,p,m,h);if((0,Be.expressionIsAnalytic)(l.returnType.expressionType)){const y=((a=i.partitionBy)!==null&&a!==void 0?a:[]).map(E=>`(${e.getField(E).getAnalyticalSQL(!1)})`);return this.generateAnalyticFragment(r.dialect.name,e,r,g,l,s,c,y,m)}return this.exprToSQL(e,r,g,s)}}generateSpread(e,r,i,s){throw new Error("Unexpanded spread encountered during SQL generation")}generateParameterFragment(e,r,i,s){var o;const u=i.path[0];(o=r.eventStream)===null||o===void 0||o.emit("source-argument-compiled",{name:u});const a=r.arguments()[u];if(a.value)return this.exprToSQL(e,r,a.value,s);throw new Error(`Can't generate SQL, no value for ${i.path}`)}generateFilterFragment(e,r,i,s){const o=new Tn.AndChain(s.whereSQL);for(const u of i.kids.filterList)o.add(this.exprToSQL(e,r,u.e,s.withWhere()));return this.exprToSQL(e,r,i.kids.e,s.withWhere(o.sql()))}generateDimFragment(e,r,i,s){let o=this.exprToSQL(e,r,i,s);return s.whereSQL&&(o=`CASE WHEN ${s.whereSQL} THEN ${o} END`),o}generateUngroupedFragment(e,r,i,s){if(s.totalGroupSet!==-1)throw new Error("Already in ALL. Cannot nest within an all calcuation.");let o,u;if(i.fields&&i.fields.length>0){const x=i.fields.sort().join("|")+i.node;if(u=e.ungroupedSets.get(x),u===void 0)throw new Error(`Internal Error, cannot find groupset with key ${x}`);o=u.groupSet}else o=e.parent?e.parent.groupSet:0;const a=this.exprToSQL(e,r,i.e,s.withTotal(o)),l=e.getUngroupPartitions(u);let c="";const f=l.map(x=>x.getAnalyticalSQL(!0)).join(", ");return f.length>0&&(c=`PARTITION BY ${f}`),`MAX(${a}) OVER (${c})`}generateDistinctKeyIfNecessary(e,r,i){let s=r;if(i&&(s=this.parent.root().getStructByName(i)),s.needsSymetricCalculation(e))return s.getDistinctKey().generateExpression(e)}generateSumFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s),u=this.generateDistinctKeyIfNecessary(e,r,i.structPath);let a;return u?this.parent.dialect.supportsSumDistinctFunction?a=this.parent.dialect.sqlSumDistinct(u,o,"SUM"):a=vae(this.parent.dialect,o,u):a=`SUM(${o})`,`COALESCE(${a},0)`}generateSymmetricFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s);return`${i.function==="distinct"?"count(distinct ":i.function+"("}${o})`}generateAvgFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s),u=this.generateDistinctKeyIfNecessary(e,r,i.structPath);if(u){let a=u;s.whereSQL&&(a=`CASE WHEN ${s.whereSQL} THEN ${u} END`);let l,c;return this.parent.dialect.supportsSumDistinctFunction?c=this.parent.dialect.sqlSumDistinct(u,o,"AVG"):(l=vae(this.parent.dialect,o,u),c=`(${l})/NULLIF(COUNT(DISTINCT CASE WHEN ${o} IS NOT NULL THEN ${a} END),0)`),c}else return`AVG(${o})`}generateCountFragment(e,r,i,s){let o="COUNT(",u="1",a=r;i.structPath&&(a=this.parent.root().getStructByName(i.structPath));const l=a.getJoinableParent().getIdentifier(),c=e.root().joins.get(l);if(!c)throw new Error(`Join ${l} not found in result set`);return(!c.leafiest||c.makeUniqueKey)&&(o="COUNT(DISTINCT ",u=a.getDistinctKey().generateExpression(e)),s.whereSQL?`${o}CASE WHEN ${s.whereSQL} THEN ${u} END)`:`${o}${u})`}generateSourceReference(e,r,i){return i.path===void 0?r.getSQLIdentifier():r.getFieldByName(i.path).getIdentifier()}getAnalyticPartitions(e,r){const i=[];let s=e.parent;for(;s!==void 0;){const u=s.fields(a=>Wp(a.f)&&a.fieldUsage.type==="result").map(a=>a.getAnalyticalSQL(!0));i.push(...u),s=s.parent}return r&&i.push(...r),i}generateAnalyticFragment(e,r,i,s,o,u,a,l,c){const f=r.root().isComplexQuery,x=this.getAnalyticPartitions(r,l),h=[...f?["group_set"]:[],...x],p=h.length>0?`PARTITION BY ${h.join(", ")}`:"";let m=c??"";const g=o.dialect[e];if(!c&&g.needsWindowOrderBy){const _=[];let v;const C=r.firstSegment.orderBy||r.calculateDefaultOrderBy();for(const b of C){typeof b.field=="string"?v={name:b.field,fif:r.getField(b.field)}:v=r.getFieldByNumber(b.field);const S=v.fif.f.fieldDef.expressionType;if(!(0,Be.expressionIsAnalytic)(S))if(r.firstSegment.type==="reduce"){const R=v.fif.getAnalyticalSQL(!1);_.push(` ${R} ${b.dir||"ASC"}`)}else r.firstSegment.type==="project"&&_.push(` ${v.fif.f.generateExpression(r)} ${b.dir||"ASC"}`)}_.length>0&&(m=" "+this.parent.dialect.sqlOrderBy(_,"analytical"))}let y="";if(g.between){const[_,v]=[g.between.preceding,g.between.following].map(C=>{if(C===-1)return"UNBOUNDED";if(typeof C=="number")return C;const b=o.params.findIndex(R=>R.name===C),S=a[b];if(S.node!=="numberLiteral")throw new Error("Invalid number of rows for window spec");return S.literal});y=`ROWS BETWEEN ${_} PRECEDING AND ${v} FOLLOWING`}let A=`${this.exprToSQL(r,i,s,u)} OVER(${p} ${m} ${y})`;return f&&(A=`CASE WHEN group_set=${r.groupSet} THEN ${A} END`),A}generateCaseSQL(e){const r=["CASE"];e.kids.caseValue!==void 0&&r.push(`${e.kids.caseValue.sql}`);for(let i=0;i<e.kids.caseWhen.length;i+=1)r.push(`WHEN ${e.kids.caseWhen[i].sql} THEN ${e.kids.caseThen[i].sql}`);return e.kids.caseElse!==void 0&&r.push(`ELSE ${e.kids.caseElse.sql}`),r.push("END"),r.join(" ")}exprToSQL(e,r,i,s=new Ty){var o;const u=function(f,x){const h=f.exprToSQL(e,r,x,s);return(0,Be.exprHasKids)(x)?`(${h})`:h};let a=i;if((0,Be.exprHasE)(i)){a={...i};const f=u(this,a.e);a.e={...a.e,sql:f}}else if((0,Be.exprHasKids)(i)){a={...i};const f=i.kids;for(const[x,h]of Object.entries(f))h!==null&&(Array.isArray(h)?a.kids[x]=h.map(p=>({...p,sql:u(this,p)})):a.kids[x]={...f[x],sql:u(this,h)})}const l=e.getQueryInfo(),c=this.parent.dialect.exprToSQL(l,a);if(c)return c;switch(a.node){case"field":return this.generateFieldFragment(e,r,a,s);case"parameter":return this.generateParameterFragment(e,r,a,s);case"filteredExpr":return this.generateFilterFragment(e,r,a,s);case"all":case"exclude":return this.generateUngroupedFragment(e,r,a,s);case"genericSQLExpr":return Array.from(this.stringsFromSQLExpression(e,r,a,s)).join("");case"aggregate":{let f="";if(a.function==="sum")f=this.generateSumFragment(e,r,a,s);else if(a.function==="avg")f=this.generateAvgFragment(e,r,a,s);else if(a.function==="count")f=this.generateCountFragment(e,r,a,s);else if(a.function==="min"||a.function==="max"||a.function==="distinct")f=this.generateSymmetricFragment(e,r,a,s);else throw new Error(`Internal Error: Unknown aggregate function ${a.function}`);if(e.root().isComplexQuery){let x=e.groupSet;return s.totalGroupSet!==-1&&(x=s.totalGroupSet),this.caseGroup([x],f)}return f}case"function_parameter":throw new Error("Internal Error: Function parameter fragment remaining during SQL generation");case"outputField":return this.generateOutputFieldFragment(e,r,a,s);case"function_call":return this.generateFunctionCallExpression(e,r,a,s);case"spread":return this.generateSpread(e,r,a,s);case"source-reference":return this.generateSourceReference(e,r,a);case"+":case"-":case"*":case"%":case"/":case">":case"<":case">=":case"<=":case"=":return`${a.kids.left.sql}${a.node}${a.kids.right.sql}`;case"!=":return`COALESCE(${`${a.kids.left.sql}!=${a.kids.right.sql}`},true)`;case"and":case"or":return`${a.kids.left.sql} ${a.node} ${a.kids.right.sql}`;case"coalesce":return`COALESCE(${a.kids.left.sql},${a.kids.right.sql})`;case"in":{const f=a.kids.oneOf.map(x=>x.sql).join(",");return`${a.kids.e.sql} ${a.not?"NOT IN":"IN"} (${f})`}case"like":case"!like":{const f=a.node==="like"?"LIKE":"NOT LIKE",x=a.kids.right.node==="stringLiteral"?this.parent.dialect.sqlLike(f,(o=a.kids.left.sql)!==null&&o!==void 0?o:"",a.kids.right.literal):`${a.kids.left.sql} ${f} ${a.kids.right.sql}`;return a.node==="like"?x:`COALESCE(${x},true)`}case"()":return`(${a.e.sql})`;case"not":return`COALESCE(NOT ${a.e.sql},TRUE)`;case"unary-":return`-${a.e.sql}`;case"is-null":return`${a.e.sql} IS NULL`;case"is-not-null":return`${a.e.sql} IS NOT NULL`;case"true":case"false":return a.node;case"null":return"NULL";case"case":return this.generateCaseSQL(a);case"":return"";case"filterCondition":return a.e.sql?(a.sql=a.e.sql,a.sql):"";case"functionDefaultOrderBy":case"functionOrderBy":return"";case"compositeField":return"{COMPOSITE_FIELD}";case"filterMatch":return this.generateAppliedFilter(r,a);case"filterLiteral":return"INTERNAL ERROR FILTER EXPRESSION VALUE SHOULD NOT BE USED";default:throw new Error(`Internal Error: Unknown expression node '${a.node}' ${JSON.stringify(a,void 0,2)}`)}}generateAppliedFilter(e,r){var i;let s=r.kids.filterExpr;for(;s.node==="()";)s=s.e;if(s.node==="parameter"){const a=s.path[0];(i=e.eventStream)===null||i===void 0||i.emit("source-argument-compiled",{name:a});const l=e.arguments()[a];if(l.value)s=l.value;else throw new Error(`Parameter ${a} was expected to be a filter expression`)}if(s.node!=="filterLiteral")throw new Error("Can only use filter expression literals or parameters as filter expressions");const o=s.filterSrc;let u;switch(r.dataType){case"string":u=U4.StringFilterExpression.parse(o);break;case"number":u=U4.NumberFilterExpression.parse(o);break;case"boolean":u=U4.BooleanFilterExpression.parse(o);break;case"date":case"timestamp":u=U4.TemporalFilterExpression.parse(o);break}if(u.log.length>0)throw new Error(`Filter expression parse error: ${u.log[0]}`);return cXe.FilterCompilers.compile(r.dataType,u.parsed,r.kids.expr.sql||"",e.dialect)}isNestedInParent(e){switch(e.type){case"record":case"array":return!0;default:return!1}}isArrayElement(e){return e.type==="array"&&e.elementTypeDef.type!=="record_element"}generateExpression(e){if((0,Be.hasExpression)(this.fieldDef))return this.exprToSQL(e,this.parent,this.fieldDef.e);for(let r=this.parent;r!==void 0;r=r.parent)if(r.structDef.type==="record"&&(0,Be.hasExpression)(r.structDef)&&r.recordAlias===void 0){if(!r.parent)throw new Error("Inconcievable record ancestor with expression but no parent");const i=this.exprToSQL(e,r.parent,r.structDef.e);r.informOfAliasValue(i)}return this.parent.sqlChildReference(this.fieldDef.name,this.parent.structDef.type==="record"?{result:e,field:this}:void 0)}includeInWildcard(){return!1}};function j4(t){return t instanceof Is&&hXe(t)}function Aae(t){return t instanceof Is&&pXe(t)}function Wp(t){return t instanceof Is&&yo(t)}function yo(t){if(t.isAtomic()){if((0,Be.hasExpression)(t.fieldDef)){const e=t.fieldDef.expressionType;if((0,Be.expressionIsCalculation)(e)||(0,Be.expressionIsAggregate)(e))return!1}return!0}return!1}function hXe(t){return t.isAtomic()&&(0,Be.hasExpression)(t.fieldDef)?(0,Be.expressionIsCalculation)(t.fieldDef.expressionType):!1}function pXe(t){return t.isAtomic()&&(0,Be.hasExpression)(t.fieldDef)?(0,Be.expressionIsAggregate)(t.fieldDef.expressionType):!1}class Is extends s${constructor(e,r,i){super(e,r,i),this.fieldDef=e}includeInWildcard(){return!0}getFilterList(){return[]}}class mXe extends Is{}class gXe extends Is{}class o$ extends Is{}class yXe extends Is{}class EXe extends Is{}class u$ extends Is{generateExpression(e){const r=this.fieldDef,i=super.generateExpression(e);if(r.timeframe){const s={node:"trunc",e:(0,Be.mkTemporal)({node:"genericSQLExpr",src:[i],kids:{args:[]}},"date"),units:r.timeframe};return this.exprToSQL(e,this.parent,s)}else return i}getChildByName(e){const r={...this.fieldDef,as:`${this.getIdentifier()}_${e}`,timeframe:e};return new u$(r,this.parent)}}class a$ extends Is{getChildByName(e){const r={...this.fieldDef,as:`${this.getIdentifier()}_${e}`,timeframe:e};return new a$(r,this.parent)}}class AXe extends Is{generateExpression(e){var r;if(this.parent.primaryKey())return this.parent.getPrimaryKeyField(this.fieldDef).generateExpression(e);if(this.parent.structDef.type==="array"){const i=(r=this.parent.parent)===null||r===void 0?void 0:r.getDistinctKey().generateExpression(e);return this.parent.dialect.sqlMakeUnnestKey(i||"",this.parent.dialect.sqlFieldReference(this.parent.getIdentifier(),"table","__row_id","string"))}else return this.parent.dialect.sqlFieldReference(this.parent.getIdentifier(),"table","__distinct_key","string")}includeInWildcard(){return!1}}const _ae=9;function vae(t,e,r){const s=t.sqlSumDistinctHashedKey(r),o=10**(9-_ae);let a=`(${`
1053
+ END`}getFullOutputName(){return this.parent.getFullOutputName()+this.getIdentifier()}generateFieldFragment(e,r,i,s){const o=r.getFieldByName(i.path);return(0,Be.hasExpression)(o.fieldDef)?`(${this.exprToSQL(e,o.parent,o.fieldDef.e,s)})`:o.generateExpression(e)}generateOutputFieldFragment(e,r,i,s){return`(${e.getField(i.name).getAnalyticalSQL(!1)})`}*stringsFromSQLExpression(e,r,i,s){const o=[...i.kids.args];for(const u of i.src){yield u;const a=o.shift();a&&(yield this.exprToSQL(e,r,a,s))}}getParameterMap(e,r){return new Map(e.params.map((i,s)=>{const o=i.isVariadic?(0,Tn.range)(s,r):[s];return[i.name,{param:i,argIndexes:o}]}))}expandFunctionCall(e,r,i,s,o){function u(c){const f=[];for(let x=0;x<c.length;)f.push(c[x]),x+=1,x<c.length&&f.push(",");return f}const a=this.getParameterMap(r,i.length);if(r.dialect[e]===void 0)throw new Error(`Function is not defined for '${e}' dialect`);return(0,Tn.exprMap)(r.dialect[e].e,c=>{var f,x;if(c.node==="spread"){const h=c.e;if(h.node!=="function_parameter")throw new Error("Invalid function definition. Argument to spread must be a function parameter.");const p=a.get(h.name);if(p===void 0)return c;const m=p.argIndexes.map(g=>i[g]);return(0,Tn.composeSQLExpr)(u(m))}else if(c.node==="function_parameter"){const h=a.get(c.name);if(h===void 0)return c;if(h.param.isVariadic){const p=h.argIndexes.map(m=>i[m]);return(0,Tn.composeSQLExpr)(u(p))}else return i[h.argIndexes[0]]}else{if(c.node==="aggregate_order_by")return s?(0,Tn.composeSQLExpr)([` ${(f=c.prefix)!==null&&f!==void 0?f:""}${s}${(x=c.suffix)!==null&&x!==void 0?x:""}`]):{node:""};if(c.node==="aggregate_limit")return o?(0,Tn.composeSQLExpr)([` ${o}`]):{node:""}}return c})}getFunctionOrderBy(e,r,i,s,o,u){if(s.length!==0)return"ORDER BY "+s.map(a=>{var l;const c=(l=u.dialect[r.dialect.name].defaultOrderByArgIndex)!==null&&l!==void 0?l:0,f=a.node==="functionOrderBy"?a.e:o[c],x=this.generateDimFragment(e,r,f,i),h=a.dir==="asc"?" ASC":a.dir==="desc"?" DESC":"";return`${x}${h}`}).join(", ")}generateAsymmetricStringAggExpression(e,r,i,s,o,u,a,l){if(u)throw new Error(`Function \`string_agg\` does not support fanning out with an order by in ${a}`);const c=this.generateDimFragment(e,r,i,l),f=s?this.generateDimFragment(e,r,s,l):"";return this.parent.dialect.sqlStringAggDistinct(o,c,f)}getParamForArgIndex(e,r){const i=e.slice(0,r).find(s=>s.isVariadic);return i??e[r]}generateFunctionCallExpression(e,r,i,s){var o,u,a;const l=i.overload,c=i.kids.args,f=(o=i.overload.isSymmetric)!==null&&o!==void 0?o:!1,x=(0,Be.expressionIsAggregate)(l.returnType.expressionType)&&!f&&this.generateDistinctKeyIfNecessary(e,r,i.structPath),h=i.limit?`LIMIT ${i.limit}`:void 0;if(i.name==="string_agg"&&x&&!r.dialect.supportsAggDistinct&&r.dialect.name!=="snowflake")return this.generateAsymmetricStringAggExpression(e,r,c[0],c[1],x,i.kids.orderBy,r.dialect.name,s);if(x){if(!r.dialect.supportsAggDistinct)throw new Error(`Function \`${i.name}\` does not support fanning out in ${r.dialect.name}`);const p=c.map(y=>this.generateDimFragment(e,r,y,s)),m=(u=i.kids.orderBy)!==null&&u!==void 0?u:[],g=m.map(y=>{var E;const A=(E=l.dialect[r.dialect.name].defaultOrderByArgIndex)!==null&&E!==void 0?E:0,_=y.node==="functionOrderBy"?y.e:c[A];return this.generateDimFragment(e,r,_,s)});return r.dialect.sqlAggDistinct(x,[...p,...g],y=>{const E=y.map((b,S)=>S<c.length&&this.getParamForArgIndex(l.params,S).allowedTypes.every(O=>(0,Be.isLiteral)(O.evalSpace))?c[S]:(0,Tn.composeSQLExpr)([b])),A=E.slice(0,p.length),_=E.slice(p.length).map((b,S)=>({node:"functionOrderBy",e:b,dir:m[S].dir})),v=this.getFunctionOrderBy(e,r,s,_,A,l),C=this.expandFunctionCall(r.dialect.name,l,A,v,h);return this.exprToSQL(e,r,C,s)})}else{const p=(0,Be.expressionIsAggregate)(l.returnType.expressionType)?c.map((y,E)=>this.getParamForArgIndex(l.params,E).allowedTypes.every(_=>(0,Be.isLiteral)(_.evalSpace))?y:(0,Tn.composeSQLExpr)([this.generateDimFragment(e,r,y,s)])):c,m=i.kids.orderBy?this.getFunctionOrderBy(e,r,s,i.kids.orderBy,c,l):"",g=this.expandFunctionCall(r.dialect.name,l,p,m,h);if((0,Be.expressionIsAnalytic)(l.returnType.expressionType)){const y=((a=i.partitionBy)!==null&&a!==void 0?a:[]).map(E=>`(${e.getField(E).getAnalyticalSQL(!1)})`);return this.generateAnalyticFragment(r.dialect.name,e,r,g,l,s,c,y,m)}return this.exprToSQL(e,r,g,s)}}generateSpread(e,r,i,s){throw new Error("Unexpanded spread encountered during SQL generation")}generateParameterFragment(e,r,i,s){var o;const u=i.path[0];(o=r.eventStream)===null||o===void 0||o.emit("source-argument-compiled",{name:u});const a=r.arguments()[u];if(a.value)return this.exprToSQL(e,r,a.value,s);throw new Error(`Can't generate SQL, no value for ${i.path}`)}generateFilterFragment(e,r,i,s){const o=new Tn.AndChain(s.whereSQL);for(const u of i.kids.filterList)o.add(this.exprToSQL(e,r,u.e,s.withWhere()));return this.exprToSQL(e,r,i.kids.e,s.withWhere(o.sql()))}generateDimFragment(e,r,i,s){let o=this.exprToSQL(e,r,i,s);return s.whereSQL&&(o=`CASE WHEN ${s.whereSQL} THEN ${o} END`),o}generateUngroupedFragment(e,r,i,s){if(s.totalGroupSet!==-1)throw new Error("Already in ALL. Cannot nest within an all calcuation.");let o,u;if(i.fields&&i.fields.length>0){const x=i.fields.sort().join("|")+i.node;if(u=e.ungroupedSets.get(x),u===void 0)throw new Error(`Internal Error, cannot find groupset with key ${x}`);o=u.groupSet}else o=e.parent?e.parent.groupSet:0;const a=this.exprToSQL(e,r,i.e,s.withTotal(o)),l=e.getUngroupPartitions(u);let c="";const f=l.map(x=>x.getAnalyticalSQL(!0)).join(", ");return f.length>0&&(c=`PARTITION BY ${f}`),`MAX(${a}) OVER (${c})`}generateDistinctKeyIfNecessary(e,r,i){let s=r;if(i&&(s=this.parent.root().getStructByName(i)),s.needsSymetricCalculation(e))return s.getDistinctKey().generateExpression(e)}generateSumFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s),u=this.generateDistinctKeyIfNecessary(e,r,i.structPath);let a;return u?this.parent.dialect.supportsSumDistinctFunction?a=this.parent.dialect.sqlSumDistinct(u,o,"SUM"):a=vae(this.parent.dialect,o,u):a=`SUM(${o})`,`COALESCE(${a},0)`}generateSymmetricFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s);return`${i.function==="distinct"?"count(distinct ":i.function+"("}${o})`}generateAvgFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s),u=this.generateDistinctKeyIfNecessary(e,r,i.structPath);if(u){let a=u;s.whereSQL&&(a=`CASE WHEN ${s.whereSQL} THEN ${u} END`);let l,c;return this.parent.dialect.supportsSumDistinctFunction?c=this.parent.dialect.sqlSumDistinct(u,o,"AVG"):(l=vae(this.parent.dialect,o,u),c=`(${l})/NULLIF(COUNT(DISTINCT CASE WHEN ${o} IS NOT NULL THEN ${a} END),0)`),c}else return`AVG(${o})`}generateCountFragment(e,r,i,s){let o="COUNT(",u="1",a=r;i.structPath&&(a=this.parent.root().getStructByName(i.structPath));const l=a.getJoinableParent().getIdentifier(),c=e.root().joins.get(l);if(!c)throw new Error(`Join ${l} not found in result set`);return(!c.leafiest||c.makeUniqueKey)&&(o="COUNT(DISTINCT ",u=a.getDistinctKey().generateExpression(e)),s.whereSQL?`${o}CASE WHEN ${s.whereSQL} THEN ${u} END)`:`${o}${u})`}generateSourceReference(e,r,i){return i.path===void 0?r.getSQLIdentifier():r.getFieldByName(i.path).getIdentifier()}getAnalyticPartitions(e,r){const i=[];let s=e.parent;for(;s!==void 0;){const u=s.fields(a=>Wp(a.f)&&a.fieldUsage.type==="result").map(a=>a.getAnalyticalSQL(!0));i.push(...u),s=s.parent}return r&&i.push(...r),i}generateAnalyticFragment(e,r,i,s,o,u,a,l,c){const f=r.root().isComplexQuery,x=this.getAnalyticPartitions(r,l),h=[...f?["group_set"]:[],...x],p=h.length>0?`PARTITION BY ${h.join(", ")}`:"";let m=c??"";const g=o.dialect[e];if(!c&&g.needsWindowOrderBy){const _=[];let v;const C=r.firstSegment.orderBy||r.calculateDefaultOrderBy();for(const b of C){typeof b.field=="string"?v={name:b.field,fif:r.getField(b.field)}:v=r.getFieldByNumber(b.field);const S=v.fif.f.fieldDef.expressionType;if(!(0,Be.expressionIsAnalytic)(S))if(r.firstSegment.type==="reduce"){const R=v.fif.getAnalyticalSQL(!1);_.push(` ${R} ${b.dir||"ASC"}`)}else r.firstSegment.type==="project"&&_.push(` ${v.fif.f.generateExpression(r)} ${b.dir||"ASC"}`)}_.length>0&&(m=" "+this.parent.dialect.sqlOrderBy(_,"analytical"))}let y="";if(g.between){const[_,v]=[g.between.preceding,g.between.following].map(C=>{if(C===-1)return"UNBOUNDED";if(typeof C=="number")return C;const b=o.params.findIndex(R=>R.name===C),S=a[b];if(S.node!=="numberLiteral")throw new Error("Invalid number of rows for window spec");return S.literal});y=`ROWS BETWEEN ${_} PRECEDING AND ${v} FOLLOWING`}let A=`${this.exprToSQL(r,i,s,u)} OVER(${p} ${m} ${y})`;return f&&(A=`CASE WHEN group_set=${r.groupSet} THEN ${A} END`),A}generateCaseSQL(e){const r=["CASE"];e.kids.caseValue!==void 0&&r.push(`${e.kids.caseValue.sql}`);for(let i=0;i<e.kids.caseWhen.length;i+=1)r.push(`WHEN ${e.kids.caseWhen[i].sql} THEN ${e.kids.caseThen[i].sql}`);return e.kids.caseElse!==void 0&&r.push(`ELSE ${e.kids.caseElse.sql}`),r.push("END"),r.join(" ")}exprToSQL(e,r,i,s=new Ty){var o;const u=function(f,x){const h=f.exprToSQL(e,r,x,s);return(0,Be.exprHasKids)(x)?`(${h})`:h};let a=i;if((0,Be.exprHasE)(i)){a={...i};const f=u(this,a.e);a.e={...a.e,sql:f}}else if((0,Be.exprHasKids)(i)){a={...i};const f=i.kids;for(const[x,h]of Object.entries(f))h!==null&&(Array.isArray(h)?a.kids[x]=h.map(p=>({...p,sql:u(this,p)})):a.kids[x]={...f[x],sql:u(this,h)})}const l=e.getQueryInfo(),c=this.parent.dialect.exprToSQL(l,a);if(c)return c;switch(a.node){case"field":return this.generateFieldFragment(e,r,a,s);case"parameter":return this.generateParameterFragment(e,r,a,s);case"filteredExpr":return this.generateFilterFragment(e,r,a,s);case"all":case"exclude":return this.generateUngroupedFragment(e,r,a,s);case"genericSQLExpr":return Array.from(this.stringsFromSQLExpression(e,r,a,s)).join("");case"aggregate":{let f="";if(a.function==="sum")f=this.generateSumFragment(e,r,a,s);else if(a.function==="avg")f=this.generateAvgFragment(e,r,a,s);else if(a.function==="count")f=this.generateCountFragment(e,r,a,s);else if(a.function==="min"||a.function==="max"||a.function==="distinct")f=this.generateSymmetricFragment(e,r,a,s);else throw new Error(`Internal Error: Unknown aggregate function ${a.function}`);if(e.root().isComplexQuery){let x=e.groupSet;return s.totalGroupSet!==-1&&(x=s.totalGroupSet),this.caseGroup([x],f)}return f}case"function_parameter":throw new Error("Internal Error: Function parameter fragment remaining during SQL generation");case"outputField":return this.generateOutputFieldFragment(e,r,a,s);case"function_call":return this.generateFunctionCallExpression(e,r,a,s);case"spread":return this.generateSpread(e,r,a,s);case"source-reference":return this.generateSourceReference(e,r,a);case"+":case"-":case"*":case"%":case"/":case">":case"<":case">=":case"<=":case"=":return`${a.kids.left.sql}${a.node}${a.kids.right.sql}`;case"!=":return`COALESCE(${`${a.kids.left.sql}!=${a.kids.right.sql}`},true)`;case"and":case"or":return`${a.kids.left.sql} ${a.node} ${a.kids.right.sql}`;case"coalesce":return`COALESCE(${a.kids.left.sql},${a.kids.right.sql})`;case"in":{const f=a.kids.oneOf.map(x=>x.sql).join(",");return`${a.kids.e.sql} ${a.not?"NOT IN":"IN"} (${f})`}case"like":case"!like":{const f=a.node==="like"?"LIKE":"NOT LIKE",x=a.kids.right.node==="stringLiteral"?this.parent.dialect.sqlLike(f,(o=a.kids.left.sql)!==null&&o!==void 0?o:"",a.kids.right.literal):`${a.kids.left.sql} ${f} ${a.kids.right.sql}`;return a.node==="like"?x:`COALESCE(${x},true)`}case"()":return`(${a.e.sql})`;case"not":return`COALESCE(NOT ${a.e.sql},TRUE)`;case"unary-":return`-${a.e.sql}`;case"is-null":return`${a.e.sql} IS NULL`;case"is-not-null":return`${a.e.sql} IS NOT NULL`;case"true":case"false":return a.node;case"null":return"NULL";case"case":return this.generateCaseSQL(a);case"":return"";case"filterCondition":return a.e.sql?(a.sql=a.e.sql,a.sql):"";case"functionDefaultOrderBy":case"functionOrderBy":return"";case"compositeField":return"{COMPOSITE_FIELD}";case"filterMatch":return this.generateAppliedFilter(r,a);case"filterLiteral":return"INTERNAL ERROR FILTER EXPRESSION VALUE SHOULD NOT BE USED";default:throw new Error(`Internal Error: Unknown expression node '${a.node}' ${JSON.stringify(a,void 0,2)}`)}}generateAppliedFilter(e,r){var i;let s=r.kids.filterExpr;for(;s.node==="()";)s=s.e;if(s.node==="parameter"){const a=s.path[0];(i=e.eventStream)===null||i===void 0||i.emit("source-argument-compiled",{name:a});const l=e.arguments()[a];if(l.value)s=l.value;else throw new Error(`Parameter ${a} was expected to be a filter expression`)}if(s.node!=="filterLiteral")throw new Error("Can only use filter expression literals or parameters as filter expressions");const o=s.filterSrc;let u;switch(r.dataType){case"string":u=U4.StringFilterExpression.parse(o);break;case"number":u=U4.NumberFilterExpression.parse(o);break;case"boolean":u=U4.BooleanFilterExpression.parse(o);break;case"date":case"timestamp":u=U4.TemporalFilterExpression.parse(o);break}if(u.log.length>0)throw new Error(`Filter expression parse error: ${u.log[0]}`);return xXe.FilterCompilers.compile(r.dataType,u.parsed,r.kids.expr.sql||"",e.dialect)}isNestedInParent(e){switch(e.type){case"record":case"array":return!0;default:return!1}}isArrayElement(e){return e.type==="array"&&e.elementTypeDef.type!=="record_element"}generateExpression(e){if((0,Be.hasExpression)(this.fieldDef))return this.exprToSQL(e,this.parent,this.fieldDef.e);for(let r=this.parent;r!==void 0;r=r.parent)if(r.structDef.type==="record"&&(0,Be.hasExpression)(r.structDef)&&r.recordAlias===void 0){if(!r.parent)throw new Error("Inconcievable record ancestor with expression but no parent");const i=this.exprToSQL(e,r.parent,r.structDef.e);r.informOfAliasValue(i)}return this.parent.sqlChildReference(this.fieldDef.name,this.parent.structDef.type==="record"?{result:e,field:this}:void 0)}includeInWildcard(){return!1}};function j4(t){return t instanceof Is&&mXe(t)}function Aae(t){return t instanceof Is&&gXe(t)}function Wp(t){return t instanceof Is&&yo(t)}function yo(t){if(t.isAtomic()){if((0,Be.hasExpression)(t.fieldDef)){const e=t.fieldDef.expressionType;if((0,Be.expressionIsCalculation)(e)||(0,Be.expressionIsAggregate)(e))return!1}return!0}return!1}function mXe(t){return t.isAtomic()&&(0,Be.hasExpression)(t.fieldDef)?(0,Be.expressionIsCalculation)(t.fieldDef.expressionType):!1}function gXe(t){return t.isAtomic()&&(0,Be.hasExpression)(t.fieldDef)?(0,Be.expressionIsAggregate)(t.fieldDef.expressionType):!1}class Is extends s${constructor(e,r,i){super(e,r,i),this.fieldDef=e}includeInWildcard(){return!0}getFilterList(){return[]}}class yXe extends Is{}class EXe extends Is{}class o$ extends Is{}class AXe extends Is{}class _Xe extends Is{}class u$ extends Is{generateExpression(e){const r=this.fieldDef,i=super.generateExpression(e);if(r.timeframe){const s={node:"trunc",e:(0,Be.mkTemporal)({node:"genericSQLExpr",src:[i],kids:{args:[]}},"date"),units:r.timeframe};return this.exprToSQL(e,this.parent,s)}else return i}getChildByName(e){const r={...this.fieldDef,as:`${this.getIdentifier()}_${e}`,timeframe:e};return new u$(r,this.parent)}}class a$ extends Is{getChildByName(e){const r={...this.fieldDef,as:`${this.getIdentifier()}_${e}`,timeframe:e};return new a$(r,this.parent)}}class vXe extends Is{generateExpression(e){var r;if(this.parent.primaryKey())return this.parent.getPrimaryKeyField(this.fieldDef).generateExpression(e);if(this.parent.structDef.type==="array"){const i=(r=this.parent.parent)===null||r===void 0?void 0:r.getDistinctKey().generateExpression(e);return this.parent.dialect.sqlMakeUnnestKey(i||"",this.parent.dialect.sqlFieldReference(this.parent.getIdentifier(),"table","__row_id","string"))}else return this.parent.dialect.sqlFieldReference(this.parent.getIdentifier(),"table","__distinct_key","string")}includeInWildcard(){return!1}}const _ae=9;function vae(t,e,r){const s=t.sqlSumDistinctHashedKey(r),o=10**(9-_ae);let a=`(${`
1054
1054
  (
1055
1055
  SUM(DISTINCT
1056
1056
  (CAST(ROUND(COALESCE(${e},0)*(${o}*1.0), ${_ae}) AS ${t.defaultDecimalType}) +
@@ -1058,7 +1058,7 @@ ${(0,Tn.indent)(u)})
1058
1058
  ))
1059
1059
  -
1060
1060
  SUM(DISTINCT ${s})
1061
- )`}/(${o}*1.0))`;return a=`CAST(${a} AS ${t.defaultNumberType})`,a}class Ui{constructor(e,r,i){this.f=e,this.fieldUsage=r,this.parent=i,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}getSQL(){let e=this.f.generateExpression(this.parent);return yo(this.f)&&(e=this.f.caseGroup(this.parent.groupSet>0?this.parent.childGroups.concat(this.additionalGroupSets):[],e)),e}getAnalyticalSQL(e){return this.analyticalSQL===void 0?this.getSQL():e&&this.partitionSQL?this.partitionSQL:this.analyticalSQL}}class Sa{constructor(e,r){this.turtleDef=e,this.parent=r,this.type="query",this.allFields=new Map,this.groupSet=0,this.depth=0,this.childGroups=[],this.hasHaving=!1,this.ungroupedSets=new Map,this.resultUsesUngrouped=!1,this.firstSegment=e.pipeline[0]}getQueryInfo(){if(!(0,Be.isIndexSegment)(this.firstSegment)&&!(0,Be.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return{}}addField(e,r,i){const s=this.allFields.get(e);if(s){if(s.type==="query")throw new Error(`Redefinition of field ${r.fieldDef.name} as struct`);if(s.fieldUsage.type==="result"){if(i.type!=="result")return;throw new Error(`Ambiguous output field name '${r.fieldDef.name}'.`)}}this.add(e,new Ui(r,i,this))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,r){this.allFields.set(e,r)}hasField(e){const r=this.allFields.get(e);return r!==void 0&&r instanceof Ui}getField(e){const r=this.allFields.get(e);if(r===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(r instanceof Ui)return r;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[r,i]of this.allFields)if(i instanceof Ui&&i.fieldUsage.type==="result"&&i.fieldUsage.resultIndex===e)return{name:r,fif:i};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,r){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[u,a]of this.ungroupedSets){const l=e++;a.groupSet=l,this.root().computeOnlyGroups.push(l)}this.groupSet=e++,this.depth=r;let i=r,s=!1,o=[this.groupSet];for(const[u,a]of this.allFields)if(a.type==="query"){const l=a;if(s=!0,l.firstSegment.type==="reduce"){const c=l.computeGroups(e,r+1);o=o.concat(c.children),e=c.nextGroupSetNumber,c.maxDepth>i&&(i=c.maxDepth)}}return this.childGroups=o,{nextGroupSetNumber:e,maxDepth:i,children:o,isComplex:s}}fields(e=void 0){const r=[];for(const i of this.allFields.values())i instanceof Ui&&(e===void 0||e(i))&&r.push(i);return r}fieldNames(e){const r=[];for(const[i,s]of this.allFields)s instanceof Ui&&(e===void 0||e(s))&&r.push(i);return r}getRepeatedResultType(){let e="inline_all_numbers";for(const r of this.fields())if(r.fieldUsage.type==="result"){if(Wp(r.f))return"nested";r.f instanceof fs&&(e="inline")}return e}structs(){const e=[];for(const r of this.allFields.values())r instanceof Sa&&e.push(r);return e}selectStructs(e,r){r(this)&&e.push(this);for(const i of this.structs())i.selectStructs(e,r);return e}calculateDefaultOrderBy(){let e;for(const[r,i]of this.allFields)if(i instanceof Ui&&i.fieldUsage.type==="result"){if(i.f.fieldDef.type==="turtle"||(0,Be.isJoined)(i.f.fieldDef)||(0,Be.expressionIsAnalytic)(i.f.fieldDef.expressionType))continue;if(e||(e=i.fieldUsage.resultIndex),["date","timestamp"].indexOf(i.f.fieldDef.type)>-1)return[{dir:"desc",field:i.fieldUsage.resultIndex}];if(Aae(i.f))return[{dir:"desc",field:i.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,r,i,s){var o;const u=e.getIdentifier();if(s.indexOf(u)!==-1)return;let a;if(a=this.root().joins.get(u)){a.uniqueKeyPossibleUses.add_use(i);return}let l;const c=(o=e.parent)===null||o===void 0?void 0:o.getJoinableParent();c&&(this.addStructToJoin(c,r,void 0,s),l=this.root().joins.get(c.getIdentifier()));const f=e.structDef;(0,Be.isJoinedSource)(f)&&e.parent&&f.onExpression&&s.indexOf(u)===-1&&r.addDependantExpr(this,e.parent,f.onExpression,[...s,u]),(a=this.root().joins.get(u))||(a=new vXe(e,u,l),this.root().joins.set(u,a)),a.uniqueKeyPossibleUses.add_use(i)}findJoins(e){for(const r of this.fields())r.f instanceof fs||this.addStructToJoin(r.f.getJoinableParent(),e,r.f.uniqueKeyPossibleUse(),[]);for(const r of this.structs())r.findJoins(e)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let r=[],i=this,s=[],o=[];if(e===void 0||e.type==="all"){const a=(e==null?void 0:e.fields)||[];s=this.fields(l=>Wp(l.f)&&l.fieldUsage.type==="result"&&a.indexOf(l.f.getIdentifier())===-1).map(l=>l.f.getIdentifier())}else s=e.fields;let u=!0;for(;i!==void 0;)(u||(e==null?void 0:e.type)==="exclude")&&(o=o.concat(i.fields(a=>yo(a.f)&&a.fieldUsage.type==="result").map(a=>a.f.getIdentifier()))),r=r.concat(i.fields(a=>yo(a.f)&&a.fieldUsage.type==="result"&&s.indexOf(a.f.getIdentifier())===-1)),i=i.parent,u=!1;for(const a of(e==null?void 0:e.fields)||[])if(o.indexOf(a)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${a}" or name not in scope.`);return r}assignFieldsToGroups(){for(const[e,r]of this.ungroupedSets)for(const i of this.getUngroupPartitions(r))i.additionalGroupSets.push(r.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}class _Xe extends Sa{constructor(e){super(e,void 0),this.joins=new Map,this.havings=new Tn.AndChain,this.isComplexQuery=!1,this.queryUsesPartitioning=!1,this.computeOnlyGroups=[],this.elimatedComputeGroups=!1}root(){return this}eliminateComputeGroupsSQL(){return this.elimatedComputeGroups||this.computeOnlyGroups.length===0?"":(this.elimatedComputeGroups=!0,`group_set NOT IN (${this.computeOnlyGroups.join(",")})`)}calculateSymmetricAggregates(){let e;for(const[r,i]of this.joins)if(i.parentRelationship()==="many_to_many"||i.forceAllSymmetricCalculations())e="0never";else if(e===void 0)e=r;else if(i.parentRelationship()==="one_to_many"){const o=i.queryStruct;o.parent&&o.parent.getIdentifier()===e?e=r:e="0never"}for(const[r,i]of this.joins)i.leafiest=r===e;for(const[r,i]of this.joins)if(i.leafiest&&i.parent!==void 0&&i.uniqueKeyPossibleUses.has("count")||!i.leafiest&&i.uniqueKeyPossibleUses.hasAsymetricFunctions()){let s=i;for(;s;)s.queryStruct.primaryKey()||(s.makeUniqueKey=!0),s.queryStruct.structDef.type==="array"?s=s.parent:s=void 0}}}class vXe{constructor(e,r,i){this.queryStruct=e,this.alias=r,this.parent=i,this.uniqueKeyPossibleUses=new xXe,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],i&&i.children.push(this);const s=this.queryStruct.structDef;(0,Be.isSourceDef)(s)&&s.filterList&&(this.joinFilterConditions=s.filterList.map(o=>new o$({type:"boolean",name:"ignoreme",e:o.e},this.queryStruct)))}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";const e=this.queryStruct.structDef;if((0,Be.isJoined)(e))switch(e.join){case"one":return"many_to_one";case"cross":return"many_to_many";case"many":return"one_to_many"}throw new Error(`Internal error unknown relationship type to parent for ${this.queryStruct.structDef.name}`)}forceAllSymmetricCalculations(){if(this.queryStruct.parent===void 0)return!1;const e=this.queryStruct.structDef;return(0,Be.isJoined)(e)?e.matrixOperation==="right"||e.matrixOperation==="full":!1}getDialectFieldList(){return zp(this.queryStruct.structDef)}}class CXe{static nextStructDef(e,r){const i=new Wl(e,void 0,{model:new q4(void 0)},{}),s={type:"turtle",name:"ignoreme",pipeline:[r]};return cs.makeQuery(s,i,new Gp(!0,void 0),!1).getResultStructDef()}}Ls.Segment=CXe;function SXe(t,e){const r=new Wl(t,void 0,{model:new q4(void 0)},{});return cs.makeQuery(e,r,new Gp(!0,void 0),!1).getResultStructDef()}Ls.getResultStructDefForView=SXe;function bXe(t,e){const i=new q4(t).compileQuery(e);return i.structs[i.structs.length-1]}Ls.getResultStructDefForQuery=bXe;class cs extends s${constructor(e,r,i,s){super(e,r),this.prepared=!1,this.maxDepth=0,this.maxGroupSet=0,this.fieldDef=e,this.rootResult=new _Xe(e),this.stageWriter=i,this.firstSegment=e.pipeline[0],this.isJoinedSubquery=s}static makeQuery(e,r,i=void 0,s){let o=r,u=r.applyStructFiltersToTurtleDef(e);const a=u.pipeline[0],l=r.structDef;switch(i!==void 0&&(0,Be.isQuerySegment)(a)&&a.extendSource!==void 0&&(o=new Wl({...l,fields:[...l.fields,...a.extendSource]},r.sourceArguments,o.parent?{struct:o}:{model:o.model},o.prepareResultOptions),u={...u,pipeline:[{...a,extendSource:void 0},...u.pipeline.slice(1)]}),(0,Be.isSourceDef)(l)&&l.queryTimezone&&(0,Be.isQuerySegment)(a)&&a.queryTimezone===void 0&&(a.queryTimezone=l.queryTimezone),a.type){case"reduce":return new TXe(u,o,i,s);case"project":return new RXe(u,o,i,s);case"index":return new FXe(u,o,i,s);case"raw":return new OXe(u,o,i,s);case"partial":throw new Error("Attempt to make query out of partial stage")}}inNestedPipeline(){return this.parent.structDef.type==="nest_source"}expandField(e){const r=e.type==="fieldref"?this.parent.getQueryFieldReference(e.path,e.annotation):this.parent.makeQueryField(e);return{as:r.getIdentifier(),field:r}}addDependantPath(e,r,i,s,o){if(i.length===0)return;const u=r.getFieldByName(i),a=u instanceof fs?u.queryStruct.getJoinableParent():u.parent.getJoinableParent();e.root().addStructToJoin(a,this,s,o)}findRecordAliases(e,r){for(const i of r){const s=e.getFieldByName([i]);if(s instanceof fs){const o=s.queryStruct;o.structDef.type==="record"&&(0,Be.hasExpression)(o.structDef)&&o.parent&&o.informOfAliasValue(this.exprToSQL(this.rootResult,o.parent,o.structDef.e)),e=o}}}addDependantExpr(e,r,i,s){var o;for(const u of(0,Tn.exprWalk)(i)){if(u.node==="function_call"){(0,Be.expressionIsAnalytic)(u.overload.returnType.expressionType)&&this.parent.dialect.cantPartitionWindowFunctionsOnExpressions&&(e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0);const a=(o=u.overload.isSymmetric)!==null&&o!==void 0?o:!1,c=(0,Be.expressionIsAggregate)(u.overload.returnType.expressionType)&&!a,f=c?"generic_asymmetric_aggregate":void 0;u.structPath?this.addDependantPath(e,r,u.structPath,f,s):c&&e.addStructToJoin(r,this,f,s),(0,Be.expressionIsAnalytic)(u.overload.returnType.expressionType)&&(e.root().queryUsesPartitioning=!0)}else if((u.node==="all"||u.node==="exclude")&&(e.resultUsesUngrouped=!0,e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0,u.fields&&u.fields.length>0)){const a=u.fields.sort().join("|")+u.node;e.ungroupedSets.get(a)===void 0&&e.ungroupedSets.set(a,{type:u.node,fields:u.fields,groupSet:-1})}if(u.node==="field"){this.findRecordAliases(r,u.path);const a=r.getDimensionOrMeasureByName(u.path);(0,Be.hasExpression)(a.fieldDef)?this.addDependantExpr(e,a.parent,a.fieldDef.e,s):e.root().addStructToJoin(a.parent.getJoinableParent(),this,void 0,s)}else u.node==="aggregate"&&(0,Be.isAsymmetricExpr)(u)&&(u.structPath?(this.findRecordAliases(r,u.structPath),this.addDependantPath(e,r,u.structPath,u.function,s)):e.addStructToJoin(r,this,u.function,s))}}addDependancies(e,r){(0,Be.hasExpression)(r.fieldDef)&&this.addDependantExpr(e,r.parent,r.fieldDef.e,[])}getSegmentFields(e){const r=e.firstSegment;return r.type==="index"?r.indexFields:(0,Be.isQuerySegment)(r)?r.queryFields:[]}expandFields(e){let r=1;for(const i of this.getSegmentFields(e)){const{as:s,field:o}=this.expandField(i);if(o instanceof cs){if(this.firstSegment.type==="project")throw new Error(`Nested views cannot be used in select - '${o.fieldDef.name}'`);const u=new Sa(o.fieldDef,e);this.expandFields(u),e.add(s,u)}else if(o instanceof Is){if(e.addField(s,o,{resultIndex:r,type:"result"}),this.addDependancies(e,o),Aae(o)&&this.firstSegment.type==="project")throw new Error(`Aggregate Fields cannot be used in select - '${o.fieldDef.name}'`)}else o instanceof fs&&(o.isAtomic()&&this.addDependancies(e,o),e.addField(s,o,{resultIndex:r,type:"result"}));r++}this.expandFilters(e)}expandFilters(e){if(e.firstSegment.filterList!==void 0){for(const r of e.firstSegment.filterList||[]){const i=this.parent;this.addDependantExpr(e,i,r.e,[])}for(const r of e.root().joins.values()||[])for(const i of r.joinFilterConditions||[])i.fieldDef.type==="boolean"&&i.fieldDef.e&&this.addDependantExpr(e,i.parent,i.fieldDef.e,[])}}generateSQLFilters(e,r){const i=new Tn.AndChain,s=e.firstSegment.filterList;if(s===void 0)return i;for(const o of s||[]){const u=this.parent;if(r==="having"&&(0,Be.expressionIsCalculation)(o.expressionType)||r==="where"&&(0,Be.expressionIsScalar)(o.expressionType)){const a=this.exprToSQL(e,u,o.e,void 0);i.add(a)}}return i}prepare(e){this.prepared||(this.expandFields(this.rootResult),this.rootResult.addStructToJoin(this.parent,this,void 0,[]),this.rootResult.findJoins(this),this.addAlwaysJoins(this.rootResult),this.rootResult.calculateSymmetricAggregates(),this.prepared=!0)}addAlwaysJoins(e){var r;const i=this.fieldDef.pipeline[0];if(i.type!=="raw"){const s=(r=i.alwaysJoins)!==null&&r!==void 0?r:[];for(const o of s){const u=this.parent.getChildByName(o);u instanceof fs&&e.addStructToJoin(u.queryStruct,this,void 0,[])}}}getResultMetadata(e){if(e instanceof Ui){if(e.fieldUsage.type==="result"){const r=e.f.fieldDef;let i;const s=e.f.parent.getFullOutputName()+(r.name||r.as||"undefined"),o=(0,Be.hasExpression)(r)?r.code:void 0,u=[s],a=e.f.referenceId,l={sourceField:s,sourceExpression:o,sourceClasses:u,referenceId:a};return j4(e.f)?(i=e.f.getFilterList(),{...l,filterList:i,fieldKind:"measure"}):Wp(e.f)?{...l,filterList:i,fieldKind:"dimension"}:void 0}return}else if(e instanceof Sa){const r=e.turtleDef.name||e.turtleDef.as,i=r?[r]:[],s=e.firstSegment.filterList,o=e.turtleDef.pipeline[e.turtleDef.pipeline.length-1],u=(0,Be.isRawSegment)(o)?void 0:o.limit;let a;if((0,Be.isQuerySegment)(o)&&(a=o.orderBy),r)return{sourceField:r,filterList:s,sourceClasses:i,fieldKind:"struct",limit:u,orderBy:a}}}getResultStructDef(e=this.rootResult,r=!0){const i=[];let s;this.prepare(void 0);let o=0;for(const[a,l]of e.allFields){const c=this.getResultMetadata(l);if(l instanceof Sa){const{structDef:f,repeatedResultType:x}=this.generateTurtlePipelineSQL(l,new Gp(!0,void 0),"<nosource>");if(x==="nested"){const h={...f,type:"array",elementTypeDef:{type:"record_element"},join:"many",name:a,resultMetadata:c};i.push(h)}else{const h={...f,type:"record",join:"one",name:a,resultMetadata:c};i.push(h)}}else if(l instanceof Ui&&l.fieldUsage.type==="result"){Wp(l.f)&&(o===0&&r?s=a:s=void 0,o++);let f=l.f.fieldDef;(0,Be.hasExpression)(f)&&(f={...f},delete f.e,delete f.code,delete f.expressionType);const x=f.location,h=f.annotation;switch(f.type){case"boolean":case"json":case"string":i.push({name:a,type:f.type,resultMetadata:c,location:x,annotation:h});break;case"date":case"timestamp":{const p=f.timeframe,m={type:f.type};p&&(m.timeframe=p),i.push({name:a,...m,resultMetadata:c,location:x,annotation:h});break}case"number":i.push({name:a,numberType:f.numberType,type:"number",resultMetadata:c,location:x,annotation:h});break;case"sql native":case"record":case"array":{i.push({...f,resultMetadata:c});break}default:throw new Error(`unknown Field Type in query ${JSON.stringify(f)}`)}}}const u={type:"query_result",name:this.resultStage||"result",fields:i,dialect:this.parent.dialect.name,primaryKey:s,connection:this.parent.connectionName,resultMetadata:this.getResultMetadata(this.rootResult),queryTimezone:e.getQueryInfo().queryTimezone};return this.parent.structDef.modelAnnotation&&(u.modelAnnotation=this.parent.structDef.modelAnnotation),u}generateSQLJoinBlock(e,r,i){var s;let o="";const u=r.queryStruct,a=u.structDef;if((s=u.eventStream)===null||s===void 0||s.emit("join-used",{name:(0,Be.getIdentifier)(a)}),u.maybeEmitParameterizedSourceUsage(),(0,Be.isJoinedSource)(a)){let l=u.structSourceSQL(e);const c=(a.matrixOperation||"left").toUpperCase();if(!this.parent.dialect.supportsFullJoin&&c==="FULL")throw new Error("FULL JOIN not supported");if(r.makeUniqueKey){const p=this.generateSQLPassthroughKeys(u);l=`(SELECT ${u.dialect.sqlGenerateUUID()} as ${u.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${p} FROM ${l} as x)`}let f="";if(u.parent===void 0)throw new Error("Expected joined struct to have a parent.");a.onExpression?f=new o$({type:"boolean",name:"ignoreme",e:a.onExpression},u.parent).generateExpression(this.rootResult):f="1=1";let x="",h;if(r.joinFilterConditions&&(h=r.joinFilterConditions.map(p=>p.generateExpression(this.rootResult))),r.children.length===0||h===void 0||!this.parent.dialect.supportsComplexFilteredSources)h!==void 0&&h.length>=1&&(x=` AND (${h.join(" AND ")})`),o+=` ${c} JOIN ${l} AS ${r.alias}
1061
+ )`}/(${o}*1.0))`;return a=`CAST(${a} AS ${t.defaultNumberType})`,a}class Ui{constructor(e,r,i){this.f=e,this.fieldUsage=r,this.parent=i,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}getSQL(){let e=this.f.generateExpression(this.parent);return yo(this.f)&&(e=this.f.caseGroup(this.parent.groupSet>0?this.parent.childGroups.concat(this.additionalGroupSets):[],e)),e}getAnalyticalSQL(e){return this.analyticalSQL===void 0?this.getSQL():e&&this.partitionSQL?this.partitionSQL:this.analyticalSQL}}class Sa{constructor(e,r){this.turtleDef=e,this.parent=r,this.type="query",this.allFields=new Map,this.groupSet=0,this.depth=0,this.childGroups=[],this.hasHaving=!1,this.ungroupedSets=new Map,this.resultUsesUngrouped=!1,this.firstSegment=e.pipeline[0]}getQueryInfo(){if(!(0,Be.isIndexSegment)(this.firstSegment)&&!(0,Be.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return{}}addField(e,r,i){const s=this.allFields.get(e);if(s){if(s.type==="query")throw new Error(`Redefinition of field ${r.fieldDef.name} as struct`);if(s.fieldUsage.type==="result"){if(i.type!=="result")return;throw new Error(`Ambiguous output field name '${r.fieldDef.name}'.`)}}this.add(e,new Ui(r,i,this))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,r){this.allFields.set(e,r)}hasField(e){const r=this.allFields.get(e);return r!==void 0&&r instanceof Ui}getField(e){const r=this.allFields.get(e);if(r===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(r instanceof Ui)return r;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[r,i]of this.allFields)if(i instanceof Ui&&i.fieldUsage.type==="result"&&i.fieldUsage.resultIndex===e)return{name:r,fif:i};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,r){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[u,a]of this.ungroupedSets){const l=e++;a.groupSet=l,this.root().computeOnlyGroups.push(l)}this.groupSet=e++,this.depth=r;let i=r,s=!1,o=[this.groupSet];for(const[u,a]of this.allFields)if(a.type==="query"){const l=a;if(s=!0,l.firstSegment.type==="reduce"){const c=l.computeGroups(e,r+1);o=o.concat(c.children),e=c.nextGroupSetNumber,c.maxDepth>i&&(i=c.maxDepth)}}return this.childGroups=o,{nextGroupSetNumber:e,maxDepth:i,children:o,isComplex:s}}fields(e=void 0){const r=[];for(const i of this.allFields.values())i instanceof Ui&&(e===void 0||e(i))&&r.push(i);return r}fieldNames(e){const r=[];for(const[i,s]of this.allFields)s instanceof Ui&&(e===void 0||e(s))&&r.push(i);return r}getRepeatedResultType(){let e="inline_all_numbers";for(const r of this.fields())if(r.fieldUsage.type==="result"){if(Wp(r.f))return"nested";r.f instanceof fs&&(e="inline")}return e}structs(){const e=[];for(const r of this.allFields.values())r instanceof Sa&&e.push(r);return e}selectStructs(e,r){r(this)&&e.push(this);for(const i of this.structs())i.selectStructs(e,r);return e}calculateDefaultOrderBy(){let e;for(const[r,i]of this.allFields)if(i instanceof Ui&&i.fieldUsage.type==="result"){if(i.f.fieldDef.type==="turtle"||(0,Be.isJoined)(i.f.fieldDef)||(0,Be.expressionIsAnalytic)(i.f.fieldDef.expressionType))continue;if(e||(e=i.fieldUsage.resultIndex),["date","timestamp"].indexOf(i.f.fieldDef.type)>-1)return[{dir:"desc",field:i.fieldUsage.resultIndex}];if(Aae(i.f))return[{dir:"desc",field:i.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,r,i,s){var o;const u=e.getIdentifier();if(s.indexOf(u)!==-1)return;let a;if(a=this.root().joins.get(u)){a.uniqueKeyPossibleUses.add_use(i);return}let l;const c=(o=e.parent)===null||o===void 0?void 0:o.getJoinableParent();c&&(this.addStructToJoin(c,r,void 0,s),l=this.root().joins.get(c.getIdentifier()));const f=e.structDef;(0,Be.isJoinedSource)(f)&&e.parent&&f.onExpression&&s.indexOf(u)===-1&&r.addDependantExpr(this,e.parent,f.onExpression,[...s,u]),(a=this.root().joins.get(u))||(a=new SXe(e,u,l),this.root().joins.set(u,a)),a.uniqueKeyPossibleUses.add_use(i)}findJoins(e){for(const r of this.fields())r.f instanceof fs||this.addStructToJoin(r.f.getJoinableParent(),e,r.f.uniqueKeyPossibleUse(),[]);for(const r of this.structs())r.findJoins(e)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let r=[],i=this,s=[],o=[];if(e===void 0||e.type==="all"){const a=(e==null?void 0:e.fields)||[];s=this.fields(l=>Wp(l.f)&&l.fieldUsage.type==="result"&&a.indexOf(l.f.getIdentifier())===-1).map(l=>l.f.getIdentifier())}else s=e.fields;let u=!0;for(;i!==void 0;)(u||(e==null?void 0:e.type)==="exclude")&&(o=o.concat(i.fields(a=>yo(a.f)&&a.fieldUsage.type==="result").map(a=>a.f.getIdentifier()))),r=r.concat(i.fields(a=>yo(a.f)&&a.fieldUsage.type==="result"&&s.indexOf(a.f.getIdentifier())===-1)),i=i.parent,u=!1;for(const a of(e==null?void 0:e.fields)||[])if(o.indexOf(a)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${a}" or name not in scope.`);return r}assignFieldsToGroups(){for(const[e,r]of this.ungroupedSets)for(const i of this.getUngroupPartitions(r))i.additionalGroupSets.push(r.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}class CXe extends Sa{constructor(e){super(e,void 0),this.joins=new Map,this.havings=new Tn.AndChain,this.isComplexQuery=!1,this.queryUsesPartitioning=!1,this.computeOnlyGroups=[],this.elimatedComputeGroups=!1}root(){return this}eliminateComputeGroupsSQL(){return this.elimatedComputeGroups||this.computeOnlyGroups.length===0?"":(this.elimatedComputeGroups=!0,`group_set NOT IN (${this.computeOnlyGroups.join(",")})`)}calculateSymmetricAggregates(){let e;for(const[r,i]of this.joins)if(i.parentRelationship()==="many_to_many"||i.forceAllSymmetricCalculations())e="0never";else if(e===void 0)e=r;else if(i.parentRelationship()==="one_to_many"){const o=i.queryStruct;o.parent&&o.parent.getIdentifier()===e?e=r:e="0never"}for(const[r,i]of this.joins)i.leafiest=r===e;for(const[r,i]of this.joins)if(i.leafiest&&i.parent!==void 0&&i.uniqueKeyPossibleUses.has("count")||!i.leafiest&&i.uniqueKeyPossibleUses.hasAsymetricFunctions()){let s=i;for(;s;)s.queryStruct.primaryKey()||(s.makeUniqueKey=!0),s.queryStruct.structDef.type==="array"?s=s.parent:s=void 0}}}class SXe{constructor(e,r,i){this.queryStruct=e,this.alias=r,this.parent=i,this.uniqueKeyPossibleUses=new hXe,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],i&&i.children.push(this);const s=this.queryStruct.structDef;(0,Be.isSourceDef)(s)&&s.filterList&&(this.joinFilterConditions=s.filterList.map(o=>new o$({type:"boolean",name:"ignoreme",e:o.e},this.queryStruct)))}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";const e=this.queryStruct.structDef;if((0,Be.isJoined)(e))switch(e.join){case"one":return"many_to_one";case"cross":return"many_to_many";case"many":return"one_to_many"}throw new Error(`Internal error unknown relationship type to parent for ${this.queryStruct.structDef.name}`)}forceAllSymmetricCalculations(){if(this.queryStruct.parent===void 0)return!1;const e=this.queryStruct.structDef;return(0,Be.isJoined)(e)?e.matrixOperation==="right"||e.matrixOperation==="full":!1}getDialectFieldList(){return zp(this.queryStruct.structDef)}}class bXe{static nextStructDef(e,r){const i=new Wl(e,void 0,{model:new q4(void 0)},{}),s={type:"turtle",name:"ignoreme",pipeline:[r]};return cs.makeQuery(s,i,new Gp(!0,void 0),!1).getResultStructDef()}}Ls.Segment=bXe;function TXe(t,e){const r=new Wl(t,void 0,{model:new q4(void 0)},{});return cs.makeQuery(e,r,new Gp(!0,void 0),!1).getResultStructDef()}Ls.getResultStructDefForView=TXe;function RXe(t,e){const i=new q4(t).compileQuery(e);return i.structs[i.structs.length-1]}Ls.getResultStructDefForQuery=RXe;class cs extends s${constructor(e,r,i,s){super(e,r),this.prepared=!1,this.maxDepth=0,this.maxGroupSet=0,this.fieldDef=e,this.rootResult=new CXe(e),this.stageWriter=i,this.firstSegment=e.pipeline[0],this.isJoinedSubquery=s}static makeQuery(e,r,i=void 0,s){let o=r,u=r.applyStructFiltersToTurtleDef(e);const a=u.pipeline[0],l=r.structDef;switch(i!==void 0&&(0,Be.isQuerySegment)(a)&&a.extendSource!==void 0&&(o=new Wl({...l,fields:[...l.fields,...a.extendSource]},r.sourceArguments,o.parent?{struct:o}:{model:o.model},o.prepareResultOptions),u={...u,pipeline:[{...a,extendSource:void 0},...u.pipeline.slice(1)]}),(0,Be.isSourceDef)(l)&&l.queryTimezone&&(0,Be.isQuerySegment)(a)&&a.queryTimezone===void 0&&(a.queryTimezone=l.queryTimezone),a.type){case"reduce":return new DXe(u,o,i,s);case"project":return new OXe(u,o,i,s);case"index":return new NXe(u,o,i,s);case"raw":return new wXe(u,o,i,s);case"partial":throw new Error("Attempt to make query out of partial stage")}}inNestedPipeline(){return this.parent.structDef.type==="nest_source"}expandField(e){const r=e.type==="fieldref"?this.parent.getQueryFieldReference(e.path,e.annotation):this.parent.makeQueryField(e);return{as:r.getIdentifier(),field:r}}addDependantPath(e,r,i,s,o){if(i.length===0)return;const u=r.getFieldByName(i),a=u instanceof fs?u.queryStruct.getJoinableParent():u.parent.getJoinableParent();e.root().addStructToJoin(a,this,s,o)}findRecordAliases(e,r){for(const i of r){const s=e.getFieldByName([i]);if(s instanceof fs){const o=s.queryStruct;o.structDef.type==="record"&&(0,Be.hasExpression)(o.structDef)&&o.parent&&o.informOfAliasValue(this.exprToSQL(this.rootResult,o.parent,o.structDef.e)),e=o}}}addDependantExpr(e,r,i,s){var o;for(const u of(0,Tn.exprWalk)(i)){if(u.node==="function_call"){(0,Be.expressionIsAnalytic)(u.overload.returnType.expressionType)&&this.parent.dialect.cantPartitionWindowFunctionsOnExpressions&&(e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0);const a=(o=u.overload.isSymmetric)!==null&&o!==void 0?o:!1,c=(0,Be.expressionIsAggregate)(u.overload.returnType.expressionType)&&!a,f=c?"generic_asymmetric_aggregate":void 0;u.structPath?this.addDependantPath(e,r,u.structPath,f,s):c&&e.addStructToJoin(r,this,f,s),(0,Be.expressionIsAnalytic)(u.overload.returnType.expressionType)&&(e.root().queryUsesPartitioning=!0)}else if((u.node==="all"||u.node==="exclude")&&(e.resultUsesUngrouped=!0,e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0,u.fields&&u.fields.length>0)){const a=u.fields.sort().join("|")+u.node;e.ungroupedSets.get(a)===void 0&&e.ungroupedSets.set(a,{type:u.node,fields:u.fields,groupSet:-1})}if(u.node==="field"){this.findRecordAliases(r,u.path);const a=r.getDimensionOrMeasureByName(u.path);(0,Be.hasExpression)(a.fieldDef)?this.addDependantExpr(e,a.parent,a.fieldDef.e,s):e.root().addStructToJoin(a.parent.getJoinableParent(),this,void 0,s)}else u.node==="aggregate"&&(0,Be.isAsymmetricExpr)(u)&&(u.structPath?(this.findRecordAliases(r,u.structPath),this.addDependantPath(e,r,u.structPath,u.function,s)):e.addStructToJoin(r,this,u.function,s))}}addDependancies(e,r){(0,Be.hasExpression)(r.fieldDef)&&this.addDependantExpr(e,r.parent,r.fieldDef.e,[])}getSegmentFields(e){const r=e.firstSegment;return r.type==="index"?r.indexFields:(0,Be.isQuerySegment)(r)?r.queryFields:[]}expandFields(e){let r=1;for(const i of this.getSegmentFields(e)){const{as:s,field:o}=this.expandField(i);if(o instanceof cs){if(this.firstSegment.type==="project")throw new Error(`Nested views cannot be used in select - '${o.fieldDef.name}'`);const u=new Sa(o.fieldDef,e);this.expandFields(u),e.add(s,u)}else if(o instanceof Is){if(e.addField(s,o,{resultIndex:r,type:"result"}),this.addDependancies(e,o),Aae(o)&&this.firstSegment.type==="project")throw new Error(`Aggregate Fields cannot be used in select - '${o.fieldDef.name}'`)}else o instanceof fs&&(o.isAtomic()&&this.addDependancies(e,o),e.addField(s,o,{resultIndex:r,type:"result"}));r++}this.expandFilters(e)}expandFilters(e){if(e.firstSegment.filterList!==void 0){for(const r of e.firstSegment.filterList||[]){const i=this.parent;this.addDependantExpr(e,i,r.e,[])}for(const r of e.root().joins.values()||[])for(const i of r.joinFilterConditions||[])i.fieldDef.type==="boolean"&&i.fieldDef.e&&this.addDependantExpr(e,i.parent,i.fieldDef.e,[])}}generateSQLFilters(e,r){const i=new Tn.AndChain,s=e.firstSegment.filterList;if(s===void 0)return i;for(const o of s||[]){const u=this.parent;if(r==="having"&&(0,Be.expressionIsCalculation)(o.expressionType)||r==="where"&&(0,Be.expressionIsScalar)(o.expressionType)){const a=this.exprToSQL(e,u,o.e,void 0);i.add(a)}}return i}prepare(e){this.prepared||(this.expandFields(this.rootResult),this.rootResult.addStructToJoin(this.parent,this,void 0,[]),this.rootResult.findJoins(this),this.addAlwaysJoins(this.rootResult),this.rootResult.calculateSymmetricAggregates(),this.prepared=!0)}addAlwaysJoins(e){var r;const i=this.fieldDef.pipeline[0];if(i.type!=="raw"){const s=(r=i.alwaysJoins)!==null&&r!==void 0?r:[];for(const o of s){const u=this.parent.getChildByName(o);u instanceof fs&&e.addStructToJoin(u.queryStruct,this,void 0,[])}}}getResultMetadata(e){if(e instanceof Ui){if(e.fieldUsage.type==="result"){const r=e.f.fieldDef;let i;const s=e.f.parent.getFullOutputName()+(r.name||r.as||"undefined"),o=(0,Be.hasExpression)(r)?r.code:void 0,u=[s],a=e.f.referenceId,l={sourceField:s,sourceExpression:o,sourceClasses:u,referenceId:a};return j4(e.f)?(i=e.f.getFilterList(),{...l,filterList:i,fieldKind:"measure"}):Wp(e.f)?{...l,filterList:i,fieldKind:"dimension"}:void 0}return}else if(e instanceof Sa){const r=e.turtleDef.name||e.turtleDef.as,i=r?[r]:[],s=e.firstSegment.filterList,o=e.turtleDef.pipeline[e.turtleDef.pipeline.length-1],u=(0,Be.isRawSegment)(o)?void 0:o.limit;let a;if((0,Be.isQuerySegment)(o)&&(a=o.orderBy),r)return{sourceField:r,filterList:s,sourceClasses:i,fieldKind:"struct",limit:u,orderBy:a}}}getResultStructDef(e=this.rootResult,r=!0){const i=[];let s;this.prepare(void 0);let o=0;for(const[a,l]of e.allFields){const c=this.getResultMetadata(l);if(l instanceof Sa){const{structDef:f,repeatedResultType:x}=this.generateTurtlePipelineSQL(l,new Gp(!0,void 0),"<nosource>");if(x==="nested"){const h={...f,type:"array",elementTypeDef:{type:"record_element"},join:"many",name:a,resultMetadata:c};i.push(h)}else{const h={...f,type:"record",join:"one",name:a,resultMetadata:c};i.push(h)}}else if(l instanceof Ui&&l.fieldUsage.type==="result"){Wp(l.f)&&(o===0&&r?s=a:s=void 0,o++);let f=l.f.fieldDef;(0,Be.hasExpression)(f)&&(f={...f},delete f.e,delete f.code,delete f.expressionType);const x=f.location,h=f.annotation;switch(f.type){case"boolean":case"json":case"string":i.push({name:a,type:f.type,resultMetadata:c,location:x,annotation:h});break;case"date":case"timestamp":{const p=f.timeframe,m={type:f.type};p&&(m.timeframe=p),i.push({name:a,...m,resultMetadata:c,location:x,annotation:h});break}case"number":i.push({name:a,numberType:f.numberType,type:"number",resultMetadata:c,location:x,annotation:h});break;case"sql native":case"record":case"array":{i.push({...f,resultMetadata:c});break}default:throw new Error(`unknown Field Type in query ${JSON.stringify(f)}`)}}}const u={type:"query_result",name:this.resultStage||"result",fields:i,dialect:this.parent.dialect.name,primaryKey:s,connection:this.parent.connectionName,resultMetadata:this.getResultMetadata(this.rootResult),queryTimezone:e.getQueryInfo().queryTimezone};return this.parent.structDef.modelAnnotation&&(u.modelAnnotation=this.parent.structDef.modelAnnotation),u}generateSQLJoinBlock(e,r,i){var s;let o="";const u=r.queryStruct,a=u.structDef;if((s=u.eventStream)===null||s===void 0||s.emit("join-used",{name:(0,Be.getIdentifier)(a)}),u.maybeEmitParameterizedSourceUsage(),(0,Be.isJoinedSource)(a)){let l=u.structSourceSQL(e);const c=(a.matrixOperation||"left").toUpperCase();if(!this.parent.dialect.supportsFullJoin&&c==="FULL")throw new Error("FULL JOIN not supported");if(r.makeUniqueKey){const p=this.generateSQLPassthroughKeys(u);l=`(SELECT ${u.dialect.sqlGenerateUUID()} as ${u.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${p} FROM ${l} as x)`}let f="";if(u.parent===void 0)throw new Error("Expected joined struct to have a parent.");a.onExpression?f=new o$({type:"boolean",name:"ignoreme",e:a.onExpression},u.parent).generateExpression(this.rootResult):f="1=1";let x="",h;if(r.joinFilterConditions&&(h=r.joinFilterConditions.map(p=>p.generateExpression(this.rootResult))),r.children.length===0||h===void 0||!this.parent.dialect.supportsComplexFilteredSources)h!==void 0&&h.length>=1&&(x=` AND (${h.join(" AND ")})`),o+=` ${c} JOIN ${l} AS ${r.alias}
1062
1062
  ON ${f}${x}
1063
1063
  `;else{let p=`SELECT ${r.alias}.*`,m="";for(const g of r.children)m+=this.generateSQLJoinBlock(e,g,i+1),p+=`, ${this.parent.dialect.sqlSelectAliasAsStruct(g.alias,zp(g.queryStruct.structDef))} AS ${g.alias}`;return p+=`
1064
1064
  FROM ${l} AS ${r.alias}
@@ -1104,7 +1104,7 @@ FROM ${r}
1104
1104
  `;const l=this.rootResult.eliminateComputeGroupsSQL();return l.length>0&&(i+=`WHERE ${l}
1105
1105
  `),a.length>0&&(i+=`GROUP BY ${a.join(",")}
1106
1106
  `),i+=this.genereateSQLOrderBy(this.firstSegment,this.rootResult),!(0,Be.isRawSegment)(this.firstSegment)&&this.firstSegment.limit&&(i+=`LIMIT ${this.firstSegment.limit}
1107
- `),this.resultStage=e.addStage(i),this.resultStage=this.generatePipelinedStages(u,this.resultStage,e),this.resultStage}buildDialectFieldList(e){const r=[];for(const[i,s]of e.allFields){const o=this.parent.dialect.sqlMaybeQuoteIdentifier(i);if(e.firstSegment.type==="reduce"&&s instanceof Sa){const{structDef:u,repeatedResultType:a}=this.generateTurtlePipelineSQL(s,new Gp(!0,void 0),"<nosource>");if(a==="nested"){const l={...u,type:"array",elementTypeDef:{type:"record_element"},join:"many",name:i};r.push({typeDef:l,sqlExpression:this.parent.dialect.sqlMaybeQuoteIdentifier(`${i}__${e.groupSet}`),rawName:i,sqlOutputName:o})}else{const l={...u,type:"record",join:"one",name:i};r.push({typeDef:l,sqlExpression:this.parent.dialect.sqlMaybeQuoteIdentifier(`${i}__${e.groupSet}`),rawName:i,sqlOutputName:o})}}else e.firstSegment.type==="reduce"&&s instanceof Ui&&s.fieldUsage.type==="result"?Eae(r,{fieldDef:s.f.fieldDef,sqlExpression:this.parent.dialect.sqlMaybeQuoteIdentifier(`${i}__${e.groupSet}`),rawName:i,sqlOutputName:o}):e.firstSegment.type==="project"&&s instanceof Ui&&s.fieldUsage.type==="result"&&Eae(r,{fieldDef:s.f.fieldDef,sqlExpression:s.f.generateExpression(e),rawName:i,sqlOutputName:o})}return r}generateTurtleSQL(e,r,i,s){let o="";const u=(0,Be.isRawSegment)(e.firstSegment)?void 0:e.firstSegment.limit,a=[];let l;const c=e.firstSegment.orderBy||e.calculateDefaultOrderBy();for(const y of c)typeof y.field=="string"?l={name:y.field,fif:e.getField(y.field)}:l=e.getFieldByNumber(y.field),e.firstSegment.type==="reduce"?a.push(" "+this.parent.dialect.sqlMaybeQuoteIdentifier(`${l.name}__${e.groupSet}`)+` ${y.dir||"ASC"}`):e.firstSegment.type==="project"&&a.push(` ${l.fif.f.generateExpression(e)} ${y.dir||"ASC"}`);a.length>0&&(o=" "+this.parent.dialect.sqlOrderBy(a,"turtle"));const f=this.buildDialectFieldList(e);let x,h;(x=e.getRepeatedResultType())!=="nested"?x==="inline_all_numbers"?h=this.parent.dialect.sqlCoaleseMeasuresInline(e.groupSet,f):h=this.parent.dialect.sqlAnyValueTurtle(e.groupSet,f):h=this.parent.dialect.sqlAggregateTurtle(e.groupSet,f,o,u);const p=new Gp(this.parent.dialect.supportsCTEinCoorelatedSubQueries,r),{structDef:m,pipeOut:g}=this.generateTurtlePipelineSQL(e,p,this.parent.dialect.supportUnnestArrayAgg?h:i);if(g!==void 0){const y=p.generateCoorelatedSubQuery(this.parent.dialect,m);this.parent.dialect.supportUnnestArrayAgg?h=`(${y})`:s.push({sqlFieldName:i,pipelineSQL:`(${y})`})}return h}generateTurtlePipelineSQL(e,r,i){let s=this.getResultStructDef(e,!1);const o=e.getRepeatedResultType(),u=e.turtleDef.pipeline.length>1;let a,l=o;if(u){const c=[...e.turtleDef.pipeline];c.shift();const f={type:"turtle",name:"starthere",pipeline:c},x={type:"nest_source",name:"~pipe~",pipeSQL:this.parent.dialect.sqlUnnestPipelineHead(o==="inline_all_numbers",i,zp(s)),fields:s.fields,connection:s.connection,dialect:s.dialect},h=new Wl(x,void 0,{model:this.parent.getModel()},this.parent.prepareResultOptions),p=cs.makeQuery(f,h,r,this.isJoinedSubquery);a=p.generateSQLFromPipeline(r),l=p.rootResult.getRepeatedResultType(),s=a.outputStruct}return s.annotation=e.turtleDef.annotation,{structDef:s,pipeOut:a,repeatedResultType:l}}generateComplexSQL(e){let r=this.generateSQLStage0(e);if(this.maxDepth>1){let i=this.maxDepth;for(;i>1;)r=this.generateSQLDepthN(i,e,r),i--}return this.genereateSQLCombineTurtles(e,r)}generateSQL(e){var r;const i=this.rootResult.computeGroups(0,0);return this.maxDepth=i.maxDepth,this.maxGroupSet=i.nextGroupSetNumber-1,this.rootResult.assignFieldsToGroups(),(r=this.rootResult).isComplexQuery||(r.isComplexQuery=this.maxDepth>0||i.isComplex),this.rootResult.isComplexQuery?this.generateComplexSQL(e):this.generateSimpleSQL(e)}generateSQLFromPipeline(e){this.parent.maybeEmitParameterizedSourceUsage(),this.prepare(e);let r=this.generateSQL(e),i=this.getResultStructDef();const s=[...this.fieldDef.pipeline];if(s.length>1){let o={...i,name:r,type:"finalize"};s.shift();for(const u of s){const a=this.parent.parent?{struct:this.parent.parent}:{model:this.parent.getModel()},l=new Wl(o,void 0,a,this.parent.prepareResultOptions),c=cs.makeQuery({type:"turtle",name:"~computeLastStage~",pipeline:[u]},l,e,this.isJoinedSubquery);c.prepare(e),r=c.generateSQL(e),i=c.getResultStructDef(),o={...i,name:r,type:"finalize"}}}return{lastStageName:r,outputStruct:i}}}class TXe extends cs{}class RXe extends cs{}class DXe extends cs{constructor(e,r,i,s){super(e,r,i,s),this.indexPaths={},this.fieldDef=e}expandField(e){const r=e.path.join("."),i=this.parent.getQueryFieldByName(e.path);return{as:r,field:i}}expandFields(e){let r=1;const i=e.groupSet;this.maxGroupSet=i;for(const o of this.firstSegment.indexFields){const{as:u,field:a}=this.expandField(o);this.indexPaths[u]=o.path,e.addField(u,a,{resultIndex:r,type:"result"}),a instanceof Is&&this.addDependancies(e,a),r++}const s=this.firstSegment.weightMeasure;if(s!==void 0){const o=this.parent.getFieldByName([s]);e.addField(s,o,{resultIndex:r,type:"result"}),this.addDependancies(e,o)}this.expandFilters(e)}generateSQL(e){let r="COUNT(*)";const i=this.parent.dialect,s=i.sqlMaybeQuoteIdentifier("fieldName"),o=i.sqlMaybeQuoteIdentifier("fieldPath"),u=i.sqlMaybeQuoteIdentifier("fieldValue"),a=i.sqlMaybeQuoteIdentifier("fieldType"),l=i.sqlMaybeQuoteIdentifier("fieldRange"),c=i.sqlMaybeQuoteIdentifier("weight"),f=this.firstSegment.weightMeasure;f&&(r=this.rootResult.getField(f).f.generateExpression(this.rootResult));const x=[];for(const[m,g]of this.rootResult.allFields){const y=g;if(y.fieldUsage.type==="result"&&yo(y.f)){const E=y.f.generateExpression(this.rootResult),A=this.indexPaths[m]||[];x.push({name:m,path:A,type:y.f.fieldDef.type,expression:E})}}let h=`SELECT
1107
+ `),this.resultStage=e.addStage(i),this.resultStage=this.generatePipelinedStages(u,this.resultStage,e),this.resultStage}buildDialectFieldList(e){const r=[];for(const[i,s]of e.allFields){const o=this.parent.dialect.sqlMaybeQuoteIdentifier(i);if(e.firstSegment.type==="reduce"&&s instanceof Sa){const{structDef:u,repeatedResultType:a}=this.generateTurtlePipelineSQL(s,new Gp(!0,void 0),"<nosource>");if(a==="nested"){const l={...u,type:"array",elementTypeDef:{type:"record_element"},join:"many",name:i};r.push({typeDef:l,sqlExpression:this.parent.dialect.sqlMaybeQuoteIdentifier(`${i}__${e.groupSet}`),rawName:i,sqlOutputName:o})}else{const l={...u,type:"record",join:"one",name:i};r.push({typeDef:l,sqlExpression:this.parent.dialect.sqlMaybeQuoteIdentifier(`${i}__${e.groupSet}`),rawName:i,sqlOutputName:o})}}else e.firstSegment.type==="reduce"&&s instanceof Ui&&s.fieldUsage.type==="result"?Eae(r,{fieldDef:s.f.fieldDef,sqlExpression:this.parent.dialect.sqlMaybeQuoteIdentifier(`${i}__${e.groupSet}`),rawName:i,sqlOutputName:o}):e.firstSegment.type==="project"&&s instanceof Ui&&s.fieldUsage.type==="result"&&Eae(r,{fieldDef:s.f.fieldDef,sqlExpression:s.f.generateExpression(e),rawName:i,sqlOutputName:o})}return r}generateTurtleSQL(e,r,i,s){let o="";const u=(0,Be.isRawSegment)(e.firstSegment)?void 0:e.firstSegment.limit,a=[];let l;const c=e.firstSegment.orderBy||e.calculateDefaultOrderBy();for(const y of c)typeof y.field=="string"?l={name:y.field,fif:e.getField(y.field)}:l=e.getFieldByNumber(y.field),e.firstSegment.type==="reduce"?a.push(" "+this.parent.dialect.sqlMaybeQuoteIdentifier(`${l.name}__${e.groupSet}`)+` ${y.dir||"ASC"}`):e.firstSegment.type==="project"&&a.push(` ${l.fif.f.generateExpression(e)} ${y.dir||"ASC"}`);a.length>0&&(o=" "+this.parent.dialect.sqlOrderBy(a,"turtle"));const f=this.buildDialectFieldList(e);let x,h;(x=e.getRepeatedResultType())!=="nested"?x==="inline_all_numbers"?h=this.parent.dialect.sqlCoaleseMeasuresInline(e.groupSet,f):h=this.parent.dialect.sqlAnyValueTurtle(e.groupSet,f):h=this.parent.dialect.sqlAggregateTurtle(e.groupSet,f,o,u);const p=new Gp(this.parent.dialect.supportsCTEinCoorelatedSubQueries,r),{structDef:m,pipeOut:g}=this.generateTurtlePipelineSQL(e,p,this.parent.dialect.supportUnnestArrayAgg?h:i);if(g!==void 0){const y=p.generateCoorelatedSubQuery(this.parent.dialect,m);this.parent.dialect.supportUnnestArrayAgg?h=`(${y})`:s.push({sqlFieldName:i,pipelineSQL:`(${y})`})}return h}generateTurtlePipelineSQL(e,r,i){let s=this.getResultStructDef(e,!1);const o=e.getRepeatedResultType(),u=e.turtleDef.pipeline.length>1;let a,l=o;if(u){const c=[...e.turtleDef.pipeline];c.shift();const f={type:"turtle",name:"starthere",pipeline:c},x={type:"nest_source",name:"~pipe~",pipeSQL:this.parent.dialect.sqlUnnestPipelineHead(o==="inline_all_numbers",i,zp(s)),fields:s.fields,connection:s.connection,dialect:s.dialect},h=new Wl(x,void 0,{model:this.parent.getModel()},this.parent.prepareResultOptions),p=cs.makeQuery(f,h,r,this.isJoinedSubquery);a=p.generateSQLFromPipeline(r),l=p.rootResult.getRepeatedResultType(),s=a.outputStruct}return s.annotation=e.turtleDef.annotation,{structDef:s,pipeOut:a,repeatedResultType:l}}generateComplexSQL(e){let r=this.generateSQLStage0(e);if(this.maxDepth>1){let i=this.maxDepth;for(;i>1;)r=this.generateSQLDepthN(i,e,r),i--}return this.genereateSQLCombineTurtles(e,r)}generateSQL(e){var r;const i=this.rootResult.computeGroups(0,0);return this.maxDepth=i.maxDepth,this.maxGroupSet=i.nextGroupSetNumber-1,this.rootResult.assignFieldsToGroups(),(r=this.rootResult).isComplexQuery||(r.isComplexQuery=this.maxDepth>0||i.isComplex),this.rootResult.isComplexQuery?this.generateComplexSQL(e):this.generateSimpleSQL(e)}generateSQLFromPipeline(e){this.parent.maybeEmitParameterizedSourceUsage(),this.prepare(e);let r=this.generateSQL(e),i=this.getResultStructDef();const s=[...this.fieldDef.pipeline];if(s.length>1){let o={...i,name:r,type:"finalize"};s.shift();for(const u of s){const a=this.parent.parent?{struct:this.parent.parent}:{model:this.parent.getModel()},l=new Wl(o,void 0,a,this.parent.prepareResultOptions),c=cs.makeQuery({type:"turtle",name:"~computeLastStage~",pipeline:[u]},l,e,this.isJoinedSubquery);c.prepare(e),r=c.generateSQL(e),i=c.getResultStructDef(),o={...i,name:r,type:"finalize"}}}return{lastStageName:r,outputStruct:i}}}class DXe extends cs{}class OXe extends cs{}class FXe extends cs{constructor(e,r,i,s){super(e,r,i,s),this.indexPaths={},this.fieldDef=e}expandField(e){const r=e.path.join("."),i=this.parent.getQueryFieldByName(e.path);return{as:r,field:i}}expandFields(e){let r=1;const i=e.groupSet;this.maxGroupSet=i;for(const o of this.firstSegment.indexFields){const{as:u,field:a}=this.expandField(o);this.indexPaths[u]=o.path,e.addField(u,a,{resultIndex:r,type:"result"}),a instanceof Is&&this.addDependancies(e,a),r++}const s=this.firstSegment.weightMeasure;if(s!==void 0){const o=this.parent.getFieldByName([s]);e.addField(s,o,{resultIndex:r,type:"result"}),this.addDependancies(e,o)}this.expandFilters(e)}generateSQL(e){let r="COUNT(*)";const i=this.parent.dialect,s=i.sqlMaybeQuoteIdentifier("fieldName"),o=i.sqlMaybeQuoteIdentifier("fieldPath"),u=i.sqlMaybeQuoteIdentifier("fieldValue"),a=i.sqlMaybeQuoteIdentifier("fieldType"),l=i.sqlMaybeQuoteIdentifier("fieldRange"),c=i.sqlMaybeQuoteIdentifier("weight"),f=this.firstSegment.weightMeasure;f&&(r=this.rootResult.getField(f).f.generateExpression(this.rootResult));const x=[];for(const[m,g]of this.rootResult.allFields){const y=g;if(y.fieldUsage.type==="result"&&yo(y.f)){const E=y.f.generateExpression(this.rootResult),A=this.indexPaths[m]||[];x.push({name:m,path:A,type:y.f.fieldDef.type,expression:E})}}let h=`SELECT
1108
1108
  group_set,
1109
1109
  `;h+=` CASE group_set
1110
1110
  `;for(let m=0;m<x.length;m++)h+=` WHEN ${m} THEN '${x[m].name}'
@@ -1132,9 +1132,9 @@ FROM ${r}
1132
1132
  COALESCE(${u}, ${l}) as ${u},
1133
1133
  ${c}
1134
1134
  FROM ${p}
1135
- `),this.resultStage}}class OXe extends cs{generateSQL(e){if(this.parent.structDef.type!=="sql_select")throw new Error("Invalid struct for QueryQueryRaw, currently only supports SQL");return e.addStage(this.parent.structDef.selectStr)}prepare(){}getResultStructDef(){if(!(0,Be.isSourceDef)(this.parent.structDef))throw new Error(`Result cannot be type ${this.parent.structDef.type}`);return{...this.parent.structDef,type:"query_result"}}getResultMetadata(e){}}class FXe extends cs{constructor(e,r,i,s){super(e,r,i,s),this.stages=[],this.fieldDef=e,this.fieldsToStages()}fieldsToStages(){const e=this.firstSegment;if(this.parent.dialect.dontUnionIndex){this.stages=[e.indexFields];return}const r={};for(const i of e.indexFields){if(i.path.length>1){const s=yae(i.path.slice(0,i.path.length-1)),o=r[s];if(o===void 0){const u=this.parent.nameMap.get(i.path[0]);if(u instanceof fs&&u.fieldDef.join==="many"&&u.fieldDef.fields.length>1){const a=[i];r[s]=a,this.stages.push(a);continue}}else{o.push(i);continue}}this.stages[0]===void 0&&(this.stages[0]=[]),this.stages[0].push(i)}}expandFields(e){}generateSQL(e){const r=this.firstSegment,i=[];for(const s of this.stages){const o=new DXe({...this.fieldDef,pipeline:[{...r,indexFields:s}]},this.parent,e,this.isJoinedSubquery);o.prepare(e);const u=o.generateSQL(e);i.push(u)}return i.length===1?this.resultStage=i[0]:this.resultStage=e.addStage(i.map(s=>`SELECT * FROM ${s}
1135
+ `),this.resultStage}}class wXe extends cs{generateSQL(e){if(this.parent.structDef.type!=="sql_select")throw new Error("Invalid struct for QueryQueryRaw, currently only supports SQL");return e.addStage(this.parent.structDef.selectStr)}prepare(){}getResultStructDef(){if(!(0,Be.isSourceDef)(this.parent.structDef))throw new Error(`Result cannot be type ${this.parent.structDef.type}`);return{...this.parent.structDef,type:"query_result"}}getResultMetadata(e){}}class NXe extends cs{constructor(e,r,i,s){super(e,r,i,s),this.stages=[],this.fieldDef=e,this.fieldsToStages()}fieldsToStages(){const e=this.firstSegment;if(this.parent.dialect.dontUnionIndex){this.stages=[e.indexFields];return}const r={};for(const i of e.indexFields){if(i.path.length>1){const s=yae(i.path.slice(0,i.path.length-1)),o=r[s];if(o===void 0){const u=this.parent.nameMap.get(i.path[0]);if(u instanceof fs&&u.fieldDef.join==="many"&&u.fieldDef.fields.length>1){const a=[i];r[s]=a,this.stages.push(a);continue}}else{o.push(i);continue}}this.stages[0]===void 0&&(this.stages[0]=[]),this.stages[0].push(i)}}expandFields(e){}generateSQL(e){const r=this.firstSegment,i=[];for(const s of this.stages){const o=new FXe({...this.fieldDef,pipeline:[{...r,indexFields:s}]},this.parent,e,this.isJoinedSubquery);o.prepare(e);const u=o.generateSQL(e);i.push(u)}return i.length===1?this.resultStage=i[0]:this.resultStage=e.addStage(i.map(s=>`SELECT * FROM ${s}
1136
1136
  `).join(` UNION ALL
1137
- `)),this.resultStage}getResultStructDef(){const e={type:"query_result",name:this.resultStage||"result",dialect:this.parent.dialect.name,fields:[{type:"string",name:"fieldName"},{type:"string",name:"fieldPath"},{type:"string",name:"fieldValue"},{type:"string",name:"fieldType"},{type:"number",name:"weight",numberType:"integer"}],connection:this.parent.connectionName};return this.parent.structDef.modelAnnotation&&(e.modelAnnotation=this.parent.structDef.modelAnnotation),e}}class fs extends s${constructor(e,r,i,s,o){super(e,i,o),this.fieldDef=e,this.queryStruct=new Wl(e,r,{struct:i},s)}getJoinableParent(){return this.queryStruct.getJoinableParent()}getFullOutputName(){return this.queryStruct.getFullOutputName()}includeInWildcard(){return this.isAtomic()}}class Wl{constructor(e,r,i,s){if(this.structDef=e,this.sourceArguments=r,this.prepareResultOptions=s,this.nameMap=new Map,this._modelTag=void 0,this._arguments=void 0,this.setParent(i),"model"in i)if(this.model=i.model,this.pathAliasMap=new Map,(0,Be.isSourceDef)(e))this.connectionName=e.connection;else throw new Error("All root StructDefs should be a baseTable");else this.model=this.getModel(),this.pathAliasMap=this.root().pathAliasMap,this.connectionName=this.root().connectionName;this.dialect=(0,uXe.getDialect)(this.findFirstDialect()),this.addFieldsFromFieldList(e.fields)}modelCompilerFlags(){if(this._modelTag===void 0){const e=this.structDef.modelAnnotation,{tag:r}=(0,lXe.annotationToTag)(e,{prefix:/^##!\s*/});this._modelTag=r}return this._modelTag}findFirstDialect(){if((0,Be.isSourceDef)(this.structDef))return this.structDef.dialect;if(this.parent)return this.parent.findFirstDialect();throw new Error("Cannot create QueryStruct from record with model parent")}informOfAliasValue(e){this.recordAlias=e}maybeEmitParameterizedSourceUsage(){var e;if((0,Be.isSourceDef)(this.structDef)){const r={...this.structDef.parameters,...this.structDef.arguments};if(Object.values(r).length===0)return;(e=this.eventStream)===null||e===void 0||e.emit("parameterized-source-compiled",{parameters:r})}}resolveParentParameterReferences(e){return{...e,value:e.value===null?null:(0,Tn.exprMap)(e.value,r=>{if(r.node==="parameter"){if(this.parent===void 0)throw new Error("No parent from which to retrieve parameter value");const i=this.parent.arguments()[r.path[0]],s=this.parent.resolveParentParameterReferences(i);if(s.value===null)throw new Error("Invalid parameter value");return s.value}return r})}}arguments(){var e;if(this._arguments!==void 0)return this._arguments;if(this._arguments={},(0,Be.isSourceDef)(this.structDef)){const r=(e=this.structDef.parameters)!==null&&e!==void 0?e:{};for(const s in r)this._arguments[s]=r[s];const i={...this.structDef.arguments,...this.sourceArguments};for(const s in i){const o=i[s];this._arguments[s]=this.resolveParentParameterReferences(o)}}return this._arguments}addFieldsFromFieldList(e){for(const r of e){const i=(0,Be.getIdentifier)(r);if(r.type==="turtle")this.addFieldToNameMap(i,cs.makeQuery(r,this,void 0,!1));else if((0,Be.isAtomic)(r)||(0,Be.isJoinedSource)(r))this.addFieldToNameMap(i,this.makeQueryField(r));else throw new Error("mtoy did nit add field")}this.nameMap.has("__distinct_key")||this.addFieldToNameMap("__distinct_key",new AXe({type:"string",name:"__distinct_key"},this))}getAliasIdentifier(){const e=this.getFullOutputName(),r=this.pathAliasMap.get(e);if(r===void 0){const i=Array.from(this.pathAliasMap.values()),s=fXe((0,Be.getIdentifier)(this.structDef));let o=`${s}_0`,u=1;for(;i.includes(o)&&u<1e3;)u++,o=`${s}_${u}`;if(u<1e3)return this.pathAliasMap.set(e,o),o;throw new Error("Internal Error: cannot create unique alias name")}else return r}getSQLIdentifier(){return this.unnestWithNumbers()&&this.parent!==void 0?this.parent.getSQLIdentifier()+"."+(0,Be.getIdentifier)(this.structDef)+`[${this.getIdentifier()}.__row_id]`:this.getIdentifier()}sqlChildReference(e,r){let i=this.getSQLIdentifier();r&&(0,Be.isAtomic)(this.structDef)&&(0,Be.hasExpression)(this.structDef)&&(i=r.field.exprToSQL(r.result,this,this.structDef.e));let s="table";this.structDef.type==="record"?s="record":this.structDef.type==="array"?s=this.structDef.elementTypeDef.type==="record_element"?"array[record]":"array[scalar]":this.structDef.type==="nest_source"&&(s="nest source");const o=this.getChildByName(e),u=(o==null?void 0:o.fieldDef.type)||"unknown";return this.dialect.sqlFieldReference(i,s,e,u)}getIdentifier(){if((0,Be.isBaseTable)(this.structDef))return"base";if(this.structDef.type==="record"&&(0,Be.hasExpression)(this.structDef)){if(this.recordAlias)return this.recordAlias;throw new Error("INTERNAL ERROR, record field alias not pre-computed")}return this.structDef.type==="record"&&this.parent?this.parent.sqlChildReference((0,Be.getIdentifier)(this.structDef),void 0):this.getAliasIdentifier()}getFullOutputName(){return this.parent?this.parent.getFullOutputName()+(0,Be.getIdentifier)(this.structDef)+".":""}needsSymetricCalculation(e){const r=this.getJoinableParent().getIdentifier(),i=e.root().joins.get(r);if(i)return!i.leafiest;throw new Error(`Join ${r} not found in result set`)}unnestWithNumbers(){return this.dialect.unnestWithNumbers&&this.structDef.type==="array"}getJoinableParent(){if(this.structDef.type==="record"){if(this.parent)return this.parent.getJoinableParent();throw new Error("Internal Error: inline struct cannot be root")}return this}addFieldToNameMap(e,r){if(this.nameMap.has(e))throw new Error(`Redefinition of ${e}`);this.nameMap.set(e,r)}getPrimaryKeyField(e){let r;if(r=this.primaryKey())return r;throw new Error(`Missing primary key for ${e}`)}resolveQueryFields(){if(this.structDef.type==="query_source"){const e=this.model.loadQuery(this.structDef.query,void 0,this.prepareResultOptions).structs.pop();if(!e)throw new Error("Internal Error, query didn't produce a struct");const r={...this.structDef};for(const i of e.fields){const s=(0,Be.getIdentifier)(i);this.nameMap.has(s)||(r.fields.push(i),this.nameMap.set(s,this.makeQueryField(i)))}this.structDef=r,!this.structDef.primaryKey&&e.primaryKey&&(this.structDef.primaryKey=e.primaryKey)}for(const[,e]of this.nameMap)e instanceof fs&&e.queryStruct.resolveQueryFields()}getModel(){if(this.model)return this.model;if(this.parent===void 0)throw new Error("Expected this query struct to have a parent, as no model was present.");return this.parent.getModel()}get eventStream(){return this.getModel().eventStream}setParent(e){"struct"in e&&(this.parent=e.struct),"model"in e?this.model=e.model:this.model=this.getModel()}makeQueryField(e,r){switch(e.type){case"array":case"record":case"query_source":case"table":case"sql_select":case"composite":return new fs(e,void 0,this,this.prepareResultOptions);case"string":return new mXe(e,this,r);case"date":return new u$(e,this,r);case"timestamp":return new a$(e,this,r);case"number":return new gXe(e,this,r);case"boolean":return new o$(e,this,r);case"json":return new yXe(e,this,r);case"sql native":return new EXe(e,this,r);case"turtle":return cs.makeQuery(e,this,void 0,!1);default:throw new Error(`unknown field definition ${JSON.stringify(e),2}`)}}structSourceSQL(e){var r,i;switch(this.structDef.type){case"table":return this.dialect.quoteTablePath(this.structDef.tablePath);case"composite":return"{COMPOSITE SOURCE}";case"finalize":return this.structDef.name;case"sql_select":return`(${this.structDef.selectStr})`;case"nest_source":return this.structDef.pipeSQL;case"query_source":return!((r=this.prepareResultOptions)===null||r===void 0)&&r.replaceMaterializedReferences&&(0,P4.shouldMaterialize)(this.structDef.query.annotation)?e.addMaterializedQuery((0,Be.getIdentifier)(this.structDef),this.structDef.query,(i=this.prepareResultOptions)===null||i===void 0?void 0:i.materializedTablePrefix):this.model.loadQuery(this.structDef.query,e,this.prepareResultOptions,!1,!0).lastStageName;default:throw new Error(`Cannot create SQL StageWriter from '${(0,Be.getIdentifier)(this.structDef)}' type '${this.structDef.type}`)}}root(){return this.parent?this.parent.root():this}primaryKey(){if((0,Be.isSourceDef)(this.structDef)&&this.structDef.primaryKey)return this.getDimensionByName([this.structDef.primaryKey])}getChildByName(e){return this.nameMap.get(e)}getFieldByName(e){let r,i=this,s=e[0];for(const o of e){if(r=i==null?void 0:i.getChildByName(o),!r){s=o;break}i=r instanceof fs?r.queryStruct:void 0}if(r===void 0){const o=e.length>1?` in ${e.join(".")}`:"";throw new Error(`${s} not found${o}`)}return r}getQueryFieldByName(e){const r=this.getFieldByName(e);if(r instanceof fs)throw new Error(`Cannot reference ${e.join(".")} as a scalar'`);return r}getQueryFieldReference(e,r){const i=this.getFieldByName(e);if(r){if(i.parent===void 0)throw new Error("Inconcievable, field reference to orphaned query field");if(i instanceof fs){const s={...i.fieldDef,annotation:r};return new fs(s,void 0,i.parent,{},i.referenceId)}else{const s={...i.fieldDef,annotation:r};return i.parent.makeQueryField(s,i.referenceId)}}return i}getDimensionOrMeasureByName(e){const r=this.getFieldByName(e);if(!r.isAtomic())throw new Error(`${e} is not an atomic field? Inconceivable!`);return r}getDimensionByName(e){const r=this.getFieldByName(e);if(Wp(r))return r;throw new Error(`${e} is not an atomic scalar field? Inconceivable!`)}getStructByName(e){if(e.length===0)return this;const r=this.getFieldByName(e);if(r instanceof fs)return r.queryStruct;throw new Error(`Error: Path to structure not found '${e.join(".")}'`)}getDistinctKey(){if(this.structDef.type!=="record")return this.getDimensionByName(["__distinct_key"]);if(this.parent)return this.parent.getDistinctKey();throw new Error("Asking a record for a primary key? Inconceivable!")}applyStructFiltersToTurtleDef(e){let r=e.pipeline;const i=e.annotation,s=e.filterList||[];return r=structuredClone(r),r[0].filterList=s.concat(r[0].filterList||[],(0,Be.isSourceDef)(this.structDef)?this.structDef.filterList||[]:[]),{type:"turtle",name:e.name,pipeline:r,annotation:i,location:e.location}}}class q4{constructor(e,r){this.eventStream=r,this.dialect=new aXe.StandardSQLDialect,this.modelDef=void 0,this.structs=new Map,this.exploreSearchSQLMap=new Map,e&&this.loadModelFromDef(e)}loadModelFromDef(e){this.modelDef=e;for(const r of Object.values(this.modelDef.contents)){let i;if((0,Be.isSourceDef)(r))i=new Wl(r,void 0,{model:this},{}),this.structs.set((0,Be.getIdentifier)(r),i),i.resolveQueryFields();else if(r.type!=="query")throw new Error("Internal Error: Unknown structure type")}}getStructByName(e){const r=this.structs.get(e);if(r)return r;throw new Error(`Struct ${e} not found in model.`)}getStructFromRef(e,r,i){var s;if(i??(i={}),typeof e=="string"){const o=this.getStructByName(e);return r!==void 0?new Wl(o.structDef,r,(s=o.parent)!==null&&s!==void 0?s:{model:this},i):o}return new Wl(e,r,{model:this},i)}loadQuery(e,r,i,s=!1,o=!1){var u;const a="";r||(r=new Gp(!0,void 0));const l={type:"turtle",name:"ignoreme",pipeline:e.pipeline,filterList:e.filterList},c=(u=e.compositeResolvedSourceDef)!==null&&u!==void 0?u:e.structRef,f=cs.makeQuery(l,this.getStructFromRef(c,e.sourceArguments,i),r,o),x=f.generateSQLFromPipeline(r);if(s&&f.parent.dialect.hasFinalStage){const h=[];for(const p of x.outputStruct.fields)if((0,Be.isAtomic)(p)){const m=f.parent.dialect.sqlMaybeQuoteIdentifier(p.name);h.push(m)}x.lastStageName=r.addStage(f.parent.dialect.sqlFinalStage(x.lastStageName,h))}return{lastStageName:x.lastStageName,malloy:a,stageWriter:r,structs:[x.outputStruct],connectionName:f.parent.connectionName}}addDefaultRowLimit(e,r){const i={query:e,addedDefaultRowLimit:void 0};if(r===void 0)return i;const s=e.pipeline[e.pipeline.length-1];return s.type==="raw"||s.limit!==void 0?i:{query:{...e,pipeline:[...e.pipeline.slice(0,-1),{...s,limit:r}]},addedDefaultRowLimit:r}}compileQuery(e,r,i=!0){var s,o;const u=this.addDefaultRowLimit(e,r==null?void 0:r.defaultRowLimit);e=u.query;const a=u.addedDefaultRowLimit,c=this.loadQuery(e,void 0,r,i,!1),f=(s=e.compositeResolvedSourceDef)!==null&&s!==void 0?s:e.structRef,x=typeof f=="string"?f:f.as||f.name;return i&&this.dialect.hasFinalStage&&(c.lastStageName=c.stageWriter.addStage(this.dialect.sqlFinalStage(c.lastStageName,[]))),{lastStageName:c.lastStageName,malloy:c.malloy,sql:c.stageWriter.generateSQLStages(),dependenciesToMaterialize:c.stageWriter.dependenciesToMaterialize,materialization:(0,P4.shouldMaterialize)(e.annotation)?(0,P4.buildQueryMaterializationSpec)((o=e.location)===null||o===void 0?void 0:o.url,e.name,r==null?void 0:r.materializedTablePrefix):void 0,structs:c.structs,sourceExplore:x,sourceFilters:e.filterList,queryName:e.name,connectionName:c.connectionName,annotation:e.annotation,queryTimezone:c.structs[0].queryTimezone,defaultRowLimitAdded:a}}async searchIndex(e,r,i,s=1e3,o=void 0){if(!e.canPersist())return;const u=this.getStructByName(r);let a=[];for(const[E,A]of u.nameMap)yo(A)&&A.includeInWildcard()&&a.push({type:"fieldref",path:[E]});a=a.sort((E,A)=>E.path[0].localeCompare(A.path[0]));const l={structRef:r,pipeline:[{type:"index",indexFields:a,sample:u.dialect.defaultSampling}]},c=u.dialect.sqlMaybeQuoteIdentifier("fieldName"),f=u.dialect.sqlMaybeQuoteIdentifier("fieldPath"),x=u.dialect.sqlMaybeQuoteIdentifier("fieldValue"),h=u.dialect.sqlMaybeQuoteIdentifier("fieldType"),p=u.dialect.sqlMaybeQuoteIdentifier("weight");let m=this.exploreSearchSQLMap.get(r);m===void 0&&(m=this.compileQuery(l,void 0,!1).sql,this.exploreSearchSQLMap.set(r,m));let g=`SELECT
1137
+ `)),this.resultStage}getResultStructDef(){const e={type:"query_result",name:this.resultStage||"result",dialect:this.parent.dialect.name,fields:[{type:"string",name:"fieldName"},{type:"string",name:"fieldPath"},{type:"string",name:"fieldValue"},{type:"string",name:"fieldType"},{type:"number",name:"weight",numberType:"integer"}],connection:this.parent.connectionName};return this.parent.structDef.modelAnnotation&&(e.modelAnnotation=this.parent.structDef.modelAnnotation),e}}class fs extends s${constructor(e,r,i,s,o){super(e,i,o),this.fieldDef=e,this.queryStruct=new Wl(e,r,{struct:i},s)}getJoinableParent(){return this.queryStruct.getJoinableParent()}getFullOutputName(){return this.queryStruct.getFullOutputName()}includeInWildcard(){return this.isAtomic()}}class Wl{constructor(e,r,i,s){if(this.structDef=e,this.sourceArguments=r,this.prepareResultOptions=s,this.nameMap=new Map,this._modelTag=void 0,this._arguments=void 0,this.setParent(i),"model"in i)if(this.model=i.model,this.pathAliasMap=new Map,(0,Be.isSourceDef)(e))this.connectionName=e.connection;else throw new Error("All root StructDefs should be a baseTable");else this.model=this.getModel(),this.pathAliasMap=this.root().pathAliasMap,this.connectionName=this.root().connectionName;this.dialect=(0,lXe.getDialect)(this.findFirstDialect()),this.addFieldsFromFieldList(e.fields)}modelCompilerFlags(){if(this._modelTag===void 0){const e=this.structDef.modelAnnotation,{tag:r}=(0,fXe.annotationToTag)(e,{prefix:/^##!\s*/});this._modelTag=r}return this._modelTag}findFirstDialect(){if((0,Be.isSourceDef)(this.structDef))return this.structDef.dialect;if(this.parent)return this.parent.findFirstDialect();throw new Error("Cannot create QueryStruct from record with model parent")}informOfAliasValue(e){this.recordAlias=e}maybeEmitParameterizedSourceUsage(){var e;if((0,Be.isSourceDef)(this.structDef)){const r={...this.structDef.parameters,...this.structDef.arguments};if(Object.values(r).length===0)return;(e=this.eventStream)===null||e===void 0||e.emit("parameterized-source-compiled",{parameters:r})}}resolveParentParameterReferences(e){return{...e,value:e.value===null?null:(0,Tn.exprMap)(e.value,r=>{if(r.node==="parameter"){if(this.parent===void 0)throw new Error("No parent from which to retrieve parameter value");const i=this.parent.arguments()[r.path[0]],s=this.parent.resolveParentParameterReferences(i);if(s.value===null)throw new Error("Invalid parameter value");return s.value}return r})}}arguments(){var e;if(this._arguments!==void 0)return this._arguments;if(this._arguments={},(0,Be.isSourceDef)(this.structDef)){const r=(e=this.structDef.parameters)!==null&&e!==void 0?e:{};for(const s in r)this._arguments[s]=r[s];const i={...this.structDef.arguments,...this.sourceArguments};for(const s in i){const o=i[s];this._arguments[s]=this.resolveParentParameterReferences(o)}}return this._arguments}addFieldsFromFieldList(e){for(const r of e){const i=(0,Be.getIdentifier)(r);if(r.type==="turtle")this.addFieldToNameMap(i,cs.makeQuery(r,this,void 0,!1));else if((0,Be.isAtomic)(r)||(0,Be.isJoinedSource)(r))this.addFieldToNameMap(i,this.makeQueryField(r));else throw new Error("mtoy did nit add field")}this.nameMap.has("__distinct_key")||this.addFieldToNameMap("__distinct_key",new vXe({type:"string",name:"__distinct_key"},this))}getAliasIdentifier(){const e=this.getFullOutputName(),r=this.pathAliasMap.get(e);if(r===void 0){const i=Array.from(this.pathAliasMap.values()),s=dXe((0,Be.getIdentifier)(this.structDef));let o=`${s}_0`,u=1;for(;i.includes(o)&&u<1e3;)u++,o=`${s}_${u}`;if(u<1e3)return this.pathAliasMap.set(e,o),o;throw new Error("Internal Error: cannot create unique alias name")}else return r}getSQLIdentifier(){return this.unnestWithNumbers()&&this.parent!==void 0?this.parent.getSQLIdentifier()+"."+(0,Be.getIdentifier)(this.structDef)+`[${this.getIdentifier()}.__row_id]`:this.getIdentifier()}sqlChildReference(e,r){let i=this.getSQLIdentifier();r&&(0,Be.isAtomic)(this.structDef)&&(0,Be.hasExpression)(this.structDef)&&(i=r.field.exprToSQL(r.result,this,this.structDef.e));let s="table";this.structDef.type==="record"?s="record":this.structDef.type==="array"?s=this.structDef.elementTypeDef.type==="record_element"?"array[record]":"array[scalar]":this.structDef.type==="nest_source"&&(s="nest source");const o=this.getChildByName(e),u=(o==null?void 0:o.fieldDef.type)||"unknown";return this.dialect.sqlFieldReference(i,s,e,u)}getIdentifier(){if((0,Be.isBaseTable)(this.structDef))return"base";if(this.structDef.type==="record"&&(0,Be.hasExpression)(this.structDef)){if(this.recordAlias)return this.recordAlias;throw new Error("INTERNAL ERROR, record field alias not pre-computed")}return this.structDef.type==="record"&&this.parent?this.parent.sqlChildReference((0,Be.getIdentifier)(this.structDef),void 0):this.getAliasIdentifier()}getFullOutputName(){return this.parent?this.parent.getFullOutputName()+(0,Be.getIdentifier)(this.structDef)+".":""}needsSymetricCalculation(e){const r=this.getJoinableParent().getIdentifier(),i=e.root().joins.get(r);if(i)return!i.leafiest;throw new Error(`Join ${r} not found in result set`)}unnestWithNumbers(){return this.dialect.unnestWithNumbers&&this.structDef.type==="array"}getJoinableParent(){if(this.structDef.type==="record"){if(this.parent)return this.parent.getJoinableParent();throw new Error("Internal Error: inline struct cannot be root")}return this}addFieldToNameMap(e,r){if(this.nameMap.has(e))throw new Error(`Redefinition of ${e}`);this.nameMap.set(e,r)}getPrimaryKeyField(e){let r;if(r=this.primaryKey())return r;throw new Error(`Missing primary key for ${e}`)}resolveQueryFields(){if(this.structDef.type==="query_source"){const e=this.model.loadQuery(this.structDef.query,void 0,this.prepareResultOptions).structs.pop();if(!e)throw new Error("Internal Error, query didn't produce a struct");const r={...this.structDef};for(const i of e.fields){const s=(0,Be.getIdentifier)(i);this.nameMap.has(s)||(r.fields.push(i),this.nameMap.set(s,this.makeQueryField(i)))}this.structDef=r,!this.structDef.primaryKey&&e.primaryKey&&(this.structDef.primaryKey=e.primaryKey)}for(const[,e]of this.nameMap)e instanceof fs&&e.queryStruct.resolveQueryFields()}getModel(){if(this.model)return this.model;if(this.parent===void 0)throw new Error("Expected this query struct to have a parent, as no model was present.");return this.parent.getModel()}get eventStream(){return this.getModel().eventStream}setParent(e){"struct"in e&&(this.parent=e.struct),"model"in e?this.model=e.model:this.model=this.getModel()}makeQueryField(e,r){switch(e.type){case"array":case"record":case"query_source":case"table":case"sql_select":case"composite":return new fs(e,void 0,this,this.prepareResultOptions);case"string":return new yXe(e,this,r);case"date":return new u$(e,this,r);case"timestamp":return new a$(e,this,r);case"number":return new EXe(e,this,r);case"boolean":return new o$(e,this,r);case"json":return new AXe(e,this,r);case"sql native":return new _Xe(e,this,r);case"turtle":return cs.makeQuery(e,this,void 0,!1);default:throw new Error(`unknown field definition ${JSON.stringify(e),2}`)}}structSourceSQL(e){var r,i;switch(this.structDef.type){case"table":return this.dialect.quoteTablePath(this.structDef.tablePath);case"composite":return"{COMPOSITE SOURCE}";case"finalize":return this.structDef.name;case"sql_select":return`(${this.structDef.selectStr})`;case"nest_source":return this.structDef.pipeSQL;case"query_source":return!((r=this.prepareResultOptions)===null||r===void 0)&&r.replaceMaterializedReferences&&(0,P4.shouldMaterialize)(this.structDef.query.annotation)?e.addMaterializedQuery((0,Be.getIdentifier)(this.structDef),this.structDef.query,(i=this.prepareResultOptions)===null||i===void 0?void 0:i.materializedTablePrefix):this.model.loadQuery(this.structDef.query,e,this.prepareResultOptions,!1,!0).lastStageName;default:throw new Error(`Cannot create SQL StageWriter from '${(0,Be.getIdentifier)(this.structDef)}' type '${this.structDef.type}`)}}root(){return this.parent?this.parent.root():this}primaryKey(){if((0,Be.isSourceDef)(this.structDef)&&this.structDef.primaryKey)return this.getDimensionByName([this.structDef.primaryKey])}getChildByName(e){return this.nameMap.get(e)}getFieldByName(e){let r,i=this,s=e[0];for(const o of e){if(r=i==null?void 0:i.getChildByName(o),!r){s=o;break}i=r instanceof fs?r.queryStruct:void 0}if(r===void 0){const o=e.length>1?` in ${e.join(".")}`:"";throw new Error(`${s} not found${o}`)}return r}getQueryFieldByName(e){const r=this.getFieldByName(e);if(r instanceof fs)throw new Error(`Cannot reference ${e.join(".")} as a scalar'`);return r}getQueryFieldReference(e,r){const i=this.getFieldByName(e);if(r){if(i.parent===void 0)throw new Error("Inconcievable, field reference to orphaned query field");if(i instanceof fs){const s={...i.fieldDef,annotation:r};return new fs(s,void 0,i.parent,{},i.referenceId)}else{const s={...i.fieldDef,annotation:r};return i.parent.makeQueryField(s,i.referenceId)}}return i}getDimensionOrMeasureByName(e){const r=this.getFieldByName(e);if(!r.isAtomic())throw new Error(`${e} is not an atomic field? Inconceivable!`);return r}getDimensionByName(e){const r=this.getFieldByName(e);if(Wp(r))return r;throw new Error(`${e} is not an atomic scalar field? Inconceivable!`)}getStructByName(e){if(e.length===0)return this;const r=this.getFieldByName(e);if(r instanceof fs)return r.queryStruct;throw new Error(`Error: Path to structure not found '${e.join(".")}'`)}getDistinctKey(){if(this.structDef.type!=="record")return this.getDimensionByName(["__distinct_key"]);if(this.parent)return this.parent.getDistinctKey();throw new Error("Asking a record for a primary key? Inconceivable!")}applyStructFiltersToTurtleDef(e){let r=e.pipeline;const i=e.annotation,s=e.filterList||[];return r=structuredClone(r),r[0].filterList=s.concat(r[0].filterList||[],(0,Be.isSourceDef)(this.structDef)?this.structDef.filterList||[]:[]),{type:"turtle",name:e.name,pipeline:r,annotation:i,location:e.location}}}class q4{constructor(e,r){this.eventStream=r,this.dialect=new cXe.StandardSQLDialect,this.modelDef=void 0,this.structs=new Map,this.exploreSearchSQLMap=new Map,e&&this.loadModelFromDef(e)}loadModelFromDef(e){this.modelDef=e;for(const r of Object.values(this.modelDef.contents)){let i;if((0,Be.isSourceDef)(r))i=new Wl(r,void 0,{model:this},{}),this.structs.set((0,Be.getIdentifier)(r),i),i.resolveQueryFields();else if(r.type!=="query")throw new Error("Internal Error: Unknown structure type")}}getStructByName(e){const r=this.structs.get(e);if(r)return r;throw new Error(`Struct ${e} not found in model.`)}getStructFromRef(e,r,i){var s;if(i??(i={}),typeof e=="string"){const o=this.getStructByName(e);return r!==void 0?new Wl(o.structDef,r,(s=o.parent)!==null&&s!==void 0?s:{model:this},i):o}return new Wl(e,r,{model:this},i)}loadQuery(e,r,i,s=!1,o=!1){var u;const a="";r||(r=new Gp(!0,void 0));const l={type:"turtle",name:"ignoreme",pipeline:e.pipeline,filterList:e.filterList},c=(u=e.compositeResolvedSourceDef)!==null&&u!==void 0?u:e.structRef,f=cs.makeQuery(l,this.getStructFromRef(c,e.sourceArguments,i),r,o),x=f.generateSQLFromPipeline(r);if(s&&f.parent.dialect.hasFinalStage){const h=[];for(const p of x.outputStruct.fields)if((0,Be.isAtomic)(p)){const m=f.parent.dialect.sqlMaybeQuoteIdentifier(p.name);h.push(m)}x.lastStageName=r.addStage(f.parent.dialect.sqlFinalStage(x.lastStageName,h))}return{lastStageName:x.lastStageName,malloy:a,stageWriter:r,structs:[x.outputStruct],connectionName:f.parent.connectionName}}addDefaultRowLimit(e,r){const i={query:e,addedDefaultRowLimit:void 0};if(r===void 0)return i;const s=e.pipeline[e.pipeline.length-1];return s.type==="raw"||s.limit!==void 0?i:{query:{...e,pipeline:[...e.pipeline.slice(0,-1),{...s,limit:r}]},addedDefaultRowLimit:r}}compileQuery(e,r,i=!0){var s,o;const u=this.addDefaultRowLimit(e,r==null?void 0:r.defaultRowLimit);e=u.query;const a=u.addedDefaultRowLimit,c=this.loadQuery(e,void 0,r,i,!1),f=(s=e.compositeResolvedSourceDef)!==null&&s!==void 0?s:e.structRef,x=typeof f=="string"?f:f.as||f.name;return i&&this.dialect.hasFinalStage&&(c.lastStageName=c.stageWriter.addStage(this.dialect.sqlFinalStage(c.lastStageName,[]))),{lastStageName:c.lastStageName,malloy:c.malloy,sql:c.stageWriter.generateSQLStages(),dependenciesToMaterialize:c.stageWriter.dependenciesToMaterialize,materialization:(0,P4.shouldMaterialize)(e.annotation)?(0,P4.buildQueryMaterializationSpec)((o=e.location)===null||o===void 0?void 0:o.url,e.name,r==null?void 0:r.materializedTablePrefix):void 0,structs:c.structs,sourceExplore:x,sourceFilters:e.filterList,queryName:e.name,connectionName:c.connectionName,annotation:e.annotation,queryTimezone:c.structs[0].queryTimezone,defaultRowLimitAdded:a}}async searchIndex(e,r,i,s=1e3,o=void 0){if(!e.canPersist())return;const u=this.getStructByName(r);let a=[];for(const[E,A]of u.nameMap)yo(A)&&A.includeInWildcard()&&a.push({type:"fieldref",path:[E]});a=a.sort((E,A)=>E.path[0].localeCompare(A.path[0]));const l={structRef:r,pipeline:[{type:"index",indexFields:a,sample:u.dialect.defaultSampling}]},c=u.dialect.sqlMaybeQuoteIdentifier("fieldName"),f=u.dialect.sqlMaybeQuoteIdentifier("fieldPath"),x=u.dialect.sqlMaybeQuoteIdentifier("fieldValue"),h=u.dialect.sqlMaybeQuoteIdentifier("fieldType"),p=u.dialect.sqlMaybeQuoteIdentifier("weight");let m=this.exploreSearchSQLMap.get(r);m===void 0&&(m=this.compileQuery(l,void 0,!1).sql,this.exploreSearchSQLMap.set(r,m));let g=`SELECT
1138
1138
  ${c},
1139
1139
  ${f},
1140
1140
  ${x},
@@ -1149,17 +1149,17 @@ FROM ${p}
1149
1149
  `;return u.dialect.hasFinalStage&&(g=`WITH __stage0 AS(
1150
1150
  ${g}
1151
1151
  )
1152
- ${u.dialect.sqlFinalStage("__stage0",[c,f,x,h,p,"match_first"])}`),(await e.runSQL(g,{rowLimit:1e3})).rows}}Ls.QueryModel=q4,function(t){var e=T&&T.__createBinding||(Object.create?function(o,u,a,l){l===void 0&&(l=a);var c=Object.getOwnPropertyDescriptor(u,a);(!c||("get"in c?!u.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return u[a]}}),Object.defineProperty(o,l,c)}:function(o,u,a,l){l===void 0&&(l=a),o[l]=u[a]}),r=T&&T.__exportStar||function(o,u){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(u,a)&&e(u,o,a)};Object.defineProperty(t,"__esModule",{value:!0}),t.composeSQLExpr=t.indent=t.QueryModel=t.Segment=void 0,r(Xe,t);var i=Ls;Object.defineProperty(t,"Segment",{enumerable:!0,get:function(){return i.Segment}}),Object.defineProperty(t,"QueryModel",{enumerable:!0,get:function(){return i.QueryModel}});var s=Bt;Object.defineProperty(t,"indent",{enumerable:!0,get:function(){return s.indent}}),Object.defineProperty(t,"composeSQLExpr",{enumerable:!0,get:function(){return s.composeSQLExpr}})}(Pi);var H4={},Tc={},Q4={},Ry={},Vp={};Object.defineProperty(Vp,"__esModule",{value:!0}),Vp.detectAndRemovePartialStages=void 0;const wXe=Pi;function NXe(t,e){const r=[];let i=!1;for(const s of t)(0,wXe.isPartialSegment)(s)?(r.push({...s,type:"reduce"}),i=!0):r.push(s);return i&&e.logError("ambiguous-view-type",{}),r}Vp.detectAndRemovePartialStages=NXe;var Dy={},Je={},Yp={},lt={},Vn={};Object.defineProperty(Vn,"__esModule",{value:!0}),Vn.getSourceInfo=Vn.rangeFromContext=Vn.rangeFromToken=Vn.rangeFromTokens=Vn.isNotUndefined=Vn.locationContainsPosition=void 0;function LXe(t,e){return t.range.start.line<=e.line&&t.range.end.line>=e.line&&(e.line!==t.range.start.line||e.character>=t.range.start.character)&&(e.line!==t.range.end.line||e.character<=t.range.end.character)}Vn.locationContainsPosition=LXe;function IXe(t){return t!==void 0}Vn.isNotUndefined=IXe;function l$(t,e,r){const i={line:e.line-1,character:e.charPositionInLine};if(t&&r.stopIndex!==-1){const s=t.lines.length-1;for(let o=e.line-1;o<=s;o++){const u=t.at[o];if(r.stopIndex>=u.begin&&r.stopIndex<u.end)return{start:i,end:{line:o,character:r.stopIndex-u.begin+1}}}return{start:i,end:{line:s,character:t.lines[s].length}}}return{start:i,end:i}}Vn.rangeFromTokens=l$;function BXe(t,e){return l$(t,e,e)}Vn.rangeFromToken=BXe;function $Xe(t,e){return l$(t,e.start,e.stop||e.start)}Vn.rangeFromContext=$Xe;function kXe(t){const e=/\r?\n/,r={at:[],lines:[],length:t.length};let i=t,s=0;for(;i!=="";){const o=i.match(e);if(o&&o.index!==void 0){r.lines.push(i.slice(0,o.index));const u=o.index+o[0].length;r.at.push({begin:s,end:s+u}),s+=u,i=i.slice(u)}else{r.lines.push(i),r.at.push({begin:s,end:s+i.length});break}}return r}Vn.getSourceInfo=kXe,Object.defineProperty(lt,"__esModule",{value:!0}),lt.compositeFieldUsageJoinPaths=lt.joinedCompositeFieldUsage=lt.compositeFieldUsageDifference=lt.emptyCompositeFieldUsage=lt.mergeCompositeFieldUsage=lt.unique=lt.formatCompositeFieldUsage=lt.compositeFieldUsageIsPlural=lt.isEmptyCompositeFieldUsage=lt.formatCompositeFieldUsages=lt.compositeFieldUsagePaths=lt.resolveCompositeSources=lt.narrowCompositeFieldResolution=lt.emptyNarrowedCompositeFieldResolution=void 0;const Cae=Vn,c$=Xe;function z4(t,e,r,i=void 0){var s,o,u,a,l,c,f;let x={...e},h;const p=GXe(e);if(r.fields.length>0||e.type==="composite")if(e.type==="composite"){let y=!1;h=(s=i==null?void 0:i.source)!==null&&s!==void 0?s:e.sources.map(A=>({source:A,nested:void 0}));const E=[...h];e:for(const{source:A,nested:_}of h){const v=new Set;for(const C of A.fields)C.accessModifier!=="private"&&v.add((o=C.as)!==null&&o!==void 0?o:C.name);for(const C of r.fields)if(!v.has(C)){E.shift();continue e}if(A.type==="composite"){const C=z4(t,A,WXe(r,A),{source:_??A.sources.map(b=>({source:b,nested:[]})),joined:{}});if("error"in C){E.shift();continue e}x={...C.success},E[0]={source:A,nested:C.narrowedCompositeFieldResolution.source}}else x={...A};y=!0,x={...x,fields:[...p,...x.fields],filterList:[...(u=e.filterList)!==null&&u!==void 0?u:[],...(a=x.filterList)!==null&&a!==void 0?a:[]]};break}if(!y)return{error:{code:"no_suitable_composite_source_input",data:{fields:r.fields,path:t}}};h=E}else return{error:{code:"not_a_composite_source",data:{path:t}}};x.arguments=e.arguments;const m={},g=(l=i==null?void 0:i.joined)!==null&&l!==void 0?l:{};for(const y of x.fields)m[(c=y.as)!==null&&c!==void 0?c:y.name]=y;for(const[y,E]of Object.entries(r.joinedUsage)){const A=m[y],_=[...t,y];if(A===void 0)return{error:{code:"composite_source_not_defined",data:{path:_}}};if((0,c$.isJoined)(A)){if(!(0,c$.isSourceDef)(A))continue}else return{error:{code:"composite_source_not_a_join",data:{path:_}}};const v=z4(_,A,E,g[y]);if("error"in v)return v;if(!(0,c$.isJoinable)(v.success))return{error:{code:"composite_source_is_not_joinable",data:{path:_}}};m[y]={...v.success,join:A.join,as:(f=A.as)!==null&&f!==void 0?f:A.name,onExpression:A.onExpression},g[y]=v.narrowedCompositeFieldResolution}return{success:{...x,fields:Object.values(m)},narrowedCompositeFieldResolution:{source:h,joined:g}}}function MXe(){return{source:void 0,joined:{}}}lt.emptyNarrowedCompositeFieldResolution=MXe;function PXe(t,e,r){const i=z4([],t,e,r);return"success"in i?{narrowedCompositeFieldResolution:i.narrowedCompositeFieldResolution,error:void 0}:{narrowedCompositeFieldResolution:void 0,error:i.error}}lt.narrowCompositeFieldResolution=PXe;function UXe(t,e){const r=z4([],t,e);return"success"in r?{sourceDef:r.success,error:void 0}:{sourceDef:void 0,error:r.error}}lt.resolveCompositeSources=UXe;function f$(t){return[...t.fields.map(e=>[e]),...Object.entries(t.joinedUsage).map(([e,r])=>f$(r).map(i=>[e,...i])).flat()]}lt.compositeFieldUsagePaths=f$;function jXe(t){return f$(t).map(e=>Sae(e)).join(", ")}lt.formatCompositeFieldUsages=jXe;function x$(t){return Object.values(t.joinedUsage).reduce((e,r)=>e+x$(r),t.fields.length)}function qXe(t){return x$(t)===0}lt.isEmptyCompositeFieldUsage=qXe;function HXe(t){return x$(t)>1}lt.compositeFieldUsageIsPlural=HXe;function Sae(t){return`\`${t.join(".")}\``}lt.formatCompositeFieldUsage=Sae;function bae(t){return Array.from(new Set(t))}lt.unique=bae;function Tae(...t){const e=t.filter(Cae.isNotUndefined),r=new Set(e.map(s=>Object.keys(s.joinedUsage)).flat()),i={};for(const s of r)i[s]=Tae(...e.map(o=>o==null?void 0:o.joinedUsage[s]).filter(Cae.isNotUndefined));return{fields:bae(e.map(s=>s.fields).flat()),joinedUsage:i}}lt.mergeCompositeFieldUsage=Tae;function QXe(){return{fields:[],joinedUsage:{}}}lt.emptyCompositeFieldUsage=QXe;function zXe(t,e){const r=new Set(e),i=[];for(const s of t)r.has(s)||i.push(s);return i}function Rae(t,e){return{fields:zXe(t.fields,e.fields),joinedUsage:Object.fromEntries(Object.entries(t.joinedUsage).map(([r,i])=>[r,r in e.joinedUsage?Rae(i,e.joinedUsage[r]):i]))}}lt.compositeFieldUsageDifference=Rae;function Dae(t,e){return t.length===0?e:Dae(t.slice(0,-1),{fields:[],joinedUsage:{[t[t.length-1]]:e}})}lt.joinedCompositeFieldUsage=Dae;function Oae(t){const e=Object.keys(t.joinedUsage);return[...e.map(r=>[r]),...e.map(r=>Oae(t.joinedUsage[r]).map(i=>[r,...i])).flat()]}lt.compositeFieldUsageJoinPaths=Oae;function Fae(t){var e;return"e"in t&&((e=t.e)===null||e===void 0?void 0:e.node)==="compositeField"}function GXe(t){return t.fields.filter(e=>!Fae(e))}function WXe(t,e){var r;const i={};for(const s of e.fields)i[(r=s.as)!==null&&r!==void 0?r:s.name]=s;return{fields:t.fields.filter(s=>Fae(i[s])),joinedUsage:{}}}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.makeLogMessage=t.MESSAGE_FORMATTERS=t.BaseMessageLogger=void 0;const e=lt;class r{constructor(o){this.eventStream=o,this.rawLog=[]}getLog(){return this.rawLog}log(o){var u;this.rawLog.push(o),(u=this.eventStream)===null||u===void 0||u.emit(`translation-${o.severity}`,{code:o.code,data:o.data,message:o.message})}reset(){this.rawLog.length=0}noErrors(){return!this.hasErrors()}hasErrors(){return this.rawLog.find(u=>u.severity!=="warn")!==void 0}empty(){return this.rawLog.length===0}}t.BaseMessageLogger=r,t.MESSAGE_FORMATTERS={"pick-type-does-not-match":s=>({message:`pick type \`${s.pickType}\` does not match return type \`${s.returnType}\``,tag:"pick-values-must-match"}),"pick-else-type-does-not-match":s=>({message:`else type \`${s.elseType}\` does not match return type \`${s.returnType}\``,tag:"pick-values-must-match"}),"pick-default-type-does-not-match":s=>({message:`default type \`${s.defaultType}\` does not match return type \`${s.returnType}\``,tag:"pick-values-must-match"}),"experimental-dialect-not-enabled":s=>`Requires compiler flag '##! experimental.dialect.${s.dialect}'`,"pick-missing-else":"pick incomplete, missing 'else'","pick-missing-value":"pick with no value can only be used with apply","pick-illegal-partial":"pick with partial when can only be used with apply","pick-when-must-be-boolean":s=>`when expression must be boolean, not ${s.whenType}`,"sql-native-not-allowed-in-expression":s=>({message:`Unsupported SQL native type '${s.rawType}' not allowed in expression`,tag:"unsupported-sql-native-type-not-allowed-in-expression"}),"experiment-not-enabled":s=>`Experimental flag \`${s.experimentId}\` is not set, feature not available`,"ambiguous-view-type":"Can't determine view type (`group_by` / `aggregate` / `nest`, `project`, `index`)","import-error":s=>s.message.includes(s.url)?`import error: ${s.message}`:`import '${s.url}' error: ${s.message}`,"parsed-non-malloy-document":s=>`'${s.url}' did not parse to malloy document`,"parse-exception":s=>`Malloy internal parser exception [${s.message}]`,"syntax-error":s=>s.message,"internal-translator-error":s=>`Internal Translator Error: ${s.message}`,"invalid-timezone":s=>`Invalid timezone: ${s.timezone}`,"case-then-type-does-not-match":s=>`Case then type ${s.thenType} does not match return type ${s.returnType}`,"case-else-type-does-not-match":s=>`Case else type ${s.elseType} does not match return type ${s.returnType}`,"case-when-must-be-boolean":s=>`Case when expression must be boolean, not ${s.whenType}`,"case-when-type-does-not-match":s=>`Case when type ${s.whenType} does not match value type ${s.valueType}`,"invalid-composite-field-usage":s=>{const o=(0,e.formatCompositeFieldUsages)(s.newUsage),u=(0,e.formatCompositeFieldUsages)(s.allUsage);return`This operation uses composite field${(0,e.compositeFieldUsageIsPlural)(s.newUsage)?"s":""} ${o}, resulting in invalid usage of the composite source, as there is no composite input source which defines all of ${u}`}};function i(s,o,u){var a,l,c,f,x;const h=t.MESSAGE_FORMATTERS[s],p=h?h instanceof Function?h(o):h:typeof o=="string"?o:void 0;if(p===void 0)throw new Error(`No message formatter for error code \`${s}\`.`);const m=typeof p=="string"?{message:p}:p,g=((a=m.data)!==null&&a!==void 0?a:typeof o=="string")?null:o;return{code:s,data:g,message:m.message,severity:(c=(l=u==null?void 0:u.severity)!==null&&l!==void 0?l:m.severity)!==null&&c!==void 0?c:"error",errorTag:(f=u==null?void 0:u.tag)!==null&&f!==void 0?f:m.tag,replacement:(x=u==null?void 0:u.replacement)!==null&&x!==void 0?x:m.replacement,at:u==null?void 0:u.at}}t.makeLogMessage=i})(Yp);var Bs={};Object.defineProperty(Bs,"__esModule",{value:!0}),Bs.errorFor=void 0;const VXe=lt;function YXe(t){return{type:"error",expressionType:"scalar",value:{node:"error",message:t},evalSpace:"constant",compositeFieldUsage:(0,VXe.emptyCompositeFieldUsage)()}}Bs.errorFor=YXe;var G4={};Object.defineProperty(G4,"__esModule",{value:!0}),G4.DialectNameSpace=void 0;class KXe{constructor(e){this.entries=new Map;const r=e.getDialectFunctions();for(const i in r){const s=r[i];this.entries.set(i,{type:"function",name:i,overloads:s.map(o=>({returnType:o.returnType,params:o.params,supportsOrderBy:o.supportsOrderBy,supportsLimit:o.supportsLimit,isSymmetric:o.isSymmetric,genericTypes:o.genericTypes,dialect:{[e.name]:{e:o.e,defaultOrderByArgIndex:o.defaultOrderByArgIndex,between:o.between,needsWindowOrderBy:o.needsWindowOrderBy}}}))})}}getEntry(e){const r=this.entries.get(e);if(r!==void 0)return{entry:r,exported:!1}}setEntry(e,r,i){throw new Error("The dialect namespace is immutable!")}}G4.DialectNameSpace=KXe;var Kp={};Object.defineProperty(Kp,"__esModule",{value:!0}),Kp.getDialectFunctions=Kp.GlobalNameSpace=void 0;const JXe=kp,XXe=va,ZXe=Pi;class eZe{constructor(){this.entries=wae()}getEntry(e){const r=this.entries.get(e);if(r!==void 0)return{entry:r,exported:!1}}setEntry(e,r,i){throw new Error("The global namespace is immutable!")}}Kp.GlobalNameSpace=eZe;function tZe(t,e){return t.params.length===e.params.length&&t.params.every((r,i)=>{const s=e.params[i];return r.isVariadic===s.isVariadic&&r.name===s.name&&r.allowedTypes.length===s.allowedTypes.length&&r.allowedTypes.every(o=>s.allowedTypes.some(u=>ZXe.TD.eq(o,u)&&o.expressionType===u.expressionType))})}function wae(){var t,e;const r=(0,JXe.getMalloyStandardFunctions)(),i={},s=(0,XXe.getDialects)();for(const u of s)i[u.name]=u.getDialectFunctionOverrides();const o=new Map;for(const u in r){const a=r[u],l={type:"function",name:u,overloads:[]};for(const c of a){const f={returnType:c.returnType,params:c.params,dialect:{},supportsOrderBy:c.supportsOrderBy,supportsLimit:c.supportsLimit,genericTypes:c.genericTypes,isSymmetric:c.isSymmetric};for(const x of s){const p=(e=((t=i[x.name][u])!==null&&t!==void 0?t:[]).find(m=>tZe(m,f)))!==null&&e!==void 0?e:c;f.dialect[x.name]={e:p.e,needsWindowOrderBy:p.needsWindowOrderBy,between:p.between,defaultOrderByArgIndex:p.defaultOrderByArgIndex}}l.overloads.push(f)}o.set(u,l)}return o}Kp.getDialectFunctions=wae;var kr={};Object.defineProperty(kr,"__esModule",{value:!0}),kr.extendNoteHelper=kr.extendNoteMethod=kr.isNoteable=void 0;function nZe(t){return t.isNoteableObj}kr.isNoteable=nZe;function rZe(t){Nae(this,t)}kr.extendNoteMethod=rZe;function Nae(t,e){(e.notes&&e.notes.length>0||e.blockNotes&&e.blockNotes.length>0||e.inherits!==void 0)&&(t.note={...t.note,...e})}kr.extendNoteHelper=Nae,Object.defineProperty(Je,"__esModule",{value:!0}),Je.Document=Je.DocStatementList=Je.ListOf=Je.isDocStatementOrDocStatementList=Je.isDocStatement=Je.ExperimentalExperiment=Je.ModelEntryReference=Je.Unimplemented=Je.MalloyElement=void 0;const Lae=kp,W4=Xe,iZe=Zo,sZe=Yp,oZe=Bs,uZe=G4,aZe=Kp,Iae=kr,lZe=Pp;class ba{constructor(e){this.children={},this.parent=null,this.logged=new Set,e&&this.has(e)}has(e){for(const r in e){const i=e[r];if(i!==void 0)if(this.children[r]=i,i instanceof ba)i.parent=this;else for(const s of i)s.parent=this}}get location(){return this.codeLocation?this.codeLocation:this.parent?this.parent.location:{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}set location(e){this.codeLocation=e}get code(){var e,r;return(r=(e=this.translator())===null||e===void 0?void 0:e.codeAtLocation(this.location))!==null&&r!==void 0?r:""}document(){var e;return this instanceof h$?this:(e=this.parent)===null||e===void 0?void 0:e.document()}namespace(){if(this instanceof h$)return this;if(this.parent)return this.parent.namespace();throw new Error("INTERNAL ERROR: Translation without document scope")}getDialectNamespace(e){var r;return(r=this.document())===null||r===void 0?void 0:r.getDialectNamespace(e)}modelEntry(e){var r;const i=e instanceof d$?e.name:e,s=(r=this.namespace())===null||r===void 0?void 0:r.getEntry(i);return e instanceof d$&&((s==null?void 0:s.entry.type)==="query"?this.addReference({type:"queryReference",text:i,definition:s.entry,location:e.location}):s&&(0,W4.isSourceDef)(s.entry)&&this.addReference({type:"exploreReference",text:i,definition:s.entry,location:e.location})),s}kupuna(){var e;return((e=this.parent)===null||e===void 0?void 0:e.kupuna())||this}translator(){if(this.xlate)return this.xlate;if(this.parent)return this.parent.translator()}setTranslator(e){this.xlate=e}addReference(e){var r;(r=this.translator())===null||r===void 0||r.addReference(e)}get sourceURL(){const e=this.translator();return(e==null?void 0:e.sourceURL)||"(missing)"}log(e,r,i){const s=(0,sZe.makeLogMessage)(e,r,{at:this.location,...i});if(this.codeLocation){if(this.logged.has(s.message))return e;this.logged.add(s.message)}return this.logger.log(s),e}logError(e,r,i){return this.log(e,r,{severity:"error",...i})}logWarning(e,r,i){return this.log(e,r,{severity:"warn",...i})}loggedErrorExpr(e,r,i){return(0,oZe.errorFor)(this.logError(e,r,i))}get logger(){var e;const r=(e=this.translator())===null||e===void 0?void 0:e.root.logger;if(r===void 0)throw new Error("Attempted to access logger without a translator");return r}toString(){return this.stringify("",0)}stringify(e,r){const i=" ".repeat(r);let s=`${i}${e}<${this.elementType}>${this.varInfo()}`;for(const o of Object.keys(this.children)){const u=this.children[o];u instanceof ba?s+=`
1152
+ ${u.dialect.sqlFinalStage("__stage0",[c,f,x,h,p,"match_first"])}`),(await e.runSQL(g,{rowLimit:1e3})).rows}}Ls.QueryModel=q4,function(t){var e=T&&T.__createBinding||(Object.create?function(o,u,a,l){l===void 0&&(l=a);var c=Object.getOwnPropertyDescriptor(u,a);(!c||("get"in c?!u.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return u[a]}}),Object.defineProperty(o,l,c)}:function(o,u,a,l){l===void 0&&(l=a),o[l]=u[a]}),r=T&&T.__exportStar||function(o,u){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(u,a)&&e(u,o,a)};Object.defineProperty(t,"__esModule",{value:!0}),t.composeSQLExpr=t.indent=t.QueryModel=t.Segment=void 0,r(Xe,t);var i=Ls;Object.defineProperty(t,"Segment",{enumerable:!0,get:function(){return i.Segment}}),Object.defineProperty(t,"QueryModel",{enumerable:!0,get:function(){return i.QueryModel}});var s=Bt;Object.defineProperty(t,"indent",{enumerable:!0,get:function(){return s.indent}}),Object.defineProperty(t,"composeSQLExpr",{enumerable:!0,get:function(){return s.composeSQLExpr}})}(Pi);var H4={},Tc={},Q4={},Ry={},Vp={};Object.defineProperty(Vp,"__esModule",{value:!0}),Vp.detectAndRemovePartialStages=void 0;const LXe=Pi;function IXe(t,e){const r=[];let i=!1;for(const s of t)(0,LXe.isPartialSegment)(s)?(r.push({...s,type:"reduce"}),i=!0):r.push(s);return i&&e.logError("ambiguous-view-type",{}),r}Vp.detectAndRemovePartialStages=IXe;var Dy={},Je={},Yp={},lt={},Vn={};Object.defineProperty(Vn,"__esModule",{value:!0}),Vn.getSourceInfo=Vn.rangeFromContext=Vn.rangeFromToken=Vn.rangeFromTokens=Vn.isNotUndefined=Vn.locationContainsPosition=void 0;function BXe(t,e){return t.range.start.line<=e.line&&t.range.end.line>=e.line&&(e.line!==t.range.start.line||e.character>=t.range.start.character)&&(e.line!==t.range.end.line||e.character<=t.range.end.character)}Vn.locationContainsPosition=BXe;function $Xe(t){return t!==void 0}Vn.isNotUndefined=$Xe;function l$(t,e,r){const i={line:e.line-1,character:e.charPositionInLine};if(t&&r.stopIndex!==-1){const s=t.lines.length-1;for(let o=e.line-1;o<=s;o++){const u=t.at[o];if(r.stopIndex>=u.begin&&r.stopIndex<u.end)return{start:i,end:{line:o,character:r.stopIndex-u.begin+1}}}return{start:i,end:{line:s,character:t.lines[s].length}}}return{start:i,end:i}}Vn.rangeFromTokens=l$;function kXe(t,e){return l$(t,e,e)}Vn.rangeFromToken=kXe;function MXe(t,e){return l$(t,e.start,e.stop||e.start)}Vn.rangeFromContext=MXe;function PXe(t){const e=/\r?\n/,r={at:[],lines:[],length:t.length};let i=t,s=0;for(;i!=="";){const o=i.match(e);if(o&&o.index!==void 0){r.lines.push(i.slice(0,o.index));const u=o.index+o[0].length;r.at.push({begin:s,end:s+u}),s+=u,i=i.slice(u)}else{r.lines.push(i),r.at.push({begin:s,end:s+i.length});break}}return r}Vn.getSourceInfo=PXe,Object.defineProperty(lt,"__esModule",{value:!0}),lt.compositeFieldUsageJoinPaths=lt.joinedCompositeFieldUsage=lt.compositeFieldUsageDifference=lt.emptyCompositeFieldUsage=lt.mergeCompositeFieldUsage=lt.unique=lt.formatCompositeFieldUsage=lt.compositeFieldUsageIsPlural=lt.isEmptyCompositeFieldUsage=lt.formatCompositeFieldUsages=lt.compositeFieldUsagePaths=lt.resolveCompositeSources=lt.narrowCompositeFieldResolution=lt.emptyNarrowedCompositeFieldResolution=void 0;const Cae=Vn,c$=Xe;function z4(t,e,r,i=void 0){var s,o,u,a,l,c,f;let x={...e},h;const p=VXe(e);if(r.fields.length>0||e.type==="composite")if(e.type==="composite"){let y=!1;h=(s=i==null?void 0:i.source)!==null&&s!==void 0?s:e.sources.map(A=>({source:A,nested:void 0}));const E=[...h];e:for(const{source:A,nested:_}of h){const v=new Set;for(const C of A.fields)C.accessModifier!=="private"&&v.add((o=C.as)!==null&&o!==void 0?o:C.name);for(const C of r.fields)if(!v.has(C)){E.shift();continue e}if(A.type==="composite"){const C=z4(t,A,YXe(r,A),{source:_??A.sources.map(b=>({source:b,nested:[]})),joined:{}});if("error"in C){E.shift();continue e}x={...C.success},E[0]={source:A,nested:C.narrowedCompositeFieldResolution.source}}else x={...A};y=!0,x={...x,fields:[...p,...x.fields],filterList:[...(u=e.filterList)!==null&&u!==void 0?u:[],...(a=x.filterList)!==null&&a!==void 0?a:[]]};break}if(!y)return{error:{code:"no_suitable_composite_source_input",data:{fields:r.fields,path:t}}};h=E}else return{error:{code:"not_a_composite_source",data:{path:t}}};x.arguments=e.arguments;const m={},g=(l=i==null?void 0:i.joined)!==null&&l!==void 0?l:{};for(const y of x.fields)m[(c=y.as)!==null&&c!==void 0?c:y.name]=y;for(const[y,E]of Object.entries(r.joinedUsage)){const A=m[y],_=[...t,y];if(A===void 0)return{error:{code:"composite_source_not_defined",data:{path:_}}};if((0,c$.isJoined)(A)){if(!(0,c$.isSourceDef)(A))continue}else return{error:{code:"composite_source_not_a_join",data:{path:_}}};const v=z4(_,A,E,g[y]);if("error"in v)return v;if(!(0,c$.isJoinable)(v.success))return{error:{code:"composite_source_is_not_joinable",data:{path:_}}};m[y]={...v.success,join:A.join,as:(f=A.as)!==null&&f!==void 0?f:A.name,onExpression:A.onExpression},g[y]=v.narrowedCompositeFieldResolution}return{success:{...x,fields:Object.values(m)},narrowedCompositeFieldResolution:{source:h,joined:g}}}function UXe(){return{source:void 0,joined:{}}}lt.emptyNarrowedCompositeFieldResolution=UXe;function jXe(t,e,r){const i=z4([],t,e,r);return"success"in i?{narrowedCompositeFieldResolution:i.narrowedCompositeFieldResolution,error:void 0}:{narrowedCompositeFieldResolution:void 0,error:i.error}}lt.narrowCompositeFieldResolution=jXe;function qXe(t,e){const r=z4([],t,e);return"success"in r?{sourceDef:r.success,error:void 0}:{sourceDef:void 0,error:r.error}}lt.resolveCompositeSources=qXe;function f$(t){return[...t.fields.map(e=>[e]),...Object.entries(t.joinedUsage).map(([e,r])=>f$(r).map(i=>[e,...i])).flat()]}lt.compositeFieldUsagePaths=f$;function HXe(t){return f$(t).map(e=>Sae(e)).join(", ")}lt.formatCompositeFieldUsages=HXe;function x$(t){return Object.values(t.joinedUsage).reduce((e,r)=>e+x$(r),t.fields.length)}function QXe(t){return x$(t)===0}lt.isEmptyCompositeFieldUsage=QXe;function zXe(t){return x$(t)>1}lt.compositeFieldUsageIsPlural=zXe;function Sae(t){return`\`${t.join(".")}\``}lt.formatCompositeFieldUsage=Sae;function bae(t){return Array.from(new Set(t))}lt.unique=bae;function Tae(...t){const e=t.filter(Cae.isNotUndefined),r=new Set(e.map(s=>Object.keys(s.joinedUsage)).flat()),i={};for(const s of r)i[s]=Tae(...e.map(o=>o==null?void 0:o.joinedUsage[s]).filter(Cae.isNotUndefined));return{fields:bae(e.map(s=>s.fields).flat()),joinedUsage:i}}lt.mergeCompositeFieldUsage=Tae;function GXe(){return{fields:[],joinedUsage:{}}}lt.emptyCompositeFieldUsage=GXe;function WXe(t,e){const r=new Set(e),i=[];for(const s of t)r.has(s)||i.push(s);return i}function Rae(t,e){return{fields:WXe(t.fields,e.fields),joinedUsage:Object.fromEntries(Object.entries(t.joinedUsage).map(([r,i])=>[r,r in e.joinedUsage?Rae(i,e.joinedUsage[r]):i]))}}lt.compositeFieldUsageDifference=Rae;function Dae(t,e){return t.length===0?e:Dae(t.slice(0,-1),{fields:[],joinedUsage:{[t[t.length-1]]:e}})}lt.joinedCompositeFieldUsage=Dae;function Oae(t){const e=Object.keys(t.joinedUsage);return[...e.map(r=>[r]),...e.map(r=>Oae(t.joinedUsage[r]).map(i=>[r,...i])).flat()]}lt.compositeFieldUsageJoinPaths=Oae;function Fae(t){var e;return"e"in t&&((e=t.e)===null||e===void 0?void 0:e.node)==="compositeField"}function VXe(t){return t.fields.filter(e=>!Fae(e))}function YXe(t,e){var r;const i={};for(const s of e.fields)i[(r=s.as)!==null&&r!==void 0?r:s.name]=s;return{fields:t.fields.filter(s=>Fae(i[s])),joinedUsage:{}}}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.makeLogMessage=t.MESSAGE_FORMATTERS=t.BaseMessageLogger=void 0;const e=lt;class r{constructor(o){this.eventStream=o,this.rawLog=[]}getLog(){return this.rawLog}log(o){var u;this.rawLog.push(o),(u=this.eventStream)===null||u===void 0||u.emit(`translation-${o.severity}`,{code:o.code,data:o.data,message:o.message})}reset(){this.rawLog.length=0}noErrors(){return!this.hasErrors()}hasErrors(){return this.rawLog.find(u=>u.severity!=="warn")!==void 0}empty(){return this.rawLog.length===0}}t.BaseMessageLogger=r,t.MESSAGE_FORMATTERS={"pick-type-does-not-match":s=>({message:`pick type \`${s.pickType}\` does not match return type \`${s.returnType}\``,tag:"pick-values-must-match"}),"pick-else-type-does-not-match":s=>({message:`else type \`${s.elseType}\` does not match return type \`${s.returnType}\``,tag:"pick-values-must-match"}),"pick-default-type-does-not-match":s=>({message:`default type \`${s.defaultType}\` does not match return type \`${s.returnType}\``,tag:"pick-values-must-match"}),"experimental-dialect-not-enabled":s=>`Requires compiler flag '##! experimental.dialect.${s.dialect}'`,"pick-missing-else":"pick incomplete, missing 'else'","pick-missing-value":"pick with no value can only be used with apply","pick-illegal-partial":"pick with partial when can only be used with apply","pick-when-must-be-boolean":s=>`when expression must be boolean, not ${s.whenType}`,"sql-native-not-allowed-in-expression":s=>({message:`Unsupported SQL native type '${s.rawType}' not allowed in expression`,tag:"unsupported-sql-native-type-not-allowed-in-expression"}),"experiment-not-enabled":s=>`Experimental flag \`${s.experimentId}\` is not set, feature not available`,"ambiguous-view-type":"Can't determine view type (`group_by` / `aggregate` / `nest`, `project`, `index`)","import-error":s=>s.message.includes(s.url)?`import error: ${s.message}`:`import '${s.url}' error: ${s.message}`,"parsed-non-malloy-document":s=>`'${s.url}' did not parse to malloy document`,"parse-exception":s=>`Malloy internal parser exception [${s.message}]`,"syntax-error":s=>s.message,"internal-translator-error":s=>`Internal Translator Error: ${s.message}`,"invalid-timezone":s=>`Invalid timezone: ${s.timezone}`,"case-then-type-does-not-match":s=>`Case then type ${s.thenType} does not match return type ${s.returnType}`,"case-else-type-does-not-match":s=>`Case else type ${s.elseType} does not match return type ${s.returnType}`,"case-when-must-be-boolean":s=>`Case when expression must be boolean, not ${s.whenType}`,"case-when-type-does-not-match":s=>`Case when type ${s.whenType} does not match value type ${s.valueType}`,"invalid-composite-field-usage":s=>{const o=(0,e.formatCompositeFieldUsages)(s.newUsage),u=(0,e.formatCompositeFieldUsages)(s.allUsage);return`This operation uses composite field${(0,e.compositeFieldUsageIsPlural)(s.newUsage)?"s":""} ${o}, resulting in invalid usage of the composite source, as there is no composite input source which defines all of ${u}`}};function i(s,o,u){var a,l,c,f,x;const h=t.MESSAGE_FORMATTERS[s],p=h?h instanceof Function?h(o):h:typeof o=="string"?o:void 0;if(p===void 0)throw new Error(`No message formatter for error code \`${s}\`.`);const m=typeof p=="string"?{message:p}:p,g=((a=m.data)!==null&&a!==void 0?a:typeof o=="string")?null:o;return{code:s,data:g,message:m.message,severity:(c=(l=u==null?void 0:u.severity)!==null&&l!==void 0?l:m.severity)!==null&&c!==void 0?c:"error",errorTag:(f=u==null?void 0:u.tag)!==null&&f!==void 0?f:m.tag,replacement:(x=u==null?void 0:u.replacement)!==null&&x!==void 0?x:m.replacement,at:u==null?void 0:u.at}}t.makeLogMessage=i})(Yp);var Bs={};Object.defineProperty(Bs,"__esModule",{value:!0}),Bs.errorFor=void 0;const KXe=lt;function JXe(t){return{type:"error",expressionType:"scalar",value:{node:"error",message:t},evalSpace:"constant",compositeFieldUsage:(0,KXe.emptyCompositeFieldUsage)()}}Bs.errorFor=JXe;var G4={};Object.defineProperty(G4,"__esModule",{value:!0}),G4.DialectNameSpace=void 0;class XXe{constructor(e){this.entries=new Map;const r=e.getDialectFunctions();for(const i in r){const s=r[i];this.entries.set(i,{type:"function",name:i,overloads:s.map(o=>({returnType:o.returnType,params:o.params,supportsOrderBy:o.supportsOrderBy,supportsLimit:o.supportsLimit,isSymmetric:o.isSymmetric,genericTypes:o.genericTypes,dialect:{[e.name]:{e:o.e,defaultOrderByArgIndex:o.defaultOrderByArgIndex,between:o.between,needsWindowOrderBy:o.needsWindowOrderBy}}}))})}}getEntry(e){const r=this.entries.get(e);if(r!==void 0)return{entry:r,exported:!1}}setEntry(e,r,i){throw new Error("The dialect namespace is immutable!")}}G4.DialectNameSpace=XXe;var Kp={};Object.defineProperty(Kp,"__esModule",{value:!0}),Kp.getDialectFunctions=Kp.GlobalNameSpace=void 0;const ZXe=kp,eZe=va,tZe=Pi;class nZe{constructor(){this.entries=wae()}getEntry(e){const r=this.entries.get(e);if(r!==void 0)return{entry:r,exported:!1}}setEntry(e,r,i){throw new Error("The global namespace is immutable!")}}Kp.GlobalNameSpace=nZe;function rZe(t,e){return t.params.length===e.params.length&&t.params.every((r,i)=>{const s=e.params[i];return r.isVariadic===s.isVariadic&&r.name===s.name&&r.allowedTypes.length===s.allowedTypes.length&&r.allowedTypes.every(o=>s.allowedTypes.some(u=>tZe.TD.eq(o,u)&&o.expressionType===u.expressionType))})}function wae(){var t,e;const r=(0,ZXe.getMalloyStandardFunctions)(),i={},s=(0,eZe.getDialects)();for(const u of s)i[u.name]=u.getDialectFunctionOverrides();const o=new Map;for(const u in r){const a=r[u],l={type:"function",name:u,overloads:[]};for(const c of a){const f={returnType:c.returnType,params:c.params,dialect:{},supportsOrderBy:c.supportsOrderBy,supportsLimit:c.supportsLimit,genericTypes:c.genericTypes,isSymmetric:c.isSymmetric};for(const x of s){const p=(e=((t=i[x.name][u])!==null&&t!==void 0?t:[]).find(m=>rZe(m,f)))!==null&&e!==void 0?e:c;f.dialect[x.name]={e:p.e,needsWindowOrderBy:p.needsWindowOrderBy,between:p.between,defaultOrderByArgIndex:p.defaultOrderByArgIndex}}l.overloads.push(f)}o.set(u,l)}return o}Kp.getDialectFunctions=wae;var kr={};Object.defineProperty(kr,"__esModule",{value:!0}),kr.extendNoteHelper=kr.extendNoteMethod=kr.isNoteable=void 0;function iZe(t){return t.isNoteableObj}kr.isNoteable=iZe;function sZe(t){Nae(this,t)}kr.extendNoteMethod=sZe;function Nae(t,e){(e.notes&&e.notes.length>0||e.blockNotes&&e.blockNotes.length>0||e.inherits!==void 0)&&(t.note={...t.note,...e})}kr.extendNoteHelper=Nae,Object.defineProperty(Je,"__esModule",{value:!0}),Je.Document=Je.DocStatementList=Je.ListOf=Je.isDocStatementOrDocStatementList=Je.isDocStatement=Je.ExperimentalExperiment=Je.ModelEntryReference=Je.Unimplemented=Je.MalloyElement=void 0;const Lae=kp,W4=Xe,oZe=Zo,uZe=Yp,aZe=Bs,lZe=G4,cZe=Kp,Iae=kr,fZe=Pp;class ba{constructor(e){this.children={},this.parent=null,this.logged=new Set,e&&this.has(e)}has(e){for(const r in e){const i=e[r];if(i!==void 0)if(this.children[r]=i,i instanceof ba)i.parent=this;else for(const s of i)s.parent=this}}get location(){return this.codeLocation?this.codeLocation:this.parent?this.parent.location:{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}set location(e){this.codeLocation=e}get code(){var e,r;return(r=(e=this.translator())===null||e===void 0?void 0:e.codeAtLocation(this.location))!==null&&r!==void 0?r:""}document(){var e;return this instanceof h$?this:(e=this.parent)===null||e===void 0?void 0:e.document()}namespace(){if(this instanceof h$)return this;if(this.parent)return this.parent.namespace();throw new Error("INTERNAL ERROR: Translation without document scope")}getDialectNamespace(e){var r;return(r=this.document())===null||r===void 0?void 0:r.getDialectNamespace(e)}modelEntry(e){var r;const i=e instanceof d$?e.name:e,s=(r=this.namespace())===null||r===void 0?void 0:r.getEntry(i);return e instanceof d$&&((s==null?void 0:s.entry.type)==="query"?this.addReference({type:"queryReference",text:i,definition:s.entry,location:e.location}):s&&(0,W4.isSourceDef)(s.entry)&&this.addReference({type:"exploreReference",text:i,definition:s.entry,location:e.location})),s}kupuna(){var e;return((e=this.parent)===null||e===void 0?void 0:e.kupuna())||this}translator(){if(this.xlate)return this.xlate;if(this.parent)return this.parent.translator()}setTranslator(e){this.xlate=e}addReference(e){var r;(r=this.translator())===null||r===void 0||r.addReference(e)}get sourceURL(){const e=this.translator();return(e==null?void 0:e.sourceURL)||"(missing)"}log(e,r,i){const s=(0,uZe.makeLogMessage)(e,r,{at:this.location,...i});if(this.codeLocation){if(this.logged.has(s.message))return e;this.logged.add(s.message)}return this.logger.log(s),e}logError(e,r,i){return this.log(e,r,{severity:"error",...i})}logWarning(e,r,i){return this.log(e,r,{severity:"warn",...i})}loggedErrorExpr(e,r,i){return(0,aZe.errorFor)(this.logError(e,r,i))}get logger(){var e;const r=(e=this.translator())===null||e===void 0?void 0:e.root.logger;if(r===void 0)throw new Error("Attempted to access logger without a translator");return r}toString(){return this.stringify("",0)}stringify(e,r){const i=" ".repeat(r);let s=`${i}${e}<${this.elementType}>${this.varInfo()}`;for(const o of Object.keys(this.children)){const u=this.children[o];u instanceof ba?s+=`
1153
1153
  `+u.stringify(`${o}: `,r+2):(s+=`
1154
1154
  ${i} ${o}: [`,u.length>0&&(s+=`
1155
1155
  `+u.map(a=>a.stringify("",r+4)).join(`
1156
1156
  `)+`
1157
- ${i} `),s+="]")}return s}*walk(){for(const e of Object.keys(this.children)){const r=this.children[e];if(r instanceof ba)yield r;else for(const i of r)yield i}}varInfo(){let e="";for(const[r,i]of Object.entries(this))r!=="elementType"&&(typeof i=="boolean"?e+=i?` ${r}`:` !${r}`:(typeof i=="string"||typeof i=="number")&&(e+=` ${r}=${i}`));return e}internalError(e){return new Error(`INTERNAL ERROR IN TRANSLATION: ${e}`)}needs(e){for(const r of this.walk()){const i=r.needs(e);if(i)return i}}inExperiment(e,r=!1){var i;const s=(i=this.translator())===null||i===void 0?void 0:i.compilerFlags.tag("experimental");return s&&(s.bare()||s.has(e))?!0:(r||this.logError("experiment-not-enabled",{experimentId:e}),!1)}}Je.MalloyElement=ba;class cZe extends ba{constructor(){super(...arguments),this.elementType="unimplemented",this.reported=!1}}Je.Unimplemented=cZe;class d$ extends ba{constructor(e){super(),this.name=e,this.elementType="modelEntryReference"}get refString(){return this.name}toString(){return this.refString}getNamed(){var e;return(e=this.modelEntry(this))===null||e===void 0?void 0:e.entry}}Je.ModelEntryReference=d$;class fZe extends ba{constructor(e){super(),this.id=e,this.elementType="experimentalExperiment"}execute(e){this.inExperiment(this.id)}}Je.ExperimentalExperiment=fZe;function Bae(t){return t.execute!==void 0}Je.isDocStatement=Bae;function xZe(t){return t instanceof Oy||Bae(t)}Je.isDocStatementOrDocStatementList=xZe;class $ae extends ba{constructor(e){super(),this.elements=e,this.newContents()}newContents(){this.has({listOf:this.elements})}get list(){return this.elements}empty(){return this.elements.length===0}notEmpty(){return this.elements.length>0}push(...e){return this.elements.push(...e),this.newContents(),this.elements}needs(e){for(const r of this.elements){const i=r.needs(e);if(i)return i}}}Je.ListOf=$ae;class Oy extends $ae{constructor(){super(...arguments),this.elementType="topLevelStatements",this.execCursor=0,this.isNoteableObj=!0,this.extendNote=Iae.extendNoteMethod,this.noteCursor=0}executeList(e){for(;this.execCursor<this.elements.length;){const r=this.elements[this.execCursor];if(this.noteCursor===this.execCursor&&(this.note&&(0,Iae.isNoteable)(r)&&r.extendNote(this.note),this.noteCursor+=1),r instanceof Oy){const i=r.executeList(e);if(i)return i}else{const i=r.needs(e);if(i)return i;r.execute(e)}this.execCursor+=1}}}Je.DocStatementList=Oy;const dZe="5a79a191-06bc-43cf-9b12-58741cd82970";function kae(t){const e=t.inherits?kae(t.inherits):[];return t.blockNotes&&e.push(...t.blockNotes.map(r=>r.text)),t.notes&&e.push(...t.notes.map(r=>r.text)),e}function hZe(t){const e=kae(t).join("");return(0,lZe.v5)(e,dZe)}class h$ extends ba{constructor(e){super(),this.elementType="document",this.globalNameSpace=new aZe.GlobalNameSpace,this.documentModel={},this.queryList=[],this.didInitModel=!1,this.annotation={},this.experiments=new iZe.Tag({}),this.modelAnnotationTodoList=[],this.dialectNameSpaces=new Map,this.statements=new Oy(e),this.has({statements:e})}initModelDef(e){if(!this.didInitModel){if(this.documentModel={},this.queryList=[],e){e.annotation&&(this.annotation.inherits=e.annotation);for(const[r,i]of Object.entries(e.contents)){const s=structuredClone(i);if((0,W4.isSourceDef)(s)||s.type==="query"||s.type==="function"){const o=e.exports.includes(r);this.setEntry(r,{entry:s,exported:o})}}}this.didInitModel=!0}}compile(){const e=this.statements.executeList(this),r=this.modelDef();if(e===void 0)for(const s of this.queryList)s.modelAnnotation===void 0&&r.annotation&&(s.modelAnnotation=r.annotation);if(r.annotation)for(const s of this.modelAnnotationTodoList)s.modelAnnotation||(s.modelAnnotation=r.annotation);return{modelDef:{...r,queryList:this.queryList},needs:e}}rememberToAddModelAnnotations(e){this.modelAnnotationTodoList.push(e)}hasAnnotation(){return this.annotation.notes&&this.annotation.notes.length>0||this.annotation.inherits!==void 0}currentModelAnnotation(){if(this.hasAnnotation()){const e={...this.annotation,id:""};return e.id=hZe(e),e}}modelDef(){const e={name:"",exports:[],contents:{},queryList:[],dependencies:{}};this.hasAnnotation()&&(e.annotation=this.currentModelAnnotation());for(const r in this.documentModel){const i=this.documentModel[r].entry;if((0,W4.isSourceDef)(i)||i.type==="query"){this.documentModel[r].exported&&e.exports.push(r);const s=structuredClone(i);s.modelAnnotation===void 0&&e.annotation&&(s.modelAnnotation=e.annotation),e.contents[r]=s}}return e}getEntry(e){var r;return(r=this.globalNameSpace.getEntry(e))!==null&&r!==void 0?r:this.documentModel[e]}setEntry(e,r){this.globalNameSpace.getEntry(e)!==void 0&&this.logError("name-conflict-with-global",`Cannot redefine '${e}', which is in global namespace`),(0,W4.isSourceDef)(r.entry)&&this.checkExperimentalDialect(this,r.entry.dialect),this.documentModel[e]=r}checkExperimentalDialect(e,r){const i=this.translator();i&&i.firstReferenceToDialect(r)&&(0,Lae.getDialect)(r).experimental&&!i.experimentalDialectEnabled(r)&&e.logError("experimental-dialect-not-enabled",{dialect:r})}getDialectNamespace(e){if(this.dialectNameSpaces.has(e))return this.dialectNameSpaces.get(e);const r=(0,Lae.getDialect)(e),i=new uZe.DialectNameSpace(r);return this.dialectNameSpaces.set(e,i),i}}Je.Document=h$;var V4={},Jp={},Zt={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.atomicDef=t.inspect=t.typeEq=t.typeIn=t.eq=t.any=t.anyAtomicT=t.aggregateBoolT=t.viewT=t.errorT=t.boolT=t.timestampT=t.dateT=t.stringT=t.numberT=t.nullT=void 0;const e=Pi,r=lt;function i(f,x="scalar",h="constant"){return{type:f,expressionType:x,evalSpace:h,compositeFieldUsage:(0,r.emptyCompositeFieldUsage)()}}t.nullT=i("null"),t.numberT=i("number"),t.stringT=i("string"),t.dateT=i("date"),t.timestampT=i("timestamp"),t.boolT=i("boolean"),t.errorT=i("error"),t.viewT=i("turtle"),t.aggregateBoolT=i("boolean","aggregate"),t.anyAtomicT=[t.numberT,t.stringT,t.dateT,t.timestampT,t.boolT];function s(f,x){return f?x.find(p=>o(p,f))!==void 0:!1}t.any=s;function o(f,x){return x!==void 0&&e.TD.eq(f,x)&&f.expressionType===x.expressionType}t.eq=o;function u(f,x){return f?x.find(p=>a(p,f))!==void 0:!1}t.typeIn=u;function a(f,x,h=!1,p=!0){const m=e.TD.eq(f,x),g=h&&(f.type==="null"||x.type==="null"),y=p&&(f.type==="error"||x.type==="error");return m||g||y}t.typeEq=a;function l(...f){return f.map(h=>{if(h){let p=h.type;return(0,e.expressionIsScalar)(h.expressionType)||(p=`${h.expressionType} ${p}`),p}return"undefined"}).join(",")}t.inspect=l;function c(f){if(e.TD.isAtomic(f))switch(f.type){case"array":return(0,e.isRepeatedRecord)(f)?{type:"array",elementTypeDef:f.elementTypeDef,fields:f.fields}:{type:"array",elementTypeDef:f.elementTypeDef};case"record":return{type:"record",fields:f.fields};case"number":return f.numberType?{type:"number",numberType:f.numberType}:{type:"number"};case"sql native":return f.rawType?{type:"sql native",rawType:f.rawType}:{type:"sql native"};default:return{type:f.type}}return{type:"error"}}t.atomicDef=c})(Zt);var Mr={},Rc={};Object.defineProperty(Rc,"__esModule",{value:!0}),Rc.canMakeEntry=Rc.SpaceEntry=void 0;class pZe{}Rc.SpaceEntry=pZe;function mZe(t){return"makeEntry"in t}Rc.canMakeEntry=mZe,Object.defineProperty(Mr,"__esModule",{value:!0}),Mr.SpaceField=void 0;const gZe=Rc,yZe=lt;class EZe extends gZe.SpaceEntry{constructor(){super(...arguments),this.refType="field"}fieldTypeFromFieldDef(e){var r,i,s;const o=e.expressionType||"scalar";return{...e,expressionType:o,evalSpace:"input",compositeFieldUsage:(r=e.compositeFieldUsage)!==null&&r!==void 0?r:((i=e.e)===null||i===void 0?void 0:i.node)==="compositeField"?{fields:[(s=e.as)!==null&&s!==void 0?s:e.name],joinedUsage:{}}:(0,yZe.emptyCompositeFieldUsage)()}}getQueryFieldDef(e){}fieldDef(){}constructorFieldDef(){}}Mr.SpaceField=EZe;var AZe=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),_Ze=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),vZe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&AZe(e,t,r);return _Ze(e,t),e};Object.defineProperty(Jp,"__esModule",{value:!0}),Jp.ViewField=void 0;const CZe=lt,SZe=vZe(Zt),bZe=Mr;class TZe extends bZe.SpaceField{constructor(e){super(),this.inSpace=e}typeDesc(){var e;const r=this.fieldDef();return{...SZe.viewT,compositeFieldUsage:(e=r.compositeFieldUsage)!==null&&e!==void 0?e:(0,CZe.emptyCompositeFieldUsage)()}}}Jp.ViewField=TZe,Object.defineProperty(V4,"__esModule",{value:!0}),V4.ASTViewField=void 0;const RZe=Jp;class DZe extends RZe.ViewField{constructor(e,r,i){super(e),this.view=r,this.name=i,this.turtleDef=void 0}getQueryFieldDef(e){return this.view.getFieldDef(e)}fieldDef(){return this.turtleDef===void 0&&(this.turtleDef=this.view.getFieldDef(this.inSpace)),this.turtleDef}}V4.ASTViewField=DZe,Object.defineProperty(Dy,"__esModule",{value:!0}),Dy.ViewFieldDeclaration=void 0;const OZe=Je,FZe=kr,wZe=Vp,NZe=V4;class LZe extends OZe.MalloyElement{constructor(e,r){super({view:r}),this.name=e,this.view=r,this.elementType="view-field-declaration",this.isNoteableObj=!0,this.extendNote=FZe.extendNoteMethod}makeEntry(e){const r=new NZe.ASTViewField(e,this,this.name);e.newEntry(this.name,this,r)}getName(){return this.name}getFieldDef(e){const{pipeline:r,annotation:i}=this.view.pipelineComp(e),s=(0,wZe.detectAndRemovePartialStages)(r,this);return{type:"turtle",name:this.name,pipeline:s,annotation:{...this.note,inherits:i},location:this.location}}}Dy.ViewFieldDeclaration=LZe;var jn={};Object.defineProperty(jn,"__esModule",{value:!0}),jn.LegalRefinementStage=jn.QueryClass=void 0;var Mae;(function(t){t.Index="index",t.Project="project",t.Grouping="grouping"})(Mae||(jn.QueryClass=Mae={}));var Pae;(function(t){t[t.Single=0]="Single",t[t.Head=1]="Head",t[t.Tail=2]="Tail"})(Pae||(jn.LegalRefinementStage=Pae={}));var IZe=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),BZe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),$Ze=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&IZe(e,t,r);return BZe(e,t),e};Object.defineProperty(Ry,"__esModule",{value:!0}),Ry.NestFieldDeclaration=void 0;const kZe=$Ze(Xe),MZe=Vp,PZe=Dy,Uae=jn;class UZe extends PZe.ViewFieldDeclaration{constructor(){super(...arguments),this.elementType="nest-field-declaration",this.queryRefinementStage=Uae.LegalRefinementStage.Single,this.forceQueryClass=Uae.QueryClass.Grouping,this.turtleDef=void 0}queryExecute(e){e.resultFS.pushFields(this)}getFieldDef(e){if(this.turtleDef)return this.turtleDef;if(e.isQueryFieldSpace()){const{pipeline:r,annotation:i}=this.view.pipelineComp(e,e.outputSpace()),s=r[0]&&kZe.isQuerySegment(r[0])?r[0].compositeFieldUsage:void 0,o=(0,MZe.detectAndRemovePartialStages)(r,this);return this.turtleDef={type:"turtle",name:this.name,pipeline:o,annotation:{...this.note,inherits:i},location:this.location,compositeFieldUsage:s},this.turtleDef}throw this.internalError("Unexpected namespace for nest")}}Ry.NestFieldDeclaration=UZe;var Xp={},ai={};Object.defineProperty(ai,"__esModule",{value:!0}),ai.ErrorFactory=void 0;const jae="~malformed~";class p${static get structDef(){return{type:"table",name:jae,dialect:"~malformed~",connection:"~unknown~",tablePath:"//undefined_error_table_path",fields:[],errorFactory:!0}}static get joinDef(){return{type:"table",name:jae,dialect:"~malformed~",connection:"~unknown~",tablePath:"//undefined_error_table_path",fields:[],join:"one",matrixOperation:"left",errorFactory:!0}}static didCreate(e){return e.type==="table"&&"errorFactory"in e}static get query(){return{structRef:p$.structDef,pipeline:[]}}static get reduceSegment(){return{type:"reduce",queryFields:[]}}static get projectSegment(){return{type:"project",queryFields:[]}}static get indexSegment(){return{type:"index",indexFields:[]}}}ai.ErrorFactory=p$,Object.defineProperty(Xp,"__esModule",{value:!0}),Xp.DefineSourceList=Xp.DefineSource=void 0;const jZe=ai,qae=Je,qZe=kr;class HZe extends qae.MalloyElement{constructor(e,r,i,s){super(),this.name=e,this.sourceExpr=r,this.exported=i,this.parameters=s,this.elementType="defineSource",this.isNoteableObj=!0,this.extendNote=qZe.extendNoteMethod,r&&this.has({sourceExpr:r}),s&&this.has({parameters:s})}execute(e){var r;if(e.modelEntry(this.name))this.logError("source-definition-name-conflict",`Cannot redefine '${this.name}'`);else{const i=(r=this.sourceExpr)===null||r===void 0?void 0:r.getSource();if(i===void 0)return;const s=this.deduplicatedParameters(),o=i.withParameters(void 0,this.parameters);if(this.validateParameterShadowing(s,o),jZe.ErrorFactory.didCreate(o))return;const u={...o,as:this.name,location:this.location};this.note&&(u.annotation=o.annotation?{...this.note,inherits:o.annotation}:this.note),e.setEntry(this.name,{entry:u,exported:this.exported})}}deduplicatedParameters(){if(this.parameters===void 0)return[];const e={},r=[];for(const i of this.parameters)i.name in e&&i.logError("parameter-name-conflict",`Cannot redefine parameter \`${i.name}\``),e[i.name]=!0,r.push(i);return r}validateParameterShadowing(e,r){for(const i of e)r.fields.find(s=>{var o;return((o=s.as)!==null&&o!==void 0?o:s.name)===i.name})&&i.logError("parameter-shadowing-field",`Illegal shadowing of field \`${i.name}\` by parameter with the same name`)}}Xp.DefineSource=HZe;class QZe extends qae.DocStatementList{constructor(e){super(e),this.elementType="defineSources"}}Xp.DefineSourceList=QZe;var Zp={};Object.defineProperty(Zp,"__esModule",{value:!0}),Zp.DefineQueryList=Zp.DefineQuery=void 0;const Hae=Je,zZe=kr;class GZe extends Hae.MalloyElement{constructor(e,r){super({queryExpr:r}),this.name=e,this.queryExpr=r,this.elementType="defineQuery",this.isNoteableObj=!0,this.extendNote=zZe.extendNoteMethod}execute(e){if(e.getEntry(this.name)){this.logError("query-definition-name-conflict",`'${this.name}' is already defined, cannot redefine`);return}const i=this.queryExpr.getQuery();if(!i){this.queryExpr.sqLog("query-definition-from-non-query","Cannot define a query from this expression");return}const s={...i.query(),type:"query",name:this.name,location:this.location};this.note&&(s.annotation=s.annotation?{...this.note,inherits:s.annotation}:this.note),e.setEntry(this.name,{entry:s,exported:!0})}}Zp.DefineQuery=GZe;class WZe extends Hae.DocStatementList{constructor(e){super(e),this.elementType="defineQueries"}}Zp.DefineQueryList=WZe;var Eo={};Object.defineProperty(Eo,"__esModule",{value:!0}),Eo.Source=void 0;const VZe=Je;class YZe extends VZe.MalloyElement{structRef(e){return{structRef:this.getSourceDef(e)}}packParameters(e){if(e===void 0)return;const r={};for(const i of e){const s=i.parameter();r[s.name]=s}return r}withParameters(e,r){return{...this.getSourceDef(e),parameters:this.packParameters(r)}}}Eo.Source=YZe;var Fy={},e2={},Y4={},Dc={};Object.defineProperty(Dc,"__esModule",{value:!0}),Dc.mergeFields=Dc.nameFromDef=void 0;function m$(t){var e;return t.type==="fieldref"?t.path[t.path.length-1]:(e=t.as)!==null&&e!==void 0?e:t.name}Dc.nameFromDef=m$;function KZe(t,e){if(t===void 0)return e;const r=new Set(e.map(s=>m$(s))),i=t.filter(s=>!r.has(m$(s)));return i.push(...e),i}Dc.mergeFields=KZe;var wy={},Pr={},Ta={},JZe=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),XZe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),ZZe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&JZe(e,t,r);return XZe(e,t),e};Object.defineProperty(Ta,"__esModule",{value:!0}),Ta.DefinedParameter=Ta.AbstractParameter=Ta.SpaceParam=void 0;const eet=Rc,Qae=ZZe(Zt),zae=lt;class g$ extends eet.SpaceEntry{constructor(){super(...arguments),this.refType="parameter"}}Ta.SpaceParam=g$;class tet extends g${constructor(e){super(),this.astParam=e,this._parameter=void 0}parameter(){return this._parameter!==void 0?this._parameter:(this._parameter=this.astParam.parameter(),this._parameter)}typeDesc(){const e=this.parameter(),r=e.type;return{...r==="filter expression"?{type:r}:Qae.atomicDef(e),expressionType:"scalar",evalSpace:"constant",compositeFieldUsage:(0,zae.emptyCompositeFieldUsage)()}}}Ta.AbstractParameter=tet;class net extends g${constructor(e){super(),this.paramDef=e}parameter(){return this.paramDef}typeDesc(){const e=this.parameter(),r=e.type;return{...r==="filter expression"?{type:r}:Qae.atomicDef(e),expressionType:"scalar",evalSpace:"input",compositeFieldUsage:(0,zae.emptyCompositeFieldUsage)()}}}Ta.DefinedParameter=net;var Xx={},ret=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),iet=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),set=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&ret(e,t,r);return iet(e,t),e};Object.defineProperty(Xx,"__esModule",{value:!0}),Xx.StructSpaceFieldBase=void 0;const Gae=lt,oet=Xe,uet=set(Zt),aet=Mr;class cet extends aet.SpaceField{constructor(e){super(),this.structDef=e}fieldDef(){return this.structDef}get joinPathElement(){return{name:this.structDef.as||this.structDef.name,joinType:this.structDef.join,joinElementType:this.structDef.type}}typeDesc(){var e,r;return(0,oet.isSourceDef)(this.structDef)?{type:this.structDef.type,evalSpace:"input",expressionType:"scalar",compositeFieldUsage:(e=this.structDef.onCompositeFieldUsage)!==null&&e!==void 0?e:(0,Gae.emptyCompositeFieldUsage)()}:{...uet.atomicDef(this.structDef),evalSpace:"input",expressionType:"scalar",compositeFieldUsage:(r=this.structDef.onCompositeFieldUsage)!==null&&r!==void 0?r:(0,Gae.emptyCompositeFieldUsage)()}}}Xx.StructSpaceFieldBase=cet;var Ny={};Object.defineProperty(Ny,"__esModule",{value:!0}),Ny.ColumnSpaceField=void 0;const fet=Mr;class xet extends fet.SpaceField{constructor(e){super(),this.sourceFieldDef=e}fieldDef(){return this.sourceFieldDef}typeDesc(){return this.fieldTypeFromFieldDef(this.sourceFieldDef)}constructorFieldDef(){return this.sourceFieldDef}}Ny.ColumnSpaceField=xet;var K4={};Object.defineProperty(K4,"__esModule",{value:!0}),K4.IRViewField=void 0;const det=Jp;class het extends det.ViewField{constructor(e,r){super(e),this.turtleDef=r}rename(e){this.turtleDef={...this.turtleDef,as:e}}fieldDef(){return this.turtleDef}constructorFieldDef(){return this.turtleDef}getQueryFieldDef(e){return this.fieldDef()}}K4.IRViewField=het,Object.defineProperty(Pr,"__esModule",{value:!0}),Pr.StaticSourceSpace=Pr.StructSpaceField=Pr.StaticSpace=void 0;const pet=va,t2=Xe,met=Ta,get=Mr,Ly=Xx,yet=Ny,Eet=K4;class y${constructor(e,r){this.type="fieldSpace",this.fromStruct=e,this.structDialect=r}dialectName(){return this.structDialect}dialectObj(){try{return(0,pet.getDialect)(this.structDialect)}catch{return}}defToSpaceField(e){return(0,t2.isJoined)(e)?new E$(e,this.structDialect):(0,t2.isTurtle)(e)?new Eet.IRViewField(this,e):new yet.ColumnSpaceField(e)}get map(){if(this.memoMap===void 0){this.memoMap={};for(const e of this.fromStruct.fields){const r=e.as||e.name;this.memoMap[r]=this.defToSpaceField(e)}if((0,t2.isSourceDef)(this.fromStruct)&&this.fromStruct.parameters)for(const[e,r]of Object.entries(this.fromStruct.parameters))e in this.memoMap||(this.memoMap[e]=new met.DefinedParameter(r))}return this.memoMap}isProtectedAccessSpace(){return!1}dropEntries(){this.memoMap={}}dropEntry(e){delete this.map[e]}entry(e){return this.map[e]}setEntry(e,r){this.map[e]=r}entries(){return Object.entries(this.map)}structDef(){return this.fromStruct}emptyStructDef(){const e={...this.fromStruct};return(0,t2.isSourceDef)(e)&&(e.parameters={}),e.fields=[],e}lookup(e){const r=e[0],i=e.slice(1);let s=this.entry(r.refString);if(!s)return{error:{message:`'${r}' is not defined`,code:"field-not-found"},found:s};if(s instanceof get.SpaceField){const u=s.fieldDef();if(u&&(!(s instanceof Ly.StructSpaceFieldBase)&&(0,t2.isJoined)(u)&&(s=new E$(u,this.structDialect)),r.addReference({type:s instanceof Ly.StructSpaceFieldBase?"joinReference":"fieldReference",definition:u,location:r.location,text:r.refString})),u!=null&&u.accessModifier&&!(this.isProtectedAccessSpace()&&u.accessModifier==="internal"&&e.length===1))return{error:{message:`'${r}' is ${u==null?void 0:u.accessModifier}`,code:"field-not-accessible"},found:void 0}}const o=s instanceof Ly.StructSpaceFieldBase?[{...s.joinPathElement,name:r.refString}]:[];if(i.length){if(s instanceof Ly.StructSpaceFieldBase){const u=s.fieldSpace.lookup(i);return u.found?{...u,joinPath:[...o,...u.joinPath]}:u}return{error:{message:`'${r}' cannot contain a '${i[0]}'`,code:"invalid-property-access-in-field-reference"},found:void 0}}return{found:s,error:void 0,joinPath:o,isOutputField:!1}}isQueryFieldSpace(){return!1}}Pr.StaticSpace=y$;class E$ extends Ly.StructSpaceFieldBase{constructor(e,r){super(e),this.forDialect=r}get fieldSpace(){return(0,t2.isSourceDef)(this.structDef)?new Wae(this.structDef):new y$(this.structDef,this.forDialect)}}Pr.StructSpaceField=E$;class Wae extends y${constructor(e){super(e,e.dialect),this.source=e}structDef(){return this.source}emptyStructDef(){const e={...this.source};return e.parameters={},e.fields=[],e}}Pr.StaticSourceSpace=Wae,Object.defineProperty(wy,"__esModule",{value:!0}),wy.JoinSpaceField=void 0;const Aet=Pr;class _et extends Aet.StructSpaceField{constructor(e,r,i){super(r.getStructDef(e),i),this.parameterSpace=e,this.join=r}}wy.JoinSpaceField=_et;var n2={};Object.defineProperty(n2,"__esModule",{value:!0}),n2.ParameterSpace=void 0;const vet=Ta;class Cet{constructor(e){this.type="fieldSpace",this._map={};for(const r of e)this._map[r.name]=new vet.AbstractParameter(r)}structDef(){throw new Error("Parameter space does not have a structDef")}emptyStructDef(){throw new Error("Parameter space does not have an emptyStructDef")}entry(e){return this._map[e]}lookup(e){const r=e[0];if(r===void 0)return{error:{message:"Invalid reference",code:"invalid-parameter-reference"},found:void 0};const i=this.entry(r.refString);return i===void 0?{error:{message:`\`${r}\` is not defined`,code:"parameter-not-found"},found:void 0}:e.length>1?{error:{message:`\`${r}\` cannot contain a \`${e.slice(1).join(".")}\``,code:"invalid-parameter-reference"},found:void 0}:{found:i,error:void 0,joinPath:[],isOutputField:!1}}entries(){return Object.entries(this._map)}dialectName(){return"~parameter-space-unknown-dialect~"}dialectObj(){}isQueryFieldSpace(){return!1}isProtectedAccessSpace(){return!1}}n2.ParameterSpace=Cet;var bet=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Tet=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Ret=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&bet(e,t,r);return Tet(e,t),e};Object.defineProperty(Y4,"__esModule",{value:!0}),Y4.DynamicSpace=void 0;const Det=Ret(Xe),Oet=Dc,Fet=ai,wet=Mr,Net=wy,Let=Jp,Vae=Ta,Iet=Pr,Bet=Xx,$et=n2;class ket extends Iet.StaticSpace{constructor(e){super(structuredClone(e),e.dialect),this.complete=!1,this.parameters=[],this.newAccessModifiers=new Map,this.newNotes=new Map,this.fromSource=e,this.sourceDef=void 0}setEntry(e,r){if(this.complete)throw new Error("Space already final");super.setEntry(e,r)}addParameters(e){for(const r of e)this.entry(r.name)===void 0&&(this.parameters.push(r),this.setEntry(r.name,new Vae.AbstractParameter(r)));return this}parameterSpace(){return new $et.ParameterSpace(this.parameters)}newEntry(e,r,i){if(this.entry(e)){r.logError("definition-name-conflict",`Cannot redefine '${e}'`);return}this.setEntry(e,i)}renameEntry(e,r,i){this.dropEntry(e),this.setEntry(r,i)}addFieldDef(e){this.setEntry((0,Oet.nameFromDef)(e),this.defToSpaceField(e))}setTimezone(e){this.newTimezone=e}structDef(){if(this.complete=!0,this.sourceDef===void 0){const e={};for(const[l,c]of this.entries())c instanceof Vae.SpaceParam&&(e[l]=c.parameter());this.sourceDef={...this.fromSource,fields:[]},this.sourceDef.parameters=e;const r=new Map,i=[],s=[],o=[];for(const[l,c]of this.entries())c instanceof Bet.StructSpaceFieldBase?s.push([l,c]):c instanceof Let.ViewField?o.push([l,c]):c instanceof wet.SpaceField&&i.push([l,c]);const u=[...i,...s,...o],a=this.parameterSpace();for(const[l,c]of u)if(c instanceof Net.JoinSpaceField){const f=c.join.getStructDef(a);Fet.ErrorFactory.didCreate(f)||(r.set(l,this.sourceDef.fields.length),this.sourceDef.fields.push(f),c.join.fixupJoinOn(this,f))}else{const f=c.fieldDef();f&&(r.set(l,this.sourceDef.fields.length),this.sourceDef.fields.push(f))}for(const[l,c]of this.newAccessModifiers){const f=this.sourceDef.fields.findIndex(x=>{var h;return(h=x.as)!==null&&h!==void 0?h:x.name===l});if(f===-1)throw new Error(`Can't find field '${l}' to set access modifier`);c==="public"?delete this.sourceDef.fields[f].accessModifier:this.sourceDef.fields[f]={...this.sourceDef.fields[f],accessModifier:c}}for(const[l,c]of this.newNotes){const f=this.sourceDef.fields.findIndex(h=>{var p;return(p=h.as)!==null&&p!==void 0?p:h.name===l});if(f===-1)throw new Error(`Can't find field '${l}' to set access modifier`);const x=this.sourceDef.fields[f];this.sourceDef.fields[f]={...x,annotation:{...c,inherits:x.annotation}}}}return this.newTimezone&&Det.isSourceDef(this.sourceDef)&&(this.sourceDef.queryTimezone=this.newTimezone),this.sourceDef}emptyStructDef(){const e={...this.fromSource};return e.fields=[],e}}Y4.DynamicSpace=ket;var Iy={};Object.defineProperty(Iy,"__esModule",{value:!0}),Iy.RenameSpaceField=void 0;const Met=Mr;class Pet extends Met.SpaceField{constructor(e,r,i){super(),this.otherField=e,this.newName=r,this.location=i}fieldDef(){const e=this.otherField.fieldDef();if(e!==void 0)return{...e,as:this.newName,location:this.location}}typeDesc(){return this.otherField.typeDesc()}}Iy.RenameSpaceField=Pet,Object.defineProperty(e2,"__esModule",{value:!0}),e2.RefinedSpace=void 0;const Uet=Y4,jet=Rc,qet=Iy,Het=Mr;class A$ extends Uet.DynamicSpace{static filteredFrom(e,r,i,s,o){const u=new A$(e),a=new Map;for(const l of s??[])a.has(l.name.refString)?l.name.logError("already-renamed",`${l.name.refString} already renamed to ${l.as}`):a.set(l.name.refString,{as:l.as,location:l.location,logTo:l.name});if(i!==void 0){const l=u.entries();u.dropEntries();for(const[c,f]of l)if(i.has(c)){const x=a.get(c);x?f instanceof Het.SpaceField?u.setEntry(x.as,new qet.RenameSpaceField(f,x.as,x.location)):x.logTo.logError("cannot-rename-non-field",`Cannot rename \`${c}\` which is not a field`):u.setEntry(c,f)}r!==void 0&&r.logError("accept-except-not-compatible-with-include","Can't use `accept:` or `except:` with `include`")}else if(r){const l=r.refs.list,c=u.entries();for(const f of l)c.find(([h])=>h===f.refString)===void 0&&(o!=null&&o.entry(f.refString)?f.logError(`${r.edit}-parameter`,`Illegal \`${r.edit}:\` of parameter`):f.logError("field-list-edit-not-found",`\`${f.refString}\` is not defined`));u.dropEntries();for(const[f,x]of c){const h=!!l.find(m=>m.refString===f),p=r.edit==="accept";h===p&&u.setEntry(f,x)}}return u}pushFields(...e){for(const r of e)this.addField(r)}addField(e){(0,jet.canMakeEntry)(e)?e.makeEntry(this):e.logError("unexpected-element-type",`Internal error, ${e.elementType} not expected in this context`)}addAccessModifiers(e){for(const[r,i]of e)this.newAccessModifiers.set(r,i)}addNotes(e){for(const[r,i]of e)this.newNotes.set(r,i)}isProtectedAccessSpace(){return!0}}e2.RefinedSpace=A$;var Oc={},$s={};Object.defineProperty($s,"__esModule",{value:!0}),$s.DefinitionList=void 0;const Qet=Je,Yae=kr;class zet extends Qet.ListOf{constructor(){super(...arguments),this.isNoteableObj=!0}extendNote(e){(0,Yae.extendNoteHelper)(this,e),this.distributeAnnotation()}distributeAnnotation(){if(this.note)for(const e of this.elements)(0,Yae.isNoteable)(e)&&e.extendNote(this.note)}newContents(){super.newContents(),this.distributeAnnotation()}}$s.DefinitionList=zet,Object.defineProperty(Oc,"__esModule",{value:!0}),Oc.DeclareFields=void 0;const Get=$s,Wet=jn;class Vet extends Get.DefinitionList{constructor(e,r){super(e),this.accessModifier=r,this.elementType="declareFields",this.queryRefinementStage=Wet.LegalRefinementStage.Single,this.forceQueryClass=void 0}queryExecute(e){for(const r of this.list)e.inputFS.extendSource(r)}get delarationNames(){return this.list.map(e=>e.defineName)}}Oc.DeclareFields=Vet;var Ra={};Object.defineProperty(Ra,"__esModule",{value:!0}),Ra.Filter=Ra.FilterElement=void 0;const Kae=Xe,Yet=Vn,Jae=Je,_$=jn;class Ket extends Jae.MalloyElement{constructor(e,r){super({expr:e}),this.expr=e,this.exprSrc=r,this.elementType="filterElement"}filterCondition(e){const r=this.expr.getExpression(e);return r.type!=="boolean"?(this.expr.logError("non-boolean-filter","Filter expression must have boolean value"),{node:"filterCondition",code:this.exprSrc,e:{node:"false"},expressionType:"scalar",compositeFieldUsage:r.compositeFieldUsage}):{node:"filterCondition",code:this.exprSrc,e:r.value,expressionType:r.expressionType,compositeFieldUsage:r.compositeFieldUsage}}}Ra.FilterElement=Ket;class Jet extends Jae.ListOf{constructor(){super(...arguments),this.elementType="filter",this.forceQueryClass=void 0,this.queryRefinementStage=_$.LegalRefinementStage.Head}set having(e){this.elementType=e?"having":"where",this.havingClause=e,this.queryRefinementStage=e?_$.LegalRefinementStage.Tail:_$.LegalRefinementStage.Head}checkedFilterCondition(e,r){const i=r.filterCondition(e);if(this.havingClause!==void 0){const s=(0,Kae.expressionIsAggregate)(i.expressionType),o=(0,Kae.expressionIsAnalytic)(i.expressionType);if(this.havingClause){if(o){r.logError("analytic-in-having","Analytic expressions are not allowed in `having:`");return}}else if(o){r.logError("analytic-in-where","Analytic expressions are not allowed in `where:`");return}else s&&r.logError("aggregate-in-where","Aggregate expressions are not allowed in `where:`; use `having:`")}return i}getFilterList(e){return this.list.map(r=>this.checkedFilterCondition(e,r)).filter(Yet.isNotUndefined)}queryExecute(e){const r=this.havingClause?e.resultFS:e.inputFS;for(const i of this.list){const s=this.checkedFilterCondition(r,i);s!==void 0&&(e.filters.push(s),e.resultFS.addCompositeFieldUserFromFilter(s,i))}}}Ra.Filter=Jet;var r2={};Object.defineProperty(r2,"__esModule",{value:!0}),r2.FieldListEdit=void 0;const Xet=Je;class Zet extends Xet.MalloyElement{constructor(e,r){super({refs:r}),this.edit=e,this.refs=r,this.elementType="fieldListEdit"}}r2.FieldListEdit=Zet;var i2={};Object.defineProperty(i2,"__esModule",{value:!0}),i2.PrimaryKey=void 0;const ett=Je;class ttt extends ett.MalloyElement{constructor(e){super({field:e}),this.field=e,this.elementType="primary key"}}i2.PrimaryKey=ttt;var s2={};Object.defineProperty(s2,"__esModule",{value:!0}),s2.Views=void 0;const ntt=$s;class rtt extends ntt.DefinitionList{constructor(e,r){super(e),this.accessModifier=r,this.elementType="turtleDefList"}get delarationNames(){return this.list.map(e=>e.name)}}s2.Views=rtt;var o2={};Object.defineProperty(o2,"__esModule",{value:!0}),o2.TimezoneStatement=void 0;const itt=Je,stt=by;class ott extends itt.MalloyElement{constructor(e){super(),this.tz=e,this.elementType="timezone",this.forceQueryClass=void 0,this.queryRefinementStage=void 0}get isValid(){try{return stt.DateTime.fromISO("2020-02-19T00:00:00",{zone:this.tz}),!0}catch{return!1}}queryExecute(e){e.resultFS.setTimezone(this.tz)}}o2.TimezoneStatement=ott;var Fc={};Object.defineProperty(Fc,"__esModule",{value:!0}),Fc.ModelAnnotation=Fc.ObjectAnnotation=void 0;const utt=Je,att=ui;class Xae extends utt.MalloyElement{constructor(e){super(),this.notes=e,this.elementType="annotation",this.forceQueryClass=void 0,this.queryRefinementStage=void 0}queryExecute(){}}Fc.ObjectAnnotation=Xae;class ltt extends Xae{constructor(){super(...arguments),this.elementType="modelAnnotation"}getCompilerFlags(e,r){const i=(0,att.annotationToTag)({notes:this.notes},{prefix:/^##! /,extending:e});return i.log.forEach(s=>r.log(s)),i.tag}execute(e){e.annotation.notes===void 0&&(e.annotation.notes=[]),e.annotation.notes.push(...this.notes)}}Fc.ModelAnnotation=ltt;var wc={};Object.defineProperty(wc,"__esModule",{value:!0}),wc.Renames=wc.RenameField=void 0;const ctt=Iy,Zae=Je,ftt=Mr;class xtt extends Zae.MalloyElement{constructor(e,r){super(),this.newName=e,this.oldName=r,this.elementType="renameField",this.has({oldName:r})}makeEntry(e){if(this.oldName.refString===this.newName){this.logError("invalid-rename-with-same-name","Can't rename field to itself");return}const r=this.oldName.getField(e);r.found?r.found instanceof ftt.SpaceField?e.renameEntry(this.oldName.refString,this.newName,new ctt.RenameSpaceField(r.found,this.newName,this.location)):this.logError("failed-rename",`'${this.oldName}' cannot be renamed`):this.logError("rename-field-not-found",`Can't rename '${this.oldName}', no such field`)}getName(){return this.newName}}wc.RenameField=xtt;class dtt extends Zae.ListOf{constructor(e,r){super(e),this.accessModifier=r,this.elementType="renameFields"}get delarationNames(){return this.list.map(e=>e.getName())}}wc.Renames=dtt;var xs={};Object.defineProperty(xs,"__esModule",{value:!0}),xs.JoinStatement=xs.ExpressionJoin=xs.KeyJoin=xs.Join=void 0;const v$=Xe,htt=wy,ptt=$s,mtt=Je,gtt=kr,ele=ai,ytt=jn;class C$ extends mtt.MalloyElement{constructor(){super(...arguments),this.isNoteableObj=!0,this.extendNote=gtt.extendNoteMethod}makeEntry(e){e.newEntry(this.name.refString,this,new htt.JoinSpaceField(e.parameterSpace(),this,e.dialectName()))}getName(){return this.name.refString}getStructDefFromExpr(e){const r=this.sourceExpr.getSource();return r?r.getSourceDef(e):(this.sourceExpr.sqLog("invalid-join-source","Cannot create a source to join from"),ele.ErrorFactory.structDef)}}xs.Join=C$;class Ett extends C${constructor(e,r,i){super({name:e,sourceExpr:r,keyExpr:i}),this.name=e,this.sourceExpr=r,this.keyExpr=i,this.elementType="joinOnKey"}getStructDef(e){var r;const i=this.getStructDefFromExpr(e);if(!(0,v$.isJoinable)(i))throw this.internalError(`Cannot join struct type '${i.type}'`);const s={...i,name:this.name.refString,join:"one",matrixOperation:"left",onExpression:{node:"error",message:"('join fixup'='not done yet')"},location:this.location};return delete s.as,this.note&&(s.annotation=this.note),(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(s),s}fixupJoinOn(e,r){const i=this.keyExpr.getExpression(e);if((0,v$.isSourceDef)(r)&&r.primaryKey){const s=r.fields.find(o=>(o.as||o.name)===r.primaryKey);if(s)if(s.type===i.type){r.join="one",r.onExpression={node:"=",kids:{left:{node:"field",path:[this.name.refString,r.primaryKey]},right:i.value}},r.onCompositeFieldUsage=i.compositeFieldUsage;return}else this.logError("join-on-primary-key-type-mismatch",`join_one: with type mismatch with primary key: ${i.type}/${s.type}`);else this.logError("join-primary-key-not-found",`join_one: Primary key '${s}' not found in source`)}else this.logError("join-with-without-primary-key","join_one: Cannot use with unless source has a primary key")}}xs.KeyJoin=Ett;class Att extends C${constructor(e,r){super({name:e,sourceExpr:r}),this.name=e,this.sourceExpr=r,this.elementType="joinOnExpr",this.joinType="one",this.matrixOperation="left"}set joinOn(e){this.expr=e,this.has({on:e})}get joinOn(){return this.expr}fixupJoinOn(e,r){if(this.expr===void 0)return;const i=this.expr.getExpression(e);if(i.type!=="boolean"){this.logError("non-boolean-join-on","join conditions must be boolean expressions");return}r.onExpression=i.value,r.onCompositeFieldUsage=i.compositeFieldUsage}getStructDef(e){var r;const i=this.sourceExpr.getSource();if(!i)return this.sourceExpr.sqLog("invalid-join-source","Cannot create a source to join from"),ele.ErrorFactory.joinDef;const s=i.getSourceDef(e);let o="left";if(this.inExperiment("join_types",!0)&&(o=this.matrixOperation),!(0,v$.isJoinable)(s))throw this.internalError(`Can't join struct type ${s.type}`);const u={...s,name:this.name.refString,join:this.joinType,matrixOperation:o,location:this.location};return delete u.as,this.note&&(u.annotation=this.note),(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(u),u}}xs.ExpressionJoin=Att;class _tt extends ptt.DefinitionList{constructor(e,r){super(e),this.accessModifier=r,this.elementType="joinStatement",this.forceQueryClass=void 0,this.queryRefinementStage=ytt.LegalRefinementStage.Single}queryExecute(e){for(const r of this.list)e.inputFS.extendSource(r),e.alwaysJoins.push(r.name.refString)}get delarationNames(){return this.list.map(e=>e.name.refString)}}xs.JoinStatement=_tt;var du={};Object.defineProperty(du,"__esModule",{value:!0}),du.IncludeListItem=du.IncludeExceptItem=du.IncludeAccessItem=du.IncludeItem=void 0;const tle=Je,nle=kr;class S$ extends tle.MalloyElement{}du.IncludeItem=S$;class vtt extends S${constructor(e,r){super(),this.kind=e,this.fields=r,this.elementType="include-access-item",this.isNoteableObj=!0,this.extendNote=nle.extendNoteMethod,this.has({fields:r})}}du.IncludeAccessItem=vtt;class Ctt extends S${constructor(e){super(),this.fields=e,this.elementType="include-except-item",this.kind="except",this.has({fields:e})}}du.IncludeExceptItem=Ctt;class Stt extends tle.MalloyElement{constructor(e,r){super({name:e}),this.name=e,this.as=r,this.elementType="include-list-item",this.isNoteableObj=!0,this.extendNote=nle.extendNoteMethod}}du.IncludeListItem=Stt;var yt={},By={},btt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Ttt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Rtt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&btt(e,t,r);return Ttt(e,t),e};Object.defineProperty(By,"__esModule",{value:!0}),By.ReferenceField=void 0;const rle=Xe,ile=Rtt(Zt),sle=Mr,Dtt=lt;class Ott extends sle.SpaceField{constructor(e,r){super(),this.fieldRef=e,this.inFS=r,this.didLookup=!1}get referenceTo(){return this.didLookup||(this.memoReference=this.inFS.lookup(this.fieldRef.list).found,this.didLookup=!0),this.memoReference}getQueryFieldDef(e){if(!this.queryFieldDef){const r=this.fieldRef.getField(e);r.error&&this.fieldRef.logError(r.error.code,r.error.message);const i=this.fieldRef.path;if(r.found&&r.found.refType==="parameter"){const o=r.found.typeDesc();if(rle.TD.isAtomic(o))this.queryFieldDef={...(0,rle.mkFieldDef)(ile.atomicDef(o),i[0]),e:{node:"parameter",path:i}};else throw new Error("impossible turtle/join parameter")}else this.queryFieldDef={type:"fieldref",path:i};const s=this.referenceTo;if(s instanceof sle.SpaceField){const o=s.constructorFieldDef();if(o){const u=this.fieldRef.note;if(o.annotation||u){const a=u||{};o.annotation&&(a.inherits=o.annotation),this.queryFieldDef.annotation=a}}}}return this.queryFieldDef}typeDesc(){if(this.memoTypeDesc)return this.memoTypeDesc;const e=this.referenceTo;if(e){const r=this.fieldRef.list.slice(0,-1).map(s=>s.refString),i=e.typeDesc();return this.memoTypeDesc={...i,compositeFieldUsage:(0,Dtt.joinedCompositeFieldUsage)(r,i.compositeFieldUsage)},this.memoTypeDesc}return ile.errorT}}By.ReferenceField=Ott;var sr={};Object.defineProperty(sr,"__esModule",{value:!0}),sr.typecheckGroupBy=sr.typecheckAggregate=sr.typecheckCalculate=sr.typecheckDeclare=sr.typecheckMeasure=sr.typecheckDimension=sr.typecheckIndex=sr.typecheckProject=void 0;const In=Pi;function Ftt(t,e){if(t.type==="turtle"||!(0,In.expressionIsScalar)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="select-of-view";else if((0,In.expressionIsAnalytic)(t.expressionType))r="a calculate",i="an analytic",s="select-of-analytic";else if((0,In.expressionIsAggregate)(t.expressionType))r="an aggregate",i="an aggregate",s="select-of-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(s,`Cannot use ${i} field in a select operation, did you mean to use ${r} operation instead?`)}}sr.typecheckProject=Ftt;function wtt(t,e){if(t.type==="turtle"||!(0,In.expressionIsScalar)(t.expressionType)){let r,i;if(t.type==="turtle")r="a view",i="index-of-view";else if((0,In.expressionIsAnalytic)(t.expressionType))r="an analytic",i="index-of-analytic";else if((0,In.expressionIsAggregate)(t.expressionType))r="an aggregate",i="index-of-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(i,`Cannot use ${r} field in an index operation`)}}sr.typecheckIndex=wtt;function Ntt(t,e){if(!(0,In.expressionIsScalar)(t.expressionType))if((0,In.expressionIsAggregate)(t.expressionType))e.logError("aggregate-in-dimension","Cannot use an aggregate field in a dimension declaration, did you mean to use a measure declaration instead?");else if((0,In.expressionIsAnalytic)(t.expressionType))e.logError("analytic-in-dimension","Cannot use an analytic field in a dimension declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}sr.typecheckDimension=Ntt;function Ltt(t,e){if(!(0,In.expressionIsAggregate)(t.expressionType))if((0,In.expressionIsScalar)(t.expressionType))e.logError("scalar-in-measure","Cannot use a scalar field in a measure declaration, did you mean to use a dimension declaration instead?");else if((0,In.expressionIsAnalytic)(t.expressionType))e.logError("analytic-in-measure","Cannot use an analytic field in a measure declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}sr.typecheckMeasure=Ltt;function Itt(t,e){t.type==="turtle"?e.logError("view-in-declare","Views cannot be used in a declare block"):(0,In.expressionIsAnalytic)(t.expressionType)&&e.logError("analytic-in-declare","Analytic expressions can not be used in a declare block")}sr.typecheckDeclare=Itt;function Btt(t,e){if(t.type==="turtle"||!(0,In.expressionIsAnalytic)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="calculate-of-view";else if((0,In.expressionIsAggregate)(t.expressionType))r="an aggregate",i="an aggregate",s="calculate-of-aggregate";else if((0,In.expressionIsScalar)(t.expressionType))r="a group_by or select",i="a scalar",s="calculate-of-scalar";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(s,`Cannot use ${i} field in a calculate operation, did you mean to use ${r} operation instead?`)}}sr.typecheckCalculate=Btt;function $tt(t,e){if(t.type==="turtle"||!(0,In.expressionIsAggregate)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="aggregate-of-view";else if((0,In.expressionIsAnalytic)(t.expressionType))r="a calculate",i="an analytic",s="aggregate-of-analytic";else if((0,In.expressionIsScalar)(t.expressionType))r="a group_by or select",i="a scalar",s="aggregate-of-scalar";else throw new Error(`Unexpected expression type ${t} not handled here`);e.logError(s,`Cannot use ${i} field in an aggregate operation, did you mean to use ${r} operation instead?`)}}sr.typecheckAggregate=$tt;function ktt(t,e){if(t.type==="turtle"||!(0,In.expressionIsScalar)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="group-by-view";else if((0,In.expressionIsAnalytic)(t.expressionType))r="a calculate",i="an analytic",s="group-by-analytic";else if((0,In.expressionIsAggregate)(t.expressionType))r="an aggregate",i="an aggregate",s="group-by-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(s,`Cannot use ${i} field in a group_by operation, did you mean to use ${r} operation instead?`)}}sr.typecheckGroupBy=ktt,Object.defineProperty(yt,"__esModule",{value:!0}),yt.FieldReferences=yt.WildcardFieldReference=yt.ViewOrScalarFieldReference=yt.DimensionFieldReference=yt.MeasureFieldReference=yt.DeclareFieldReference=yt.ProjectFieldReference=yt.GroupByFieldReference=yt.AggregateFieldReference=yt.IndexFieldReference=yt.CalculateFieldReference=yt.ParameterFieldReference=yt.PartitionByFieldReference=yt.ExpressionFieldReference=yt.AccessModifierFieldReference=yt.AcceptExceptFieldReference=yt.FieldReference=void 0;const Mtt=By,Ptt=$s,ole=Je,ule=kr,Nc=sr;class ji extends ole.ListOf{constructor(e){super(e),this.isNoteableObj=!0,this.extendNote=ule.extendNoteMethod}makeEntry(e){const r=this.outputName;if(e.entry(r))this.logError("output-name-conflict",`Output already has a field named '${r}'`);else{const i=e.isQueryFieldSpace()?e.inputSpace():e;e.newEntry(r,this,new Mtt.ReferenceField(this,i))}}getName(){return this.nameString}get refToField(){return{type:"fieldref",path:this.list.map(e=>e.refString)}}get refString(){return this.path.join(".")}get path(){return this.list.map(e=>e.refString)}get outputName(){return this.list[this.list.length-1].refString}get sourceString(){if(this.list.length>1)return this.list.slice(0,-1).map(e=>e.refString).join(".")}get nameString(){return this.list[this.list.length-1].refString}getField(e){const r=e.lookup(this.list);if(r.found){const i=r.found.typeDesc();this.typecheck(i)}return r}}yt.FieldReference=ji;class Utt extends ji{constructor(){super(...arguments),this.elementType="acceptExceptFieldReference"}typecheck(){}}yt.AcceptExceptFieldReference=Utt;class jtt extends ji{constructor(){super(...arguments),this.elementType="accessModifierFieldReference"}typecheck(){}}yt.AccessModifierFieldReference=jtt;class qtt extends ji{constructor(){super(...arguments),this.elementType="expressionFieldReference"}typecheck(){}}yt.ExpressionFieldReference=qtt;class Htt extends ji{constructor(){super(...arguments),this.elementType="partitionByFieldReference"}typecheck(){}}yt.PartitionByFieldReference=Htt;class Qtt extends ji{constructor(){super(...arguments),this.elementType="parameterFieldReference"}typecheck(){}}yt.ParameterFieldReference=Qtt;class ztt extends ji{constructor(){super(...arguments),this.elementType="calculateFieldReference"}typecheck(e){(0,Nc.typecheckCalculate)(e,this)}}yt.CalculateFieldReference=ztt;class b$ extends ji{constructor(){super(...arguments),this.elementType="indexFieldReference"}typecheck(e){(0,Nc.typecheckIndex)(e,this)}static indexOutputName(e){return e.map(r=>encodeURIComponent(r)).join("/")}get outputName(){return b$.indexOutputName(this.path)}}yt.IndexFieldReference=b$;class Gtt extends ji{constructor(){super(...arguments),this.elementType="aggregateFieldReference"}typecheck(e){(0,Nc.typecheckAggregate)(e,this)}}yt.AggregateFieldReference=Gtt;class Wtt extends ji{constructor(){super(...arguments),this.elementType="groupByFieldReference"}typecheck(e){(0,Nc.typecheckGroupBy)(e,this)}}yt.GroupByFieldReference=Wtt;class Vtt extends ji{constructor(){super(...arguments),this.elementType="projectFieldReference"}typecheck(e){(0,Nc.typecheckProject)(e,this)}}yt.ProjectFieldReference=Vtt;class Ytt extends ji{constructor(){super(...arguments),this.elementType="declareFieldReference"}typecheck(e){(0,Nc.typecheckDeclare)(e,this)}}yt.DeclareFieldReference=Ytt;class Ktt extends ji{constructor(){super(...arguments),this.elementType="measureFieldReference"}typecheck(e){(0,Nc.typecheckMeasure)(e,this)}}yt.MeasureFieldReference=Ktt;class Jtt extends ji{constructor(){super(...arguments),this.elementType="dimensionFieldReference"}typecheck(e){(0,Nc.typecheckDimension)(e,this)}}yt.DimensionFieldReference=Jtt;class Xtt extends ji{constructor(){super(...arguments),this.elementType="viewOrScalarFieldReference"}typecheck(e){}}yt.ViewOrScalarFieldReference=Xtt;class Ztt extends ole.MalloyElement{constructor(e){super(),this.joinPath=e,this.elementType="wildcardFieldReference",this.isNoteableObj=!0,this.extendNote=ule.extendNoteMethod,this.except=new Set,this.has({joinPath:e})}getFieldDef(){throw this.internalError("fielddef request from wildcard reference")}get refString(){return this.joinPath?`${this.joinPath.refString}.*`:"*"}}yt.WildcardFieldReference=Ztt;class ent extends Ptt.DefinitionList{constructor(e){super(e),this.elementType="fieldReferenceList"}}yt.FieldReferences=ent,Object.defineProperty(Fy,"__esModule",{value:!0}),Fy.RefinedSource=void 0;const tnt=Xe,nnt=e2,rnt=Oc,int=Ra,snt=r2,ont=i2,unt=s2,ant=Eo,lnt=o2,cnt=Fc,fnt=wc,xnt=n2,dnt=xs,ale=du,T$=yt;class hnt extends ant.Source{constructor(e,r,i){super({source:e,refinement:r}),this.source=e,this.refinement=r,this.includeList=i,this.elementType="refinedSource",i&&this.has({includeList:i})}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,r){var i;let s,o;const u=[],a=[];let l;const c=[];for(const v of this.refinement.list){if(v instanceof cnt.ObjectAnnotation)continue;const C=v;if(v instanceof ont.PrimaryKey){if(s){const b="multiple-primary-keys";s.logError(b,"Primary key already defined"),v.logError(b,"Primary key redefined")}s=v}else if(v instanceof snt.FieldListEdit){if(o){const b="multiple-field-list-edits";o.logError(b,"Too many accept/except statements"),v.logError(b,"Too many accept/except statements")}o=v}else v instanceof rnt.DeclareFields||v instanceof dnt.JoinStatement||v instanceof unt.Views||v instanceof fnt.Renames?(u.push(...v.list),v.accessModifier&&c.push({fields:v.delarationNames,access:v.accessModifier})):v instanceof int.Filter?a.push(v):v instanceof lnt.TimezoneStatement?l=v.tz:C.logError("unexpected-source-property",`Unexpected source property: '${C.elementType}'`)}const f=r?new xnt.ParameterSpace(r):void 0,x=structuredClone(this.source.getSourceDef(f)),{fieldsToInclude:h,modifiers:p,renames:m,notes:g}=pnt(this.includeList,x);for(const v of c)for(const C of v.fields)p.set(C,v.access);s&&(x.primaryKey=s.field.name);const y=nnt.RefinedSpace.filteredFrom(x,o,h,m,f);if(l&&y.setTimezone(l),r&&y.addParameters(r),y.pushFields(...u),s){const v=s.field.getField(y);v.error&&s.logError(v.error.code,v.error.message)}y.addAccessModifiers(p),y.addNotes(g);const E=y.structDef(),A=E.filterList||[];let _=!1;for(const v of a)for(const C of v.list){const b=C.filterCondition(y);(0,tnt.expressionIsCalculation)(b.expressionType)?C.logError("aggregate-in-source-filter","Can't use aggregate computations in top level filters"):(A.push(b),_=!0)}return _?{...E,filterList:A}:((i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(E),E)}}Fy.RefinedSource=hnt;function pnt(t,e){var r,i,s,o,u,a,l,c,f;const x=new Set(e.fields.map(b=>b.name)),h=new Set(e.fields.filter(b=>b.accessModifier==="private").map(b=>b.name));let p;const m=new Set;let g,y;const E=new Map,A=[],_=new Map;if(t===void 0)return{fieldsToInclude:void 0,modifiers:E,renames:A,notes:_};for(const b of t)if(b instanceof ale.IncludeAccessItem)for(const S of b.fields)if(S.name instanceof T$.WildcardFieldReference)S.name.joinPath&&S.logError("unsupported-path-in-include","Wildcards with paths are not supported in `include` blocks"),g!==void 0?b.logError("already-used-star-in-include","Wildcard already used in this include block"):(g=(r=b.kind)!==null&&r!==void 0?r:"inherit",y={notes:(s=(i=S.note)===null||i===void 0?void 0:i.notes)!==null&&s!==void 0?s:[],blockNotes:(u=(o=b.note)===null||o===void 0?void 0:o.blockNotes)!==null&&u!==void 0?u:[]});else{if(p==="exclude"){b.logError("include-after-exclude","Cannot include specific fields if specific fields are already excluded");continue}p="include";const R=S.name.refString;h.has(R)&&S.logError("cannot-expand-access",`Cannot expand access of \`${R}\` from private to ${b.kind}`),E.has(R)?S.logError("duplicate-include",`Field \`${R}\` already referenced in include list`):(b.kind!==void 0&&E.set(R,b.kind),m.add(R),(S.note||b.note)&&_.set(R,{notes:(l=(a=S.note)===null||a===void 0?void 0:a.notes)!==null&&l!==void 0?l:[],blockNotes:(f=(c=b.note)===null||c===void 0?void 0:c.blockNotes)!==null&&f!==void 0?f:[]})),S.as&&(S.name instanceof T$.WildcardFieldReference?S.logError("wildcard-include-rename","Cannot rename a wildcard field in an `include` block"):A.push({name:S.name,as:S.as,location:S.location}))}else if(b instanceof ale.IncludeExceptItem)for(const S of b.fields)S instanceof T$.WildcardFieldReference?S.joinPath?S.logError("unsupported-path-in-include","Wildcards with paths are not supported in `include` blocks"):S.logWarning("wildcard-except-redundant","`except: *` is implied, unless another clause uses *"):p==="include"?b.logError("exclude-after-include","Cannot exclude specific fields if specific fields are already included"):(p="exclude",g="inherit",m.add(S.refString));const v=new Set(x);m.forEach(b=>v.delete(b)),h.forEach(b=>v.delete(b));let C;if(g!==void 0)for(const b of v)g!=="inherit"&&E.set(b,g),y&&_.set(b,{...y});return p!=="exclude"?g!==void 0?C=x:C=m:C=v,{fieldsToInclude:C,modifiers:E,renames:A,notes:_}}var hu={};Object.defineProperty(hu,"__esModule",{value:!0}),hu.SourceQueryElement=void 0;const mnt=Je;class R$ extends mnt.MalloyElement{constructor(){super(...arguments),this.errored=!1}getSource(){}getQuery(){}isSource(){return!1}sqLog(e,r,i){return this.isErrorFree()&&this.logError(e,r,i),this.errored=!0,e}isErrorFree(){if(this.errored)return!1;let e=!0;for(const r of this.walk())if(r instanceof R$&&r.errored){e=!1;break}return e}}hu.SourceQueryElement=R$;var J4={},Zx={};Object.defineProperty(Zx,"__esModule",{value:!0}),Zx.QuerySource=void 0;const gnt=Eo,ynt=Pp;class Ent extends gnt.Source{constructor(e){super({query:e}),this.query=e,this.elementType="querySource"}getSourceDef(e){return this.withParameters(e,void 0)}withParameters(e,r){var i;const s=this.query.queryComp(!1),o={...s.outputStruct,name:`QuerySource-${(0,ynt.v4)()}`,type:"query_source",query:s.query};return(i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(o),{...o,parameters:this.packParameters(r)}}}Zx.QuerySource=Ent;var u2={},$y={};Object.defineProperty($y,"__esModule",{value:!0}),$y.QueryBase=void 0;const D$=lt,lle=Xe,Ant=Vp,_nt=Je;class vnt extends _nt.MalloyElement{resolveCompositeSource(e,r){var i;const s=r.pipeline[0];if(s&&((0,lle.isQuerySegment)(s)||(0,lle.isIndexSegment)(s))){const o=(i=s.compositeFieldUsage)!==null&&i!==void 0?i:(0,D$.emptyCompositeFieldUsage)();if(!(0,D$.isEmptyCompositeFieldUsage)(o)||e.type==="composite")return(0,D$.resolveCompositeSources)(e,o).sourceDef}}query(){const{query:e}=this.queryComp(!0);return{...e,pipeline:(0,Ant.detectAndRemovePartialStages)(e.pipeline,this)}}}$y.QueryBase=vnt,Object.defineProperty(u2,"__esModule",{value:!0}),u2.QueryArrow=void 0;const Cnt=Xe,Snt=Eo,cle=Pr,bnt=$y;class Tnt extends bnt.QueryBase{constructor(e,r){super({source:e,view:r}),this.source=e,this.view=r,this.elementType="arrow"}queryComp(e){var r;let i,s,o;if(this.source instanceof Snt.Source){const h=e?this.source.structRef(void 0):{structRef:this.source.getSourceDef(void 0)};s={type:"query",...h,pipeline:[],location:this.location},i=(0,Cnt.refIsStructDef)(h.structRef)?h.structRef:this.source.getSourceDef(void 0),o=new cle.StaticSourceSpace(i)}else{const h=this.source.queryComp(e);s=h.query,i=h.outputStruct,o=new cle.StaticSourceSpace(h.outputStruct)}const{pipeline:u,annotation:a,outputStruct:l,name:c}=this.view.pipelineComp(o),f={...s,name:c,annotation:a,pipeline:[...s.pipeline,...u]},x=(r=f.compositeResolvedSourceDef)!==null&&r!==void 0?r:this.resolveCompositeSource(i,f);return{query:{...f,compositeResolvedSourceDef:x},outputStruct:l,inputStruct:i}}}u2.QueryArrow=Tnt,Object.defineProperty(J4,"__esModule",{value:!0}),J4.SQArrow=void 0;const Rnt=hu,Dnt=Zx,Ont=u2;class Fnt extends Rnt.SourceQueryElement{constructor(e,r){super({applyTo:e,operation:r}),this.applyTo=e,this.operation=r,this.elementType="sq-arrow"}getQuery(){const e=this.applyTo.isSource()?this.applyTo.getSource():this.applyTo.getQuery();if(e===void 0){this.sqLog("failed-to-compute-arrow-source","Could not get LHS of arrow operation");return}const r=new Ont.QueryArrow(e,this.operation);return this.has({query:r}),r}getSource(){const e=this.getQuery();if(!e){this.sqLog("failed-to-compute-source-from-query","Couldn't comprehend query well enough to make a source");return}const r=new Dnt.QuerySource(e);return this.has({asSource:r}),r}}J4.SQArrow=Fnt;var X4={},a2={},ks={};Object.defineProperty(ks,"__esModule",{value:!0}),ks.getStructFieldDef=ks.getFinalStruct=ks.opOutputStruct=void 0;const fle=lc,wnt=Ls,Z4=Xe,xle=ai;function dle(t,e,r){const i=xle.ErrorFactory.didCreate(e)||(0,Z4.structHasErrors)(e);(0,Z4.isPartialSegment)(r)&&(r={...r,type:"reduce"});const s=(0,Z4.segmentHasErrors)(r);if(!i&&!s)try{const o=wnt.Segment.nextStructDef(e,r);if((0,Z4.isSourceDef)(o))return o;t.logError("failed-to-compute-output-schema",`INTERNAL ERROR model/Segment.nextStructDef: RETURNED A NON SOURCE
1157
+ ${i} `),s+="]")}return s}*walk(){for(const e of Object.keys(this.children)){const r=this.children[e];if(r instanceof ba)yield r;else for(const i of r)yield i}}varInfo(){let e="";for(const[r,i]of Object.entries(this))r!=="elementType"&&(typeof i=="boolean"?e+=i?` ${r}`:` !${r}`:(typeof i=="string"||typeof i=="number")&&(e+=` ${r}=${i}`));return e}internalError(e){return new Error(`INTERNAL ERROR IN TRANSLATION: ${e}`)}needs(e){for(const r of this.walk()){const i=r.needs(e);if(i)return i}}inExperiment(e,r=!1){var i;const s=(i=this.translator())===null||i===void 0?void 0:i.compilerFlags.tag("experimental");return s&&(s.bare()||s.has(e))?!0:(r||this.logError("experiment-not-enabled",{experimentId:e}),!1)}}Je.MalloyElement=ba;class xZe extends ba{constructor(){super(...arguments),this.elementType="unimplemented",this.reported=!1}}Je.Unimplemented=xZe;class d$ extends ba{constructor(e){super(),this.name=e,this.elementType="modelEntryReference"}get refString(){return this.name}toString(){return this.refString}getNamed(){var e;return(e=this.modelEntry(this))===null||e===void 0?void 0:e.entry}}Je.ModelEntryReference=d$;class dZe extends ba{constructor(e){super(),this.id=e,this.elementType="experimentalExperiment"}execute(e){this.inExperiment(this.id)}}Je.ExperimentalExperiment=dZe;function Bae(t){return t.execute!==void 0}Je.isDocStatement=Bae;function hZe(t){return t instanceof Oy||Bae(t)}Je.isDocStatementOrDocStatementList=hZe;class $ae extends ba{constructor(e){super(),this.elements=e,this.newContents()}newContents(){this.has({listOf:this.elements})}get list(){return this.elements}empty(){return this.elements.length===0}notEmpty(){return this.elements.length>0}push(...e){return this.elements.push(...e),this.newContents(),this.elements}needs(e){for(const r of this.elements){const i=r.needs(e);if(i)return i}}}Je.ListOf=$ae;class Oy extends $ae{constructor(){super(...arguments),this.elementType="topLevelStatements",this.execCursor=0,this.isNoteableObj=!0,this.extendNote=Iae.extendNoteMethod,this.noteCursor=0}executeList(e){for(;this.execCursor<this.elements.length;){const r=this.elements[this.execCursor];if(this.noteCursor===this.execCursor&&(this.note&&(0,Iae.isNoteable)(r)&&r.extendNote(this.note),this.noteCursor+=1),r instanceof Oy){const i=r.executeList(e);if(i)return i}else{const i=r.needs(e);if(i)return i;r.execute(e)}this.execCursor+=1}}}Je.DocStatementList=Oy;const pZe="5a79a191-06bc-43cf-9b12-58741cd82970";function kae(t){const e=t.inherits?kae(t.inherits):[];return t.blockNotes&&e.push(...t.blockNotes.map(r=>r.text)),t.notes&&e.push(...t.notes.map(r=>r.text)),e}function mZe(t){const e=kae(t).join("");return(0,fZe.v5)(e,pZe)}class h$ extends ba{constructor(e){super(),this.elementType="document",this.globalNameSpace=new cZe.GlobalNameSpace,this.documentModel={},this.queryList=[],this.didInitModel=!1,this.annotation={},this.experiments=new oZe.Tag({}),this.modelAnnotationTodoList=[],this.dialectNameSpaces=new Map,this.statements=new Oy(e),this.has({statements:e})}initModelDef(e){if(!this.didInitModel){if(this.documentModel={},this.queryList=[],e){e.annotation&&(this.annotation.inherits=e.annotation);for(const[r,i]of Object.entries(e.contents)){const s=structuredClone(i);if((0,W4.isSourceDef)(s)||s.type==="query"||s.type==="function"){const o=e.exports.includes(r);this.setEntry(r,{entry:s,exported:o})}}}this.didInitModel=!0}}compile(){const e=this.statements.executeList(this),r=this.modelDef();if(e===void 0)for(const s of this.queryList)s.modelAnnotation===void 0&&r.annotation&&(s.modelAnnotation=r.annotation);if(r.annotation)for(const s of this.modelAnnotationTodoList)s.modelAnnotation||(s.modelAnnotation=r.annotation);return{modelDef:{...r,queryList:this.queryList},needs:e}}rememberToAddModelAnnotations(e){this.modelAnnotationTodoList.push(e)}hasAnnotation(){return this.annotation.notes&&this.annotation.notes.length>0||this.annotation.inherits!==void 0}currentModelAnnotation(){if(this.hasAnnotation()){const e={...this.annotation,id:""};return e.id=mZe(e),e}}modelDef(){const e={name:"",exports:[],contents:{},queryList:[],dependencies:{}};this.hasAnnotation()&&(e.annotation=this.currentModelAnnotation());for(const r in this.documentModel){const i=this.documentModel[r].entry;if((0,W4.isSourceDef)(i)||i.type==="query"){this.documentModel[r].exported&&e.exports.push(r);const s=structuredClone(i);s.modelAnnotation===void 0&&e.annotation&&(s.modelAnnotation=e.annotation),e.contents[r]=s}}return e}getEntry(e){var r;return(r=this.globalNameSpace.getEntry(e))!==null&&r!==void 0?r:this.documentModel[e]}setEntry(e,r){this.globalNameSpace.getEntry(e)!==void 0&&this.logError("name-conflict-with-global",`Cannot redefine '${e}', which is in global namespace`),(0,W4.isSourceDef)(r.entry)&&this.checkExperimentalDialect(this,r.entry.dialect),this.documentModel[e]=r}checkExperimentalDialect(e,r){const i=this.translator();i&&i.firstReferenceToDialect(r)&&(0,Lae.getDialect)(r).experimental&&!i.experimentalDialectEnabled(r)&&e.logError("experimental-dialect-not-enabled",{dialect:r})}getDialectNamespace(e){if(this.dialectNameSpaces.has(e))return this.dialectNameSpaces.get(e);const r=(0,Lae.getDialect)(e),i=new lZe.DialectNameSpace(r);return this.dialectNameSpaces.set(e,i),i}}Je.Document=h$;var V4={},Jp={},Zt={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.atomicDef=t.inspect=t.typeEq=t.typeIn=t.eq=t.any=t.anyAtomicT=t.aggregateBoolT=t.viewT=t.errorT=t.boolT=t.timestampT=t.dateT=t.stringT=t.numberT=t.nullT=void 0;const e=Pi,r=lt;function i(f,x="scalar",h="constant"){return{type:f,expressionType:x,evalSpace:h,compositeFieldUsage:(0,r.emptyCompositeFieldUsage)()}}t.nullT=i("null"),t.numberT=i("number"),t.stringT=i("string"),t.dateT=i("date"),t.timestampT=i("timestamp"),t.boolT=i("boolean"),t.errorT=i("error"),t.viewT=i("turtle"),t.aggregateBoolT=i("boolean","aggregate"),t.anyAtomicT=[t.numberT,t.stringT,t.dateT,t.timestampT,t.boolT];function s(f,x){return f?x.find(p=>o(p,f))!==void 0:!1}t.any=s;function o(f,x){return x!==void 0&&e.TD.eq(f,x)&&f.expressionType===x.expressionType}t.eq=o;function u(f,x){return f?x.find(p=>a(p,f))!==void 0:!1}t.typeIn=u;function a(f,x,h=!1,p=!0){const m=e.TD.eq(f,x),g=h&&(f.type==="null"||x.type==="null"),y=p&&(f.type==="error"||x.type==="error");return m||g||y}t.typeEq=a;function l(...f){return f.map(h=>{if(h){let p=h.type;return(0,e.expressionIsScalar)(h.expressionType)||(p=`${h.expressionType} ${p}`),p}return"undefined"}).join(",")}t.inspect=l;function c(f){if(e.TD.isAtomic(f))switch(f.type){case"array":return(0,e.isRepeatedRecord)(f)?{type:"array",elementTypeDef:f.elementTypeDef,fields:f.fields}:{type:"array",elementTypeDef:f.elementTypeDef};case"record":return{type:"record",fields:f.fields};case"number":return f.numberType?{type:"number",numberType:f.numberType}:{type:"number"};case"sql native":return f.rawType?{type:"sql native",rawType:f.rawType}:{type:"sql native"};default:return{type:f.type}}return{type:"error"}}t.atomicDef=c})(Zt);var Mr={},Rc={};Object.defineProperty(Rc,"__esModule",{value:!0}),Rc.canMakeEntry=Rc.SpaceEntry=void 0;class gZe{}Rc.SpaceEntry=gZe;function yZe(t){return"makeEntry"in t}Rc.canMakeEntry=yZe,Object.defineProperty(Mr,"__esModule",{value:!0}),Mr.SpaceField=void 0;const EZe=Rc,AZe=lt;class _Ze extends EZe.SpaceEntry{constructor(){super(...arguments),this.refType="field"}fieldTypeFromFieldDef(e){var r,i,s;const o=e.expressionType||"scalar";return{...e,expressionType:o,evalSpace:"input",compositeFieldUsage:(r=e.compositeFieldUsage)!==null&&r!==void 0?r:((i=e.e)===null||i===void 0?void 0:i.node)==="compositeField"?{fields:[(s=e.as)!==null&&s!==void 0?s:e.name],joinedUsage:{}}:(0,AZe.emptyCompositeFieldUsage)()}}getQueryFieldDef(e){}fieldDef(){}constructorFieldDef(){}}Mr.SpaceField=_Ze;var vZe=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),CZe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),SZe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&vZe(e,t,r);return CZe(e,t),e};Object.defineProperty(Jp,"__esModule",{value:!0}),Jp.ViewField=void 0;const bZe=lt,TZe=SZe(Zt),RZe=Mr;class DZe extends RZe.SpaceField{constructor(e){super(),this.inSpace=e}typeDesc(){var e;const r=this.fieldDef();return{...TZe.viewT,compositeFieldUsage:(e=r.compositeFieldUsage)!==null&&e!==void 0?e:(0,bZe.emptyCompositeFieldUsage)()}}}Jp.ViewField=DZe,Object.defineProperty(V4,"__esModule",{value:!0}),V4.ASTViewField=void 0;const OZe=Jp;class FZe extends OZe.ViewField{constructor(e,r,i){super(e),this.view=r,this.name=i,this.turtleDef=void 0}getQueryFieldDef(e){return this.view.getFieldDef(e)}fieldDef(){return this.turtleDef===void 0&&(this.turtleDef=this.view.getFieldDef(this.inSpace)),this.turtleDef}}V4.ASTViewField=FZe,Object.defineProperty(Dy,"__esModule",{value:!0}),Dy.ViewFieldDeclaration=void 0;const wZe=Je,NZe=kr,LZe=Vp,IZe=V4;class BZe extends wZe.MalloyElement{constructor(e,r){super({view:r}),this.name=e,this.view=r,this.elementType="view-field-declaration",this.isNoteableObj=!0,this.extendNote=NZe.extendNoteMethod}makeEntry(e){const r=new IZe.ASTViewField(e,this,this.name);e.newEntry(this.name,this,r)}getName(){return this.name}getFieldDef(e){const{pipeline:r,annotation:i}=this.view.pipelineComp(e),s=(0,LZe.detectAndRemovePartialStages)(r,this);return{type:"turtle",name:this.name,pipeline:s,annotation:{...this.note,inherits:i},location:this.location}}}Dy.ViewFieldDeclaration=BZe;var jn={};Object.defineProperty(jn,"__esModule",{value:!0}),jn.LegalRefinementStage=jn.QueryClass=void 0;var Mae;(function(t){t.Index="index",t.Project="project",t.Grouping="grouping"})(Mae||(jn.QueryClass=Mae={}));var Pae;(function(t){t[t.Single=0]="Single",t[t.Head=1]="Head",t[t.Tail=2]="Tail"})(Pae||(jn.LegalRefinementStage=Pae={}));var $Ze=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),kZe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),MZe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&$Ze(e,t,r);return kZe(e,t),e};Object.defineProperty(Ry,"__esModule",{value:!0}),Ry.NestFieldDeclaration=void 0;const PZe=MZe(Xe),UZe=Vp,jZe=Dy,Uae=jn;class qZe extends jZe.ViewFieldDeclaration{constructor(){super(...arguments),this.elementType="nest-field-declaration",this.queryRefinementStage=Uae.LegalRefinementStage.Single,this.forceQueryClass=Uae.QueryClass.Grouping,this.turtleDef=void 0}queryExecute(e){e.resultFS.pushFields(this)}getFieldDef(e){if(this.turtleDef)return this.turtleDef;if(e.isQueryFieldSpace()){const{pipeline:r,annotation:i}=this.view.pipelineComp(e,e.outputSpace()),s=r[0]&&PZe.isQuerySegment(r[0])?r[0].compositeFieldUsage:void 0,o=(0,UZe.detectAndRemovePartialStages)(r,this);return this.turtleDef={type:"turtle",name:this.name,pipeline:o,annotation:{...this.note,inherits:i},location:this.location,compositeFieldUsage:s},this.turtleDef}throw this.internalError("Unexpected namespace for nest")}}Ry.NestFieldDeclaration=qZe;var Xp={},ai={};Object.defineProperty(ai,"__esModule",{value:!0}),ai.ErrorFactory=void 0;const jae="~malformed~";class p${static get structDef(){return{type:"table",name:jae,dialect:"~malformed~",connection:"~unknown~",tablePath:"//undefined_error_table_path",fields:[],errorFactory:!0}}static get joinDef(){return{type:"table",name:jae,dialect:"~malformed~",connection:"~unknown~",tablePath:"//undefined_error_table_path",fields:[],join:"one",matrixOperation:"left",errorFactory:!0}}static didCreate(e){return e.type==="table"&&"errorFactory"in e}static get query(){return{structRef:p$.structDef,pipeline:[]}}static get reduceSegment(){return{type:"reduce",queryFields:[]}}static get projectSegment(){return{type:"project",queryFields:[]}}static get indexSegment(){return{type:"index",indexFields:[]}}}ai.ErrorFactory=p$,Object.defineProperty(Xp,"__esModule",{value:!0}),Xp.DefineSourceList=Xp.DefineSource=void 0;const HZe=ai,qae=Je,QZe=kr;class zZe extends qae.MalloyElement{constructor(e,r,i,s){super(),this.name=e,this.sourceExpr=r,this.exported=i,this.parameters=s,this.elementType="defineSource",this.isNoteableObj=!0,this.extendNote=QZe.extendNoteMethod,r&&this.has({sourceExpr:r}),s&&this.has({parameters:s})}execute(e){var r;if(e.modelEntry(this.name))this.logError("source-definition-name-conflict",`Cannot redefine '${this.name}'`);else{const i=(r=this.sourceExpr)===null||r===void 0?void 0:r.getSource();if(i===void 0)return;const s=this.deduplicatedParameters(),o=i.withParameters(void 0,this.parameters);if(this.validateParameterShadowing(s,o),HZe.ErrorFactory.didCreate(o))return;const u={...o,as:this.name,location:this.location};this.note&&(u.annotation=o.annotation?{...this.note,inherits:o.annotation}:this.note),e.setEntry(this.name,{entry:u,exported:this.exported})}}deduplicatedParameters(){if(this.parameters===void 0)return[];const e={},r=[];for(const i of this.parameters)i.name in e&&i.logError("parameter-name-conflict",`Cannot redefine parameter \`${i.name}\``),e[i.name]=!0,r.push(i);return r}validateParameterShadowing(e,r){for(const i of e)r.fields.find(s=>{var o;return((o=s.as)!==null&&o!==void 0?o:s.name)===i.name})&&i.logError("parameter-shadowing-field",`Illegal shadowing of field \`${i.name}\` by parameter with the same name`)}}Xp.DefineSource=zZe;class GZe extends qae.DocStatementList{constructor(e){super(e),this.elementType="defineSources"}}Xp.DefineSourceList=GZe;var Zp={};Object.defineProperty(Zp,"__esModule",{value:!0}),Zp.DefineQueryList=Zp.DefineQuery=void 0;const Hae=Je,WZe=kr;class VZe extends Hae.MalloyElement{constructor(e,r){super({queryExpr:r}),this.name=e,this.queryExpr=r,this.elementType="defineQuery",this.isNoteableObj=!0,this.extendNote=WZe.extendNoteMethod}execute(e){if(e.getEntry(this.name)){this.logError("query-definition-name-conflict",`'${this.name}' is already defined, cannot redefine`);return}const i=this.queryExpr.getQuery();if(!i){this.queryExpr.sqLog("query-definition-from-non-query","Cannot define a query from this expression");return}const s={...i.query(),type:"query",name:this.name,location:this.location};this.note&&(s.annotation=s.annotation?{...this.note,inherits:s.annotation}:this.note),e.setEntry(this.name,{entry:s,exported:!0})}}Zp.DefineQuery=VZe;class YZe extends Hae.DocStatementList{constructor(e){super(e),this.elementType="defineQueries"}}Zp.DefineQueryList=YZe;var Eo={};Object.defineProperty(Eo,"__esModule",{value:!0}),Eo.Source=void 0;const KZe=Je;class JZe extends KZe.MalloyElement{structRef(e){return{structRef:this.getSourceDef(e)}}packParameters(e){if(e===void 0)return;const r={};for(const i of e){const s=i.parameter();r[s.name]=s}return r}withParameters(e,r){return{...this.getSourceDef(e),parameters:this.packParameters(r)}}}Eo.Source=JZe;var Fy={},e2={},Y4={},Dc={};Object.defineProperty(Dc,"__esModule",{value:!0}),Dc.mergeFields=Dc.nameFromDef=void 0;function m$(t){var e;return t.type==="fieldref"?t.path[t.path.length-1]:(e=t.as)!==null&&e!==void 0?e:t.name}Dc.nameFromDef=m$;function XZe(t,e){if(t===void 0)return e;const r=new Set(e.map(s=>m$(s))),i=t.filter(s=>!r.has(m$(s)));return i.push(...e),i}Dc.mergeFields=XZe;var wy={},Pr={},Ta={},ZZe=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),eet=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),tet=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&ZZe(e,t,r);return eet(e,t),e};Object.defineProperty(Ta,"__esModule",{value:!0}),Ta.DefinedParameter=Ta.AbstractParameter=Ta.SpaceParam=void 0;const net=Rc,Qae=tet(Zt),zae=lt;class g$ extends net.SpaceEntry{constructor(){super(...arguments),this.refType="parameter"}}Ta.SpaceParam=g$;class ret extends g${constructor(e){super(),this.astParam=e,this._parameter=void 0}parameter(){return this._parameter!==void 0?this._parameter:(this._parameter=this.astParam.parameter(),this._parameter)}typeDesc(){const e=this.parameter(),r=e.type;return{...r==="filter expression"?{type:r}:Qae.atomicDef(e),expressionType:"scalar",evalSpace:"constant",compositeFieldUsage:(0,zae.emptyCompositeFieldUsage)()}}}Ta.AbstractParameter=ret;class iet extends g${constructor(e){super(),this.paramDef=e}parameter(){return this.paramDef}typeDesc(){const e=this.parameter(),r=e.type;return{...r==="filter expression"?{type:r}:Qae.atomicDef(e),expressionType:"scalar",evalSpace:"input",compositeFieldUsage:(0,zae.emptyCompositeFieldUsage)()}}}Ta.DefinedParameter=iet;var Xx={},set=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),oet=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),uet=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&set(e,t,r);return oet(e,t),e};Object.defineProperty(Xx,"__esModule",{value:!0}),Xx.StructSpaceFieldBase=void 0;const Gae=lt,aet=Xe,cet=uet(Zt),fet=Mr;class xet extends fet.SpaceField{constructor(e){super(),this.structDef=e}fieldDef(){return this.structDef}get joinPathElement(){return{name:this.structDef.as||this.structDef.name,joinType:this.structDef.join,joinElementType:this.structDef.type}}typeDesc(){var e,r;return(0,aet.isSourceDef)(this.structDef)?{type:this.structDef.type,evalSpace:"input",expressionType:"scalar",compositeFieldUsage:(e=this.structDef.onCompositeFieldUsage)!==null&&e!==void 0?e:(0,Gae.emptyCompositeFieldUsage)()}:{...cet.atomicDef(this.structDef),evalSpace:"input",expressionType:"scalar",compositeFieldUsage:(r=this.structDef.onCompositeFieldUsage)!==null&&r!==void 0?r:(0,Gae.emptyCompositeFieldUsage)()}}}Xx.StructSpaceFieldBase=xet;var Ny={};Object.defineProperty(Ny,"__esModule",{value:!0}),Ny.ColumnSpaceField=void 0;const det=Mr;class het extends det.SpaceField{constructor(e){super(),this.sourceFieldDef=e}fieldDef(){return this.sourceFieldDef}typeDesc(){return this.fieldTypeFromFieldDef(this.sourceFieldDef)}constructorFieldDef(){return this.sourceFieldDef}}Ny.ColumnSpaceField=het;var K4={};Object.defineProperty(K4,"__esModule",{value:!0}),K4.IRViewField=void 0;const pet=Jp;class met extends pet.ViewField{constructor(e,r){super(e),this.turtleDef=r}rename(e){this.turtleDef={...this.turtleDef,as:e}}fieldDef(){return this.turtleDef}constructorFieldDef(){return this.turtleDef}getQueryFieldDef(e){return this.fieldDef()}}K4.IRViewField=met,Object.defineProperty(Pr,"__esModule",{value:!0}),Pr.StaticSourceSpace=Pr.StructSpaceField=Pr.StaticSpace=void 0;const get=va,t2=Xe,yet=Ta,Eet=Mr,Ly=Xx,Aet=Ny,_et=K4;class y${constructor(e,r){this.type="fieldSpace",this.fromStruct=e,this.structDialect=r}dialectName(){return this.structDialect}dialectObj(){try{return(0,get.getDialect)(this.structDialect)}catch{return}}defToSpaceField(e){return(0,t2.isJoined)(e)?new E$(e,this.structDialect):(0,t2.isTurtle)(e)?new _et.IRViewField(this,e):new Aet.ColumnSpaceField(e)}get map(){if(this.memoMap===void 0){this.memoMap={};for(const e of this.fromStruct.fields){const r=e.as||e.name;this.memoMap[r]=this.defToSpaceField(e)}if((0,t2.isSourceDef)(this.fromStruct)&&this.fromStruct.parameters)for(const[e,r]of Object.entries(this.fromStruct.parameters))e in this.memoMap||(this.memoMap[e]=new yet.DefinedParameter(r))}return this.memoMap}isProtectedAccessSpace(){return!1}dropEntries(){this.memoMap={}}dropEntry(e){delete this.map[e]}entry(e){return this.map[e]}setEntry(e,r){this.map[e]=r}entries(){return Object.entries(this.map)}structDef(){return this.fromStruct}emptyStructDef(){const e={...this.fromStruct};return(0,t2.isSourceDef)(e)&&(e.parameters={}),e.fields=[],e}lookup(e){const r=e[0],i=e.slice(1);let s=this.entry(r.refString);if(!s)return{error:{message:`'${r}' is not defined`,code:"field-not-found"},found:s};if(s instanceof Eet.SpaceField){const u=s.fieldDef();if(u&&(!(s instanceof Ly.StructSpaceFieldBase)&&(0,t2.isJoined)(u)&&(s=new E$(u,this.structDialect)),r.addReference({type:s instanceof Ly.StructSpaceFieldBase?"joinReference":"fieldReference",definition:u,location:r.location,text:r.refString})),u!=null&&u.accessModifier&&!(this.isProtectedAccessSpace()&&u.accessModifier==="internal"&&e.length===1))return{error:{message:`'${r}' is ${u==null?void 0:u.accessModifier}`,code:"field-not-accessible"},found:void 0}}const o=s instanceof Ly.StructSpaceFieldBase?[{...s.joinPathElement,name:r.refString}]:[];if(i.length){if(s instanceof Ly.StructSpaceFieldBase){const u=s.fieldSpace.lookup(i);return u.found?{...u,joinPath:[...o,...u.joinPath]}:u}return{error:{message:`'${r}' cannot contain a '${i[0]}'`,code:"invalid-property-access-in-field-reference"},found:void 0}}return{found:s,error:void 0,joinPath:o,isOutputField:!1}}isQueryFieldSpace(){return!1}}Pr.StaticSpace=y$;class E$ extends Ly.StructSpaceFieldBase{constructor(e,r){super(e),this.forDialect=r}get fieldSpace(){return(0,t2.isSourceDef)(this.structDef)?new Wae(this.structDef):new y$(this.structDef,this.forDialect)}}Pr.StructSpaceField=E$;class Wae extends y${constructor(e){super(e,e.dialect),this.source=e}structDef(){return this.source}emptyStructDef(){const e={...this.source};return e.parameters={},e.fields=[],e}}Pr.StaticSourceSpace=Wae,Object.defineProperty(wy,"__esModule",{value:!0}),wy.JoinSpaceField=void 0;const vet=Pr;class Cet extends vet.StructSpaceField{constructor(e,r,i){super(r.getStructDef(e),i),this.parameterSpace=e,this.join=r}}wy.JoinSpaceField=Cet;var n2={};Object.defineProperty(n2,"__esModule",{value:!0}),n2.ParameterSpace=void 0;const bet=Ta;class Tet{constructor(e){this.type="fieldSpace",this._map={};for(const r of e)this._map[r.name]=new bet.AbstractParameter(r)}structDef(){throw new Error("Parameter space does not have a structDef")}emptyStructDef(){throw new Error("Parameter space does not have an emptyStructDef")}entry(e){return this._map[e]}lookup(e){const r=e[0];if(r===void 0)return{error:{message:"Invalid reference",code:"invalid-parameter-reference"},found:void 0};const i=this.entry(r.refString);return i===void 0?{error:{message:`\`${r}\` is not defined`,code:"parameter-not-found"},found:void 0}:e.length>1?{error:{message:`\`${r}\` cannot contain a \`${e.slice(1).join(".")}\``,code:"invalid-parameter-reference"},found:void 0}:{found:i,error:void 0,joinPath:[],isOutputField:!1}}entries(){return Object.entries(this._map)}dialectName(){return"~parameter-space-unknown-dialect~"}dialectObj(){}isQueryFieldSpace(){return!1}isProtectedAccessSpace(){return!1}}n2.ParameterSpace=Tet;var Ret=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Det=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Oet=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Ret(e,t,r);return Det(e,t),e};Object.defineProperty(Y4,"__esModule",{value:!0}),Y4.DynamicSpace=void 0;const Fet=Oet(Xe),wet=Dc,Net=ai,Let=Mr,Iet=wy,Bet=Jp,Vae=Ta,$et=Pr,ket=Xx,Met=n2;class Pet extends $et.StaticSpace{constructor(e){super(structuredClone(e),e.dialect),this.complete=!1,this.parameters=[],this.newAccessModifiers=new Map,this.newNotes=new Map,this.fromSource=e,this.sourceDef=void 0}setEntry(e,r){if(this.complete)throw new Error("Space already final");super.setEntry(e,r)}addParameters(e){for(const r of e)this.entry(r.name)===void 0&&(this.parameters.push(r),this.setEntry(r.name,new Vae.AbstractParameter(r)));return this}parameterSpace(){return new Met.ParameterSpace(this.parameters)}newEntry(e,r,i){if(this.entry(e)){r.logError("definition-name-conflict",`Cannot redefine '${e}'`);return}this.setEntry(e,i)}renameEntry(e,r,i){this.dropEntry(e),this.setEntry(r,i)}addFieldDef(e){this.setEntry((0,wet.nameFromDef)(e),this.defToSpaceField(e))}setTimezone(e){this.newTimezone=e}structDef(){if(this.complete=!0,this.sourceDef===void 0){const e={};for(const[l,c]of this.entries())c instanceof Vae.SpaceParam&&(e[l]=c.parameter());this.sourceDef={...this.fromSource,fields:[]},this.sourceDef.parameters=e;const r=new Map,i=[],s=[],o=[];for(const[l,c]of this.entries())c instanceof ket.StructSpaceFieldBase?s.push([l,c]):c instanceof Bet.ViewField?o.push([l,c]):c instanceof Let.SpaceField&&i.push([l,c]);const u=[...i,...s,...o],a=this.parameterSpace();for(const[l,c]of u)if(c instanceof Iet.JoinSpaceField){const f=c.join.getStructDef(a);Net.ErrorFactory.didCreate(f)||(r.set(l,this.sourceDef.fields.length),this.sourceDef.fields.push(f),c.join.fixupJoinOn(this,f))}else{const f=c.fieldDef();f&&(r.set(l,this.sourceDef.fields.length),this.sourceDef.fields.push(f))}for(const[l,c]of this.newAccessModifiers){const f=this.sourceDef.fields.findIndex(x=>{var h;return(h=x.as)!==null&&h!==void 0?h:x.name===l});if(f===-1)throw new Error(`Can't find field '${l}' to set access modifier`);c==="public"?delete this.sourceDef.fields[f].accessModifier:this.sourceDef.fields[f]={...this.sourceDef.fields[f],accessModifier:c}}for(const[l,c]of this.newNotes){const f=this.sourceDef.fields.findIndex(h=>{var p;return(p=h.as)!==null&&p!==void 0?p:h.name===l});if(f===-1)throw new Error(`Can't find field '${l}' to set access modifier`);const x=this.sourceDef.fields[f];this.sourceDef.fields[f]={...x,annotation:{...c,inherits:x.annotation}}}}return this.newTimezone&&Fet.isSourceDef(this.sourceDef)&&(this.sourceDef.queryTimezone=this.newTimezone),this.sourceDef}emptyStructDef(){const e={...this.fromSource};return e.fields=[],e}}Y4.DynamicSpace=Pet;var Iy={};Object.defineProperty(Iy,"__esModule",{value:!0}),Iy.RenameSpaceField=void 0;const Uet=Mr;class jet extends Uet.SpaceField{constructor(e,r,i){super(),this.otherField=e,this.newName=r,this.location=i}fieldDef(){const e=this.otherField.fieldDef();if(e!==void 0)return{...e,as:this.newName,location:this.location}}typeDesc(){return this.otherField.typeDesc()}}Iy.RenameSpaceField=jet,Object.defineProperty(e2,"__esModule",{value:!0}),e2.RefinedSpace=void 0;const qet=Y4,Het=Rc,Qet=Iy,zet=Mr;class A$ extends qet.DynamicSpace{static filteredFrom(e,r,i,s,o){const u=new A$(e),a=new Map;for(const l of s??[])a.has(l.name.refString)?l.name.logError("already-renamed",`${l.name.refString} already renamed to ${l.as}`):a.set(l.name.refString,{as:l.as,location:l.location,logTo:l.name});if(i!==void 0){const l=u.entries();u.dropEntries();for(const[c,f]of l)if(i.has(c)){const x=a.get(c);x?f instanceof zet.SpaceField?u.setEntry(x.as,new Qet.RenameSpaceField(f,x.as,x.location)):x.logTo.logError("cannot-rename-non-field",`Cannot rename \`${c}\` which is not a field`):u.setEntry(c,f)}r!==void 0&&r.logError("accept-except-not-compatible-with-include","Can't use `accept:` or `except:` with `include`")}else if(r){const l=r.refs.list,c=u.entries();for(const f of l)c.find(([h])=>h===f.refString)===void 0&&(o!=null&&o.entry(f.refString)?f.logError(`${r.edit}-parameter`,`Illegal \`${r.edit}:\` of parameter`):f.logError("field-list-edit-not-found",`\`${f.refString}\` is not defined`));u.dropEntries();for(const[f,x]of c){const h=!!l.find(m=>m.refString===f),p=r.edit==="accept";h===p&&u.setEntry(f,x)}}return u}pushFields(...e){for(const r of e)this.addField(r)}addField(e){(0,Het.canMakeEntry)(e)?e.makeEntry(this):e.logError("unexpected-element-type",`Internal error, ${e.elementType} not expected in this context`)}addAccessModifiers(e){for(const[r,i]of e)this.newAccessModifiers.set(r,i)}addNotes(e){for(const[r,i]of e)this.newNotes.set(r,i)}isProtectedAccessSpace(){return!0}}e2.RefinedSpace=A$;var Oc={},$s={};Object.defineProperty($s,"__esModule",{value:!0}),$s.DefinitionList=void 0;const Get=Je,Yae=kr;class Wet extends Get.ListOf{constructor(){super(...arguments),this.isNoteableObj=!0}extendNote(e){(0,Yae.extendNoteHelper)(this,e),this.distributeAnnotation()}distributeAnnotation(){if(this.note)for(const e of this.elements)(0,Yae.isNoteable)(e)&&e.extendNote(this.note)}newContents(){super.newContents(),this.distributeAnnotation()}}$s.DefinitionList=Wet,Object.defineProperty(Oc,"__esModule",{value:!0}),Oc.DeclareFields=void 0;const Vet=$s,Yet=jn;class Ket extends Vet.DefinitionList{constructor(e,r){super(e),this.accessModifier=r,this.elementType="declareFields",this.queryRefinementStage=Yet.LegalRefinementStage.Single,this.forceQueryClass=void 0}queryExecute(e){for(const r of this.list)e.inputFS.extendSource(r)}get delarationNames(){return this.list.map(e=>e.defineName)}}Oc.DeclareFields=Ket;var Ra={};Object.defineProperty(Ra,"__esModule",{value:!0}),Ra.Filter=Ra.FilterElement=void 0;const Kae=Xe,Jet=Vn,Jae=Je,_$=jn;class Xet extends Jae.MalloyElement{constructor(e,r){super({expr:e}),this.expr=e,this.exprSrc=r,this.elementType="filterElement"}filterCondition(e){const r=this.expr.getExpression(e);return r.type!=="boolean"?(this.expr.logError("non-boolean-filter","Filter expression must have boolean value"),{node:"filterCondition",code:this.exprSrc,e:{node:"false"},expressionType:"scalar",compositeFieldUsage:r.compositeFieldUsage}):{node:"filterCondition",code:this.exprSrc,e:r.value,expressionType:r.expressionType,compositeFieldUsage:r.compositeFieldUsage}}}Ra.FilterElement=Xet;class Zet extends Jae.ListOf{constructor(){super(...arguments),this.elementType="filter",this.forceQueryClass=void 0,this.queryRefinementStage=_$.LegalRefinementStage.Head}set having(e){this.elementType=e?"having":"where",this.havingClause=e,this.queryRefinementStage=e?_$.LegalRefinementStage.Tail:_$.LegalRefinementStage.Head}checkedFilterCondition(e,r){const i=r.filterCondition(e);if(this.havingClause!==void 0){const s=(0,Kae.expressionIsAggregate)(i.expressionType),o=(0,Kae.expressionIsAnalytic)(i.expressionType);if(this.havingClause){if(o){r.logError("analytic-in-having","Analytic expressions are not allowed in `having:`");return}}else if(o){r.logError("analytic-in-where","Analytic expressions are not allowed in `where:`");return}else s&&r.logError("aggregate-in-where","Aggregate expressions are not allowed in `where:`; use `having:`")}return i}getFilterList(e){return this.list.map(r=>this.checkedFilterCondition(e,r)).filter(Jet.isNotUndefined)}queryExecute(e){const r=this.havingClause?e.resultFS:e.inputFS;for(const i of this.list){const s=this.checkedFilterCondition(r,i);s!==void 0&&(e.filters.push(s),e.resultFS.addCompositeFieldUserFromFilter(s,i))}}}Ra.Filter=Zet;var r2={};Object.defineProperty(r2,"__esModule",{value:!0}),r2.FieldListEdit=void 0;const ett=Je;class ttt extends ett.MalloyElement{constructor(e,r){super({refs:r}),this.edit=e,this.refs=r,this.elementType="fieldListEdit"}}r2.FieldListEdit=ttt;var i2={};Object.defineProperty(i2,"__esModule",{value:!0}),i2.PrimaryKey=void 0;const ntt=Je;class rtt extends ntt.MalloyElement{constructor(e){super({field:e}),this.field=e,this.elementType="primary key"}}i2.PrimaryKey=rtt;var s2={};Object.defineProperty(s2,"__esModule",{value:!0}),s2.Views=void 0;const itt=$s;class stt extends itt.DefinitionList{constructor(e,r){super(e),this.accessModifier=r,this.elementType="turtleDefList"}get delarationNames(){return this.list.map(e=>e.name)}}s2.Views=stt;var o2={};Object.defineProperty(o2,"__esModule",{value:!0}),o2.TimezoneStatement=void 0;const ott=Je,utt=by;class att extends ott.MalloyElement{constructor(e){super(),this.tz=e,this.elementType="timezone",this.forceQueryClass=void 0,this.queryRefinementStage=void 0}get isValid(){try{return utt.DateTime.fromISO("2020-02-19T00:00:00",{zone:this.tz}),!0}catch{return!1}}queryExecute(e){e.resultFS.setTimezone(this.tz)}}o2.TimezoneStatement=att;var Fc={};Object.defineProperty(Fc,"__esModule",{value:!0}),Fc.ModelAnnotation=Fc.ObjectAnnotation=void 0;const ltt=Je,ctt=ui;class Xae extends ltt.MalloyElement{constructor(e){super(),this.notes=e,this.elementType="annotation",this.forceQueryClass=void 0,this.queryRefinementStage=void 0}queryExecute(){}}Fc.ObjectAnnotation=Xae;class ftt extends Xae{constructor(){super(...arguments),this.elementType="modelAnnotation"}getCompilerFlags(e,r){const i=(0,ctt.annotationToTag)({notes:this.notes},{prefix:/^##! /,extending:e});return i.log.forEach(s=>r.log(s)),i.tag}execute(e){e.annotation.notes===void 0&&(e.annotation.notes=[]),e.annotation.notes.push(...this.notes)}}Fc.ModelAnnotation=ftt;var wc={};Object.defineProperty(wc,"__esModule",{value:!0}),wc.Renames=wc.RenameField=void 0;const xtt=Iy,Zae=Je,dtt=Mr;class htt extends Zae.MalloyElement{constructor(e,r){super(),this.newName=e,this.oldName=r,this.elementType="renameField",this.has({oldName:r})}makeEntry(e){if(this.oldName.refString===this.newName){this.logError("invalid-rename-with-same-name","Can't rename field to itself");return}const r=this.oldName.getField(e);r.found?r.found instanceof dtt.SpaceField?e.renameEntry(this.oldName.refString,this.newName,new xtt.RenameSpaceField(r.found,this.newName,this.location)):this.logError("failed-rename",`'${this.oldName}' cannot be renamed`):this.logError("rename-field-not-found",`Can't rename '${this.oldName}', no such field`)}getName(){return this.newName}}wc.RenameField=htt;class ptt extends Zae.ListOf{constructor(e,r){super(e),this.accessModifier=r,this.elementType="renameFields"}get delarationNames(){return this.list.map(e=>e.getName())}}wc.Renames=ptt;var xs={};Object.defineProperty(xs,"__esModule",{value:!0}),xs.JoinStatement=xs.ExpressionJoin=xs.KeyJoin=xs.Join=void 0;const v$=Xe,mtt=wy,gtt=$s,ytt=Je,Ett=kr,ele=ai,Att=jn;class C$ extends ytt.MalloyElement{constructor(){super(...arguments),this.isNoteableObj=!0,this.extendNote=Ett.extendNoteMethod}makeEntry(e){e.newEntry(this.name.refString,this,new mtt.JoinSpaceField(e.parameterSpace(),this,e.dialectName()))}getName(){return this.name.refString}getStructDefFromExpr(e){const r=this.sourceExpr.getSource();return r?r.getSourceDef(e):(this.sourceExpr.sqLog("invalid-join-source","Cannot create a source to join from"),ele.ErrorFactory.structDef)}}xs.Join=C$;class _tt extends C${constructor(e,r,i){super({name:e,sourceExpr:r,keyExpr:i}),this.name=e,this.sourceExpr=r,this.keyExpr=i,this.elementType="joinOnKey"}getStructDef(e){var r;const i=this.getStructDefFromExpr(e);if(!(0,v$.isJoinable)(i))throw this.internalError(`Cannot join struct type '${i.type}'`);const s={...i,name:this.name.refString,join:"one",matrixOperation:"left",onExpression:{node:"error",message:"('join fixup'='not done yet')"},location:this.location};return delete s.as,this.note&&(s.annotation=this.note),(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(s),s}fixupJoinOn(e,r){const i=this.keyExpr.getExpression(e);if((0,v$.isSourceDef)(r)&&r.primaryKey){const s=r.fields.find(o=>(o.as||o.name)===r.primaryKey);if(s)if(s.type===i.type){r.join="one",r.onExpression={node:"=",kids:{left:{node:"field",path:[this.name.refString,r.primaryKey]},right:i.value}},r.onCompositeFieldUsage=i.compositeFieldUsage;return}else this.logError("join-on-primary-key-type-mismatch",`join_one: with type mismatch with primary key: ${i.type}/${s.type}`);else this.logError("join-primary-key-not-found",`join_one: Primary key '${s}' not found in source`)}else this.logError("join-with-without-primary-key","join_one: Cannot use with unless source has a primary key")}}xs.KeyJoin=_tt;class vtt extends C${constructor(e,r){super({name:e,sourceExpr:r}),this.name=e,this.sourceExpr=r,this.elementType="joinOnExpr",this.joinType="one",this.matrixOperation="left"}set joinOn(e){this.expr=e,this.has({on:e})}get joinOn(){return this.expr}fixupJoinOn(e,r){if(this.expr===void 0)return;const i=this.expr.getExpression(e);if(i.type!=="boolean"){this.logError("non-boolean-join-on","join conditions must be boolean expressions");return}r.onExpression=i.value,r.onCompositeFieldUsage=i.compositeFieldUsage}getStructDef(e){var r;const i=this.sourceExpr.getSource();if(!i)return this.sourceExpr.sqLog("invalid-join-source","Cannot create a source to join from"),ele.ErrorFactory.joinDef;const s=i.getSourceDef(e);let o="left";if(this.inExperiment("join_types",!0)&&(o=this.matrixOperation),!(0,v$.isJoinable)(s))throw this.internalError(`Can't join struct type ${s.type}`);const u={...s,name:this.name.refString,join:this.joinType,matrixOperation:o,location:this.location};return delete u.as,this.note&&(u.annotation=this.note),(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(u),u}}xs.ExpressionJoin=vtt;class Ctt extends gtt.DefinitionList{constructor(e,r){super(e),this.accessModifier=r,this.elementType="joinStatement",this.forceQueryClass=void 0,this.queryRefinementStage=Att.LegalRefinementStage.Single}queryExecute(e){for(const r of this.list)e.inputFS.extendSource(r),e.alwaysJoins.push(r.name.refString)}get delarationNames(){return this.list.map(e=>e.name.refString)}}xs.JoinStatement=Ctt;var du={};Object.defineProperty(du,"__esModule",{value:!0}),du.IncludeListItem=du.IncludeExceptItem=du.IncludeAccessItem=du.IncludeItem=void 0;const tle=Je,nle=kr;class S$ extends tle.MalloyElement{}du.IncludeItem=S$;class Stt extends S${constructor(e,r){super(),this.kind=e,this.fields=r,this.elementType="include-access-item",this.isNoteableObj=!0,this.extendNote=nle.extendNoteMethod,this.has({fields:r})}}du.IncludeAccessItem=Stt;class btt extends S${constructor(e){super(),this.fields=e,this.elementType="include-except-item",this.kind="except",this.has({fields:e})}}du.IncludeExceptItem=btt;class Ttt extends tle.MalloyElement{constructor(e,r){super({name:e}),this.name=e,this.as=r,this.elementType="include-list-item",this.isNoteableObj=!0,this.extendNote=nle.extendNoteMethod}}du.IncludeListItem=Ttt;var yt={},By={},Rtt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Dtt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Ott=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Rtt(e,t,r);return Dtt(e,t),e};Object.defineProperty(By,"__esModule",{value:!0}),By.ReferenceField=void 0;const rle=Xe,ile=Ott(Zt),sle=Mr,Ftt=lt;class wtt extends sle.SpaceField{constructor(e,r){super(),this.fieldRef=e,this.inFS=r,this.didLookup=!1}get referenceTo(){return this.didLookup||(this.memoReference=this.inFS.lookup(this.fieldRef.list).found,this.didLookup=!0),this.memoReference}getQueryFieldDef(e){if(!this.queryFieldDef){const r=this.fieldRef.getField(e);r.error&&this.fieldRef.logError(r.error.code,r.error.message);const i=this.fieldRef.path;if(r.found&&r.found.refType==="parameter"){const o=r.found.typeDesc();if(rle.TD.isAtomic(o))this.queryFieldDef={...(0,rle.mkFieldDef)(ile.atomicDef(o),i[0]),e:{node:"parameter",path:i}};else throw new Error("impossible turtle/join parameter")}else this.queryFieldDef={type:"fieldref",path:i};const s=this.referenceTo;if(s instanceof sle.SpaceField){const o=s.constructorFieldDef();if(o){const u=this.fieldRef.note;if(o.annotation||u){const a=u||{};o.annotation&&(a.inherits=o.annotation),this.queryFieldDef.annotation=a}}}}return this.queryFieldDef}typeDesc(){if(this.memoTypeDesc)return this.memoTypeDesc;const e=this.referenceTo;if(e){const r=this.fieldRef.list.slice(0,-1).map(s=>s.refString),i=e.typeDesc();return this.memoTypeDesc={...i,compositeFieldUsage:(0,Ftt.joinedCompositeFieldUsage)(r,i.compositeFieldUsage)},this.memoTypeDesc}return ile.errorT}}By.ReferenceField=wtt;var sr={};Object.defineProperty(sr,"__esModule",{value:!0}),sr.typecheckGroupBy=sr.typecheckAggregate=sr.typecheckCalculate=sr.typecheckDeclare=sr.typecheckMeasure=sr.typecheckDimension=sr.typecheckIndex=sr.typecheckProject=void 0;const In=Pi;function Ntt(t,e){if(t.type==="turtle"||!(0,In.expressionIsScalar)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="select-of-view";else if((0,In.expressionIsAnalytic)(t.expressionType))r="a calculate",i="an analytic",s="select-of-analytic";else if((0,In.expressionIsAggregate)(t.expressionType))r="an aggregate",i="an aggregate",s="select-of-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(s,`Cannot use ${i} field in a select operation, did you mean to use ${r} operation instead?`)}}sr.typecheckProject=Ntt;function Ltt(t,e){if(t.type==="turtle"||!(0,In.expressionIsScalar)(t.expressionType)){let r,i;if(t.type==="turtle")r="a view",i="index-of-view";else if((0,In.expressionIsAnalytic)(t.expressionType))r="an analytic",i="index-of-analytic";else if((0,In.expressionIsAggregate)(t.expressionType))r="an aggregate",i="index-of-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(i,`Cannot use ${r} field in an index operation`)}}sr.typecheckIndex=Ltt;function Itt(t,e){if(!(0,In.expressionIsScalar)(t.expressionType))if((0,In.expressionIsAggregate)(t.expressionType))e.logError("aggregate-in-dimension","Cannot use an aggregate field in a dimension declaration, did you mean to use a measure declaration instead?");else if((0,In.expressionIsAnalytic)(t.expressionType))e.logError("analytic-in-dimension","Cannot use an analytic field in a dimension declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}sr.typecheckDimension=Itt;function Btt(t,e){if(!(0,In.expressionIsAggregate)(t.expressionType))if((0,In.expressionIsScalar)(t.expressionType))e.logError("scalar-in-measure","Cannot use a scalar field in a measure declaration, did you mean to use a dimension declaration instead?");else if((0,In.expressionIsAnalytic)(t.expressionType))e.logError("analytic-in-measure","Cannot use an analytic field in a measure declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}sr.typecheckMeasure=Btt;function $tt(t,e){t.type==="turtle"?e.logError("view-in-declare","Views cannot be used in a declare block"):(0,In.expressionIsAnalytic)(t.expressionType)&&e.logError("analytic-in-declare","Analytic expressions can not be used in a declare block")}sr.typecheckDeclare=$tt;function ktt(t,e){if(t.type==="turtle"||!(0,In.expressionIsAnalytic)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="calculate-of-view";else if((0,In.expressionIsAggregate)(t.expressionType))r="an aggregate",i="an aggregate",s="calculate-of-aggregate";else if((0,In.expressionIsScalar)(t.expressionType))r="a group_by or select",i="a scalar",s="calculate-of-scalar";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(s,`Cannot use ${i} field in a calculate operation, did you mean to use ${r} operation instead?`)}}sr.typecheckCalculate=ktt;function Mtt(t,e){if(t.type==="turtle"||!(0,In.expressionIsAggregate)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="aggregate-of-view";else if((0,In.expressionIsAnalytic)(t.expressionType))r="a calculate",i="an analytic",s="aggregate-of-analytic";else if((0,In.expressionIsScalar)(t.expressionType))r="a group_by or select",i="a scalar",s="aggregate-of-scalar";else throw new Error(`Unexpected expression type ${t} not handled here`);e.logError(s,`Cannot use ${i} field in an aggregate operation, did you mean to use ${r} operation instead?`)}}sr.typecheckAggregate=Mtt;function Ptt(t,e){if(t.type==="turtle"||!(0,In.expressionIsScalar)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="group-by-view";else if((0,In.expressionIsAnalytic)(t.expressionType))r="a calculate",i="an analytic",s="group-by-analytic";else if((0,In.expressionIsAggregate)(t.expressionType))r="an aggregate",i="an aggregate",s="group-by-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(s,`Cannot use ${i} field in a group_by operation, did you mean to use ${r} operation instead?`)}}sr.typecheckGroupBy=Ptt,Object.defineProperty(yt,"__esModule",{value:!0}),yt.FieldReferences=yt.WildcardFieldReference=yt.ViewOrScalarFieldReference=yt.DimensionFieldReference=yt.MeasureFieldReference=yt.DeclareFieldReference=yt.ProjectFieldReference=yt.GroupByFieldReference=yt.AggregateFieldReference=yt.IndexFieldReference=yt.CalculateFieldReference=yt.ParameterFieldReference=yt.PartitionByFieldReference=yt.ExpressionFieldReference=yt.AccessModifierFieldReference=yt.AcceptExceptFieldReference=yt.FieldReference=void 0;const Utt=By,jtt=$s,ole=Je,ule=kr,Nc=sr;class ji extends ole.ListOf{constructor(e){super(e),this.isNoteableObj=!0,this.extendNote=ule.extendNoteMethod}makeEntry(e){const r=this.outputName;if(e.entry(r))this.logError("output-name-conflict",`Output already has a field named '${r}'`);else{const i=e.isQueryFieldSpace()?e.inputSpace():e;e.newEntry(r,this,new Utt.ReferenceField(this,i))}}getName(){return this.nameString}get refToField(){return{type:"fieldref",path:this.list.map(e=>e.refString)}}get refString(){return this.path.join(".")}get path(){return this.list.map(e=>e.refString)}get outputName(){return this.list[this.list.length-1].refString}get sourceString(){if(this.list.length>1)return this.list.slice(0,-1).map(e=>e.refString).join(".")}get nameString(){return this.list[this.list.length-1].refString}getField(e){const r=e.lookup(this.list);if(r.found){const i=r.found.typeDesc();this.typecheck(i)}return r}}yt.FieldReference=ji;class qtt extends ji{constructor(){super(...arguments),this.elementType="acceptExceptFieldReference"}typecheck(){}}yt.AcceptExceptFieldReference=qtt;class Htt extends ji{constructor(){super(...arguments),this.elementType="accessModifierFieldReference"}typecheck(){}}yt.AccessModifierFieldReference=Htt;class Qtt extends ji{constructor(){super(...arguments),this.elementType="expressionFieldReference"}typecheck(){}}yt.ExpressionFieldReference=Qtt;class ztt extends ji{constructor(){super(...arguments),this.elementType="partitionByFieldReference"}typecheck(){}}yt.PartitionByFieldReference=ztt;class Gtt extends ji{constructor(){super(...arguments),this.elementType="parameterFieldReference"}typecheck(){}}yt.ParameterFieldReference=Gtt;class Wtt extends ji{constructor(){super(...arguments),this.elementType="calculateFieldReference"}typecheck(e){(0,Nc.typecheckCalculate)(e,this)}}yt.CalculateFieldReference=Wtt;class b$ extends ji{constructor(){super(...arguments),this.elementType="indexFieldReference"}typecheck(e){(0,Nc.typecheckIndex)(e,this)}static indexOutputName(e){return e.map(r=>encodeURIComponent(r)).join("/")}get outputName(){return b$.indexOutputName(this.path)}}yt.IndexFieldReference=b$;class Vtt extends ji{constructor(){super(...arguments),this.elementType="aggregateFieldReference"}typecheck(e){(0,Nc.typecheckAggregate)(e,this)}}yt.AggregateFieldReference=Vtt;class Ytt extends ji{constructor(){super(...arguments),this.elementType="groupByFieldReference"}typecheck(e){(0,Nc.typecheckGroupBy)(e,this)}}yt.GroupByFieldReference=Ytt;class Ktt extends ji{constructor(){super(...arguments),this.elementType="projectFieldReference"}typecheck(e){(0,Nc.typecheckProject)(e,this)}}yt.ProjectFieldReference=Ktt;class Jtt extends ji{constructor(){super(...arguments),this.elementType="declareFieldReference"}typecheck(e){(0,Nc.typecheckDeclare)(e,this)}}yt.DeclareFieldReference=Jtt;class Xtt extends ji{constructor(){super(...arguments),this.elementType="measureFieldReference"}typecheck(e){(0,Nc.typecheckMeasure)(e,this)}}yt.MeasureFieldReference=Xtt;class Ztt extends ji{constructor(){super(...arguments),this.elementType="dimensionFieldReference"}typecheck(e){(0,Nc.typecheckDimension)(e,this)}}yt.DimensionFieldReference=Ztt;class ent extends ji{constructor(){super(...arguments),this.elementType="viewOrScalarFieldReference"}typecheck(e){}}yt.ViewOrScalarFieldReference=ent;class tnt extends ole.MalloyElement{constructor(e){super(),this.joinPath=e,this.elementType="wildcardFieldReference",this.isNoteableObj=!0,this.extendNote=ule.extendNoteMethod,this.except=new Set,this.has({joinPath:e})}getFieldDef(){throw this.internalError("fielddef request from wildcard reference")}get refString(){return this.joinPath?`${this.joinPath.refString}.*`:"*"}}yt.WildcardFieldReference=tnt;class nnt extends jtt.DefinitionList{constructor(e){super(e),this.elementType="fieldReferenceList"}}yt.FieldReferences=nnt,Object.defineProperty(Fy,"__esModule",{value:!0}),Fy.RefinedSource=void 0;const rnt=Xe,int=e2,snt=Oc,ont=Ra,unt=r2,ant=i2,lnt=s2,cnt=Eo,fnt=o2,xnt=Fc,dnt=wc,hnt=n2,pnt=xs,ale=du,T$=yt;class mnt extends cnt.Source{constructor(e,r,i){super({source:e,refinement:r}),this.source=e,this.refinement=r,this.includeList=i,this.elementType="refinedSource",i&&this.has({includeList:i})}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,r){var i;let s,o;const u=[],a=[];let l;const c=[];for(const v of this.refinement.list){if(v instanceof xnt.ObjectAnnotation)continue;const C=v;if(v instanceof ant.PrimaryKey){if(s){const b="multiple-primary-keys";s.logError(b,"Primary key already defined"),v.logError(b,"Primary key redefined")}s=v}else if(v instanceof unt.FieldListEdit){if(o){const b="multiple-field-list-edits";o.logError(b,"Too many accept/except statements"),v.logError(b,"Too many accept/except statements")}o=v}else v instanceof snt.DeclareFields||v instanceof pnt.JoinStatement||v instanceof lnt.Views||v instanceof dnt.Renames?(u.push(...v.list),v.accessModifier&&c.push({fields:v.delarationNames,access:v.accessModifier})):v instanceof ont.Filter?a.push(v):v instanceof fnt.TimezoneStatement?l=v.tz:C.logError("unexpected-source-property",`Unexpected source property: '${C.elementType}'`)}const f=r?new hnt.ParameterSpace(r):void 0,x=structuredClone(this.source.getSourceDef(f)),{fieldsToInclude:h,modifiers:p,renames:m,notes:g}=gnt(this.includeList,x);for(const v of c)for(const C of v.fields)p.set(C,v.access);s&&(x.primaryKey=s.field.name);const y=int.RefinedSpace.filteredFrom(x,o,h,m,f);if(l&&y.setTimezone(l),r&&y.addParameters(r),y.pushFields(...u),s){const v=s.field.getField(y);v.error&&s.logError(v.error.code,v.error.message)}y.addAccessModifiers(p),y.addNotes(g);const E=y.structDef(),A=E.filterList||[];let _=!1;for(const v of a)for(const C of v.list){const b=C.filterCondition(y);(0,rnt.expressionIsCalculation)(b.expressionType)?C.logError("aggregate-in-source-filter","Can't use aggregate computations in top level filters"):(A.push(b),_=!0)}return _?{...E,filterList:A}:((i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(E),E)}}Fy.RefinedSource=mnt;function gnt(t,e){var r,i,s,o,u,a,l,c,f;const x=new Set(e.fields.map(b=>b.name)),h=new Set(e.fields.filter(b=>b.accessModifier==="private").map(b=>b.name));let p;const m=new Set;let g,y;const E=new Map,A=[],_=new Map;if(t===void 0)return{fieldsToInclude:void 0,modifiers:E,renames:A,notes:_};for(const b of t)if(b instanceof ale.IncludeAccessItem)for(const S of b.fields)if(S.name instanceof T$.WildcardFieldReference)S.name.joinPath&&S.logError("unsupported-path-in-include","Wildcards with paths are not supported in `include` blocks"),g!==void 0?b.logError("already-used-star-in-include","Wildcard already used in this include block"):(g=(r=b.kind)!==null&&r!==void 0?r:"inherit",y={notes:(s=(i=S.note)===null||i===void 0?void 0:i.notes)!==null&&s!==void 0?s:[],blockNotes:(u=(o=b.note)===null||o===void 0?void 0:o.blockNotes)!==null&&u!==void 0?u:[]});else{if(p==="exclude"){b.logError("include-after-exclude","Cannot include specific fields if specific fields are already excluded");continue}p="include";const R=S.name.refString;h.has(R)&&S.logError("cannot-expand-access",`Cannot expand access of \`${R}\` from private to ${b.kind}`),E.has(R)?S.logError("duplicate-include",`Field \`${R}\` already referenced in include list`):(b.kind!==void 0&&E.set(R,b.kind),m.add(R),(S.note||b.note)&&_.set(R,{notes:(l=(a=S.note)===null||a===void 0?void 0:a.notes)!==null&&l!==void 0?l:[],blockNotes:(f=(c=b.note)===null||c===void 0?void 0:c.blockNotes)!==null&&f!==void 0?f:[]})),S.as&&(S.name instanceof T$.WildcardFieldReference?S.logError("wildcard-include-rename","Cannot rename a wildcard field in an `include` block"):A.push({name:S.name,as:S.as,location:S.location}))}else if(b instanceof ale.IncludeExceptItem)for(const S of b.fields)S instanceof T$.WildcardFieldReference?S.joinPath?S.logError("unsupported-path-in-include","Wildcards with paths are not supported in `include` blocks"):S.logWarning("wildcard-except-redundant","`except: *` is implied, unless another clause uses *"):p==="include"?b.logError("exclude-after-include","Cannot exclude specific fields if specific fields are already included"):(p="exclude",g="inherit",m.add(S.refString));const v=new Set(x);m.forEach(b=>v.delete(b)),h.forEach(b=>v.delete(b));let C;if(g!==void 0)for(const b of v)g!=="inherit"&&E.set(b,g),y&&_.set(b,{...y});return p!=="exclude"?g!==void 0?C=x:C=m:C=v,{fieldsToInclude:C,modifiers:E,renames:A,notes:_}}var hu={};Object.defineProperty(hu,"__esModule",{value:!0}),hu.SourceQueryElement=void 0;const ynt=Je;class R$ extends ynt.MalloyElement{constructor(){super(...arguments),this.errored=!1}getSource(){}getQuery(){}isSource(){return!1}sqLog(e,r,i){return this.isErrorFree()&&this.logError(e,r,i),this.errored=!0,e}isErrorFree(){if(this.errored)return!1;let e=!0;for(const r of this.walk())if(r instanceof R$&&r.errored){e=!1;break}return e}}hu.SourceQueryElement=R$;var J4={},Zx={};Object.defineProperty(Zx,"__esModule",{value:!0}),Zx.QuerySource=void 0;const Ent=Eo,Ant=Pp;class _nt extends Ent.Source{constructor(e){super({query:e}),this.query=e,this.elementType="querySource"}getSourceDef(e){return this.withParameters(e,void 0)}withParameters(e,r){var i;const s=this.query.queryComp(!1),o={...s.outputStruct,name:`QuerySource-${(0,Ant.v4)()}`,type:"query_source",query:s.query};return(i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(o),{...o,parameters:this.packParameters(r)}}}Zx.QuerySource=_nt;var u2={},$y={};Object.defineProperty($y,"__esModule",{value:!0}),$y.QueryBase=void 0;const D$=lt,lle=Xe,vnt=Vp,Cnt=Je;class Snt extends Cnt.MalloyElement{resolveCompositeSource(e,r){var i;const s=r.pipeline[0];if(s&&((0,lle.isQuerySegment)(s)||(0,lle.isIndexSegment)(s))){const o=(i=s.compositeFieldUsage)!==null&&i!==void 0?i:(0,D$.emptyCompositeFieldUsage)();if(!(0,D$.isEmptyCompositeFieldUsage)(o)||e.type==="composite")return(0,D$.resolveCompositeSources)(e,o).sourceDef}}query(){const{query:e}=this.queryComp(!0);return{...e,pipeline:(0,vnt.detectAndRemovePartialStages)(e.pipeline,this)}}}$y.QueryBase=Snt,Object.defineProperty(u2,"__esModule",{value:!0}),u2.QueryArrow=void 0;const bnt=Xe,Tnt=Eo,cle=Pr,Rnt=$y;class Dnt extends Rnt.QueryBase{constructor(e,r){super({source:e,view:r}),this.source=e,this.view=r,this.elementType="arrow"}queryComp(e){var r;let i,s,o;if(this.source instanceof Tnt.Source){const h=e?this.source.structRef(void 0):{structRef:this.source.getSourceDef(void 0)};s={type:"query",...h,pipeline:[],location:this.location},i=(0,bnt.refIsStructDef)(h.structRef)?h.structRef:this.source.getSourceDef(void 0),o=new cle.StaticSourceSpace(i)}else{const h=this.source.queryComp(e);s=h.query,i=h.outputStruct,o=new cle.StaticSourceSpace(h.outputStruct)}const{pipeline:u,annotation:a,outputStruct:l,name:c}=this.view.pipelineComp(o),f={...s,name:c,annotation:a,pipeline:[...s.pipeline,...u]},x=(r=f.compositeResolvedSourceDef)!==null&&r!==void 0?r:this.resolveCompositeSource(i,f);return{query:{...f,compositeResolvedSourceDef:x},outputStruct:l,inputStruct:i}}}u2.QueryArrow=Dnt,Object.defineProperty(J4,"__esModule",{value:!0}),J4.SQArrow=void 0;const Ont=hu,Fnt=Zx,wnt=u2;class Nnt extends Ont.SourceQueryElement{constructor(e,r){super({applyTo:e,operation:r}),this.applyTo=e,this.operation=r,this.elementType="sq-arrow"}getQuery(){const e=this.applyTo.isSource()?this.applyTo.getSource():this.applyTo.getQuery();if(e===void 0){this.sqLog("failed-to-compute-arrow-source","Could not get LHS of arrow operation");return}const r=new wnt.QueryArrow(e,this.operation);return this.has({query:r}),r}getSource(){const e=this.getQuery();if(!e){this.sqLog("failed-to-compute-source-from-query","Couldn't comprehend query well enough to make a source");return}const r=new Fnt.QuerySource(e);return this.has({asSource:r}),r}}J4.SQArrow=Nnt;var X4={},a2={},ks={};Object.defineProperty(ks,"__esModule",{value:!0}),ks.getStructFieldDef=ks.getFinalStruct=ks.opOutputStruct=void 0;const fle=lc,Lnt=Ls,Z4=Xe,xle=ai;function dle(t,e,r){const i=xle.ErrorFactory.didCreate(e)||(0,Z4.structHasErrors)(e);(0,Z4.isPartialSegment)(r)&&(r={...r,type:"reduce"});const s=(0,Z4.segmentHasErrors)(r);if(!i&&!s)try{const o=Lnt.Segment.nextStructDef(e,r);if((0,Z4.isSourceDef)(o))return o;t.logError("failed-to-compute-output-schema",`INTERNAL ERROR model/Segment.nextStructDef: RETURNED A NON SOURCE
1158
1158
  STRUCTDEF: ${(0,fle.inspect)(o,{breakLength:72,depth:1/0})}`)}catch(o){t.logError("failed-to-compute-output-schema",`INTERNAL ERROR model/Segment.nextStructDef: ${o.message}
1159
- QUERY: ${(0,fle.inspect)(r,{breakLength:72,depth:1/0})}`)}return xle.ErrorFactory.structDef}ks.opOutputStruct=dle;function Nnt(t,e,r){for(const i of r)e=dle(t,e,i);return e}ks.getFinalStruct=Nnt;function Lnt(t,e){return t.fields.find(r=>(r.as||r.name)===e)}ks.getStructFieldDef=Lnt,Object.defineProperty(a2,"__esModule",{value:!0}),a2.QueryRefine=void 0;const Int=Pr,Bnt=ks,$nt=$y;class knt extends $nt.QueryBase{constructor(e,r){super({base:e,refinement:r}),this.base=e,this.refinement=r,this.elementType="query-refine"}queryComp(e){const r=this.base.queryComp(e),i=new Int.StaticSourceSpace(r.inputStruct),s=this.refinement.refine(i,r.query.pipeline,void 0),o={...r.query,pipeline:s},u=this.resolveCompositeSource(r.inputStruct,o);return{query:{...o,compositeResolvedSourceDef:u},outputStruct:(0,Bnt.getFinalStruct)(this.refinement,r.inputStruct,s),inputStruct:r.inputStruct}}}a2.QueryRefine=knt;var ky={},l2={},ds={};Object.defineProperty(ds,"__esModule",{value:!0}),ds.mkTimeResult=ds.resolution=ds.castTo=ds.timeOffset=void 0;const O$=Xe;function Mnt(t,e,r,i,s){return{node:"delta",kids:{base:(0,O$.mkTemporal)(e,t),delta:i},op:r,units:s}}ds.timeOffset=Mnt;function Pnt(t,e,r,i=!1){let s;return typeof t!="string"?s={node:"cast",dstSQLType:t.raw,e,safe:i}:s={node:"cast",dstType:{type:t},e,safe:i},(0,O$.isCastType)(r)&&(s.srcType={type:r}),s}ds.castTo=Pnt;function Unt(t){switch(t){case"hour":case"minute":case"second":case"microsecond":case"millisecond":return"timestamp"}return"date"}ds.resolution=Unt;function jnt(t,e){if(e){if(t.type==="timestamp")return{...t,timeframe:e};if((0,O$.isDateUnit)(e))return{...t,timeframe:e}}return t}ds.mkTimeResult=jnt;var ed={},ct={},Gt={};Object.defineProperty(Gt,"__esModule",{value:!0}),Gt.literalTimeResult=Gt.literalExprValue=Gt.computedErrorExprValue=Gt.computedTimeResult=Gt.computedExprValue=void 0;const hle=Pi,F$=lt;function My({value:t,dataType:e,from:r}){return{...e,value:t,expressionType:(0,hle.maxOfExpressionTypes)(r.map(i=>i.expressionType)),evalSpace:(0,hle.mergeEvalSpaces)(...r.map(i=>i.evalSpace)),compositeFieldUsage:(0,F$.mergeCompositeFieldUsage)(...r.map(i=>i.compositeFieldUsage))}}Gt.computedExprValue=My;function qnt({value:t,dataType:e,from:r,timeframe:i}){const s=My({value:t,dataType:e,from:r}),o={...e,expressionType:s.expressionType,evalSpace:s.evalSpace,value:s.value,compositeFieldUsage:(0,F$.mergeCompositeFieldUsage)(...r.map(u=>u.compositeFieldUsage))};return i&&(o.timeframe=i),o}Gt.computedTimeResult=qnt;function Hnt({dataType:t,from:e,error:r}){return My({dataType:t??{type:"error"},value:{node:"error",message:r},from:e})}Gt.computedErrorExprValue=Hnt;function Qnt(t){return My({...t,from:[]})}Gt.literalExprValue=Qnt;function znt({value:t,dataType:e,timeframe:r}){const i=My({value:t,dataType:e,from:[]}),s={...e,expressionType:i.expressionType,evalSpace:i.evalSpace,value:i.value,compositeFieldUsage:(0,F$.emptyCompositeFieldUsage)()};return r&&(s.timeframe=r),s}Gt.literalTimeResult=znt;var c2={};Object.defineProperty(c2,"__esModule",{value:!0}),c2.isGranularResult=void 0;function Gnt(t){return t.type==="date"||t.type==="timestamp"?t.timeframe!==void 0:!1}c2.isGranularResult=Gnt;var pu={};Object.defineProperty(pu,"__esModule",{value:!0}),pu.isComparison=pu.isEquality=pu.getExprNode=void 0;function Wnt(t){switch(t){case"~":return"like";case"!~":return"!like"}return t}pu.getExprNode=Wnt;function ple(t){return t==="="||t==="!="||t==="~"||t==="!~"}pu.isEquality=ple;function Vnt(t){return ple(t)||t===">="||t==="<="||t===">"||t==="<"}pu.isComparison=Vnt;var Ynt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Knt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Jnt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Ynt(e,t,r);return Knt(e,t),e};Object.defineProperty(ct,"__esModule",{value:!0}),ct.checkFilterExpression=ct.applyBinary=ct.getMorphicValue=ct.ExprDuration=ct.ExpressionDef=ct.ATNodeType=void 0;const Lc=Xe,td=Jnt(Zt),w$=Bs,Vl=Gt,Xnt=ds,mle=c2,Znt=Je,Py=pu,Uy=Cy;class ert extends Error{}var N$;(function(t){t[t.And=0]="And",t[t.Or=1]="Or",t[t.Value=2]="Value",t[t.Partial=3]="Partial"})(N$||(ct.ATNodeType=N$={}));class gle extends Znt.MalloyElement{constructor(){super(...arguments),this.legalChildTypes=td.anyAtomicT}granular(){return!1}requestExpression(e){return this.getExpression(e)}defaultFieldName(){}typeCheck(e,r){return r.type!=="error"&&!td.any(r,this.legalChildTypes)?(r.type==="sql native"?e.logError("sql-native-not-allowed-in-expression",{rawType:r.rawType}):e.logError("expression-type-error",`'${this.elementType}' Can't use type ${td.inspect(r)}`),!1):!0}apply(e,r,i,s=!1){return _le(e,i,r,this)}canSupportPartitionBy(){return!1}canSupportOrderBy(){return!1}canSupportLimit(){return!1}supportsWhere(e){return(0,Lc.expressionIsAggregate)(e.expressionType)}atNodeType(){return N$.Value}atExpr(){return this}}ct.ExpressionDef=gle;class L$ extends gle{constructor(e,r){super({n:e}),this.n=e,this.timeframe=r,this.elementType="duration",this.legalChildTypes=[td.timestampT,td.dateT]}apply(e,r,i){const s=i.getExpression(e);if(this.typeCheck(this,s),(0,Lc.isTemporalType)(s.type)&&(r==="+"||r==="-")){const o=this.n.getExpression(e);if(!td.typeEq(o,td.numberT))return this.logError("invalid-duration-quantity",`Duration quantity needs number not '${o.type}`),(0,w$.errorFor)("illegal unit expression");let u;return(0,mle.isGranularResult)(s)&&s.timeframe===this.timeframe&&(u=s.timeframe),s.type==="date"&&!(0,Lc.isDateUnit)(this.timeframe)?this.loggedErrorExpr("invalid-timeframe-for-time-offset",`Cannot offset date by ${this.timeframe}`):(0,Vl.computedTimeResult)({dataType:{type:s.type},value:(0,Xnt.timeOffset)(s.type,s.value,r,o.value,this.timeframe),timeframe:u,from:[s,o]})}return super.apply(e,r,i)}getExpression(e){const r=this.n.getExpression(e);return(0,Vl.computedErrorExprValue)({dataType:{type:"duration"},error:"Duration is not a value",from:[r]})}}ct.ExprDuration=L$;function yle(t,e){return t.type===e?t.value:t.morphic&&t.morphic[e]}function trt(t,e){if(t.type===e)return t;if(t.morphic&&t.morphic[e])return(0,Vl.computedExprValue)({dataType:{type:e},value:t.morphic[e],from:[t]})}ct.getMorphicValue=trt;function Ele(t,e,r,i){const s=(0,Lc.isTemporalType)(e.type),o=(0,Lc.isTemporalType)(i.type),u=(0,Py.getExprNode)(r);if(s&&o)if(e.type!==i.type){const a=yle(e,"timestamp"),l=yle(i,"timestamp");if(a&&l)return{node:u,kids:{left:a,right:a}}}else return{node:u,kids:{left:e.value,right:i.value}};if((s||o)&&e.type!=="null"&&i.type!=="null")return t.logError("time-comparison-type-mismatch",`Cannot compare a ${e.type} to a ${i.type}`),{node:"false"}}function nrt(t,e){if(t.type==="string"){if(e.type==="regular expression")return{node:"regexpMatch",kids:{expr:t.value,regex:e.value}}}else if(e.type==="string"&&t.type==="regular expression")return{node:"regexpMatch",kids:{expr:e.value,regex:t.value}}}function rrt(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=(0,Py.getExprNode)(r),a=jy("boolean",s,o);if(a)return a;const l=Lc.TD.isSQL(s)?s.rawType||"typeless-left":void 0,c=Lc.TD.isSQL(o)?o.rawType||"typeless-right":void 0;if((l||c)&&!(s.type==="null"||o.type==="null"||l===c)){const h=qy(e,s,i,o);if(h)return{...h,type:"boolean"}}let f;if(o.type==="filter expression"){if(r!=="~"&&r!=="!~")return i.loggedErrorExpr("filter-expression-error",`Cannot use the '${r}' operator with a filter expression`);if((0,Uy.isFilterable)(s.type)){let x=o.value;for(;x.node==="()";)x=x.e;x.node!=="parameter"&&vle(i,s.type,x);const h={node:"filterMatch",dataType:s.type,kids:{filterExpr:o.value,expr:s.value}};r==="!~"&&(h.notMatch=!0),f=h}else return e.loggedErrorExpr("filter-expression-type",`Cannot use filter expressions with type '${s.type}'`)}else if(f=Ele(e,s,r,o)||{node:u,kids:{left:s.value,right:o.value}},s.type!=="error"&&o.type!=="error"&&(r==="~"||r==="!~")&&(s.type!=="string"||o.type!=="string")){let x=nrt(s,o);if(x)r[0]==="!"&&(x={node:"not",e:{...x}});else throw new ert("Incompatible types for match('~') operator");f=x}return(0,Vl.computedExprValue)({dataType:{type:"boolean"},value:f,from:[s,o]})}function irt(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=jy("boolean",s,o);if(u)return u;const a=qy(e,s,i,o);if(a)return{...a,type:"boolean"};const l=Ele(e,s,r,o)||{node:(0,Py.getExprNode)(r),kids:{left:s.value,right:o.value}};return(0,Vl.computedExprValue)({dataType:{type:"boolean"},value:l,from:[s,o]})}function Ale(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=jy("number",s,o);if(u)return u;const a=qy(e,s,i,o);if(a)return a;if(s.type!=="number")e.logError("arithmetic-operation-type-mismatch",`The '${r}' operator requires a number, not a '${s.type}'`);else if(o.type!=="number")i.logError("arithmetic-operation-type-mismatch",`The '${r}' operator requires a number, not a '${o.type}'`);else return(0,Vl.computedExprValue)({dataType:{type:"number"},value:{node:r,kids:{left:s.value,right:o.value}},from:[s,o]});return(0,w$.errorFor)("numbers required")}function srt(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=qy(e,s,i,o);if(u)return u;const a=(0,Lc.isTemporalType)(s.type),l=jy(a?"error":"number",s,o);if(l)return l;if(a){let c=i;if(o.type!=="duration")if((0,mle.isGranularResult)(s))c=new L$(i,s.timeframe);else if(s.type==="date")c=new L$(i,"day");else return e.loggedErrorExpr("time-offset-type-mismatch",`Can not offset time by '${o.type}'`);return c.apply(t,r,e)}return Ale(t,e,r,i)}function _le(t,e,r,i){if((0,Py.isEquality)(r))return rrt(t,e,r,i);if((0,Py.isComparison)(r))return irt(t,e,r,i);if(r==="+"||r==="-")return srt(t,e,r,i);if(r==="*")return Ale(t,e,r,i);if(r==="/"||r==="%"){const s=e.getExpression(t),o=i.getExpression(t),u=qy(e,s,i,o);if(u)return u;const a=jy("number",s,o);if(a)return a;if(s.type!=="number")e.logError("arithmetic-operation-type-mismatch","Numerator must be a number");else if(o.type!=="number")i.logError("arithmetic-operation-type-mismatch","Denominator must be a number");else{const l={node:r,kids:{left:s.value,right:o.value}};return(0,Vl.computedExprValue)({dataType:{type:"number"},value:l,from:[s,o]})}return(0,w$.errorFor)("divide type mismatch")}return e.loggedErrorExpr("unexpected-binary-operator",`Cannot use ${r} operator here`)}ct.applyBinary=_le;function jy(t,...e){if(e.some(r=>r.type==="error"))return(0,Vl.computedExprValue)({dataType:{type:t},value:{node:"error",message:"cascading error"},from:e})}function qy(t,e,r,i){const s=(0,Vl.computedExprValue)({dataType:e,value:{node:"error",message:"sql-native unsupported"},from:[e,i]});if(e.type==="sql native")return t.logError("sql-native-not-allowed-in-expression",{rawType:e.rawType}),s.type=i.type,s;if(i.type==="sql native")return r.logError("sql-native-not-allowed-in-expression",{rawType:i.rawType}),s}function vle(t,e,r){for(var i,s,o,u;r.node==="()";)r=r.e;if(r.node!=="filterLiteral"){t.logError("filter-expression-error","Expected a filter expression literal here");return}const a=r.filterSrc;let l;e==="date"||e==="timestamp"?l=(i=Uy.TemporalFilterExpression.parse(a).log[0])===null||i===void 0?void 0:i.message:e==="string"?l=(s=Uy.StringFilterExpression.parse(a).log[0])===null||s===void 0?void 0:s.message:e==="number"?l=(o=Uy.NumberFilterExpression.parse(a).log[0])===null||o===void 0?void 0:o.message:e==="boolean"?l=(u=Uy.BooleanFilterExpression.parse(a).log[0])===null||u===void 0?void 0:u.message:t.logError("filter-expression-type",`Cannot apply filter expression to type ${e}`),l!==void 0&&t.logError("filter-expression-error",`Filter syntax error: ${l}`)}ct.checkFilterExpression=vle,Object.defineProperty(ed,"__esModule",{value:!0}),ed.ExprIdReference=void 0;const ort=Xe,urt=ct,art=lt;class lrt extends urt.ExpressionDef{constructor(e){super(),this.fieldReference=e,this.elementType="ExpressionIdReference",this.has({fieldPath:e})}get refString(){return this.fieldReference.refString}getExpression(e){const r=this.fieldReference.getField(e),i=this.fieldReference.list.map(s=>s.name).slice(0,-1);if(r.found){const s=r.found.typeDesc(),o=(0,art.joinedCompositeFieldUsage)(i,s.compositeFieldUsage);if(r.isOutputField)return{...s,evalSpace:s.evalSpace==="constant"?"constant":"output",value:{node:"outputField",name:this.refString},compositeFieldUsage:o};const u={node:r.found.refType,path:this.fieldReference.path},a=(0,ort.expressionIsAggregate)(s.expressionType)?"output":s.evalSpace;return{...s,value:u,evalSpace:a,compositeFieldUsage:o}}return this.loggedErrorExpr(r.error.code,r.error.message)}}ed.ExprIdReference=lrt,Object.defineProperty(l2,"__esModule",{value:!0}),l2.NamedSource=void 0;const I$=Xe,crt=Eo,frt=ai,xrt=ds,Cle=Je,drt=ed,hrt=n2,prt=ct;class mrt extends crt.Source{constructor(e,r,i){super(),this.ref=e,this.sourceArguments=r,this.args=i,this.elementType="namedSource",i&&this.has({args:i}),e instanceof Cle.ModelEntryReference&&this.has({ref:e})}get refName(){return this.ref instanceof Cle.ModelEntryReference?this.ref.name:this.ref}structRef(e){const r=this.modelEntry(this.ref);return r&&!r.exported?{structRef:this.getSourceDef(e)}:{structRef:this.refName,sourceArguments:this.evaluateArgumentsForRef(e)}}refLogError(e,r,i){typeof this.ref=="string"?this.logError(e,r,i):this.ref.logError(e,r,i)}modelStruct(){var e;const r=this.modelEntry(this.ref),i=r==null?void 0:r.entry;if(!i){this.refLogError("source-not-found",`Undefined source '${this.refName}'`);return}if(i.type==="query"){this.logError("invalid-source-from-query",`Cannot construct a source from query '${this.refName}'`);return}else if(i.type==="function"){this.logError("invalid-source-from-function",`Cannot construct a source from a function '${this.refName}'`);return}else if(i.type==="connection"){this.logError("invalid-source-from-connection",`Cannot construct a source from a connection '${this.refName}'`);return}else if((e=this.document())===null||e===void 0||e.checkExperimentalDialect(this,i.dialect),(0,I$.isSourceDef)(i))return{...i};this.logError("invalid-source-source","Cannot construct a source from a never type")}evaluateArgumentsForRef(e){const r=this.modelStruct();return r===void 0?{}:this.evaluateArguments(e,r.parameters,[])}evaluateArguments(e,r,i){var s,o;const u={...this.sourceArguments},a=new Set;for(const l of(s=this.args)!==null&&s!==void 0?s:[]){const c=(o=l.id)!==null&&o!==void 0?o:l.value instanceof drt.ExprIdReference?l.value.fieldReference:void 0;if(c===void 0){l.value.logError("unnamed-source-argument","Parameterized source arguments must be named with `parameter_name is`");continue}const f=c.outputName;if(a.has(f)){l.logError("duplicate-source-argument",`Cannot pass argument for \`${f}\` more than once`);continue}a.add(f);const x=(r??{})[f];if(!x)c.logError("source-parameter-not-found",`\`${this.refName}\` has no declared parameter named \`${c.refString}\``);else{const h=e??new hrt.ParameterSpace(i??[]),p=l.value.getExpression(h);let m=p.value;p.type==="filter expression"&&x.type==="filter expression"&&x.filterType&&(0,prt.checkFilterExpression)(l.value,x.filterType,m),p.type!==x.type&&(0,I$.isCastType)(x.type)&&(m=(0,xrt.castTo)(x.type,p.value,p.type,!0)),u[f]={...x,value:m}}}for(const l in r)l in u||((0,I$.paramHasValue)(r[l])?u[l]={...r[l]}:this.refLogError("missing-source-argument",`Argument not provided for required parameter \`${l}\``));return u}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,r){var i;const s=this.modelStruct();if(!s){const l=frt.ErrorFactory.structDef,c=`${this.refName}-undefined`;return l.name=l.name+c,l.dialect=l.dialect+c,l}const o={};for(const l of r??[]){const c=l.parameter();o[c.name]=c}const u=this.evaluateArguments(e,s.parameters,r),a={...s,parameters:o,arguments:u};return(i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(a),a}}l2.NamedSource=mrt;var Hy={},eb={};Object.defineProperty(eb,"__esModule",{value:!0}),eb.QueryHeadStruct=void 0;const grt=Xe,yrt=Eo,Ert=l2;class Art extends yrt.Source{constructor(e,r){super(),this.fromRef=e,this.sourceArguments=r,this.elementType="internalOnlyQueryHead"}structRef(){return{structRef:this.fromRef}}getSourceDef(e){if((0,grt.refIsStructDef)(this.fromRef))return this.fromRef;const r=new Ert.NamedSource(this.fromRef,this.sourceArguments,void 0);return this.has({exploreReference:r}),r.getSourceDef(e)}}eb.QueryHeadStruct=Art,Object.defineProperty(Hy,"__esModule",{value:!0}),Hy.QueryReference=void 0;const B$=ai,_rt=Je,vrt=eb,Crt=Xe,Srt=ks;class brt extends _rt.MalloyElement{constructor(e){super(),this.name=e,this.elementType="query-reference"}queryComp(e){const r=this.modelEntry(this.name),i=r==null?void 0:r.entry,s=function(){return{inputStruct:B$.ErrorFactory.structDef,outputStruct:B$.ErrorFactory.structDef,query:B$.ErrorFactory.query}};if(!i)return this.logError("query-reference-not-found",`Reference to undefined query '${this.name.refString}'`),s();if(i.type==="query"){const o=new vrt.QueryHeadStruct(i.structRef,i.sourceArguments);this.has({queryHead:o});const u=o.getSourceDef(void 0),a=(0,Srt.getFinalStruct)(this,u,i.pipeline);return{query:e||(0,Crt.refIsStructDef)(i.structRef)?i:{...i,structRef:u},outputStruct:a,inputStruct:u}}return this.logError("non-query-used-as-query",`Illegal reference to '${this.name}', query expected`),s()}query(){return this.queryComp(!0).query}}Hy.QueryReference=brt,Object.defineProperty(ky,"__esModule",{value:!0}),ky.SQReference=void 0;const Trt=hu,Rrt=Zx,Drt=l2,Sle=Hy,ble=Pi;class Ort extends Trt.SourceQueryElement{constructor(e,r){super({ref:e}),this.ref=e,this.args=r,this.elementType="sq-reference",r!==void 0&&this.has({args:r})}getQuery(){const e=this.ref.getNamed();if(e)if(e.type==="query"){const r=new Sle.QueryReference(this.ref);return this.has({query:r}),r}else this.sqLog("cannot-use-as-query",`Illegal reference to '${e.as||e.name}', query expected`);else this.ref.logError("source-or-query-not-found",`Reference to undefined object '${this.ref.refString}'`),this.errored=!0}isSource(){const e=this.ref.getNamed();return e!==void 0&&(0,ble.isSourceDef)(e)}getSource(){if(this.asSource)return this.asSource;const e=this.ref.getNamed();if(!e){this.ref.logError("source-not-found",`Reference to undefined object '${this.ref.refString}'`),this.errored=!0;return}if(e.type==="query"){this.args!==void 0&&this.ref.logError("illegal-query-argument","Arguments cannot be passed to queries");const r=new Sle.QueryReference(this.ref);this.asSource=new Rrt.QuerySource(r)}else if((0,ble.isSourceDef)(e))this.asSource=new Drt.NamedSource(this.ref,void 0,this.args);else{this.sqLog("cannot-use-struct-as-source",`Expected '${this.ref.refString}' to be of type query or source, not '${e.type}'`);return}return this.has({asSource:this.asSource}),this.asSource}}ky.SQReference=Ort,Object.defineProperty(X4,"__esModule",{value:!0}),X4.SQRefine=void 0;const Frt=hu,wrt=Zx,Nrt=a2,Lrt=ky;class Irt extends Frt.SourceQueryElement{constructor(e,r){super({toRefine:e,refine:r}),this.toRefine=e,this.refine=r,this.elementType="sq-refine"}getQuery(){if(this.toRefine.isSource()){this.toRefine instanceof Lrt.SQReference?this.sqLog("illegal-refinement-of-source",`Cannot add view refinements to '${this.toRefine.ref.refString}' because it is a source`):this.sqLog("illegal-refinement-of-source","Cannot add view refinements to a source");return}const e=this.toRefine.getQuery();if(e){const r=new Nrt.QueryRefine(e,this.refine);return this.has({query:r}),r}}getSource(){const e=this.getQuery();if(e){const r=new wrt.QuerySource(e);return this.has({queryAsSource:r}),r}}}X4.SQRefine=Irt;var tb={},Qy={};Object.defineProperty(Qy,"__esModule",{value:!0}),Qy.QueryRaw=void 0;const Brt=Xe,$rt=Je;class krt extends $rt.MalloyElement{constructor(e){super({source:e}),this.source=e,this.elementType="query-raw"}queryComp(e){const r=e?this.source.structRef(void 0):{structRef:this.source.getSourceDef(void 0)},i=(0,Brt.refIsStructDef)(r.structRef)?r.structRef:this.source.getSourceDef(void 0);return{query:{type:"query",...r,pipeline:[{type:"raw",fields:[]}],location:this.location},outputStruct:i,inputStruct:i}}query(){return this.queryComp(!0).query}}Qy.QueryRaw=krt;var zy={},Yl={};Object.defineProperty(Yl,"__esModule",{value:!0}),Yl.sqlKey=Yl.compileSQLInterpolation=void 0;const Mrt=Ls,Prt=Xe,Urt=Bt;function jrt(t,e,r){let i,s="",o=!1;for(const u of t)if((0,Prt.isSegmentSQL)(u))s+=u.sql,o=u.sql.match(/\(\s*$/)!==null;else{if(!i){if(!r)throw new Error("Internal error: Partial model missing when compiling SQL block");i=new Mrt.QueryModel(r)}const a=i.compileQuery(u,{defaultRowLimit:void 0},!1).sql;s+=o?a:`(${a})`,o=!1}return{connection:e,selectStr:s}}Yl.compileSQLInterpolation=jrt;function qrt(t,e){return`sql://${t}/${(0,Urt.generateHash)(e)}`}Yl.sqlKey=qrt,Object.defineProperty(zy,"__esModule",{value:!0}),zy.SQLSource=void 0;const $$=Yl,Hrt=Eo,Gy=ai;class Qrt extends Hrt.Source{constructor(e,r){super({connectionName:e,select:r}),this.connectionName=e,this.select=r,this.elementType="sqlSource",this.connectionNameInvalid=!1}sqlSourceRequest(e){const r=this.select.containsQueries?e.modelDef():void 0;return(0,$$.compileSQLInterpolation)(this.select.sqlPhrases(),this.connectionName.refString,r)}structRef(){return{structRef:this.getSourceDef()}}validateConnectionName(){var e;const r=this.modelEntry(this.connectionName),i=this.connectionName.refString;if(this.connectionNameInvalid)return!1;if(r===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(i,{entry:{type:"connection",name:i},exported:!0},!0);else if(r.entry.type!=="connection")return this.connectionName.logError("invalid-connection-for-sql-source",`${this.connectionName.refString} is not a connection`),this.connectionNameInvalid=!0,!1;return!0}needs(e){var r;if(!this.validateConnectionName())return;const i=super.needs(e);if(i)return i;this.requestBlock===void 0&&(this.requestBlock=this.sqlSourceRequest(e));const s=this.requestBlock,o=(r=this.translator())===null||r===void 0?void 0:r.root.sqlQueryZone;if(!o){this.logError("failed-to-fetch-sql-source-schema","Cant't look up schema for sql block");return}const u=(0,$$.sqlKey)(s.connection,s.selectStr);o.reference(u,this.location);const a=o.getEntry(u);if(a.status==="reference")return{compileSQL:s};a.status==="present"&&e.checkExperimentalDialect(this,a.value.dialect)}getSourceDef(){var e;if(!this.validateConnectionName())return Gy.ErrorFactory.structDef;const r=(e=this.translator())===null||e===void 0?void 0:e.root.sqlQueryZone;if(!r)return this.logError("failed-to-fetch-sql-source-schema","Cant't look up schema for sql block"),Gy.ErrorFactory.structDef;if(this.requestBlock===void 0)return this.logError("failed-to-fetch-sql-source-schema","Expected to have already compiled the sql block"),Gy.ErrorFactory.structDef;const i=this.requestBlock,s=(0,$$.sqlKey)(i.connection,i.selectStr);r.reference(s,this.location);const o=r.getEntry(s);if(o.status==="error"){const u=o.message.split(/\r?\n/);return this.select.logError("invalid-sql-source","Invalid SQL, "+u.join(`
1160
- `)),Gy.ErrorFactory.structDef}else if(o.status==="present"){const u=this.select.location,a={...o.value,fields:o.value.fields.map(f=>({...f,location:u})),location:this.location},l=this.document(),c=l==null?void 0:l.currentModelAnnotation();return c&&(a.modelAnnotation=c),a}else return this.logError("non-top-level-sql-source","`connection_name.sql(...)` can currently only be used in top level source/query definitions"),Gy.ErrorFactory.structDef}}zy.SQLSource=Qrt,Object.defineProperty(tb,"__esModule",{value:!0}),tb.SQSource=void 0;const zrt=hu,Grt=Qy,Wrt=zy;class Vrt extends zrt.SourceQueryElement{constructor(e){super({theSource:e}),this.theSource=e,this.elementType="sq-source"}isSource(){return!0}getSource(){return this.theSource}getQuery(){if(this.theSource instanceof Wrt.SQLSource){const e=new Grt.QueryRaw(this.theSource);return this.has({rawQuery:e}),e}else this.sqLog("invalid-source-as-query","This source cannot be used as a query")}}tb.SQSource=Vrt;var nb={};Object.defineProperty(nb,"__esModule",{value:!0}),nb.SQExtend=void 0;const Yrt=Fy,Krt=hu;class Jrt extends Krt.SourceQueryElement{constructor(e,r,i){super({sqSrc:e,extend:r}),this.sqSrc=e,this.extend=r,this.includeList=i,this.elementType="sq-extend"}getSource(){if(this.asSource)return this.asSource;const e=this.sqSrc.getSource();if(e)return this.asSource=new Yrt.RefinedSource(e,this.extend,this.includeList),this.has({asSource:this.asSource}),this.asSource;this.sqLog("failed-to-compute-source-to-extend","Could not compute source to extend")}isSource(){return!0}}nb.SQExtend=Jrt;var rb={},ib={};Object.defineProperty(ib,"__esModule",{value:!0}),ib.CompositeSource=void 0;const Xrt=Xe,Zrt=Eo;class eit extends Zrt.Source{constructor(e){super({sources:e}),this.sources=e,this.elementType="compositeSource"}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,r){const i=this.sources.map(c=>c.withParameters(e,r)),s=i[0].connection,o=i[0].dialect,u="composite_source",a=[],l=new Map;return this.sources.forEach((c,f)=>{var x;const h=i[f];h.connection!==s&&c.logError("composite-source-connection-mismatch",`All sources in a composite source must share the same connection; connection \`${h.connection}\` differs from previous connection \`${s}\``);for(const p of h.fields){if(!(0,Xrt.isAtomic)(p)){c.logWarning("composite-source-atomic-fields-only",`Only atomic fields are supported in composite sources; field \`${p.name}\` is not atomic and will be ignored`);continue}if(p.accessModifier==="private")continue;const m=(x=p.as)!==null&&x!==void 0?x:p.name,g=l.get(m);if(g===void 0){const y={...p,name:m,as:void 0,e:{node:"compositeField"},compositeFieldUsage:{fields:[m],joinedUsage:{}},code:this.code,location:this.codeLocation};l.set(m,y),a.push(y)}else p.accessModifier==="internal"&&(g.accessModifier="internal")}}),{type:"composite",sources:i,connection:s,fields:a,dialect:o,name:u,parameters:i[0].parameters}}}ib.CompositeSource=eit,Object.defineProperty(rb,"__esModule",{value:!0}),rb.SQCompose=void 0;const tit=ib,nit=hu;class rit extends nit.SourceQueryElement{constructor(e){super({sources:e}),this.sources=e,this.elementType="sq-compose"}getSource(){if(this.asSource)return this.asSource;const e=this.sources.map(r=>r.getSource());if(e.length===0){this.sqLog("empty-composite-source","Composite source must have at least one input source");return}else e.length===1&&this.sqLog("unnecessary-composite-source","A composite source with one input is equivalent to that input",{severity:"warn"});if(iit(e))return this.asSource=new tit.CompositeSource(e),this.has({asSource:this.asSource}),this.asSource;this.sqLog("invalid-composite-source-input","All composite source inputs must be valid sources")}isSource(){return!0}}rb.SQCompose=rit;function iit(t){return t.every(e=>e!==void 0)}var sb={},Kl={},Wy={},sit=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),oit=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),uit=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&sit(e,t,r);return oit(e,t),e};Object.defineProperty(Wy,"__esModule",{value:!0}),Wy.BinaryBoolean=void 0;const ait=Bs,lit=uit(Zt),cit=pu,fit=Gt,xit=ct;class dit extends xit.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="abstract boolean binary",this.legalChildTypes=[lit.boolT]}getExpression(e){const r=this.left.getExpression(e),i=this.right.getExpression(e);return this.typeCheck(this.left,r)&&this.typeCheck(this.right,i)?(0,fit.computedExprValue)({dataType:{type:"boolean"},value:{node:(0,cit.getExprNode)(this.op),kids:{left:r.value,right:i.value}},from:[r,i]}):(0,ait.errorFor)("logical-op expected boolean")}}Wy.BinaryBoolean=dit;var hit=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),pit=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),mit=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&hit(e,t,r);return pit(e,t),e};Object.defineProperty(Kl,"__esModule",{value:!0}),Kl.ExprLegacyIn=Kl.ExprEquality=Kl.ExprCompare=void 0;const fn=mit(Zt),git=Gt,yit=ct,Eit=Wy,Ait={"~":[fn.stringT],"!~":[fn.stringT],"<":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT],"<=":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT],"=":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT],"!=":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT],">=":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT],">":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT]};class Tle extends Eit.BinaryBoolean{constructor(e,r,i){super(e,r,i),this.elementType="a<=>b",this.legalChildTypes=Ait[r]}getExpression(e){return this.right.apply(e,this.op,this.left)}}Kl.ExprCompare=Tle;class _it extends Tle{constructor(e,r,i){super(e,r,i),this.elementType="a~=b"}getExpression(e){return this.right.apply(e,this.op,this.left,!0)}apply(e,r,i){return super.apply(e,r,i,!0)}}Kl.ExprEquality=_it;class vit extends yit.ExpressionDef{constructor(e,r,i){super(),this.expr=e,this.notIn=r,this.choices=i,this.elementType="in",this.has({expr:e,choices:i})}getExpression(e){const r=this.expr.getExpression(e),i=this.choices.map(s=>s.getExpression(e));return(0,git.computedExprValue)({dataType:{type:"boolean"},value:{node:"in",not:this.notIn,kids:{e:r.value,oneOf:i.map(s=>s.value)}},from:[r,...i]})}}Kl.ExprLegacyIn=vit;var Vy={},f2={};Object.defineProperty(f2,"__esModule",{value:!0}),f2.ExprTime=void 0;const Cit=Xe,Sit=Gt,bit=ct;class k$ extends bit.ExpressionDef{constructor(e,r,i){super(),this.elementType="timestampOrDate",this.elementType=e,this.translationValue=(0,Sit.computedExprValue)({dataType:{type:e},value:r,from:i??[]})}getExpression(e){return this.translationValue}static fromValue(e,r){let i=r.value;if(e!==r.type){const s={node:"cast",safe:!1,dstType:{type:e},e:r.value};(0,Cit.isTemporalType)(r.type)&&(s.srcType={type:r.type}),i=s}return new k$(e,i,[r])}}f2.ExprTime=k$;var Ic={};Object.defineProperty(Ic,"__esModule",{value:!0}),Ic.Range=void 0;const Tit=Bs,Rit=Gt,Dit=ct;class Oit extends Dit.ExpressionDef{constructor(e,r){super({first:e,last:r}),this.first=e,this.last=r,this.elementType="range"}apply(e,r,i){switch(r){case"=":case"!=":{const s=r==="="?">=":"<",o=r==="="?"and":"or",u=r==="="?"<":">=",a=this.first.apply(e,s,i),l=this.last.apply(e,u,i);return(0,Rit.computedExprValue)({dataType:{type:"boolean"},value:{node:o,kids:{left:a.value,right:l.value}},from:[a,l]})}case">":return this.last.apply(e,">=",i);case">=":return this.first.apply(e,">=",i);case"<":return this.first.apply(e,"<",i);case"<=":return this.last.apply(e,"<",i)}throw new Error("mysterious error in range computation")}requestExpression(e){}getExpression(e){return this.logError("range-as-value","A Range is not a value"),(0,Tit.errorFor)("a range is not a value")}}Ic.Range=Oit;var Fit=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),wit=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Nit=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Fit(e,t,r);return wit(e,t),e};Object.defineProperty(Vy,"__esModule",{value:!0}),Vy.ExprGranularTime=void 0;const M$=Xe,Lit=Bs,Rle=Nit(Zt),Dle=ds,Iit=ct,ob=f2,Ole=Ic;class Bit extends Iit.ExpressionDef{constructor(e,r,i){super({expr:e}),this.expr=e,this.units=r,this.truncate=i,this.elementType="granularTime",this.legalChildTypes=[Rle.timestampT,Rle.dateT]}granular(){return!0}getExpression(e){const r=this.units,i=this.expr.getExpression(e);if(M$.TD.isTemporal(i)){const o={...i,timeframe:r};return this.truncate&&(o.value={node:"trunc",e:(0,M$.mkTemporal)(i.value,i.type),units:r}),o}i.type!=="error"&&this.logError("unsupported-type-for-time-truncation",`Cannot do time truncation on type '${i.type}'`);const s={...i};return i.type==="error"&&(s.type=(0,M$.isDateUnit)(r)?"date":"timestamp"),{...s,value:(0,Lit.errorFor)("granularity typecheck").value,evalSpace:"constant"}}toRange(e){const r=this.getExpression(e),i={node:"numberLiteral",literal:"1"};if(r.type==="timestamp"){const a=ob.ExprTime.fromValue("timestamp",r),l=new ob.ExprTime("timestamp",(0,Dle.timeOffset)("timestamp",r.value,"+",i,this.units),[r]);return new Ole.Range(a,l)}const s=new ob.ExprTime("date",r.value,[r]),o=(0,Dle.timeOffset)("date",r.value,"+",i,this.units),u=new ob.ExprTime("date",o,[r]);return new Ole.Range(s,u)}}Vy.ExprGranularTime=Bit,Object.defineProperty(sb,"__esModule",{value:!0}),sb.Apply=void 0;const $it=Kl,kit=c2,Fle=Vy;class Mit extends $it.ExprCompare{constructor(e,r){super(e,"=",r),this.left=e,this.right=r,this.elementType="apply"}getExpression(e){let r=this.right;if(!this.right.granular()){const i=this.right.requestExpression(e);i&&(0,kit.isGranularResult)(i)&&(r=new Fle.ExprGranularTime(this.right,i.timeframe,!1))}return r instanceof Fle.ExprGranularTime?r.toRange(e).apply(e,this.op,this.left):super.getExpression(e)}}sb.Apply=Mit;var x2={},Pit=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Uit=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),jit=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Pit(e,t,r);return Uit(e,t),e};Object.defineProperty(x2,"__esModule",{value:!0}),x2.BinaryNumeric=void 0;const qit=jit(Zt),Hit=ct;class Qit extends Hit.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="numeric binary abstract",this.legalChildTypes=[qit.numberT]}getExpression(e){return this.right.apply(e,this.op,this.left)}}x2.BinaryNumeric=Qit;var ub={},zit=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Git=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Wit=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&zit(e,t,r);return Git(e,t),e};Object.defineProperty(ub,"__esModule",{value:!0}),ub.Boolean=void 0;const Vit=ct,Yit=Wit(Zt);let Kit=class extends Vit.ExpressionDef{constructor(e){super(),this.value=e,this.elementType="boolean literal"}getExpression(){return{...Yit.boolT,value:{node:this.value}}}};ub.Boolean=Kit;var d2={};Object.defineProperty(d2,"__esModule",{value:!0}),d2.ConstantExpression=d2.ConstantFieldSpace=void 0;const Jit=ct;class wle{constructor(){this.type="fieldSpace"}structDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}emptyStructDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}lookup(e){return{error:{message:"Only constants allowed in parameter default values",code:"illegal-reference-in-parameter-default"},found:void 0}}entries(){return[]}entry(){}dialectName(){return"~constant-space-unknown-dialect~"}dialectObj(){}isQueryFieldSpace(){return!1}isProtectedAccessSpace(){return!1}}d2.ConstantFieldSpace=wle;class Xit extends Jit.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="constantExpression"}getExpression(e){return this.constantValue()}get constantFs(){return this.cfs||(this.cfs=new wle),this.cfs}constantValue(){return this.expr.getExpression(this.constantFs)}apply(e,r,i){return this.expr.apply(e,r,i)}requestExpression(e){return this.expr.requestExpression(e)}}d2.ConstantExpression=Xit;var Bc={};Object.defineProperty(Bc,"__esModule",{value:!0}),Bc.FunctionOrdering=Bc.FunctionOrderBy=void 0;const P$=Xe,Nle=Je,Zit=ed;class est extends Nle.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e&&this.has({field:e})}getAnalyticOrderBy(e){if(!this.field)return this.logError("analytic-order-by-missing-field","analytic `order_by` must specify an aggregate expression or output field reference"),{node:"functionOrderBy",e:{node:"error"},dir:this.dir};const r=this.field.getExpression(e);return(0,P$.expressionIsAggregate)(r.expressionType)||((0,P$.expressionIsScalar)(r.expressionType)?(!(this.field instanceof Zit.ExprIdReference)||r.evalSpace==="input")&&this.field.logError("analytic-order-by-not-output","analytic `order_by` must be an aggregate or an output field reference"):this.field.logError("analytic-order-by-not-aggregate-or-output","analytic `order_by` must be scalar or aggregate")),{node:"functionOrderBy",e:r.value,dir:this.dir}}getAggregateOrderBy(e,r){if(this.field){const i=this.field.getExpression(e);return(0,P$.expressionIsScalar)(i.expressionType)||this.field.logError("aggregate-order-by-not-scalar","aggregate `order_by` must be scalar"),r||this.field.logError("aggregate-order-by-expression-not-allowed","`order_by` must be only `asc` or `desc` with no expression"),{node:"functionOrderBy",e:i.value,dir:this.dir}}else return this.dir===void 0?(this.logError("aggregate-order-by-without-field-or-direction","field or order direction must be specified"),{node:"functionDefaultOrderBy",dir:"asc"}):{node:"functionDefaultOrderBy",dir:this.dir}}}Bc.FunctionOrderBy=est;class tst extends Nle.ListOf{constructor(e){super(e),this.elementType="function-ordering"}getAnalyticOrderBy(e){return this.list.map(r=>r.getAnalyticOrderBy(e))}getAggregateOrderBy(e,r){return this.list.map(i=>i.getAggregateOrderBy(e,r))}}Bc.FunctionOrdering=tst;var ab={};Object.defineProperty(ab,"__esModule",{value:!0}),ab.ExprAddSub=void 0;const nst=x2;class rst extends nst.BinaryNumeric{constructor(){super(...arguments),this.elementType="+-"}}ab.ExprAddSub=rst;var Jl={},ist=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),sst=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),ost=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&ist(e,t,r);return sst(e,t),e};Object.defineProperty(Jl,"__esModule",{value:!0}),Jl.ExprAggregateFunction=void 0;const Yy=Xe,ust=Bt,ast=Bs,Lle=Pr,Ile=ost(Zt),lst=yt,cst=ct,fst=Mr,xst=ed;class dst extends cst.ExpressionDef{constructor(e,r,i){super(),this.func=e,this.legalChildTypes=[Ile.numberT],this.elementType=e,this.explicitSource=i,r&&(this.expr=r,this.has({expr:r}))}getExpression(e){var r,i,s;const o=e.isQueryFieldSpace()?e.inputSpace():e;let u=this.expr,a=(r=this.expr)===null||r===void 0?void 0:r.getExpression(o),l=(i=this.source)===null||i===void 0?void 0:i.path,c=[];if(this.source){const x=this.source.getField(o);if(x.found){c=x.joinPath;const h=x.found,p=h.typeDesc();if(!(h instanceof Lle.StructSpaceField))if((0,Yy.isAtomicFieldType)(p.type)){u=this.source,a={...Ile.atomicDef(p),expressionType:p.expressionType,value:p.evalSpace==="output"?{node:"outputField",name:this.source.refString}:{node:"field",path:this.source.path},evalSpace:p.evalSpace,compositeFieldUsage:p.compositeFieldUsage},l=this.source.path.slice(0,-1);const m=this.getJoinUsage(o);(m.length===1||m.length>1&&m.slice(1).every(y=>hst(y,m[0])))&&(l=m[0].map(y=>y.name),c=m[0])}else return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${p.type}`)}else return this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}if(a===void 0)return this.loggedErrorExpr("missing-aggregate-expression","Missing expression for aggregate function");if((0,Yy.expressionIsAggregate)(a.expressionType))return this.loggedErrorExpr("aggregate-of-aggregate","Aggregate expression cannot be aggregate");if(!(a.type==="error")){const x=this.getJoinUsage(o),h=this.source!==void 0||this.explicitSource;if(u&&!(!this.source&&x.every(m=>m.length===0))&&!this.isSymmetricFunction()){const m=j$(c,x),g=q$(this.elementType,m),y=h?g==null?void 0:g.message:"Join path is required for this calculation";if(y){const E=pst(y,x,u,this.elementType),A=(s=g==null?void 0:g.code)!==null&&s!==void 0?s:"bad-join-usage";g?this.logError(A,E):this.logWarning(A,E)}}}if(this.typeCheck(this.expr||this,{...a,expressionType:"scalar"})){const x={node:"aggregate",function:this.func,e:a.value};return l&&l.length>0&&(x.structPath=l),{...this.returns(a),expressionType:"aggregate",value:x,evalSpace:"output"}}return(0,ast.errorFor)("aggregate type check")}isSymmetricFunction(){return!0}getJoinUsage(e){const r=[];if(this.source&&this.source.getField(e).found){const s={node:"field",path:this.source.path};r.push(...U$(e,s))}if(this.expr){const i=this.expr.getExpression(e).value;r.push(...U$(e,i))}return r}}Jl.ExprAggregateFunction=dst;function hst(t,e){let r=t.length;if(r!==e.length)return!1;for(;r>0;)if(r-=1,t[r].name!==e[r].name)return!1;return!0}function U$(t,e){const r=[],i=(s,o)=>{const u=o[0],a=o.slice(1),l=s.entry(u);if(l===void 0)throw new Error(`Invalid field lookup ${u}`);if(l instanceof Lle.StructSpaceField&&a.length>0){const c=i(l.fieldSpace,a);return{...c,joinPath:[{...l.joinPathElement,name:u},...c.joinPath]}}else if(l instanceof fst.SpaceField){if(a.length!==0)throw new Error(`${u} cannot contain a ${a.join(".")}`);const c=l.fieldDef();if(c)return{fs:s,def:c,joinPath:[]};throw new Error("No field def")}else throw new Error("expected a field def or struct")};for(const s of(0,ust.exprWalk)(e))if(s.node==="field"){const o=i(t,s.path),u=o.def;if((0,Yy.isAtomic)(u)&&!(0,Yy.isJoined)(u))if((0,Yy.hasExpression)(u)){const a=U$(o.fs,u.e);r.push(...a.map(l=>[...o.joinPath,...l]))}else r.push(o.joinPath)}else if(s.node==="source-reference")if(s.path){const o=i(t,s.path);r.push(o.joinPath)}else r.push([]);return r}function j$(t,e){const r=[];for(const i of e){let s=0;for(let l=0;l<t.length&&l<i.length&&t[l].name===i[l].name;l++)s=l+1;const o=t.slice(s),u=i.slice(s),a=[...o.map(l=>({...l,reverse:!0})),...u.map(l=>({...l,reverse:!1}))];r.push(a)}return r}function q$(t,e){for(const r of e)for(const i of r){if(i.joinType==="cross")return{code:"aggregate-traverses-join-cross",message:`Cannot compute \`${t}\` across \`join_cross\` relationship \`${i.name}\``};if(i.joinElementType==="array"&&!i.reverse)return{code:"aggregate-traverses-repeated-relationship",message:`Cannot compute \`${t}\` across repeated relationship \`${i.name}\``};if(i.joinType==="many"&&!i.reverse)return{code:"aggregate-traverses-join-many",message:`Cannot compute \`${t}\` across \`join_many\` relationship \`${i.name}\``}}}function pst(t,e,r,i){if(e.length===0)return t;let s=e[0];for(const m of e.slice(1))for(let g=0;g<s.length;g++){const y=s[g],E=m[g];if(y.name!==E.name){s=s.slice(0,g);break}}const o=j$(s,e),u=q$(i,o),a=s.slice().reverse().findIndex(m=>m.joinType==="many"||m.joinType==="cross"),l=a===-1?0:s.length-a,c=s.slice(0,l),f=j$(c,e),x=q$(i,f),h=s.length>0?s.map(m=>m.name).join("."):"source",p=c.length>0?c.map(m=>m.name).join("."):"source";if(u)return"Aggregated dimensional expression contains multiple join paths; rewrite, for example `sum(first_join.field + second_join.field)` as `first_join.field.sum() + second_join.field.sum()`";{const m=r instanceof lst.FieldReference?`${r.refString}.${i}()`:r instanceof xst.ExprIdReference?`${r.fieldReference.refString}.${i}()`:`${h}.${i}(${r.code})`,g=`${p}.${i}(${r.code})`;let y=`${t}; use \`${m}\``;return x===void 0&&p!==h&&(y+=` or \`${g}\` to get a result weighted with respect to \`${p}\``),y}}var lb={};Object.defineProperty(lb,"__esModule",{value:!0}),lb.ExprAlternationTree=void 0;const Ble=Gt,h2=ct,mst=pu;function H$(t){const e=t.atExpr();switch(e.atNodeType()){case h2.ATNodeType.And:case h2.ATNodeType.Partial:return;case h2.ATNodeType.Or:{if(e instanceof $le){const r=H$(e.left);if(r){const i=H$(e.right);if(i)return[...r,...i]}}return}default:return e.granular()?void 0:[e]}}class $le extends h2.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="alternation",this.elementType=`${r}alternation${r}`}equalityList(){return this.inList===void 0&&(this.inList=H$(this)||[]),this.inList}apply(e,r,i,s){if((0,mst.isEquality)(r)){const a=this.equalityList();if(a.length>0&&(r==="="||r==="!=")){const l=i.getExpression(e),c=a.map(f=>f.getExpression(e));return(0,Ble.computedExprValue)({dataType:{type:"boolean"},value:{node:"in",not:r==="!=",kids:{e:l.value,oneOf:c.map(f=>f.value)}},from:[l,...c]})}a.length===0&&s&&this.logWarning("or-choices-only",`Only | seperated values are legal when used with ${r} operator`)}const o=this.left.apply(e,r,i),u=this.right.apply(e,r,i);return(0,Ble.computedExprValue)({dataType:{type:"boolean"},value:{node:this.op==="&"?"and":"or",kids:{left:o.value,right:u.value}},from:[o,u]})}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("alternation-as-value","Alternation tree has no value")}atNodeType(){return this.op==="|"?h2.ATNodeType.Or:h2.ATNodeType.And}}lb.ExprAlternationTree=$le;var p2={};Object.defineProperty(p2,"__esModule",{value:!0}),p2.ExprAsymmetric=void 0;const gst=Jl;class yst extends gst.ExprAggregateFunction{constructor(e,r,i,s){super(e,r,s),this.func=e,this.expr=r,this.source=i,this.has({source:i})}isSymmetricFunction(){return!1}returns(e){return e}defaultFieldName(){if(this.source&&this.expr===void 0){const e=this.source.nameString;switch(this.func){case"sum":return`total_${e}`;case"avg":return`avg_${e}`}}}}p2.ExprAsymmetric=yst;var cb={};Object.defineProperty(cb,"__esModule",{value:!0}),cb.ExprAvg=void 0;const Est=p2;class Ast extends Est.ExprAsymmetric{constructor(e,r,i){super("avg",e,r,i),this.has({source:r})}}cb.ExprAvg=Ast;var fb={};Object.defineProperty(fb,"__esModule",{value:!0}),fb.ExprCast=void 0;const _st=ds,vst=Gt,Cst=ct;class Sst extends Cst.ExpressionDef{constructor(e,r,i=!1){super({expr:e}),this.expr=e,this.castType=r,this.safe=i,this.elementType="cast"}getExpression(e){const r=this.expr.getExpression(e);let i={type:"error"};if(typeof this.castType=="string")i={type:this.castType};else{const s=e.dialectObj();s&&(s.validateTypeName(this.castType.raw)?i=s.sqlTypeToMalloyType(this.castType.raw):this.logError("invalid-sql-native-type",`Cast type \`${this.castType.raw}\` is invalid for ${s.name} dialect`),this.safe&&!s.supportsSafeCast&&this.logError("dialect-cast-unsafe-only",`The SQL dialect '${e.dialectName()}' does not supply a safe cast operator`))}return(0,vst.computedExprValue)({dataType:i,value:(0,_st.castTo)(this.castType,r.value,r.type,this.safe),from:[r]})}}fb.ExprCast=Sst;var xb={},bst=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Tst=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Rst=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&bst(e,t,r);return Tst(e,t),e};Object.defineProperty(xb,"__esModule",{value:!0}),xb.ExprCoalesce=void 0;const kle=Pi,Mle=Rst(Zt),Dst=ct;class Ost extends Dst.ExpressionDef{constructor(e,r){super({expr:e,altExpr:r}),this.expr=e,this.altExpr=r,this.elementType="coalesce expression",this.legalChildTypes=Mle.anyAtomicT}getExpression(e){const r=this.expr.getExpression(e),i=this.altExpr.getExpression(e);return r.type==="null"?i:(Mle.typeEq(r,i)||this.logError("mismatched-coalesce-types",`Mismatched types for coalesce (${r.type}, ${i.type})`),{...r.type==="error"?i:r,expressionType:(0,kle.maxExpressionType)(r.expressionType,i.expressionType),value:{node:"coalesce",kids:{left:r.value,right:i.value}},evalSpace:(0,kle.mergeEvalSpaces)(r.evalSpace,i.evalSpace)})}}xb.ExprCoalesce=Ost;var db={};Object.defineProperty(db,"__esModule",{value:!0}),db.ExprCount=void 0;const Fst=lt,wst=Jl;class Nst extends wst.ExprAggregateFunction{constructor(e){super("count"),this.source=e,this.elementType="count",this.has({source:e})}defaultFieldName(){if(this.source)return"count_"+this.source.nameString}returns(e){return{type:"number",numberType:"integer",evalSpace:e.evalSpace,expressionType:"aggregate",value:e.value,compositeFieldUsage:e.compositeFieldUsage}}getExpression(e){const r={node:"aggregate",function:"count",e:{node:""}};return this.source&&(r.structPath=this.source.path),{type:"number",numberType:"integer",expressionType:"aggregate",value:r,evalSpace:"output",compositeFieldUsage:(0,Fst.emptyCompositeFieldUsage)()}}}db.ExprCount=Nst;var hb={},Lst=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Ist=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Bst=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Lst(e,t,r);return Ist(e,t),e};Object.defineProperty(hb,"__esModule",{value:!0}),hb.ExprCountDistinct=void 0;const pb=Bst(Zt),$st=Jl;class kst extends $st.ExprAggregateFunction{constructor(e){super("distinct",e),this.legalChildTypes=[pb.numberT,pb.stringT,pb.dateT,pb.timestampT]}returns(e){return{type:"number",numberType:"integer",evalSpace:e.evalSpace,expressionType:"aggregate",value:e.value,compositeFieldUsage:e.compositeFieldUsage}}}hb.ExprCountDistinct=kst;var mb={},$c={};Object.defineProperty($c,"__esModule",{value:!0}),$c.Limit=void 0;const Mst=Je,Pst=jn;class Ust extends Mst.MalloyElement{constructor(e){super(),this.limit=e,this.elementType="limit",this.queryRefinementStage=Pst.LegalRefinementStage.Tail,this.forceQueryClass=void 0}}$c.Limit=Ust;var m2={};Object.defineProperty(m2,"__esModule",{value:!0}),m2.PartitionBy=void 0;const jst=Je;class qst extends jst.ListOf{constructor(e){super(e),this.partitionFields=e,this.elementType="partition_by"}}m2.PartitionBy=qst;var Ky={},kc={};Object.defineProperty(kc,"__esModule",{value:!0}),kc.FieldName=void 0;const Hst=Je;class Qst extends Hst.MalloyElement{constructor(e){super(),this.name=e,this.elementType="fieldName"}get refString(){return this.name}toString(){return this.refString}getField(e){return e.lookup([this])}}kc.FieldName=Qst;var zst=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Gst=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Wst=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&zst(e,t,r);return Gst(e,t),e};Object.defineProperty(Ky,"__esModule",{value:!0}),Ky.ExprFunc=void 0;const Cr=Xe,Vst=Bs,Yst=Xx,Kst=Gt,Jst=ct,Xst=kc,Ple=Bt,Ule=Wst(Zt),Zst=lt;class eot extends Jst.ExpressionDef{constructor(e,r,i,s,o){super({args:r}),this.name=e,this.args=r,this.isRaw=i,this.rawType=s,this.source=o,this.elementType="function call()",this.has({source:o})}canSupportPartitionBy(){return!0}canSupportOrderBy(){return!0}canSupportLimit(){return!0}getExpression(e){return this.getPropsExpression(e)}findFunctionDef(e){var r,i,s;const o=this.name.toLowerCase(),u=e?(i=(r=this.getDialectNamespace(e))===null||r===void 0?void 0:r.getEntry(o))===null||i===void 0?void 0:i.entry:void 0,a=u??((s=this.modelEntry(o))===null||s===void 0?void 0:s.entry);return a===void 0?(this.logError("function-not-found",`Unknown function '${this.name}'. Use '${this.name}!(...)' to call a SQL function directly.`),{found:void 0,error:"unknown function"}):a.type!=="function"?(this.logError("call-of-non-function",`'${this.name}' (with type ${a.type}) is not a function`),{found:void 0,error:"called non function"}):(a.name!==this.name&&this.logWarning("case-insensitive-function",`Case insensitivity for function names is deprecated, use '${a.name}' instead`),{found:a,error:void 0})}getPropsExpression(e,r){var i,s,o,u;const a=this.args.map(B=>B.getExpression(e));if(this.isRaw){const B=[`${this.name}(`];a.forEach((q,Y)=>{Y!==0&&B.push(","),B.push(q.value)}),B.push(")");const D=(i=a[0])!==null&&i!==void 0?i:{type:"number"},k=this.rawType?{type:this.rawType}:D;return(0,Kst.computedExprValue)({dataType:k,value:(0,Ple.composeSQLExpr)(B),from:a})}const l=(s=e.dialectObj())===null||s===void 0?void 0:s.name,{found:c,error:f}=this.findFunctionDef(l);if(c===void 0)return(0,Vst.errorFor)(f);let x,h=(o=this.source)===null||o===void 0?void 0:o.path;if(this.source){const D=this.source.getField(e).found;if(D){const k=D.typeDesc();if((0,Cr.isAtomicFieldType)(k.type))x={...Ule.atomicDef(k),expressionType:k.expressionType,value:{node:"field",path:this.source.path},evalSpace:k.evalSpace,compositeFieldUsage:k.compositeFieldUsage},h=this.source.path.slice(0,-1);else if(!(D instanceof Yst.StructSpaceFieldBase))return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${k.type}`)}else this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}const p=[...x?[x]:[],...a],m=tot(c,p);if(m===void 0)return this.loggedErrorExpr("no-matching-function-overload",`No matching overload for function ${this.name}(${p.map(B=>B.type).join(", ")})`);const{overload:g,expressionTypeErrors:y,evalSpaceErrors:E,nullabilityErrors:A,returnType:_}=m;for(const B of y){const D=B.argIndex-(x?1:0),k=(0,Cr.expressionIsScalar)(B.maxExpressionType)?"scalar":"scalar or aggregate";this.args[D].logError("invalid-function-argument-expression-type",`Parameter ${B.argIndex+1} ('${B.param.name}') of ${this.name} must be ${k}, but received ${B.actualExpressionType}`)}for(const B of E){const D=B.argIndex-(x?1:0),k=B.maxEvalSpace==="literal"?"literal":B.maxEvalSpace==="constant"?"literal or constant":"literal, constant or output";this.args[D].logError("invalid-function-argument-evaluation-space",`Parameter ${B.argIndex+1} ('${B.param.name}') of ${this.name} must be ${k}, but received ${B.actualEvalSpace}`)}for(const B of A){const D=B.argIndex-(x?1:0);this.args[D].logError("literal-null-function-argument",`Parameter ${B.argIndex+1} ('${B.param.name}') of ${this.name} must not be a literal null`)}m.returnTypeError&&this.logError(m.returnTypeError.code,m.returnTypeError.parameters);const v=g.returnType,C=(0,Cr.maxOfExpressionTypes)([(u=v.expressionType)!==null&&u!==void 0?u:"scalar",...p.map(B=>B.expressionType)]);if(!(0,Cr.expressionIsAggregate)(g.returnType.expressionType)&&this.source!==void 0)return this.loggedErrorExpr("non-aggregate-function-with-source",`Cannot call function ${this.name}(${p.map(B=>B.type).join(", ")}) with source`);const b={node:"function_call",overload:g,name:this.name,kids:{args:p.map(B=>B.value)},expressionType:C,structPath:h};let S=b;if(r!=null&&r.orderBys&&r.orderBys.length>0){const B=(0,Cr.expressionIsAnalytic)(g.returnType.expressionType);if(B||this.inExperiment("aggregate_order_by",!0)||r.orderBys[0].logError("aggregate-order-by-experiment-not-enabled","Enable experiment `aggregate_order_by` to use `order_by` with an aggregate function"),g.supportsOrderBy||B){const D=g.supportsOrderBy!=="only_default",k=r.orderBys.flatMap(q=>B?q.getAnalyticOrderBy(e):q.getAggregateOrderBy(e,D));b.kids.orderBy=k}else r.orderBys[0].logError("function-does-not-support-order-by",`Function \`${this.name}\` does not support \`order_by\``)}if((r==null?void 0:r.limit)!==void 0&&(g.supportsLimit?b.limit=r.limit.limit:this.logError("function-does-not-support-limit",`Function ${this.name} does not support limit`)),r!=null&&r.partitionBys&&r.partitionBys.length>0){const B=[];for(const D of r.partitionBys)for(const k of D.partitionFields){const q=k.getField(e);q.found===void 0?k.logError("partition-by-not-found",`${k.refString} is not defined`):(0,Cr.expressionIsAnalytic)(q.found.typeDesc().expressionType)||(0,Cr.expressionIsUngroupedAggregate)(q.found.typeDesc().expressionType)?k.logError("non-scalar-or-aggregate-partition-by","Partition expression must be scalar or aggregate"):B.push(k.nameString)}b.partitionBy=B}if(["sql_number","sql_string","sql_date","sql_timestamp","sql_boolean"].includes(c.name)){if(!this.inExperiment("sql_functions",!0))return this.loggedErrorExpr("sql-functions-experiment-not-enabled",`Cannot use sql_function \`${c.name}\`; use \`sql_functions\` experiment to enable this behavior`);const B=p[0].value;if(B.node!=="stringLiteral")this.logError("invalid-sql-function-argument",`Invalid string literal for \`${c.name}\``);else{const D=B.literal,k=not(D),q=k.filter(Q=>Q.type==="interpolation"&&Q.name.includes(".")).map(Q=>Q.type==="interpolation"?`\${${Q.name}}`:`\${${Q.value}}`);if(q.length>0){const Q=q.length===1?`'.' paths are not yet supported in sql interpolations, found ${q.at(0)}`:`'.' paths are not yet supported in sql interpolations, found (${q.join(", ")})`;return this.loggedErrorExpr("unsupported-sql-function-interpolation",Q)}const Y=[];for(const Q of k)if(Q.type==="string")Y.push(Q.value);else if(Q.name==="TABLE")Y.push({node:"source-reference"});else{const X=new Xst.FieldName(Q.name);this.has({name:X});const ce=e.lookup([X]);if(ce.found===void 0)return this.loggedErrorExpr("sql-function-interpolation-not-found",`Invalid interpolation: ${ce.error.message}`);if(ce.found.typeDesc().type==="filter expression")return this.loggedErrorExpr("filter-expression-error","Filter expressions cannot be used in sql_ functions");ce.found.refType==="parameter"?Y.push({node:"parameter",path:[Q.name]}):Y.push({node:"field",path:[Q.name]})}S=(0,Ple.composeSQLExpr)(Y)}}const R=(0,Cr.mergeEvalSpaces)(...p.map(B=>B.evalSpace)),O=R==="constant"?"constant":(0,Cr.expressionIsScalar)(C)?R:"output";return{...(0,Cr.isAtomic)(_)?Ule.atomicDef(_):_,expressionType:C,value:S,evalSpace:O,compositeFieldUsage:(0,Zst.mergeCompositeFieldUsage)(...p.map(B=>B.compositeFieldUsage))}}}Ky.ExprFunc=eot;function tot(t,e){var r;for(const i of t.overloads){const s=new Map;let o=0,u=!0,a=!1;const l=[],c=[],f=[];for(let p=0;p<e.length;p++){const m=e[p],g=i.params[o];if(g===void 0){u=!1;break}if(!g.allowedTypes.some(E=>{var A;const{dataTypeMatch:_,genericsSet:v}=g2(s,(A=i.genericTypes)!==null&&A!==void 0?A:[],m,E);for(const C of v)s.set(C.name,C.type);return E.expressionType&&((0,Cr.isExpressionTypeLEQ)(m.expressionType,E.expressionType)||l.push({argIndex:p,maxExpressionType:E.expressionType,actualExpressionType:m.expressionType,param:g})),(E.evalSpace==="literal"&&m.evalSpace!=="literal"||E.evalSpace==="constant"&&(m.evalSpace==="input"||m.evalSpace==="output")||(0,Cr.expressionIsAnalytic)(i.returnType.expressionType)&&m.evalSpace==="input")&&c.push({argIndex:p,param:g,maxEvalSpace:E.evalSpace,actualEvalSpace:m.evalSpace}),E.evalSpace==="literal"&&m.type==="null"&&f.push({argIndex:p,param:g}),_})){u=!1;break}g.isVariadic?p===e.length-1&&(a=!0):o++}if(!a&&(o!==e.length||o!==i.params.length))continue;const x=gb(i.returnType,s),h=(r=x.returnType)!==null&&r!==void 0?r:{type:"number"};if(u)return{overload:i,expressionTypeErrors:l,evalSpaceErrors:c,nullabilityErrors:f,returnTypeError:x.error,returnType:h}}}function not(t){const e=[];let r=t;for(;r.length;){const i=r.indexOf("${");if(i===-1){e.push({type:"string",value:r});break}else{const s=r.slice(i).indexOf("}");if(s===-1){e.push({type:"string",value:r});break}i>0&&e.push({type:"string",value:r.slice(0,i)}),e.push({type:"interpolation",name:r.slice(i+2,s+i)}),r=r.slice(s+i+1)}}return e}function g2(t,e,r,i){var s,o,u,a;if(Cr.TD.eq(i,r)||i.type==="any"||i.type!=="generic"&&(r.type==="null"||r.type==="error"))return{dataTypeMatch:!0,genericsSet:[]};if(i.type==="array"&&r.type==="array"){if((0,Cr.isBasicArray)(r))return(0,Cr.isRepeatedRecordFunctionParam)(i)?{dataTypeMatch:!1,genericsSet:[]}:g2(t,e,r.elementTypeDef,i.elementTypeDef);if((0,Cr.isRepeatedRecordFunctionParam)(i)){const l={type:"record",fields:i.fields},c={type:"record",fields:r.fields};return g2(t,e,c,l)}else return{dataTypeMatch:!1,genericsSet:[]}}else if(i.type==="record"&&r.type==="record"){const l=[],c=new Map;for(const f of i.fields)c.set((s=f.as)!==null&&s!==void 0?s:f.name,f);for(const f of r.fields){const x=c.get((o=f.as)!==null&&o!==void 0?o:f.name);if(x===void 0)return{dataTypeMatch:!1,genericsSet:[]};const h=g2(new Map([...t.entries(),...l.map(p=>[p.name,p.type])]),e,f,x);l.push(...h.genericsSet)}return{dataTypeMatch:!0,genericsSet:l}}else if(i.type==="generic"){const l=t.get(i.generic);if(l!==void 0&&l.type!=="null"&&l.type!=="error")return g2(t,e,r,l);const c=(a=(u=e.find(f=>f.name===i.generic))===null||u===void 0?void 0:u.acceptibleTypes)!==null&&a!==void 0?a:[];for(const f of c){const x=g2(t,e,r,f);if(x.dataTypeMatch){if(!(0,Cr.isAtomic)(r)&&r.type!=="null")continue;const h={name:i.generic,type:r};return{dataTypeMatch:!0,genericsSet:[...x.genericsSet,h]}}}}return{dataTypeMatch:!1,genericsSet:[]}}function gb(t,e){switch(t.type){case"array":{if("fields"in t){const s=t.fields.map(o=>{const u=gb(o,e);return{...o,...u}});return{error:void 0,returnType:{type:"array",elementTypeDef:t.elementTypeDef,fields:s}}}const r=gb(t.elementTypeDef,e);if(r.error)return r;const i=r.returnType;return i.type==="record"?{error:void 0,returnType:{type:"array",elementTypeDef:{type:"record_element"},fields:i.fields}}:(0,Cr.isAtomic)(i)?{error:void 0,returnType:{type:"array",elementTypeDef:i}}:{error:{code:"invalid-resolved-type-for-array",parameters:"Invalid resolved type for array; cannot be non-atomic"},returnType:void 0}}case"record":return{error:void 0,returnType:{type:"record",fields:t.fields.map(i=>{const s=gb(i,e);return{...i,...s}})}};case"generic":{const r=e.get(t.generic);return r===void 0?{error:{code:"generic-not-resolved",parameters:`Generic ${t.generic} in return type could not be resolved`},returnType:void 0}:{error:void 0,returnType:r}}default:return{error:void 0,returnType:t}}}var rot=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),iot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),sot=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&rot(e,t,r);return iot(e,t),e};Object.defineProperty(mb,"__esModule",{value:!0}),mb.ExprProps=void 0;const oot=Xe,uot=Bs,aot=sot(Zt),lot=Bc,cot=$c,fot=m2,xot=ct,dot=Ky,hot=lt;class pot extends xot.ExpressionDef{constructor(e,r){super({expr:e,statements:r}),this.expr=e,this.statements=r,this.elementType="expression with props",this.legalChildTypes=aot.anyAtomicT}getFilteredExpression(e,r,i){if(i.length>0){if(!this.expr.supportsWhere(r))return this.expr.logError("filter-of-non-aggregate","Filtered expression requires an aggregate computation"),r;const s=[];for(const o of i){const u=o.getFilterList(e);if(u.find(a=>(0,oot.expressionIsCalculation)(a.expressionType)))return o.logError("aggregate-filter-expression-not-scalar","Cannot filter an expresion with an aggregate or analytical computation"),r;s.push(...u)}return this.typeCheck(this.expr,{...r,expressionType:"scalar"})?{...r,compositeFieldUsage:(0,hot.mergeCompositeFieldUsage)(r.compositeFieldUsage,...s.map(o=>o.compositeFieldUsage)),value:{node:"filteredExpr",kids:{e:r.value,filterList:s}}}:(this.expr.logError("filter-of-non-aggregate",`Cannot filter '${r.expressionType}' data`),(0,uot.errorFor)("cannot filter type"))}return r}getExpression(e){const r=[];let i;const s=[],o=[];for(const a of this.statements)a instanceof fot.PartitionBy?this.expr.canSupportPartitionBy()?r.push(a):a.logError("partition-by-of-non-window-function","`partition_by` is not supported for this kind of expression"):a instanceof cot.Limit?i?a.logError("expression-limit-already-specified","limit already specified"):this.expr.canSupportLimit()?i=a:a.logError("limit-of-non-aggregate-function","`limit` is not supported for this kind of expression"):a instanceof lot.FunctionOrdering?this.expr.canSupportOrderBy()?s.push(a):a.logError("order-by-of-non-aggregate-function","`order_by` is not supported for this kind of expression"):o.push(a);const u=this.expr instanceof dot.ExprFunc?this.expr.getPropsExpression(e,{partitionBys:r,limit:i,orderBys:s}):this.expr.getExpression(e);return this.getFilteredExpression(e,u,o)}}mb.ExprProps=pot;var yb={},mot=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),got=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),yot=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&mot(e,t,r);return got(e,t),e};Object.defineProperty(yb,"__esModule",{value:!0}),yb.ExprLogicalOp=void 0;const Eot=Wy,jle=yot(Zt);class Aot extends Eot.BinaryBoolean{constructor(){super(...arguments),this.elementType="logical operator",this.legalChildTypes=[jle.boolT,jle.aggregateBoolT]}}yb.ExprLogicalOp=Aot;var Eb={},_ot=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),vot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Cot=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&_ot(e,t,r);return vot(e,t),e};Object.defineProperty(Eb,"__esModule",{value:!0}),Eb.ExprMax=void 0;const Ab=Cot(Zt),Sot=Jl;class bot extends Sot.ExprAggregateFunction{constructor(e){super("max",e),this.legalChildTypes=[Ab.numberT,Ab.stringT,Ab.dateT,Ab.timestampT]}returns(e){return e}}Eb.ExprMax=bot;var _b={},Tot=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Rot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Dot=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Tot(e,t,r);return Rot(e,t),e};Object.defineProperty(_b,"__esModule",{value:!0}),_b.ExprMin=void 0;const vb=Dot(Zt),Oot=Jl;class Fot extends Oot.ExprAggregateFunction{constructor(e){super("min",e),this.legalChildTypes=[vb.numberT,vb.stringT,vb.dateT,vb.timestampT]}returns(e){return e}}_b.ExprMin=Fot;var Cb={},wot=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Not=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Lot=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&wot(e,t,r);return Not(e,t),e};Object.defineProperty(Cb,"__esModule",{value:!0}),Cb.ExprMinus=void 0;const Iot=Bs,qle=Lot(Zt),Bot=ct;class $ot extends Bot.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="unary minus",this.legalChildTypes=[qle.numberT]}getExpression(e){const r=this.expr.getExpression(e);return qle.typeIn(r,this.legalChildTypes)?{...r,type:"number",value:{node:"unary-",e:r.value}}:(0,Iot.errorFor)("negate requires number")}}Cb.ExprMinus=$ot;var Sb={};Object.defineProperty(Sb,"__esModule",{value:!0}),Sb.ExprMulDiv=void 0;const kot=x2;class Mot extends kot.BinaryNumeric{constructor(){super(...arguments),this.elementType="*/%"}}Sb.ExprMulDiv=Mot;var bb={},Jy={};Object.defineProperty(Jy,"__esModule",{value:!0}),Jy.Unary=void 0;const Pot=ct;class Uot extends Pot.ExpressionDef{constructor(e){super({expr:e}),this.expr=e}}Jy.Unary=Uot;var jot=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),qot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Hot=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&jot(e,t,r);return qot(e,t),e};Object.defineProperty(bb,"__esModule",{value:!0}),bb.ExprNot=void 0;const Q$=Hot(Zt),Qot=Jy;class zot extends Qot.Unary{constructor(e){super(e),this.elementType="not",this.legalChildTypes=[Q$.boolT,Q$.nullT]}getExpression(e){var r;const i=this.expr.getExpression(e);!((r=e.dialectObj())===null||r===void 0)&&r.booleanAsNumbers&&this.legalChildTypes.find(o=>o.type==="number")===void 0&&this.legalChildTypes.push(Q$.numberT);const s=this.typeCheck(this.expr,i);return{...i,type:"boolean",value:{node:"not",e:s?i.value:{node:"false"}}}}}bb.ExprNot=zot;var Tb={};Object.defineProperty(Tb,"__esModule",{value:!0}),Tb.ExprNow=void 0;const Got=ct,Wot=lt;class Vot extends Got.ExpressionDef{constructor(){super(...arguments),this.elementType="timestamp"}getExpression(e){return{type:"timestamp",expressionType:"scalar",evalSpace:"constant",value:{node:"now",typeDef:{type:"timestamp"}},compositeFieldUsage:(0,Wot.emptyCompositeFieldUsage)()}}}Tb.ExprNow=Vot;var Mc={};Object.defineProperty(Mc,"__esModule",{value:!0}),Mc.ExprIsNull=Mc.PartialIsNull=Mc.ExprNULL=void 0;const Yot=Gt,Rb=ct;function z$(t,e,r){const i=r.getExpression(t);return i.type="boolean",i.value={node:e==="="?"is-null":"is-not-null",e:i.value},i}class Kot extends Rb.ExpressionDef{constructor(){super(...arguments),this.elementType="NULL"}getExpression(){return(0,Yot.literalExprValue)({dataType:{type:"null"},value:{node:"null"}})}apply(e,r,i){return r==="!="||r==="="?z$(e,r,i):super.apply(e,r,i,!0)}}Mc.ExprNULL=Kot;class Jot extends Rb.ExpressionDef{constructor(e){super(),this.op=e,this.elementType="<=> NULL"}apply(e,r,i){return z$(e,this.op,i)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("partial-as-value","Partial null check does not have a value")}atNodeType(){return Rb.ATNodeType.Partial}}Mc.PartialIsNull=Jot;class Xot extends Rb.ExpressionDef{constructor(e,r){super(),this.expr=e,this.op=r,this.elementType="is null",this.has({expr:e})}getExpression(e){return z$(e,this.op,this.expr)}}Mc.ExprIsNull=Xot;var Db={};Object.defineProperty(Db,"__esModule",{value:!0}),Db.ExprNumber=void 0;const Zot=Gt,eut=ct;class tut extends eut.ExpressionDef{constructor(e){super(),this.n=e,this.elementType="numeric literal"}getExpression(e){return this.constantExpression()}constantExpression(){const e=Number(this.n),r=Number.isNaN(e)?{type:"number"}:{type:"number",numberType:Number.isInteger(e)?"integer":"float"};return(0,Zot.literalExprValue)({dataType:r,value:{node:"numberLiteral",literal:this.n}})}}Db.ExprNumber=tut;var Ob={};Object.defineProperty(Ob,"__esModule",{value:!0}),Ob.ExprParens=void 0;const G$=ct;class nut extends G$.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="(expression)"}requestExpression(e){return this.expr.requestExpression(e)}getExpression(e){const r=this.expr.getExpression(e);return{...r,value:{node:"()",e:r.value}}}apply(e,r,i,s){return this.expr.atNodeType()===G$.ATNodeType.Or?this.expr.apply(e,r,i,s):(0,G$.applyBinary)(e,i,r,this)}atNodeType(){return this.expr.atNodeType()}atExpr(){return this.expr}}Ob.ExprParens=nut;var Fb={};Object.defineProperty(Fb,"__esModule",{value:!0}),Fb.ExprFilterExpression=void 0;const rut=ct;class iut extends rut.ExpressionDef{constructor(e){super(),this.filterText=e,this.elementType="filter expression literal"}getExpression(){return{type:"filter expression",value:{node:"filterLiteral",filterSrc:this.filterText},expressionType:"scalar",evalSpace:"constant",compositeFieldUsage:{fields:[],joinedUsage:{}}}}}Fb.ExprFilterExpression=iut;var wb={};Object.defineProperty(wb,"__esModule",{value:!0}),wb.ExprRegEx=void 0;const sut=Gt,out=ct;class uut extends out.ExpressionDef{constructor(e){super(),this.regex=e,this.elementType="regular expression literal"}getExpression(){return(0,sut.literalExprValue)({dataType:{type:"regular expression"},value:{node:"regexpLiteral",literal:this.regex}})}}wb.ExprRegEx=uut;var Nb={};Object.defineProperty(Nb,"__esModule",{value:!0}),Nb.ExprString=void 0;const aut=ct,lut=Gt;class cut extends aut.ExpressionDef{constructor(e){super(),this.elementType="string literal",this.value=e}getExpression(e){return(0,lut.literalExprValue)({dataType:{type:"string"},value:{node:"stringLiteral",literal:this.value}})}}Nb.ExprString=cut;var Lb={};Object.defineProperty(Lb,"__esModule",{value:!0}),Lb.ExprSum=void 0;const fut=p2;class xut extends fut.ExprAsymmetric{constructor(e,r,i){super("sum",e,r,i),this.has({source:r})}}Lb.ExprSum=xut;var Ib={};Object.defineProperty(Ib,"__esModule",{value:!0}),Ib.ExprTimeExtract=void 0;const Xl=Xe,Bb=Gt,W$=ct,dut=Ic;class Xy extends W$.ExpressionDef{static extractor(e){const r=Xy.pluralMap[e];if(r)return r;if((0,Xl.isExtractUnit)(e))return e}constructor(e,r){super({args:r}),this.extractText=e,this.args=r,this.elementType="timeExtract"}getExpression(e){const r=Xy.extractor(this.extractText);if(r){if(this.args.length!==1)return this.loggedErrorExpr("too-many-arguments-for-time-extraction",`Extraction function ${r} requires one argument`);const i=this.args[0];if(i instanceof dut.Range){let s=i.first.getExpression(e),o=i.last.getExpression(e);if(s.type==="error"||o.type==="error")return(0,Bb.computedErrorExprValue)({dataType:{type:"number"},error:"extract from error",from:[s,o]});if(!(0,Xl.isTemporalType)(s.type))return i.first.loggedErrorExpr("invalid-type-for-time-extraction",`Can't extract ${r} from '${s.type}'`);if(!(0,Xl.isTemporalType)(o.type))return i.last.loggedErrorExpr("invalid-type-for-time-extraction",`Cannot extract ${r} from '${o.type}'`);let u=s.type;if(!Xl.TD.eq(s,o)){let a=!0;if(u="timestamp",s.type==="date"){const l=(0,W$.getMorphicValue)(s,"timestamp");l&&(s=l,a=!1)}else{const l=(0,W$.getMorphicValue)(o,"timestamp");l&&(o=l,a=!1)}if(a)return i.first.loggedErrorExpr("invalid-types-for-time-measurement",`Cannot measure from ${s.type} to ${o.type}`)}return["week","month","quarter","year"].includes(r)?this.loggedErrorExpr("invalid-timeframe-for-time-measurement",`Cannot measure interval using '${r}'`):(0,Xl.isTimestampUnit)(r)?(0,Bb.computedExprValue)({dataType:{type:"number",numberType:"integer"},value:{node:"timeDiff",units:r,kids:{left:(0,Xl.mkTemporal)(s.value,u),right:(0,Xl.mkTemporal)(o.value,u)}},from:[s,o]}):this.loggedErrorExpr("invalid-time-extraction-unit",`Cannot extract ${r} from a range`)}else{const s=i.getExpression(e);return(0,Xl.isTemporalType)(s.type)?(0,Bb.computedExprValue)({dataType:{type:"number",numberType:"integer"},value:{node:"extract",e:(0,Xl.mkTemporal)(s.value,s.type),units:r},from:[s]}):(s.type!=="error"&&this.logError("unsupported-type-for-time-extraction",`${this.extractText}() requires time type, not '${s.type}'`),(0,Bb.computedErrorExprValue)({dataType:{type:"number",numberType:"integer"},error:`${this.extractText} bad type ${s.type}`,from:[s]}))}}throw this.internalError(`Illegal extraction unit '${this.extractText}'`)}}Ib.ExprTimeExtract=Xy,Xy.pluralMap={years:"year",quarters:"quarter",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second"};var $b={},mu={},kb={};Object.defineProperty(kb,"__esModule",{value:!0}),kb.QueryInputSpace=void 0;const hut=xs,put=e2;class mut extends put.RefinedSpace{constructor(e,r,i){super(e),this.queryOutput=r,this._isProtectedAccessSpace=i,this.extendList=[]}extendSource(e){this.pushFields(e),e instanceof hut.Join?this.extendList.push(e.name.refString):this.extendList.push(e.defineName)}isQueryFieldSpace(){return!0}outputSpace(){return this.queryOutput}inputSpace(){return this}isProtectedAccessSpace(){return this._isProtectedAccessSpace}}kb.QueryInputSpace=mut;var gut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),yut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Eut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&gut(e,t,r);return yut(e,t),e};Object.defineProperty(mu,"__esModule",{value:!0}),mu.ReduceFieldSpace=mu.QuerySpace=mu.QueryOperationSpace=void 0;const Mb=Eut(Xe),V$=Dc,Hle=kc,Qle=Mr,Aut=yt,_ut=e2,vut=Ny,Cut=Pr,Sut=kb,Da=lt,but=Xx;class zle extends _ut.RefinedSpace{get compositeFieldUsage(){if(this._compositeFieldUsage===void 0)throw new Error("Composite field usage accessed before computed");return this._compositeFieldUsage}constructor(e,r,i,s){super(e.emptyStructDef()),this.queryInputSpace=e,this.nestParent=i,this.astEl=s,this.expandedWild={},this.compositeFieldUsers=[],this._compositeFieldUsage=void 0,this.exprSpace=new Sut.QueryInputSpace(e.structDef(),this,e.isProtectedAccessSpace()),r&&this.addRefineFromFields(r)}logError(e,r,i){return this.astEl&&this.astEl.logError(e,r,i),e}inputSpace(){return this.exprSpace}outputSpace(){return this}addWild(e){var r;let i=this.exprSpace;const s=[];if(e.joinPath)for(const a of e.joinPath.list){const l=a.refString;s.push(l);const c=i.entry(l);if(c)if(c instanceof Cut.StructSpaceField)i=c.fieldSpace;else{a.logError("invalid-wildcard-source",`Field '${l}' does not contain rows and cannot be expanded with '*'`);return}else{a.logError("wildcard-source-not-defined",`No such field as '${l}'`);return}}const o=this.dialectObj(),u=[];for(const[a,l]of i.entries())if(!e.except.has(a)&&l.refType!=="parameter")if(this.entry(a)){const c=(r=this.expandedWild[a])===null||r===void 0?void 0:r.path.join(".");e.logError("name-conflict-in-wildcard-expansion",`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${c?` (conflicts with ${c})`:""}`)}else{const c=l.typeDesc();Mb.TD.isAtomic(c)&&Mb.expressionIsScalar(c.expressionType)&&(o===void 0||!o.ignoreInProject(a))&&(u.push({name:a,entry:l}),this.expandedWild[a]={path:s.concat(a),entry:l})}for(const a of u.sort((l,c)=>l.name.localeCompare(c.name)))this.newEntry(a.name,e,a.entry)}addValidatedCompositeFieldUserFromEntry(e,r){r instanceof Qle.SpaceField&&this.compositeFieldUsers.push({type:"field",name:e,field:r,logTo:void 0})}getJoinOnCompositeFieldUsage(e){var r;const i=e.map(o=>new Hle.FieldName(o));this.astEl.has({reference:i});const s=this.exprSpace.lookup(i);if(s.found&&s.found instanceof but.StructSpaceFieldBase)return(0,Da.joinedCompositeFieldUsage)(e.slice(0,-1),(r=s.found.fieldDef().onCompositeFieldUsage)!==null&&r!==void 0?r:(0,Da.emptyCompositeFieldUsage)());throw new Error("Unexpected join lookup was not found or not a struct")}getCompositeFieldUsageIncludingJoinOns(e){let r=e;const i=(0,Da.compositeFieldUsageJoinPaths)(e);for(const s of i)r=(0,Da.mergeCompositeFieldUsage)(this.getJoinOnCompositeFieldUsage(s),r);return r}addCompositeFieldUserFromFilter(e,r){e.compositeFieldUsage!==void 0&&this.compositeFieldUsers.push({type:"filter",filter:e,logTo:r})}newEntry(e,r,i){i instanceof Qle.SpaceField&&this.compositeFieldUsers.push({type:"field",name:e,field:i,logTo:r}),super.newEntry(e,r,i)}applyNextCompositeFieldUsage(e,r,i,s,o){if(s){const u=this.getCompositeFieldUsageIncludingJoinOns((0,Da.compositeFieldUsageDifference)(s,r));if(r=(0,Da.mergeCompositeFieldUsage)(r,u),!(0,Da.isEmptyCompositeFieldUsage)(u)){const a=(0,Da.narrowCompositeFieldResolution)(e,r,i);a.error?(o??this).logError("invalid-composite-field-usage",{newUsage:u,allUsage:r}):i=a.narrowedCompositeFieldResolution}}return{compositeFieldUsage:r,narrowedCompositeFieldResolution:i}}}mu.QueryOperationSpace=zle;class Gle extends zle{addRefineFromFields(e){var r;if(Mb.isQuerySegment(e)){if(e!=null&&e.extendSource)for(const i of e.extendSource)this.exprSpace.addFieldDef(i);for(const i of e.queryFields)if(i.type==="fieldref"){const s=this.exprSpace.lookup(i.path.map(o=>new Hle.FieldName(o)));if(s.found){const o=i.path[i.path.length-1];this.setEntry(o,s.found),this.addValidatedCompositeFieldUserFromEntry(o,s.found)}}else if(i.type!=="turtle"){const s=new vut.ColumnSpaceField(i),o=(r=i.as)!==null&&r!==void 0?r:i.name;this.setEntry(o,s),this.addValidatedCompositeFieldUserFromEntry(o,s)}}}pushFields(...e){for(const r of e)r instanceof Aut.WildcardFieldReference?this.addWild(r):super.pushFields(r)}canContain(e){return!0}queryFieldDefs(){const e=[];let r=(0,Da.emptyCompositeFieldUsage)(),i=(0,Da.emptyNarrowedCompositeFieldResolution)();const s=this.inputSpace().structDef();for(const o of this.compositeFieldUsers){let u;if(o.type==="filter")o.filter.compositeFieldUsage&&(u=o.filter.compositeFieldUsage);else{const{name:l,field:c}=o,f=this.expandedWild[l];if(f)e.push({type:"fieldref",path:f.path}),u=f.entry.typeDesc().compositeFieldUsage;else{const x=c.getQueryFieldDef(this.exprSpace);if(x){const h=c.typeDesc();u=h.compositeFieldUsage,h&&h.type!=="error"&&this.canContain(h)&&!Rut(x)&&e.push(x)}}}const a=this.applyNextCompositeFieldUsage(s,r,i,u,o.logTo);r=a.compositeFieldUsage,i=a.narrowedCompositeFieldResolution}return this._compositeFieldUsage=r,e}getQuerySegment(e){const r=this.getPipeSegment(e);if(Mb.isQuerySegment(r))return r;throw new Error("TODO NOT POSSIBLE")}getPipeSegment(e){if(this.segmentType==="index")return this.logError("unexpected-index-segment","internal error generating index segment from non index query"),{type:"reduce",queryFields:[]};const r={type:this.segmentType,queryFields:this.queryFieldDefs()};if(r.queryFields=(0,V$.mergeFields)(e==null?void 0:e.queryFields,r.queryFields),e!=null&&e.extendSource&&(r.extendSource=e.extendSource),this.exprSpace.extendList.length>0){const i=[],s=this.exprSpace.structDef();for(const o of this.exprSpace.extendList){const u=s.fields.find(a=>(0,V$.nameFromDef)(a)===o);u&&i.push(u)}r.extendSource=(0,V$.mergeFields)(r.extendSource,i)}return this.newTimezone&&(r.queryTimezone=this.newTimezone),r}lookup(e){const r=super.lookup(e);return r.found?{...r,isOutputField:!0}:this.exprSpace.lookup(e)}isQueryFieldSpace(){return!0}}mu.QuerySpace=Gle;class Tut extends Gle{constructor(){super(...arguments),this.segmentType="reduce"}}mu.ReduceFieldSpace=Tut;function Rut(t){return typeof t!="string"&&t.type==="turtle"&&t.pipeline.length===0}var Dut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Out=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Fut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Dut(e,t,r);return Out(e,t),e};Object.defineProperty($b,"__esModule",{value:!0}),$b.ExprUngroup=void 0;const Wle=Xe,wut=mu,Vle=Fut(Zt),Nut=ct;class Lut extends Nut.ExpressionDef{constructor(e,r,i){super({expr:r,fields:i}),this.control=e,this.expr=r,this.fields=i,this.legalChildTypes=Vle.anyAtomicT,this.elementType="ungroup"}getExpression(e){const r=this.expr.getExpression(e);if(!(0,Wle.expressionIsAggregate)(r.expressionType))return this.expr.loggedErrorExpr("ungroup-of-non-aggregate",`${this.control}() expression must be an aggregate`);if((0,Wle.expressionIsUngroupedAggregate)(r.expressionType))return this.expr.loggedErrorExpr("ungroup-of-ungrouped-aggregate",`${this.control}() expression must not already be ungrouped`);const i={node:this.control,e:r.value};if(this.typeCheck(this.expr,{...r,expressionType:"scalar"})){if(e.isQueryFieldSpace()&&this.fields.length>0){const s=[],o=this.control==="exclude";for(const u of this.fields){let a=e.outputSpace(),l=!0;for(;a;){const c=a.lookup([u]);if(c.found&&c.isOutputField)s.push(u.refString),l=!1;else if(a instanceof wut.QuerySpace){a=a.nestParent;continue}break}if(l){const c=o?"exclude()":"all()";u.logError("ungroup-field-not-in-output",`${c} '${u.refString}' is missing from query output`)}}i.fields=s}return{...Vle.atomicDef(r),expressionType:"ungrouped_aggregate",value:i,evalSpace:"output",compositeFieldUsage:r.compositeFieldUsage}}return this.loggedErrorExpr("ungroup-with-non-scalar",`${this.control}() incompatible type`)}}$b.ExprUngroup=Lut;var Pb={},Iut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),But=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),$ut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Iut(e,t,r);return But(e,t),e};Object.defineProperty(Pb,"__esModule",{value:!0}),Pb.ForRange=void 0;const kut=Bs,Yle=$ut(Zt),Ub=ds,Mut=Gt,Put=ct,jb=f2,Kle=Ic;class Uut extends Put.ExpressionDef{constructor(e,r,i){super({from:e,duration:r,timeframe:i}),this.from=e,this.duration=r,this.timeframe=i,this.elementType="forRange",this.legalChildTypes=[Yle.timestampT,Yle.dateT]}apply(e,r,i){const s=this.from.getExpression(e),o=i.getExpression(e);if(!this.typeCheck(i,o))return(0,kut.errorFor)("no time for range");const u=this.duration.getExpression(e);if(u.type!=="number")return u.type!=="error"&&this.logError("invalid-duration-quantity",`FOR duration count must be a number, not '${u.type}'`),(0,Mut.computedErrorExprValue)({dataType:{type:"boolean"},error:"for not number",from:[s,o]});const a=this.timeframe.text;let l=(0,Ub.resolution)(a);if(s.type==="timestamp"&&(l="timestamp"),o.type==="date"&&l==="date"){const m=this.from,g=(0,Ub.timeOffset)("date",s.value,"+",u.value,a),y=new jb.ExprTime("date",g);return new Kle.Range(m,y).apply(e,r,i)}const c=jb.ExprTime.fromValue("timestamp",o);let f=this.from,x=s.value;if(s.type==="date"){const m=s.morphic&&s.morphic.timestamp;m?x=m:x=(0,Ub.castTo)("timestamp",x,"date"),f=new jb.ExprTime("timestamp",x,[s])}const h=(0,Ub.timeOffset)("timestamp",x,"+",u.value,a),p=new jb.ExprTime("timestamp",h,[s,u]);return new Kle.Range(f,p).apply(e,r,c)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("range-as-value","A Range is not a value")}}Pb.ForRange=Uut;var Sr={};Object.defineProperty(Sr,"__esModule",{value:!0}),Sr.LiteralYear=Sr.LiteralQuarter=Sr.LiteralMonth=Sr.LiteralWeek=Sr.LiteralDay=Sr.LiteralHour=Sr.LiteralTimestamp=Sr.TimeFormatError=void 0;const Pc=by,jut=Xe,qut=Gt,Hut=Ic,Jle=f2,Y$=ct;class Qut extends Error{}Sr.TimeFormatError=Qut;function nd(t,e){const r=t.slice(1);if(e){const i=r.match(/\[[^\]]+]$/);if(i)return{tzSpec:i[0].slice(1,-1),text:r.slice(0,-i[0].length)}}return{text:r}}const Xle="yyyy",Zle=`${Xle}-LL`,Ao=`${Zle}-dd`,e0e=`${Ao} HH`,t0e=`${e0e}:mm`,K$=`${t0e}:ss`;class n0e extends Y$.ExpressionDef{constructor(e,r,i){super(),this.units=r,this.timeType=i,this.literalPart=e.text,e.tzSpec&&(this.timeZone=e.tzSpec)}makeLiteral(e,r){const i={node:"timeLiteral",literal:e,typeDef:{type:r}};return this.timeZone&&(i.timezone=this.timeZone),i}makeValue(e,r){const i=this.makeLiteral(e,r);return(0,qut.literalTimeResult)({value:i,dataType:{type:r},timeframe:this.units})}getExpression(e){return this.makeValue(this.literalPart,this.timeType)}getNext(){if(this.nextLit)return this.makeValue(this.nextLit,this.timeType)}granular(){return this.nextLit!==void 0}}class J$ extends n0e{constructor(e,r){super(e,r,"timestamp"),this.elementType="literal:timestamp"}static parse(e){let r;const i=nd(e,!0);e=i.text,e[10]==="T"&&(e=e.slice(0,10)+" "+e.slice(11),i.text=e);const s=e.match(/^([^.,]+)[,.](\d+)$/);s&&(e=s[1]);let o=Pc.DateTime.fromFormat(e,K$);if(o.isValid)return new J$(i,r);if(o=Pc.DateTime.fromFormat(e,t0e),o.isValid){i.text=i.text+":00",r="minute";const u=o.plus({minute:1}).toFormat(K$);return new X$(i,r,"timestamp",u)}}}Sr.LiteralTimestamp=J$;class X$ extends n0e{constructor(e,r,i,s){super(e,r,i),this.nextLit=s,this.elementType="granularTimeLiteral"}apply(e,r,i){let s=this.getExpression(e),o=this.getNext();if(o){const u=i.getExpression(e);if(u.type==="timestamp"){const a=(0,Y$.getMorphicValue)(s,"timestamp"),l=(0,Y$.getMorphicValue)(o,"timestamp");if(a&&l)s=a,o=l;else return super.apply(e,r,i)}if(o&&(0,jut.isTemporalType)(u.type)){const a=u.type;return new Hut.Range(new Jle.ExprTime(a,s.value),new Jle.ExprTime(a,o.value)).apply(e,r,i)}}return super.apply(e,r,i)}}class Z$ extends X${constructor(e,r){super(e,"hour","timestamp",r),this.elementType="literal:hour"}static parse(e){const r=nd(e,!1);let i=r.text;const s=Pc.DateTime.fromFormat(r.text,e0e);if(s.isValid)return r.text=r.text+":00:00",i=s.plus({hour:1}).toFormat(K$),new Z$(r,i)}}Sr.LiteralHour=Z$;class Zy extends X${constructor(e,r,i){super(e,r,"date",i)}getExpression(e){const r=this.makeValue(this.literalPart,"date"),i=this.makeLiteral(`${this.literalPart} 00:00:00`,"timestamp");return{...r,morphic:{timestamp:i},evalSpace:"literal"}}getNext(){const e=this.makeValue(this.nextLit,"date"),r=this.makeLiteral(`${this.nextLit} 00:00:00`,"timestamp");return{...e,morphic:{timestamp:r}}}}class ek extends Zy{constructor(e,r){super(e,"day",r),this.elementType="literal:day"}static parse(e){const r=nd(e,!1);let i=r.text;const s=Pc.DateTime.fromFormat(r.text,Ao);if(s.isValid)return i=s.plus({day:1}).toFormat(Ao),new ek(r,i)}}Sr.LiteralDay=ek;class tk extends Zy{constructor(e,r){super(e,"week",r),this.elementType="literal:week"}static parse(e){const r=nd(e,!1);let i=r.text;const s=r.text.slice(0,10),o=Pc.DateTime.fromFormat(s,Ao);if(o.isValid&&o.weekday===7){const a=o.plus({days:7});return r.text=o.toFormat(Ao),i=a.toFormat(Ao),new tk(r,i)}}}Sr.LiteralWeek=tk;class nk extends Zy{constructor(e,r){super(e,"month",r),this.elementType="literal:month"}static parse(e){const r=nd(e,!1);let i=r.text;const s=Pc.DateTime.fromFormat(r.text,Zle);if(s.isValid){const o=s.plus({months:1});return r.text=s.toFormat(Ao),i=o.toFormat(Ao),new nk(r,i)}}}Sr.LiteralMonth=nk;class rk extends Zy{constructor(e,r){super(e,"quarter",r),this.elementType="literal:quarter"}static parse(e){const r=nd(e,!1);let i=r.text;const s=r.text.match(/(^\d{4})-[qQ](\d)$/);if(s){const o=Number.parseInt(s[2])-1;let u=Pc.DateTime.fromFormat(s[1],"yyyy");o>0&&(u=u.plus({quarters:o}));const a=u.plus({quarter:1});return r.text=u.toFormat(Ao),i=a.toFormat(Ao),new rk(r,i)}}}Sr.LiteralQuarter=rk;class ik extends Zy{constructor(e,r){super(e,"year",r),this.elementType="literal:year"}static parse(e){const r=nd(e,!1);let i=r.text;const s=Pc.DateTime.fromFormat(r.text,Xle);if(s.isValid){const o=s.plus({year:1});return r.text=s.toFormat(Ao),i=o.toFormat(Ao),new ik(r,i)}}}Sr.LiteralYear=ik;var qb={};Object.defineProperty(qb,"__esModule",{value:!0}),qb.PartialCompare=void 0;const r0e=ct;class zut extends r0e.ExpressionDef{constructor(e,r){super({right:r}),this.op=e,this.right=r,this.elementType="<=> a"}granular(){return this.right.granular()}apply(e,r,i){return this.right.apply(e,this.op,i)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("partial-as-value","Partial comparison does not have a value")}atNodeType(){return r0e.ATNodeType.Partial}}qb.PartialCompare=zut;var y2={},Gut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Wut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Vut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Gut(e,t,r);return Wut(e,t),e};Object.defineProperty(y2,"__esModule",{value:!0}),y2.PickWhen=y2.Pick=void 0;const E2=Vut(Zt),i0e=Gt,Yut=ct,Kut=Je;function Hb(t,e){return t===void 0||t.type==="null"||t.type==="error"?e:t}class Jut extends Yut.ExpressionDef{constructor(e,r){super({choices:e}),this.choices=e,this.elsePick=r,this.elementType="pick",this.has({elsePick:r})}requestExpression(e){if(this.elsePick!==void 0){for(const r of this.choices){if(r.pick===void 0)return;const i=r.when.requestExpression(e);if(i===void 0||i.type!=="boolean")return}return this.getExpression(e)}}apply(e,r,i){var s;const o={node:"case",kids:{caseWhen:[],caseThen:[]}};let u;const a=[];for(const h of this.choices){const p=h.when.apply(e,"=",i),m=h.pick?h.pick.getExpression(e):i.getExpression(e);if(a.push(p,m),u&&!E2.typeEq(u,m,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:m.type,returnType:u.type});u=Hb(u,m),o.kids.caseWhen.push(p.value),o.kids.caseThen.push(m.value)}const l=(s=this.elsePick)===null||s===void 0?void 0:s.getExpression(e),c=i.getExpression(e);a.push(c),l&&a.push(l);const f=l??c,x=Hb(u,f);return E2.typeEq(x,f,!0)?x.type==="filter expression"?this.loggedErrorExpr("filter-expression-error","Pick statments cannot have filter expression values"):(o.kids.caseElse=f.value,(0,i0e.computedExprValue)({dataType:x,value:o,from:a})):this.elsePick?this.loggedErrorExpr("pick-else-type-does-not-match",{elseType:f.type,returnType:x.type}):this.loggedErrorExpr("pick-default-type-does-not-match",{defaultType:f.type,returnType:x.type})}getExpression(e){const r={node:"case",kids:{caseWhen:[],caseThen:[]}};if(this.elsePick===void 0)return this.loggedErrorExpr("pick-missing-else","pick incomplete, missing 'else'");const i=[],s=[];for(const l of this.choices){if(l.pick===void 0)return this.loggedErrorExpr("pick-missing-value","pick with no value can only be used with apply");l.when.requestExpression(e)===void 0&&this.loggedErrorExpr("pick-illegal-partial","pick with partial when can only be used with apply");const f=l.pick.getExpression(e),x=l.when.getExpression(e);i.push({pick:f,when:x}),s.push(f,x)}let o;for(const l of i){if(!E2.typeEq(l.when,E2.boolT))return this.loggedErrorExpr("pick-when-must-be-boolean",{whenType:l.when.type});if(o&&!E2.typeEq(o,l.pick,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:l.pick.type,returnType:o.type});o=Hb(o,l.pick),r.kids.caseWhen.push(l.when.value),r.kids.caseThen.push(l.pick.value)}const u=this.elsePick.getExpression(e);s.push(u);const a=Hb(o,u);return E2.typeEq(a,u,!0)?a.type==="filter expression"?this.loggedErrorExpr("filter-expression-error","Pick statments cannot have filter expression values"):(r.kids.caseElse=u.value,(0,i0e.computedExprValue)({dataType:a,value:r,from:s})):this.elsePick.loggedErrorExpr("pick-else-type-does-not-match",{elseType:u.type,returnType:a.type})}}y2.Pick=Jut;class Xut extends Kut.MalloyElement{constructor(e,r){super({when:r}),this.pick=e,this.when=r,this.elementType="caseWhen",this.has({pick:e})}}y2.PickWhen=Xut;var A2={},Zut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),eat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),tat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Zut(e,t,r);return eat(e,t),e};Object.defineProperty(A2,"__esModule",{value:!0}),A2.CaseWhen=A2.Case=void 0;const nat=Gt,rat=ct,iat=Je,_2=tat(Zt);function s0e(t,e){return t===void 0||t.type==="null"||t.type==="error"?e:t}class sat extends rat.ExpressionDef{constructor(e,r,i){super({choices:r}),this.value=e,this.choices=r,this.elseValue=i,this.elementType="case",this.has({elseValue:i,value:e})}getExpression(e){const r={node:"case",kids:{caseWhen:[],caseThen:[]}},i=[];let s;if(this.value){const a=this.value.getExpression(e);i.push(a),r.kids.caseValue=a.value,s=a}const o=[];for(const a of this.choices){const l=a.when.getExpression(e),c=a.then.getExpression(e);o.push({when:l,then:c}),i.push(l,c)}let u;for(const a of o){if(s!==void 0){if(!_2.typeEq(a.when,s))return this.loggedErrorExpr("case-when-type-does-not-match",{whenType:a.when.type,valueType:s.type})}else if(!_2.typeEq(a.when,_2.boolT))return this.loggedErrorExpr("case-when-must-be-boolean",{whenType:a.when.type});if(u&&!_2.typeEq(u,a.then,!0))return this.loggedErrorExpr("case-then-type-does-not-match",{thenType:a.then.type,returnType:u.type});u=s0e(u,a.then),r.kids.caseWhen.push(a.when.value),r.kids.caseThen.push(a.then.value)}if(this.elseValue){const a=this.elseValue.getExpression(e);if(u&&!_2.typeEq(u,a,!0))return this.loggedErrorExpr("case-else-type-does-not-match",{elseType:a.type,returnType:u.type});u=s0e(u,a),i.push(a),r.kids.caseElse=a.value}return(0,nat.computedExprValue)({value:r,dataType:u?_2.atomicDef(u):{type:"null"},from:i})}}A2.Case=sat;class oat extends iat.MalloyElement{constructor(e,r){super({when:e,then:r}),this.when=e,this.then=r,this.elementType="caseWhen"}}A2.CaseWhen=oat;var Qb={},rd={},uat=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),aat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),lat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&uat(e,t,r);return aat(e,t),e};Object.defineProperty(rd,"__esModule",{value:!0}),rd.RecordLiteral=rd.RecordElement=void 0;const o0e=Pi,cat=Gt,fat=ct,xat=Je,dat=lat(Zt);class hat extends xat.MalloyElement{constructor(e){if(super(),this.elementType="record element","value"in e)this.value=e.value,this.has({value:e.value}),e.key&&(this.key=e.key);else{this.has({path:e.path}),this.value=e.path;const r=e.path.fieldReference.path;this.key=r[r.length-1]}}}rd.RecordElement=hat;class pat extends fat.ExpressionDef{constructor(e){super(),this.pairs=e,this.elementType="record literal",this.has({pairs:e})}getExpression(e){return this.getRecord(e,[])}getRecord(e,r){var i;const s={node:"recordLiteral",kids:{},typeDef:{type:"record",fields:[]}},o=[];let u=0;for(const a of this.pairs){const l=(i=a.key)!==null&&i!==void 0?i:r[u];if(u+=1,l===void 0){a.logError("record-literal-needs-keys","Anonymous record element not legal here");continue}const c=a.value.getExpression(e);o0e.TD.isAtomic(c)?(o.push(c),s.kids[l]=c.value,s.typeDef.fields.push((0,o0e.mkFieldDef)(dat.atomicDef(c),l))):a.value.logError("illegal-record-property-type",`Record property '${a.key} is type '${c.type}', which is not a legal property value type`)}return(0,cat.computedExprValue)({value:s,dataType:s.typeDef,from:o})}getNextElement(e,r){const i=r.value;return i.node==="recordLiteral"?this.getRecord(e,Object.keys(i.kids)):this.getRecord(e,[])}}rd.RecordLiteral=pat;var mat=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),gat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),yat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&mat(e,t,r);return gat(e,t),e};Object.defineProperty(Qb,"__esModule",{value:!0}),Qb.ArrayLiteral=void 0;const Eat=Gt,Aat=ct,u0e=yat(Zt),_at=rd;class vat extends Aat.ExpressionDef{constructor(e){super(),this.elements=e,this.elementType="array literal",this.has({elements:e})}getExpression(e){const r=[],i=[];let s;if(this.elements.length>0)for(const l of this.elements){const c=s&&l instanceof _at.RecordLiteral?l.getNextElement(e,s):l.getExpression(e);if(i.push(c),c.type!=="error"){if(s){if(c.type!=="null"&&!u0e.typeEq(s,c)){l.logError("array-values-incompatible","All array elements must be same type");continue}}else c.type!=="null"&&(s=c);r.push(c.value)}}const o=u0e.atomicDef(s||{type:"number"}),u=o.type==="record"?{type:"array",elementTypeDef:{type:"record_element"},fields:o.fields}:{type:"array",elementTypeDef:o},a={node:"arrayLiteral",kids:{values:r},typeDef:u};return(0,Eat.computedExprValue)({dataType:u,value:a,from:i})}}Qb.ArrayLiteral=vat;var zb={};Object.defineProperty(zb,"__esModule",{value:!0}),zb.Timeframe=void 0;const Cat=Xe,Sat=Je;class bat extends Sat.MalloyElement{constructor(e){super(),this.elementType="timeframe";let r=e.toLowerCase();r.endsWith("s")&&(r=r.slice(0,-1)),this.text=(0,Cat.isTimestampUnit)(r)?r:"second"}}zb.Timeframe=bat;var Uc={};Object.defineProperty(Uc,"__esModule",{value:!0}),Uc.ImportStatement=Uc.ImportSelect=Uc.ImportSourceName=void 0;const sk=Je;class Tat extends sk.MalloyElement{constructor(e){super(),this.text=e,this.elementType="importSourceName"}}Uc.ImportSourceName=Tat;class Rat extends sk.MalloyElement{constructor(e,r){super(),this.text=e,this.from=r,this.elementType="importName",r&&this.has({from:r})}}Uc.ImportSelect=Rat;class Dat extends sk.ListOf{constructor(e,r){super([]),this.url=e,this.elementType="import statement";try{this.fullURL=decodeURI(new URL(e,r).toString())}catch{this.logError("invalid-import-url","Invalid URL in import statement")}}needs(){const e=this.translator();if(e&&this.fullURL&&e.root.importZone.getEntry(this.fullURL).status==="present"){const i=e.childRequest(this.fullURL);if(i)return i}}execute(e){const r=this.translator();if(!r)this.logError("no-translator-for-import","Cannot import without translation context");else if(this.fullURL){const i=r.root.pretranslatedModels.get(this.fullURL),s=r.root.importZone.getEntry(this.fullURL);if(i||s.status==="present"){const o=r.getChildExports(this.fullURL);if(this.notEmpty())for(const u of this.list){const a=u.from||u;if(e.getEntry(u.text))u.logError("name-conflict-on-selective-import",`Cannot redefine '${u.text}'`);else if(o[a.text]){const l={...o[a.text]};u.from&&(l.as=u.text),e.setEntry(u.text,{entry:l,exported:!1})}else a.logError("selective-import-not-found",`Cannot find '${a.text}', not imported`)}else for(const[u,a]of Object.entries(r.getChildExports(this.fullURL)))e.getEntry(u)?this.logError("name-conflict-on-indiscriminate-import",`Cannot redefine '${u}'`):e.setEntry(u,{entry:a,exported:!1})}else s.status==="error"?this.logError("failed-import",`import failed: '${s.message}'`):this.logError("failed-import",`import failed with status: '${s.status}'`)}}}Uc.ImportStatement=Dat;var eE={};Object.defineProperty(eE,"__esModule",{value:!0}),eE.ExtendBlock=void 0;const Oat=Je,Fat=jn;class wat extends Oat.ListOf{constructor(){super(...arguments),this.elementType="extendBlock",this.forceQueryClass=void 0,this.queryRefinementStage=Fat.LegalRefinementStage.Single}queryExecute(e){for(const r of this.list)for(const i of r.list)e.inputFS.extendSource(i)}}eE.ExtendBlock=wat;var Gb={};Object.defineProperty(Gb,"__esModule",{value:!0}),Gb.Argument=void 0;const Nat=Je;class Lat extends Nat.MalloyElement{constructor(e){super({...e}),this.elementType="Argument",this.id=e.id,this.value=e.value}}Gb.Argument=Lat;var Wb={};Object.defineProperty(Wb,"__esModule",{value:!0}),Wb.HasParameter=void 0;const a0e=Xe,Iat=Je,Bat=ct;class $at extends Iat.MalloyElement{constructor(e){super(),this.elementType="hasParameter",this.name=e.name,e.type&&(0,a0e.isParameterType)(e.type)&&(this.type=e.type),e.default&&(this.default=e.default,this.has({default:this.default})),e.filterType&&(this.filterType=e.filterType)}parameter(){var e;let r;if(this.default!==void 0){const i=this.default.constantValue();if(this.type&&this.type!==i.type&&i.type!=="null"&&i.type!=="error"&&this.default.logError("parameter-default-does-not-match-declared-type",`Default value for parameter does not match declared type \`${this.type}\``),i.type==="null")return this.type?{type:this.type,value:i.value,name:this.name}:(this.default.logError("parameter-null-default-without-declared-type","Default value cannot have type `null` unless parameter type is also specified"),{value:i.value,name:this.name,type:"error"});if(i.type==="filter expression")return this.type!=="filter expression"&&this.logError("parameter-missing-default-or-type",`Filter expression parameters must have expicit filter type, for example '${this.name}::filter<string>'`),this.filterType&&(0,Bat.checkFilterExpression)(this,this.filterType,i.value),{value:i.value,name:this.name,type:i.type};if(!(0,a0e.isCastType)(i.type)&&i.type!=="error")return this.default.logError("parameter-illegal-default-type",`Default value cannot have type \`${i.type}\``),{value:i.value,name:this.name,type:"error"};r={value:i.value,name:this.name,type:i.type}}else this.type===void 0&&this.logError("parameter-missing-default-or-type","Parameter must have default value or declared type"),r={value:null,name:this.name,type:(e=this.type)!==null&&e!==void 0?e:"error"};return r.type==="filter expression"&&this.filterType&&(r.filterType=this.filterType),r}}Wb.HasParameter=$at;var Vb={};Object.defineProperty(Vb,"__esModule",{value:!0}),Vb.AnonymousQuery=void 0;const kat=Je,Mat=kr;class Pat extends kat.MalloyElement{constructor(e){super(),this.queryExpr=e,this.elementType="anonymousQuery",this.isNoteableObj=!0,this.extendNote=Mat.extendNoteMethod,this.has({queryExpr:e})}execute(e){const r=this.queryExpr.getQuery();if(!r){this.queryExpr.sqLog("non-query-used-as-query","Cannot run this object as a query");return}const i={...r.query()},s=this.note||{};i.annotation&&(s.inherits=i.annotation),(s.notes||s.blockNotes||s.inherits)&&(i.annotation=s),e.queryList.push(i)}}Vb.AnonymousQuery=Pat;var jc={};Object.defineProperty(jc,"__esModule",{value:!0}),jc.View=void 0;const Uat=Je;class jat extends Uat.MalloyElement{pipeline(e,r){return this.pipelineComp(e,r).pipeline}}jc.View=jat;var Yb={};Object.defineProperty(Yb,"__esModule",{value:!0}),Yb.ViewArrow=void 0;const qat=Pr,Hat=jc;class Qat extends Hat.View{constructor(e,r){super({base:e,operation:r}),this.base=e,this.operation=r,this.elementType="viewArrow"}pipelineComp(e){const r=this.base.pipelineComp(e),i=new qat.StaticSourceSpace(r.outputStruct),s=this.operation.pipelineComp(i);return{pipeline:[...r.pipeline,...s.pipeline],outputStruct:s.outputStruct}}refine(e,r,i){return this.logError("refinement-with-multistage-view","A multi-segment view cannot be used as a refinement"),[]}getImplicitName(){return this.operation.getImplicitName()}}Yb.ViewArrow=Qat;var Kb={},tE={};Object.defineProperty(tE,"__esModule",{value:!0}),tE.refine=void 0;const ok=Pi,zat=lt,uk=Dc;function Gat(t,e,r){var i,s;if(e.length!==1)return t.logError("refinement-with-multistage-view","Named refinements of multi-stage views are not supported"),e;const o={...e[0]},u=r;if((0,ok.isRawSegment)(o))t.logError("refinement-of-raw-query","Cannot refine raw query, must add an explicit query stage");else if(o.type==="partial"&&u.type!=="index"&&u.type!=="raw"?o.type=u.type:u.type!==o.type&&t.logError("mismatched-view-types-for-refinement",`cannot refine ${o.type} view with ${u.type} view`),u.type!=="index"&&o.type!=="index"&&u.type!=="raw"&&(u.orderBy!==void 0&&!u.defaultOrderBy&&(o.orderBy===void 0||o.defaultOrderBy?o.orderBy=u.orderBy:t.logError("ordering-overridden-in-refinement","refinement cannot override existing ordering")),u.limit!==void 0&&(o.limit===void 0?o.limit=u.limit:t.logError("limit-overridden-in-refinement","refinement cannot override existing limit"))),o.filterList=o.filterList!==void 0||u.filterList!==void 0?[...(i=o.filterList)!==null&&i!==void 0?i:[],...(s=u.filterList)!==null&&s!==void 0?s:[]]:void 0,(0,ok.isQuerySegment)(u)&&(0,ok.isQuerySegment)(o)){const a=[],l=[],c=new Map(o.queryFields.map(f=>[(0,uk.nameFromDef)(f),f]));for(const f of u.queryFields)c.has((0,uk.nameFromDef)(f))?a.push(f):l.push(f);o.queryFields=[...o.queryFields,...l],a.length>0&&t.logError("name-conflict-in-refinement",`overlapping fields in refinement: ${a.map(uk.nameFromDef)}`),o.compositeFieldUsage=(0,zat.mergeCompositeFieldUsage)(o.compositeFieldUsage,u.compositeFieldUsage)}else u.type==="index"&&o.type==="index"&&(o.indexFields=[...u.indexFields,...o.indexFields]);return[o]}tE.refine=Gat,Object.defineProperty(Kb,"__esModule",{value:!0}),Kb.ViewRefine=void 0;const Wat=ai,Vat=ks,Yat=tE,Kat=jc;class Jat extends Kat.View{constructor(e,r){super({base:e,refinement:r}),this.base=e,this.refinement=r,this.elementType="refine"}pipelineComp(e,r){const i=this.base.pipelineComp(e),s=this.refinement.refine(e,i.pipeline,r);return{pipeline:s,annotation:i.annotation,outputStruct:s.length>0?(0,Vat.getFinalStruct)(this.refinement,e.structDef(),s):Wat.ErrorFactory.structDef}}refine(e,r,i){const s=this.pipeline(e,i);return s.length!==1?(this.refinement.logError("refinement-with-multistage-view","refinement must have exactly one stage"),r):(0,Yat.refine)(this,r,s[0])}getImplicitName(){return this.base.getImplicitName()}}Kb.ViewRefine=Jat;var Jb={};Object.defineProperty(Jb,"__esModule",{value:!0}),Jb.ReferenceView=void 0;const ak=Xe,l0e=ai,Xat=ks,Zat=Mr,elt=tE,tlt=jc;class nlt extends tlt.View{constructor(e){super({reference:e}),this.reference=e,this.elementType="reference-view"}pipelineComp(e,r){return this._pipelineComp(e)}_pipelineComp(e,{forRefinement:r}={forRefinement:!1}){const i=this.reference.getField(e),s=function(){return{inputStruct:l0e.ErrorFactory.structDef,outputStruct:l0e.ErrorFactory.structDef,pipeline:[],error:!0}};if(!i.found)return this.reference.logError(i.error.code,i.error.message),s();if(!(i.found instanceof Zat.SpaceField))throw new Error("Expected space field");const o=i.found.fieldDef();if(o===void 0)throw new Error("Expected field to have definition");if((0,ak.isAtomic)(o)){const u={type:"reduce",queryFields:[this.reference.refToField],compositeFieldUsage:o.compositeFieldUsage},a=this.reference.nameString,l={...(0,ak.sourceBase)(e.structDef()),type:"query_result",name:a,fields:[o]};return{pipeline:[u],name:a,outputStruct:l}}else return(0,ak.isTurtle)(o)?this.reference.list.length>1?(r?this.logError("refinement-with-joined-view","Cannot use view from join as refinement"):this.logError("nest-of-joined-view","Cannot use view from join"),s()):{pipeline:[...o.pipeline],name:o.name,annotation:o.annotation,outputStruct:(0,Xat.getFinalStruct)(this.reference,e.structDef(),o.pipeline)}:(r?this.reference.logError("refinement-with-source",`named refinement \`${this.reference.refString}\` must be a view, found a ${o.type}`):this.reference.logError("nest-of-source","This operation is not supported"),s())}getRefinementSegment(e){const{pipeline:r,error:i}=this._pipelineComp(e,{forRefinement:!0});if(!i){if(r.length!==1){this.reference.logError("refinement-with-multistage-view",`named refinement \`${this.reference.refString}\` must have exactly one stage`);return}return r[0]}}refine(e,r,i){const s=this.getRefinementSegment(e);return s?(0,elt.refine)(this,r,s):r}getImplicitName(){return this.reference.nameString}}Jb.ReferenceView=nlt;var Xb={},nE={},Zb={},rE={};Object.defineProperty(rE,"__esModule",{value:!0}),rE.Index=void 0;const rlt=Je,ilt=jn;class slt extends rlt.MalloyElement{constructor(e){super({fields:e}),this.fields=e,this.elementType="index",this.forceQueryClass=ilt.QueryClass.Index,this.queryRefinementStage=void 0}useWeight(e){this.has({weightBy:e}),this.weightBy=e}}rE.Index=slt;var iE={};Object.defineProperty(iE,"__esModule",{value:!0}),iE.SampleProperty=void 0;const olt=Je,c0e=jn;class ult extends olt.MalloyElement{constructor(e){super(),this.sample=e,this.elementType="sampleProperty",this.queryRefinementStage=c0e.LegalRefinementStage.Tail,this.forceQueryClass=c0e.QueryClass.Index}sampling(){return this.sample}}iE.SampleProperty=ult;var eT={};Object.defineProperty(eT,"__esModule",{value:!0}),eT.IndexFieldSpace=void 0;const f0e=lt,x0e=Xe,lk=yt,alt=Mr,llt=mu,clt=By,flt=Pr;class xlt extends llt.QueryOperationSpace{constructor(){super(...arguments),this.segmentType="index"}pushFields(...e){for(const r of e)r instanceof lk.FieldReference?super.pushFields(r):r instanceof lk.WildcardFieldReference?this.addWild(r):r.logError("invalid-field-in-index-query","Internal error, not expected in index query")}getPipeSegment(e){if(e)return this.logError("refinement-of-index-segment","index query operations cannot be refined"),{type:"index",indexFields:[]};let r=(0,f0e.emptyCompositeFieldUsage)(),i=(0,f0e.emptyNarrowedCompositeFieldResolution)();const s=[],o=this.inputSpace().structDef();for(const[u,a]of this.entries())if(a instanceof alt.SpaceField){let l,c;const f=this.expandedWild[u];if(f)s.push({type:"fieldref",path:f.path}),l=f.entry.typeDesc().compositeFieldUsage;else if(a instanceof clt.ReferenceField){const h=a.fieldRef,p=h.getField(this.exprSpace);p.error?h.logError(p.error.code,p.error.message):(s.push(h.refToField),l=p.found.typeDesc().compositeFieldUsage,c=h)}const x=this.applyNextCompositeFieldUsage(o,r,i,l,c);r=x.compositeFieldUsage,i=x.narrowedCompositeFieldResolution}return this._compositeFieldUsage=r,{type:"index",indexFields:s}}addRefineFromFields(e){}addWild(e){var r;let i=this.exprSpace;const s=[];if(e.joinPath)for(const a of e.joinPath.list){const l=a.refString;s.push(l);const c=i.entry(l);if(c)if(c instanceof flt.StructSpaceField)i=c.fieldSpace;else{a.logError("invalid-wildcard-source",`Field '${l}' does not contain rows and cannot be expanded with '*'`);return}else{a.logError("wildcard-source-not-found",`No such field as '${l}'`);return}}const o=this.dialectObj(),u=[];for(const[a,l]of i.entries()){if(e.except.has(a)||l.refType==="parameter")continue;const c=lk.IndexFieldReference.indexOutputName([...s,a]);if(this.entry(c)){const f=(r=this.expandedWild[c].path)===null||r===void 0?void 0:r.join(".");e.logError("name-conflict-in-wildcard-expansion",`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${f?` (conflicts with ${f})`:""}`)}else{const f=l.typeDesc();x0e.TD.isBasicAtomic(f)&&(0,x0e.expressionIsScalar)(f.expressionType)&&(o===void 0||!o.ignoreInProject(a))&&(u.push({name:c,entry:l}),this.expandedWild[c]={path:s.concat(a),entry:l})}}for(const a of u.sort((l,c)=>l.name.localeCompare(c.name)))this.setEntry(a.name,a.entry)}}eT.IndexFieldSpace=xlt,Object.defineProperty(Zb,"__esModule",{value:!0}),Zb.IndexBuilder=void 0;const ck=Xe,dlt=ai,hlt=Ra,plt=rE,mlt=$c,glt=iE,ylt=eT,fk=lt;class Elt{constructor(e,r,i,s){this.filters=[],this.alwaysJoins=[],this.type="index",this.resultFS=new ylt.IndexFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}execute(e){e instanceof hlt.Filter?e.queryExecute(this):e instanceof mlt.Limit?(this.limit&&this.limit.logError("index-limit-already-specified","Ignored, too many limit: statements"),this.limit=e):e instanceof plt.Index?(this.resultFS.pushFields(...e.fields.list),e.weightBy&&(this.indexOn&&this.indexOn.logError("index-by-already-specified","Ignoring previous BY"),this.indexOn=e.weightBy)):e instanceof glt.SampleProperty?this.sample=e.sampling():e.logError("illegal-operation-for-index","Not legal in an index query operation")}get compositeFieldUsage(){return this.resultFS.compositeFieldUsage}finalize(e){var r;if(e&&!(0,ck.isIndexSegment)(e)&&!(0,ck.isPartialSegment)(e))return this.resultFS.logError("refinement-of-index-segment",`Can't refine index with ${e.type}`),dlt.ErrorFactory.indexSegment;const i=this.resultFS.getPipeSegment(e),s=(e==null?void 0:e.filterList)||[];this.filters.length>0&&!s?i.filterList=this.filters:s&&(i.filterList=[...s,...this.filters]),e!=null&&e.limit&&(i.limit=e.limit),this.limit&&(i.limit=this.limit.limit),this.indexOn&&(i.weightMeasure=this.indexOn.refString),e&&(0,ck.isIndexSegment)(e)&&(e!=null&&e.sample)&&(i.sample=e.sample),this.sample&&(i.sample=this.sample),this.alwaysJoins.length>0&&(i.alwaysJoins=[...this.alwaysJoins]);const o=e&&e.type==="index"&&(r=e.compositeFieldUsage)!==null&&r!==void 0?r:(0,fk.emptyCompositeFieldUsage)();return i.compositeFieldUsage=(0,fk.mergeCompositeFieldUsage)(o,this.compositeFieldUsage),i}}Zb.IndexBuilder=Elt;var tT={},sE={};Object.defineProperty(sE,"__esModule",{value:!0}),sE.GroupBy=void 0;const Alt=$s,d0e=jn;class _lt extends Alt.DefinitionList{constructor(){super(...arguments),this.elementType="groupBy",this.queryRefinementStage=d0e.LegalRefinementStage.Single,this.forceQueryClass=d0e.QueryClass.Grouping}}sE.GroupBy=_lt;var nT={};Object.defineProperty(nT,"__esModule",{value:!0}),nT.ProjectFieldSpace=void 0;const rT=Xe,vlt=mu;class Clt extends vlt.QuerySpace{constructor(){super(...arguments),this.segmentType="project"}canContain(e){return e===void 0||!rT.TD.isAtomic(e)||(0,rT.expressionIsAggregate)(e.expressionType)?!1:(0,rT.expressionInvolvesAggregate)(e.expressionType)&&(0,rT.expressionIsAnalytic)(e.expressionType)?(this.logError("aggregate-analytic-in-select","Cannot add aggregate analyics to select"),!1):!0}}nT.ProjectFieldSpace=Clt;var qc={},id={};Object.defineProperty(id,"__esModule",{value:!0}),id.Ordering=id.OrderBy=void 0;const Slt=Xe,h0e=kc,p0e=Je,blt=jn;class Tlt extends p0e.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e instanceof h0e.FieldName&&this.has({field:e})}get modelField(){return typeof this.field=="number"?this.field:this.field.refString}getOrderBy(e){var r;if(this.field instanceof h0e.FieldName&&e.isQueryFieldSpace()){const s=e.outputSpace(),o=this.field.getField(s);o.error&&this.field.logError(o.error.code,o.error.message),(!o.found||!o.isOutputField)&&this.logError("order-by-not-found-in-output",`Unknown field ${this.field.refString} in output space`),(0,Slt.expressionIsAnalytic)((r=o.found)===null||r===void 0?void 0:r.typeDesc().expressionType)&&this.logError("order-by-analytic",`Illegal order by of analytic field ${this.field.refString}`)}const i={field:this.modelField};return this.dir&&(i.dir=this.dir),i}}id.OrderBy=Tlt;class Rlt extends p0e.ListOf{constructor(e){super(e),this.elementType="ordering",this.queryRefinementStage=blt.LegalRefinementStage.Tail,this.forceQueryClass=void 0}getOrderBy(e){return this.list.map(r=>r.getOrderBy(e))}}id.Ordering=Rlt,Object.defineProperty(qc,"__esModule",{value:!0}),qc.ReduceBuilder=qc.QuerySegmentBuilder=void 0;const gu=Xe,Dlt=ai,Olt=kc,Flt=$c,wlt=id,Nlt=mu,Llt=$s,xk=lt;function m0e(t){return t.type==="fieldref"?t.path[t.path.length-1]:t.name}class g0e{constructor(){this.alwaysJoins=[],this.filters=[]}execute(e){if(e.queryExecute){e.queryExecute(this);return}e instanceof Llt.DefinitionList?this.resultFS.pushFields(...e.list):e instanceof Flt.Limit?this.limit?e.logError("limit-already-specified","Query operation already limited"):this.limit=e.limit:e instanceof wlt.Ordering&&(this.order?e.logError("ordering-already-specified","Query operation already sorted"):this.order=e)}get compositeFieldUsage(){return this.resultFS.compositeFieldUsage}refineFrom(e,r){var i;e&&e.type!=="index"&&e.type!=="raw"&&(!this.limit&&e.orderBy&&!e.defaultOrderBy&&(r.orderBy=e.orderBy),!this.limit&&e.limit&&(r.limit=e.limit)),this.order&&(r.orderBy=this.order.getOrderBy(this.inputFS),delete r.defaultOrderBy),this.limit&&(r.limit=this.limit);const s=(e==null?void 0:e.filterList)||[];this.filters.length>0&&!s?r.filterList=this.filters:s&&(r.filterList=[...s,...this.filters]),this.alwaysJoins.length>0&&(r.alwaysJoins=[...this.alwaysJoins]);const o=e&&(0,gu.isQuerySegment)(e)&&(i=e.compositeFieldUsage)!==null&&i!==void 0?i:(0,xk.emptyCompositeFieldUsage)();r.compositeFieldUsage=(0,xk.mergeCompositeFieldUsage)(o,this.compositeFieldUsage)}}qc.QuerySegmentBuilder=g0e;class Ilt extends g0e{constructor(e,r,i,s){super(),this.type="grouping",this.resultFS=new Nlt.ReduceFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}finalize(e){let r;if(e)if((0,gu.isReduceSegment)(e)||(0,gu.isPartialSegment)(e))r=e;else return this.resultFS.logError("incompatible-segment-for-reduce-refinement",`Can't refine reduce with ${e.type}`),Dlt.ErrorFactory.reduceSegment;const i=this.resultFS.getQuerySegment(r);if(this.refineFrom(r,i),i.orderBy){for(const s of i.orderBy)if(typeof s.field=="number"){const o=i.queryFields[s.field-1];s.field=m0e(o)}}if(i.orderBy===void 0||i.defaultOrderBy){let s;for(const o of i.queryFields){let u=!1,a=!1,l;const c=m0e(o);if(o.type==="fieldref"){const f=o.path.map(h=>new Olt.FieldName(h)),x=this.inputFS.lookup(f).found;if(x){const h=x.typeDesc();l=h.type,u=(0,gu.expressionIsAggregate)(h.expressionType),a=(0,gu.expressionIsAnalytic)(h.expressionType)}else continue}else l=o.type,u=(0,gu.hasExpression)(o)&&(0,gu.expressionIsAggregate)(o.expressionType),a=(0,gu.hasExpression)(o)&&(0,gu.expressionIsAnalytic)(o.expressionType);if((0,gu.isTemporalType)(l)||u){i.defaultOrderBy=!0,i.orderBy=[{field:c,dir:"desc"}],s=void 0;break}(0,gu.canOrderBy)(l)&&!a&&!s&&(s=c)}s&&(i.defaultOrderBy=!0,i.orderBy=[{field:s,dir:"asc"}])}return i}}qc.ReduceBuilder=Ilt,Object.defineProperty(tT,"__esModule",{value:!0}),tT.ProjectBuilder=void 0;const y0e=Xe,Blt=ai,$lt=sE,klt=nT,Mlt=qc;class Plt extends Mlt.QuerySegmentBuilder{constructor(e,r,i,s){super(),this.type="project",this.resultFS=new klt.ProjectFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}execute(e){e.elementType==="having"||e instanceof $lt.GroupBy?e.logError("illegal-operation-in-select-segment","Illegal statement in a select query operation"):super.execute(e)}finalize(e){let r;if(e)if((0,y0e.isProjectSegment)(e)||(0,y0e.isPartialSegment)(e))r=e;else return this.resultFS.logError("incompatible-segment-for-select-refinement",`Can't refine select with ${e.type}`),Blt.ErrorFactory.projectSegment;const i=this.resultFS.getQuerySegment(r);return this.refineFrom(r,i),i}}tT.ProjectBuilder=Plt;var iT={};Object.defineProperty(iT,"__esModule",{value:!0}),iT.PartialBuilder=void 0;const Ult=Pi,jlt=qc;class qlt extends jlt.ReduceBuilder{finalize(e){const r=super.finalize(e);if((0,Ult.isQuerySegment)(r))return{...r,type:"partial"};throw new Error(`Partial Builder cannot finalize from ${r.type}`)}}iT.PartialBuilder=qlt,Object.defineProperty(nE,"__esModule",{value:!0}),nE.QOpDesc=void 0;const Hlt=Zb,Qlt=tT,zlt=qc,Glt=Je,Wlt=ks,Vlt=Pr,sd=jn,Ylt=iT;class Klt extends Glt.ListOf{constructor(){super(...arguments),this.elementType="queryOperation"}computeType(){var e;let r,i=!1;this.refineThis&&(this.refineThis.type==="reduce"?r=sd.QueryClass.Grouping:this.refineThis.type==="project"?r=sd.QueryClass.Project:this.refineThis.type==="index"&&(r=sd.QueryClass.Index));for(const s of this.list)s.forceQueryClass&&(r?r!==s.forceQueryClass&&s.logError(`illegal-${r}-operation`,`Not legal in ${r} query`):r=s.forceQueryClass),i||(i=(e=s.needsExplicitQueryClass)!==null&&e!==void 0?e:!1);return r===void 0&&i&&(this.logError("ambiguous-view-type",{}),r=sd.QueryClass.Project),this.opClass=r,r}refineFrom(e){this.refineThis=e}getBuilder(e,r,i){switch(this.computeType()){case sd.QueryClass.Grouping:return new zlt.ReduceBuilder(e,this.refineThis,r,i);case sd.QueryClass.Project:return new Qlt.ProjectBuilder(e,this.refineThis,r,i);case sd.QueryClass.Index:return new Hlt.IndexBuilder(e,this.refineThis,r,i);case void 0:return new Ylt.PartialBuilder(e,this.refineThis,r,i)}}getOp(e,r){const i=this.getBuilder(e,r,this);for(const o of this.list)i.execute(o);const s=i.finalize(this.refineThis);return{segment:s,outputSpace:()=>new Vlt.StaticSourceSpace((0,Wlt.opOutputStruct)(this,e.structDef(),s))}}}nE.QOpDesc=Klt,Object.defineProperty(Xb,"__esModule",{value:!0}),Xb.QOpDescView=void 0;const Jlt=Xe,Xlt=Pr,E0e=nE,Zlt=ks,dk=jn,e0t=jc;class t0t extends e0t.View{constructor(e){super({operation:e}),this.operation=e,this.elementType="qopdesc-view"}pipelineComp(e,r){const i=this.operation.getOp(e,r);return{pipeline:[i.segment],outputStruct:i.outputSpace().structDef()}}getOp(e,r,i,s){return(0,Jlt.isRawSegment)(s)?(this.logError("refinement-of-raw-query","A raw query cannot be refined"),s):(i.refineFrom(s),i.getOp(e,r).segment)}refine(e,r,i){const s=[...r];if(s.length===0)return s;if(s.length===1)return this.operation.refineFrom(s[0]),[this.getOp(e,i,this.operation,s[0])];const o=new E0e.QOpDesc([]),u=new E0e.QOpDesc([]);for(const a of this.operation.list)switch(a.queryRefinementStage){case dk.LegalRefinementStage.Head:o.push(a);break;case dk.LegalRefinementStage.Single:a.logError("illegal-multistage-refinement-operation","Illegal in refinement of a query with more than one stage");break;case dk.LegalRefinementStage.Tail:u.push(a);break;default:a.logError("illegal-refinement-operation","Illegal query refinement")}if(o.notEmpty()&&(this.has({headRefinements:o}),s[0]=this.getOp(e,void 0,o,s[0])),u.notEmpty()){const a=s.length-1;this.has({tailRefinements:u});const l=(0,Zlt.getFinalStruct)(this,e.structDef(),s.slice(-1));s[a]=this.getOp(new Xlt.StaticSourceSpace(l),void 0,u,s[a])}return s}getImplicitName(){}}Xb.QOpDescView=t0t;var Rn={},n0t=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),r0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&n0t(e,t,r);return r0t(e,t),e};Object.defineProperty(Rn,"__esModule",{value:!0}),Rn.FieldDefinitionValue=Rn.DefSpace=Rn.DimensionFieldDeclaration=Rn.MeasureFieldDeclaration=Rn.DeclareFieldDeclaration=Rn.ProjectFieldDeclaration=Rn.GroupByFieldDeclaration=Rn.AggregateFieldDeclaration=Rn.CalculateFieldDeclaration=Rn.AtomicFieldDeclaration=void 0;const hk=Xe,A0e=i0t(Zt),s0t=c2,o0t=Je,od=sr,u0t=kr,a0t=Mr;class Hc extends o0t.MalloyElement{constructor(e,r,i){super({expr:e}),this.expr=e,this.defineName=r,this.exprSrc=i,this.isNoteableObj=!0,this.extendNote=u0t.extendNoteMethod}getName(){return this.defineName}fieldDef(e,r){return this.queryFieldDef(new pk(e,this),r)}executesInOutputSpace(){return!1}queryFieldDef(e,r){let i;function s(){if(e.isQueryFieldSpace())return e.outputSpace();throw new Error("must be in a query -- weird internal error")}try{const u=this.executesInOutputSpace()?s():e;i=this.expr.getExpression(u)}catch(u){return this.logError("failed-field-definition",`Cannot define '${r}', ${u.message}`),{name:r,type:"error"}}if(i.type==="null"&&(this.expr.logWarning("null-typed-field-definition",'null value defaults to type number, use "null::TYPE" to specify correct type'),i={type:"number",value:i.value,expressionType:i.expressionType,evalSpace:i.evalSpace,compositeFieldUsage:i.compositeFieldUsage}),(0,hk.isAtomicFieldType)(i.type)&&i.type!=="error"){this.typecheckExprValue(i);const u=(0,hk.mkFieldDef)(A0e.atomicDef(i),r);return(u.type==="date"||u.type==="timestamp")&&(0,s0t.isGranularResult)(i)&&(u.timeframe=i.timeframe),u.location=this.location,u.e=i.value,u.compositeFieldUsage=i.compositeFieldUsage,i.expressionType&&(u.expressionType=i.expressionType),this.exprSrc&&(u.code=this.exprSrc),this.note&&(u.annotation=this.note),u}if(!(e instanceof pk&&e.foundCircle)&&i.type!=="error"){const u=A0e.inspect(i);this.logError("invalid-type-for-field-definition",`Cannot define '${r}', unexpected type: ${u}`)}return{name:r,type:"error"}}makeEntry(e){e.newEntry(this.defineName,this,new _0e(e,this))}}Rn.AtomicFieldDeclaration=Hc;class l0t extends Hc{constructor(){super(...arguments),this.elementType="calculateFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckCalculate)(e,this)}executesInOutputSpace(){return!0}}Rn.CalculateFieldDeclaration=l0t;class c0t extends Hc{constructor(){super(...arguments),this.elementType="aggregateFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckAggregate)(e,this)}}Rn.AggregateFieldDeclaration=c0t;class f0t extends Hc{constructor(){super(...arguments),this.elementType="groupByFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckGroupBy)(e,this)}}Rn.GroupByFieldDeclaration=f0t;class x0t extends Hc{constructor(){super(...arguments),this.elementType="projectFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckProject)(e,this)}}Rn.ProjectFieldDeclaration=x0t;class d0t extends Hc{constructor(){super(...arguments),this.elementType="declareFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckDeclare)(e,this)}}Rn.DeclareFieldDeclaration=d0t;class h0t extends Hc{constructor(){super(...arguments),this.elementType="measureFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckMeasure)(e,this)}}Rn.MeasureFieldDeclaration=h0t;class p0t extends Hc{constructor(){super(...arguments),this.elementType="dimensionFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckDimension)(e,this)}}Rn.DimensionFieldDeclaration=p0t;class pk{constructor(e,r){this.realFS=e,this.circular=r,this.type="fieldSpace",this.foundCircle=!1}structDef(){return this.realFS.structDef()}emptyStructDef(){return this.realFS.emptyStructDef()}entry(e){return this.realFS.entry(e)}lookup(e){return e[0]&&e[0].refString===this.circular.defineName?(this.foundCircle=!0,{error:{message:`Circular reference to '${this.circular.defineName}' in definition`,code:"circular-reference-in-field-definition"},found:void 0}):this.realFS.lookup(e)}entries(){return this.realFS.entries()}dialectName(){return this.realFS.dialectName()}dialectObj(){return this.realFS.dialectObj()}isQueryFieldSpace(){return this.realFS.isQueryFieldSpace()}outputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.outputSpace();throw new Error("Not a query field space")}inputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.inputSpace();throw new Error("Not a query field space")}isProtectedAccessSpace(){return!0}}Rn.DefSpace=pk;class _0e extends a0t.SpaceField{constructor(e,r){super(),this.space=e,this.exprDef=r,this.fieldName=r.defineName}get name(){return this.fieldName}fieldDef(){var e;const r=(e=this.defInSource)!==null&&e!==void 0?e:this.exprDef.fieldDef(this.space,this.name);return this.defInSource=r,r}getQueryFieldDef(e){if(!this.defInQuery){const r=this.exprDef.queryFieldDef(e,this.name);this.defInQuery=r}return this.defInQuery}typeDesc(){const e=this.defInQuery||this.fieldDef();if((0,hk.isAtomic)(e))return this.fieldTypeFromFieldDef(e);throw new Error(`Can't get typeDesc for ${e.type}`)}}Rn.FieldDefinitionValue=_0e;var sT={};Object.defineProperty(sT,"__esModule",{value:!0}),sT.Aggregate=void 0;const m0t=$s,v0e=jn;class g0t extends m0t.DefinitionList{constructor(){super(...arguments),this.elementType="aggregateList",this.queryRefinementStage=v0e.LegalRefinementStage.Single,this.forceQueryClass=v0e.QueryClass.Grouping}}sT.Aggregate=g0t;var oT={};Object.defineProperty(oT,"__esModule",{value:!0}),oT.Calculate=void 0;const y0t=$s,E0t=jn;class A0t extends y0t.DefinitionList{constructor(){super(...arguments),this.elementType="calculate",this.forceQueryClass=void 0,this.needsExplicitQueryClass=!0,this.queryRefinementStage=E0t.LegalRefinementStage.Single}}oT.Calculate=A0t;var oE={};Object.defineProperty(oE,"__esModule",{value:!0}),oE.Dimensions=void 0;const _0t=Oc;class v0t extends _0t.DeclareFields{constructor(){super(...arguments),this.elementType="dimensionList"}}oE.Dimensions=v0t;var uE={};Object.defineProperty(uE,"__esModule",{value:!0}),uE.Measures=void 0;const C0t=Oc;class S0t extends C0t.DeclareFields{constructor(){super(...arguments),this.elementType="measureList"}}uE.Measures=S0t;var uT={};Object.defineProperty(uT,"__esModule",{value:!0}),uT.Nests=void 0;const b0t=$s,C0e=jn;class T0t extends b0t.DefinitionList{constructor(e){super(e),this.elementType="nestedQueries",this.queryRefinementStage=C0e.LegalRefinementStage.Single,this.forceQueryClass=C0e.QueryClass.Grouping}}uT.Nests=T0t;var aT={};Object.defineProperty(aT,"__esModule",{value:!0}),aT.ProjectStatement=void 0;const R0t=$s,S0e=jn;class D0t extends R0t.DefinitionList{constructor(){super(...arguments),this.elementType="projectStatement",this.forceQueryClass=S0e.QueryClass.Project,this.queryRefinementStage=S0e.LegalRefinementStage.Single}queryExecute(e){e.type==="project"&&e.resultFS.pushFields(...this.list)}}aT.ProjectStatement=D0t;var Qc={},Zl={},Bn={};Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.getPlainString=Bn.unIndent=Bn.getOptionalId=Bn.idToStr=Bn.getId=Bn.getStringParts=Bn.getStringIfShort=Bn.getShortString=void 0;const b0e=Zo;function T0e(t){var e,r;const i=((e=t.DQ_STRING())===null||e===void 0?void 0:e.text)||((r=t.SQ_STRING())===null||r===void 0?void 0:r.text);return i?b0e.ParseUtil.parseString(i,i[0]):""}Bn.getShortString=T0e;function R0e(t){const e=t.string().shortString();if(e)return T0e(e)}Bn.getStringIfShort=R0e;function*D0e(t){var e;if(t){for(const i of t.sqlInterpolation()){const s=i.OPEN_CODE().text;s.length>2&&(yield s.slice(0,s.length-2)),i.sqExpr()&&(yield i.sqExpr())}const r=(e=t.SQL_END())===null||e===void 0?void 0:e.text.slice(0,-3);r&&r.length>0&&(yield r)}}Bn.getStringParts=D0e;function O0e(t){return F0e(t.id())}Bn.getId=O0e;function F0e(t){const e=t.BQ_STRING();return e?b0e.ParseUtil.parseString(e.text,"`"):t.text}Bn.idToStr=F0e;function O0t(t){function e(r){return"id"in r}if(e(t)&&t.id())return O0e(t)}Bn.getOptionalId=O0t;function*w0e(t){for(;t.length>0;){const e=t.match(/^.*?\r?\n/);let r=t;e&&(r=e[0]),yield r,t=t.slice(r.length)}}function F0t(t){let e;for(const r of w0e(t)){const i=r.match(/^( *).*[^\s]/);if(i){const s=i[1].length;(e===void 0||s<e)&&(e=s)}}return e}function N0e(t){let e;for(const r of t)if(typeof r=="string"){const i=F0t(r);i!==void 0&&(e===void 0||i<e)&&(e=i)}if(e)for(let r=0;r<=t.length;r+=1){const i=t[r];if(typeof i=="string"){let s="";for(let o of w0e(i))o[0]===" "&&(o=o.slice(e)),s+=o;t[r]=s}}}Bn.unIndent=N0e;function w0t(t,e=!1){const r=[],i=R0e(t);if(i)return[i,r];const s=[],o=t.string().sqlString();if(o){for(const u of D0e(o))if(typeof u=="string")s.push(u);else if(r.push(u),e)return[void 0,r];return N0e(s),[s.join(""),r]}return["",r]}Bn.getPlainString=w0t,Object.defineProperty(Zl,"__esModule",{value:!0}),Zl.findReferences=Zl.deprecatedParseTableURI=Zl.constructTableKey=void 0;const N0t=uc,mk=Bn;function L0e(t){const e=(0,mk.getStringIfShort)(t);if(e)return e;const r=[],i=t.string().sqlString();if(i){for(const s of(0,mk.getStringParts)(i))typeof s=="string"&&r.push(s);return r.join("")}return""}class L0t{constructor(e,r){this.trans=e,this.tokens=r,this.needTables={},this.needImports={}}registerTableReference(e,r,i){const s=I0e(e,r);this.needTables[s]||(this.needTables[s]={connectionName:e,tablePath:r,firstReference:i})}enterExploreTable(e){const r=(0,mk.getId)(e.connectionId()),i=L0e(e.tablePath()),s=this.trans.rangeFromContext(e);this.registerTableReference(r,i,s)}enterImportURL(e){const r=L0e(e);this.needImports[r]||(this.needImports[r]=this.trans.rangeFromContext(e))}}function I0e(t,e){return t===void 0?e:`${t}:${e}`}Zl.constructTableKey=I0e;function I0t(t){const e=t.match(/^([^:]*):(.*)$/);if(e){const[,r,i]=e;return{connectionName:r,tablePath:i}}else return{tablePath:t}}Zl.deprecatedParseTableURI=I0t;function B0t(t,e,r){const i=new L0t(t,e),s=i;return N0t.ParseTreeWalker.DEFAULT.walk(s,r),{tables:i.needTables,urls:i.needImports}}Zl.findReferences=B0t,Object.defineProperty(Qc,"__esModule",{value:!0}),Qc.TableFunctionSource=Qc.TableMethodSource=Qc.TableSource=void 0;const B0e=Zl,$0t=Eo,$0e=ai;class gk extends $0t.Source{getSourceDef(){var e,r,i;const s=this.getTableInfo();if(s===void 0)return $0e.ErrorFactory.structDef;const{tablePath:o,connectionName:u}=s,a=(0,B0e.constructTableKey)(u,o),l=(e=this.translator())===null||e===void 0?void 0:e.root.schemaZone.getEntry(a);let c=`Schema read failure for table '${o}' for connection '${u}'`;if(l){if(l.status==="present"){(r=this.document())===null||r===void 0||r.checkExperimentalDialect(this,l.value.dialect),l.value.location=this.location,l.value.fields.forEach(x=>{x.location=this.location});const f={...l.value,fields:l.value.fields.map(x=>({...x,location:this.location})),location:this.location};return(i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(f),f}l.status==="error"&&(c=l.message)}return this.logError("failed-to-fetch-table-schema",c),$0e.ErrorFactory.structDef}}Qc.TableSource=gk;class k0t extends gk{constructor(e,r){super(),this.connectionName=e,this.tablePath=r,this.elementType="tableMethodSource",this.has({connectionName:e})}getTableInfo(){var e;const r=this.modelEntry(this.connectionName),i=this.connectionName.refString;if(r===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(i,{entry:{type:"connection",name:i},exported:!0},!0);else if(r.entry.type!=="connection"){this.connectionName.logError("invalid-connection-for-table-source",`${this.connectionName.refString} is not a connection`);return}return{tablePath:this.tablePath,connectionName:this.connectionName.refString}}}Qc.TableMethodSource=k0t;class M0t extends gk{constructor(e){super(),this.tableURI=e,this.elementType="tableFunctionSource"}getTableInfo(){return(0,B0e.deprecatedParseTableURI)(this.tableURI)}}Qc.TableFunctionSource=M0t;var lT={};Object.defineProperty(lT,"__esModule",{value:!0}),lT.SQLString=void 0;const P0t=Je,k0e=hu;class U0t extends P0t.MalloyElement{constructor(){super(...arguments),this.elementType="sqlString",this.elements=[],this.containsQueries=!1}complete(){this.has({queries:this.elements.filter(j0t)})}push(e){typeof e=="string"?e.length>0&&this.elements.push(e):e instanceof k0e.SourceQueryElement?(this.elements.push(e),this.containsQueries=!0,e.parent=this):e.logError("invalid-sql-source-interpolation","This element is not legal inside an SQL string")}sqlPhrases(){const e=[];for(const r of this.elements)if(typeof r=="string")e.push({sql:r});else{const i=r.getQuery();i?e.push(i.query()):r.sqLog("failed-to-expand-sql-source","Cannot expand into a query")}return e}}lT.SQLString=U0t;function j0t(t){return t instanceof k0e.SourceQueryElement}var cT={};Object.defineProperty(cT,"__esModule",{value:!0}),cT.SourceDesc=void 0;const q0t=Je;class H0t extends q0t.ListOf{constructor(){super(...arguments),this.elementType="sourceDescription"}}cT.SourceDesc=H0t;var fT={};Object.defineProperty(fT,"__esModule",{value:!0}),fT.isSourceProperty=void 0;const Q0t=Ra,z0t=Oc,G0t=r2,W0t=wc,V0t=i2,Y0t=s2,K0t=o2,J0t=Fc,X0t=xs;function Z0t(t){return t instanceof Q0t.Filter||t instanceof X0t.JoinStatement||t instanceof z0t.DeclareFields||t instanceof G0t.FieldListEdit||t instanceof W0t.Renames||t instanceof V0t.PrimaryKey||t instanceof J0t.ObjectAnnotation||t instanceof Y0t.Views||t instanceof K0t.TimezoneStatement}fT.isSourceProperty=Z0t;var xT={};Object.defineProperty(xT,"__esModule",{value:!0}),xT.isFieldCollectionMember=void 0;const ect=Rn,M0e=yt;function tct(t){return t instanceof M0e.FieldReference||t instanceof M0e.WildcardFieldReference||t instanceof ect.AtomicFieldDeclaration}xT.isFieldCollectionMember=tct;var dT={};Object.defineProperty(dT,"__esModule",{value:!0}),dT.isQueryElement=void 0;const nct=u2,rct=a2,ict=Hy,sct=Qy;function oct(t){return t instanceof nct.QueryArrow||t instanceof rct.QueryRefine||t instanceof ict.QueryReference||t instanceof sct.QueryRaw}dT.isQueryElement=oct;var P0e={};Object.defineProperty(P0e,"__esModule",{value:!0});var hT={};Object.defineProperty(hT,"__esModule",{value:!0}),hT.isQueryProperty=void 0;function uct(t){return"queryRefinementStage"in t&&"forceQueryClass"in t}hT.isQueryProperty=uct;var pT={};Object.defineProperty(pT,"__esModule",{value:!0}),pT.isQueryExtendProperty=void 0;const act=oE,lct=xs,cct=uE;function fct(t){return t instanceof act.Dimensions||t instanceof cct.Measures||t instanceof lct.JoinStatement}pT.isQueryExtendProperty=fct;var mT={};Object.defineProperty(mT,"__esModule",{value:!0}),mT.isFieldPropStatement=void 0;const xct=Bc,dct=Ra,hct=$c,pct=m2;function mct(t){return t instanceof dct.Filter||t instanceof hct.Limit||t instanceof pct.PartitionBy||t instanceof xct.FunctionOrdering}mT.isFieldPropStatement=mct,function(t){var e=T&&T.__createBinding||(Object.create?function(i,s,o,u){u===void 0&&(u=o);var a=Object.getOwnPropertyDescriptor(s,o);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,u,a)}:function(i,s,o,u){u===void 0&&(u=o),i[u]=s[o]}),r=T&&T.__exportStar||function(i,s){for(var o in i)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,i,o)};Object.defineProperty(t,"__esModule",{value:!0}),r(Ry,t),r(Xp,t),r(Zp,t),r(Eo,t),r(Fy,t),r(hu,t),r(J4,t),r(X4,t),r(tb,t),r(ky,t),r(nb,t),r(rb,t),r(du,t),r(r2,t),r(i2,t),r(wc,t),r(s2,t),r(o2,t),r(sb,t),r(x2,t),r(ub,t),r(d2,t),r(Bc,t),r(ab,t),r(Jl,t),r(lb,t),r(p2,t),r(cb,t),r(fb,t),r(xb,t),r(Kl,t),r(db,t),r(hb,t),r(mb,t),r(Ky,t),r(Vy,t),r(ed,t),r(yb,t),r(Eb,t),r(_b,t),r(Cb,t),r(Sb,t),r(bb,t),r(Tb,t),r(Mc,t),r(Db,t),r(Ob,t),r(Fb,t),r(wb,t),r(Nb,t),r(Lb,t),r(Ib,t),r($b,t),r(Pb,t),r(Sr,t),r(qb,t),r(m2,t),r(y2,t),r(A2,t),r(Qb,t),r(rd,t),r(Ic,t),r(zb,t),r(Jy,t),r(Uc,t),r(eE,t),r(Gb,t),r(Wb,t),r(Vb,t),r(a2,t),r(u2,t),r(jc,t),r(Yb,t),r(Kb,t),r(Jb,t),r(Xb,t),r(Rn,t),r(yt,t),r(sT,t),r(oT,t),r(Oc,t),r(oE,t),r(eE,t),r(Ra,t),r(sE,t),r(rE,t),r(xs,t),r(Dy,t),r($c,t),r(uE,t),r(Ry,t),r(uT,t),r(id,t),r(aT,t),r(nE,t),r(iE,t),r(l2,t),r(Zx,t),r(zy,t),r(Qc,t),r(lT,t),r(Fc,t),r(pu,t),r(cT,t),r(fT,t),r(ct,t),r(xT,t),r(kc,t),r(Je,t),r(dT,t),r(P0e,t),r(hT,t),r(pT,t),r(mT,t)}(Q4);var gT={},gct=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),yct=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Ect=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&gct(e,t,r);return yct(e,t),e};Object.defineProperty(gT,"__esModule",{value:!0}),gT.MalloyToAST=void 0;const U0e=py,Act=Kh,ie=Ect(Q4),yk=Yp,j0e=Er,_ct=Q4,Yn=Bn,yT=Xe,vct=Zo,q0e=Vn,Cct=Cy;class H0e extends ie.SourceQueryElement{constructor(){super(...arguments),this.elementType="parseErrorSourceQuery"}}class Ek extends ie.MalloyElement{constructor(e){super(),this.elementType="ignoredByParser",this.malloySrc=e}}const Sct=[];class bct extends Act.AbstractParseTreeVisitor{constructor(e,r,i){super(),this.parseInfo=e,this.msgLog=r,this.compilerFlags=i;for(const s of Sct){const o=vct.Tag.fromTagLine(s,0,this.compilerFlags);this.compilerFlags=o.tag}}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}astError(e,r,i,s){this.msgLog.log((0,yk.makeLogMessage)(r,i,{at:e.location,...s}))}rangeFromContext(e){return(0,q0e.rangeFromContext)(this.parseInfo.sourceInfo,e)}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.rangeFromContext(e)}}getSourceString(e){return this.parseInfo.sourceStream.getText(new j0e.Interval(e.start.startIndex,e.stop?e.stop.stopIndex:e.start.startIndex))}contextError(e,r,i,s){this.msgLog.log((0,yk.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}warnWithReplacement(e,r,i,s){this.msgLog.log((0,yk.makeLogMessage)(e,r,{at:{url:this.parseInfo.sourceURL,range:i},severity:"warn",replacement:s}))}inExperiment(e,r){const i=this.compilerFlags.tag("experimental");return i&&(i.bare()||i.has(e))?!0:(this.contextError(r,"experiment-not-enabled",{experimentId:e}),!1)}only(e,r,i){const s=[];for(const o of e){const u=r(o);u?s.push(u):o instanceof Ek||this.astError(o,"unexpected-statement-in-translation",`Parser enountered unexpected statement type '${o.elementType}' when it needed '${i}'`)}return s}getNumber(e){return Number.parseInt(e.text)}getFieldName(e){return this.astAt(new ie.FieldName((0,Yn.getId)(e)),e.id())}getModelEntryName(e){return this.astAt(new ie.ModelEntryReference((0,Yn.getId)(e)),e.id())}defaultResult(){return new ie.Unimplemented}astAt(e,r){return e.location={url:this.parseInfo.sourceURL,range:this.rangeFromContext(r)},e}getSourceCode(e){const r=e.start.startIndex,i=e.stop||e.start,s=new j0e.Interval(r,i.stopIndex);return this.parseInfo.sourceStream.getText(s)}getFilterElement(e){const r=this.getFieldExpr(e),i=new ie.FilterElement(r,this.getSourceCode(e));return this.astAt(i,e)}getFieldDefs(e,r){return e.map(i=>this.getFieldDef(i,r))}getFieldExpr(e){const r=this.visit(e);if(r instanceof ie.ExpressionDef)return this.astAt(r,e);throw this.internalError(e,`expression node unknown type '${r.elementType}'`)}getPlainStringFrom(e){const[r,i]=(0,Yn.getPlainString)(e);for(const s of i)s instanceof U0e.ParserRuleContext&&this.contextError(s,"illegal-query-interpolation-outside-sql-block","%{ query } illegal in this string");return r||""}makeSqlString(e,r){for(const i of(0,Yn.getStringParts)(e))i instanceof U0e.ParserRuleContext?r.push(this.visit(i)):r.push(i);r.complete(),this.astAt(r,e)}parseTime(e,r){let i=r(e.text);return i||(this.contextError(e,"failed-to-parse-time-literal","Time data parse error"),i=new ie.LiteralTimestamp({text:e.text})),this.astAt(i,e)}getNotes(e){return e.ANNOTATION().map(r=>({text:r.text,at:this.getLocation(e)}))}getIsNotes(e){return this.getNotes(e._beforeIs).concat(this.getNotes(e._afterIs))}visitMalloyDocument(e){const r=this.only(e.malloyStatement().map(i=>this.visit(i)),i=>ie.isDocStatementOrDocStatementList(i)&&i,"statement");return new ie.Document(r)}visitDefineSourceStatement(e){const i=e.sourcePropertyList().sourceDefinition().map(u=>this.visitSourceDefinition(u)),s=this.getNotes(e.tags()),o=new ie.DefineSourceList(i);return o.extendNote({blockNotes:s}),o}getSourceParameter(e){const r=(0,Yn.getId)(e.parameterNameDef());let i,s;const o=e.legalParamType();if(o){const l=o.malloyType();if(l){const f=this.getMalloyType(l);(0,Cct.isFilterable)(f)?s=f:this.contextError(o,"parameter-illegal-default-type",`Unknown filter type ${f}`)}const c=o.FILTER()?"filter expression":o.text.toLowerCase();if(!(0,yT.isParameterType)(c))return this.contextError(o,"parameter-illegal-default-type",`Unknown parameter type ${c}`),null;i=c}const u=e.fieldExpr();let a;if(u){const l=new ie.ConstantExpression(this.getFieldExpr(u));a=this.astAt(l,u)}return this.astAt(new ie.HasParameter({name:r,type:i,default:a,filterType:s}),e)}getSourceParameters(e){if(e===void 0)return[];this.inExperiment("parameters",e);function r(i){return i!==null}return e.sourceParameter().map(i=>this.getSourceParameter(i)).filter(r)}visitSourceDefinition(e){const r=this.visit(e.sqExplore()),i=this.getSourceParameters(e.sourceParameters()),s=new ie.DefineSource((0,Yn.getId)(e.sourceNameDef()),r instanceof ie.SourceQueryElement?r:void 0,!0,i),o=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return s.extendNote({notes:o}),this.astAt(s,e)}getSourceExtensions(e){return this.astAt(this.visitExploreProperties(e),e)}visitExploreProperties(e){const r=this.only(e.exploreStatement().map(s=>this.visit(s)),s=>ie.isSourceProperty(s)&&s,"source property");return new ie.SourceDesc(r)}visitExploreTable(e){const r=e.connectionId(),i=this.astAt(this.getModelEntryName(r),r),s=this.getPlainStringFrom(e.tablePath());return this.astAt(new ie.TableMethodSource(i,s),e)}visitSqlSource(e){const r=e.connectionId(),i=this.astAt(this.getModelEntryName(r),r),s=new ie.SQLString,o=e.sqlString();o&&this.makeSqlString(o,s);const u=e.shortString();u&&s.push((0,Yn.getShortString)(u));const a=new ie.SQLSource(i,s);return this.astAt(a,e)}visitDefJoinMany(e){const r=this.getAccessLabel(e.accessLabel()),i=[];for(const o of e.joinList().joinDef()){const u=this.visit(o);u instanceof ie.Join&&(i.push(u),u instanceof ie.ExpressionJoin?(u.joinType="many",u.joinOn===void 0&&this.contextError(e,"missing-on-in-join-many","join_many: requires ON expression")):u instanceof ie.KeyJoin&&this.contextError(e,"foreign-key-in-join-many","Foreign key join not legal in join_many:"))}const s=new ie.JoinStatement(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),s}visitDefJoinOne(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getJoinList(e.joinList()),s=[];for(const u of i)u instanceof ie.Join&&(s.push(u),u instanceof ie.ExpressionJoin&&(u.joinType="one"));const o=new ie.JoinStatement(s,r);return o.extendNote({blockNotes:this.getNotes(e.tags())}),o}visitDefJoinCross(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getJoinList(e.joinList()),s=[];for(const u of i)u instanceof ie.Join&&(s.push(u),u instanceof ie.ExpressionJoin?u.joinType="cross":u.logError("foreign-key-in-join-cross","Foreign key join not legal in join_cross:"));const o=new ie.JoinStatement(s,r);return o.extendNote({blockNotes:this.getNotes(e.tags())}),o}getJoinList(e){return this.only(e.joinDef().map(r=>this.visit(r)),r=>r instanceof ie.Join&&r,"join")}getJoinFrom(e){const r=e.isExplore(),i=this.getModelEntryName(e.joinNameDef());if(r){const o=this.getSqExpr(r.sqExpr()),u=this.getNotes(r._before_is).concat(this.getNotes(r._after_is));return{joinFrom:o,notes:u,joinAs:i}}const s=e.sourceArguments();return s?{joinFrom:this.astAt(new ie.SQReference(i,this.getSQArguments(s)),e),notes:[],joinAs:i}:{joinAs:i,joinFrom:new ie.SQReference(i),notes:[]}}visitQueryJoinStatement(e){return this.astAt(this.visit(e.joinStatement()),e)}visitJoinOn(e){var r;const{joinAs:i,joinFrom:s,notes:o}=this.getJoinFrom(e.joinFrom()),u=new ie.ExpressionJoin(i,s),a=e.joinExpression(),l=((r=e.matrixOperation())===null||r===void 0?void 0:r.text.toLocaleLowerCase())||"left";return(0,yT.isMatrixOperation)(l)?u.matrixOperation=l:this.contextError(e,"unknown-matrix-operation","Internal Error: Unknown matrixOperation"),a&&(u.joinOn=this.getFieldExpr(a)),u.extendNote({notes:this.getNotes(e).concat(o)}),this.astAt(u,e)}visitJoinWith(e){const{joinAs:r,joinFrom:i,notes:s}=this.getJoinFrom(e.joinFrom()),o=this.getFieldExpr(e.fieldExpr()),u=new ie.KeyJoin(r,i,o);return u.extendNote({notes:this.getNotes(e).concat(s)}),this.astAt(u,e)}getFieldDef(e,r){const i=e.fieldExpr(),s=(0,Yn.getId)(e.fieldNameDef()),o=this.getFieldExpr(i),u=new r(o,s,this.getSourceCode(i)),a=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return u.extendNote({notes:a}),this.astAt(u,e)}visitDefDimensions(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getFieldDefs(e.defList().fieldDef(),ie.DimensionFieldDeclaration),s=new ie.Dimensions(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(s,e)}getAccessLabel(e){if(e!==void 0){if(e.INTERNAL_KW())return"internal";if(e.PRIVATE_KW())return"private";if(e.PUBLIC_KW())return"public";throw this.internalError(e,`Unknown access modifier label ${e.text}`)}}getAccessLabelProp(e){if(e!==void 0){if(e.INTERNAL())return"internal";if(e.PRIVATE())return"private";if(e.PUBLIC())return"public";throw this.internalError(e,`Unknown access modifier label ${e.text}`)}}visitDefMeasures(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getFieldDefs(e.defList().fieldDef(),ie.MeasureFieldDeclaration),s=new ie.Measures(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(s,e)}visitQueryExtend(e){const r=[],i=e.queryExtendStatementList().queryExtendStatement().map(o=>this.visit(o));for(const o of i)if(ie.isQueryExtendProperty(o))r.push(o);else throw this.internalError(e,`Query extend matched, but ${o.elementType} found`);const s=new ie.ExtendBlock(r);return this.astAt(s,e)}visitExploreRenameDef(e){const r=e.fieldName(0),i=e.fieldName(1),s=new ie.RenameField((0,Yn.getId)(r),this.getFieldName(i));return this.astAt(s,e)}visitDefExploreRename(e){const r=this.getAccessLabel(e.accessLabel()),s=e.renameList().exploreRenameDef().map(u=>this.visitExploreRenameDef(u)),o=new ie.Renames(s,r);return this.astAt(o,e)}visitFilterClauseList(e){return new ie.Filter(e.fieldExpr().map(r=>this.getFilterElement(r)))}visitWhereStatement(e){const r=this.visitFilterClauseList(e.filterClauseList());return r.having=!1,this.astAt(r,e)}visitHavingStatement(e){const r=this.visitFilterClauseList(e.filterClauseList());return r.having=!0,this.astAt(r,e)}visitDefExploreQuery(e){const r=this.getAccessLabel(e.accessLabel()),i=e.subQueryDefList().exploreQueryDef().map(u=>this.visitExploreQueryDef(u)),s=new ie.Views(i,r),o=this.getNotes(e.tags());return s.extendNote({blockNotes:o}),s}visitDefExplorePrimaryKey(e){const r=new ie.PrimaryKey(this.getFieldName(e.fieldName()));return this.astAt(r,e)}getFieldNameList(e,r){const i=e.fieldName().map(s=>this.astAt(new r([this.getFieldName(s)]),s));return new ie.FieldReferences(i)}visitDefExploreEditField(e){const r=e.ACCEPT()?"accept":"except";return new ie.FieldListEdit(r,this.getFieldNameList(e.fieldNameList(),ie.AcceptExceptFieldReference))}visitSQInclude(e){const r=this.getSqExpr(e.sqExpr()),i=e.includeBlock(),s=i?this.getIncludeItems(i):void 0,o=new ie.SQExtend(r,new ie.SourceDesc([]),s);return this.astAt(o,e)}visitDefExploreTimezone(e){return this.visitTimezoneStatement(e.timezoneStatement())}visitTimezoneStatement(e){const r=this.getPlainStringFrom(e),i=this.astAt(new ie.TimezoneStatement(r),e.string());return i.isValid||this.astError(i,"invalid-timezone",{timezone:i.tz}),this.astAt(i,e)}visitQueryProperties(e){const r=this.only(e.queryStatement().map(i=>this.astAt(this.visit(i),i)),i=>ie.isQueryProperty(i)&&i,"query statement");return new ie.QOpDesc(r)}getFieldPath(e,r){const i=e.fieldName().map(s=>this.getFieldName(s));return this.astAt(new r(i),e)}getQueryFieldDef(e,r){const i=this.getFieldDef(e,r);return this.astAt(i,e)}getQueryFieldEntry(e,r,i){const s=e.taggedRef();if(s)return this.getTaggedRef(s,r,i);const o=e.fieldDef();if(o)return this.getQueryFieldDef(o,r);throw new Error("Expected query field entry to be a field reference or definition")}getQueryItems(e,r,i){return this.only(e.queryFieldEntry().map(s=>this.getQueryFieldEntry(s,r,i)),s=>s instanceof ie.FieldReference||s instanceof ie.AtomicFieldDeclaration?s:!1,"view field")}visitAggregateStatement(e){const r=new ie.Aggregate(this.getQueryItems(e.queryFieldList(),ie.AggregateFieldDeclaration,ie.AggregateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitGroupByStatement(e){const r=new ie.GroupBy(this.getQueryItems(e.queryFieldList(),ie.GroupByFieldDeclaration,ie.GroupByFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCalculateStatement(e){const r=new ie.Calculate(this.getQueryItems(e.queryFieldList(),ie.CalculateFieldDeclaration,ie.CalculateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}getTaggedRef(e,r,i){const s=e.refExpr();if(s){const u=this.getFieldPath(e.fieldPath(),ie.ExpressionFieldReference);let a;const l=s.timeframe();l&&(a=new ie.ExprGranularTime(new ie.ExprIdReference(u),this.visitTimeframe(l).text,!0));const c=s.aggregate();if(c){const x=c.text.toLowerCase();if(x==="sum")a=new ie.ExprSum(void 0,u);else return this.contextError(c,"invalid-reference-only-aggregation",`\`${x}\` is not legal in a reference-only aggregation`),u}const f=new r(a,u.outputName);return f.extendNote({notes:this.getNotes(e.tags())}),f}const o=this.getFieldPath(e.fieldPath(),i);return o.extendNote({notes:this.getNotes(e.tags())}),o}getFieldCollectionMember(e,r,i){const s=e.fieldDef();if(s)return this.getFieldDef(s,r);const o=e.taggedRef();if(o)return this.getTaggedRef(o,r,i);const u=e.collectionWildCard();if(u)return this.visitCollectionWildCard(u);throw this.internalError(e,"Unexpected element in fieldCollectionMember")}visitFieldCollection(e){const r=e.collectionMember().map(i=>this.getFieldCollectionMember(i,ie.ProjectFieldDeclaration,ie.ProjectFieldReference));return this.astAt(new ie.ProjectStatement(r),e)}visitProjectStatement(e){const r=this.visitFieldCollection(e.fieldCollection());return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCollectionWildCard(e){var r;const i=e.fieldPath(),s=i?this.getFieldPath(i,ie.ProjectFieldReference):void 0,o=this.astAt(new ie.WildcardFieldReference(s),e),u=((r=e.starQualified())===null||r===void 0?void 0:r.fieldNameList())||[];for(const a of u)for(const l of a.fieldName())o.except.add((0,Yn.getId)(l));return o}visitIndexFields(e){const r=e.indexElement().map(i=>{const s=i.fieldPath();if(!s)return this.astAt(new ie.WildcardFieldReference(void 0),e);const o=this.getFieldPath(s,ie.IndexFieldReference);return i.STAR()?this.astAt(new ie.WildcardFieldReference(o),e):this.astAt(o,e)});return new ie.FieldReferences(r)}visitIndexStatement(e){const r=this.visitIndexFields(e.indexFields()),i=new ie.Index(r),s=e.fieldName();return s&&i.useWeight(this.getFieldName(s)),this.astAt(i,e)}visitFieldPropertyLimitStatement(e){return this.inExperiment("aggregate_limit",e),this.visitLimitStatement(e.limitStatement())}visitLimitStatement(e){return new ie.Limit(this.getNumber(e.INTEGER_LITERAL()))}visitAggregateOrderBySpec(e){const r=e.ASC()?"asc":e.DESC()?"desc":void 0,i=e.fieldExpr(),s=i?this.getFieldExpr(i):void 0;return this.astAt(new ie.FunctionOrderBy(s,r),e)}visitAggregateOrderByStatement(e){return this.visitAggregateOrdering(e.aggregateOrdering())}visitAggregateOrdering(e){const r=e.aggregateOrderBySpec().map(i=>this.visitAggregateOrderBySpec(i));return this.astAt(new ie.FunctionOrdering(r),e)}visitOrderBySpec(e){const r=e.ASC()?"asc":e.DESC()?"desc":void 0,i=e.INTEGER_LITERAL();if(i)return new ie.OrderBy(this.getNumber(i),r);const s=e.fieldName();if(s)return new ie.OrderBy(this.getFieldName(s),r);throw this.internalError(e,"can't parse order_by specification")}visitOrdering(e){const r=e.orderBySpec().map(i=>this.visitOrderBySpec(i));return this.astAt(new ie.Ordering(r),e)}visitTopStatement(e){const r=this.getNumber(e.INTEGER_LITERAL());return this.astAt(new ie.Limit(r),e)}visitTopLevelQueryDefs(e){const r=e.topLevelQueryDef().map(o=>this.visitTopLevelQueryDef(o)),i=this.getNotes(e.tags()),s=new ie.DefineQueryList(r);return s.extendNote({blockNotes:i}),s}visitTopLevelQueryDef(e){const r=(0,Yn.getId)(e.queryName()),i=this.visit(e.sqExpr()),s=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));if(i instanceof ie.SourceQueryElement){const o=new ie.DefineQuery(r,i);return o.extendNote({notes:s}),this.astAt(o,e)}throw this.internalError(e,`Expected query definition, got a '${i.elementType}'`)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getSqExpr(r.sqExpr()),s=this.astAt(new ie.AnonymousQuery(i),r),o=this.getNotes(e.topLevelAnonQueryDef().tags()),u=this.getNotes(e.tags());return s.extendNote({notes:o,blockNotes:u}),this.astAt(s,e)}visitNestStatement(e){const r=this.visitNestedQueryList(e.nestedQueryList());return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitNestedQueryList(e){return new ie.Nests(this.only(e.nestEntry().map(r=>this.visit(r)),r=>r instanceof ie.NestFieldDeclaration&&r,"query"))}visitNestDef(e){const r=e.queryName();let i;const s=this.getVExpr(e.vExpr());if(r)i=(0,Yn.getId)(r);else{const a=s.getImplicitName();a===void 0&&this.contextError(e,"anonymous-nest","`nest:` view requires a name (add `nest_name is ...`)"),i=a??"__unnamed__"}const o=new ie.NestFieldDeclaration(i,s),u=e.isDefine();return o.extendNote({notes:this.getNotes(e.tags()).concat(u?this.getIsNotes(u):[])}),this.astAt(o,e)}visitExploreQueryDef(e){const r=(0,Yn.getId)(e.exploreQueryNameDef()),i=new ie.ViewFieldDeclaration(r,this.getVExpr(e.vExpr())),s=this.getNotes(e).concat(this.getIsNotes(e.isDefine()));return i.extendNote({notes:s}),this.astAt(i,e)}visitExprNot(e){return new ie.ExprNot(this.getFieldExpr(e.fieldExpr()))}visitExprBool(e){return new ie.Boolean(e.TRUE()?"true":"false")}allFieldExpressions(e){return e.map(r=>this.getFieldExpr(r))}visitExprLogicalOr(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1));return new ie.ExprLogicalOp(r,"or",i)}visitExprLogicalAnd(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1));return new ie.ExprLogicalOp(r,"and",i)}visitExprOrTree(e){const r=this.getFieldExpr(e.fieldExpr()),i=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new ie.ExprAlternationTree(r,"|",i),e)}visitExprAndTree(e){const r=this.getFieldExpr(e.fieldExpr()),i=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new ie.ExprAlternationTree(r,"&",i),e)}visitExprCoalesce(e){const r=this.getFieldExpr(e.fieldExpr()[0]),i=this.getFieldExpr(e.fieldExpr()[1]);return this.astAt(new ie.ExprCoalesce(r,i),e)}visitPartialCompare(e){const r=e.compareOp().text;if(ie.isComparison(r))return this.astAt(new ie.PartialCompare(r,this.getFieldExpr(e.fieldExpr())),e);throw this.internalError(e,`partial comparison '${r}' not recognized`)}visitPartialTest(e){const r=e.partialCompare();return r?this.visitPartialCompare(r):this.astAt(new ie.PartialIsNull(e.NOT()?"!=":"="),e)}visitPartialAllowedFieldExpr(e){const r=e.fieldExpr();if(r)return this.getFieldExpr(r);const i=e.partialTest();if(i)return this.visitPartialTest(i);throw this.internalError(e,"impossible partial")}visitExprString(e){const r=this.getPlainStringFrom(e);return new ie.ExprString(r)}visitRawString(e){const r=e.text.slice(1).trimStart();if(r[r.length-1]===`
1161
- `){const o=r[0]==="'"?'"':"'";this.contextError(e,"literal-string-newline",`Missing ${o}${r[0]}${o} before end-of-line`)}const s=new ie.ExprString(r.slice(1,-1));return this.astAt(s,e)}visitExprRegex(e){const r=e.HACKY_REGEX().text;return new ie.ExprRegEx(r.slice(2,-1))}visitExprNow(e){return new ie.ExprNow}visitExprNumber(e){return new ie.ExprNumber(e.text)}visitExprFieldPath(e){const r=new ie.ExprIdReference(this.getFieldPath(e.fieldPath(),ie.ExpressionFieldReference));return this.astAt(r,e)}visitExprNULL(e){return new ie.ExprNULL}visitExprExpr(e){return new ie.ExprParens(this.getFieldExpr(e.fieldExpr()))}visitExprMinus(e){return new ie.ExprMinus(this.getFieldExpr(e.fieldExpr()))}visitExprAddSub(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1)),s=e.PLUS()?"+":"-";return new ie.ExprAddSub(r,s,i)}visitExprMulDiv(e){const r=e.STAR()?"*":e.SLASH()?"/":"%";return new ie.ExprMulDiv(this.getFieldExpr(e.fieldExpr(0)),r,this.getFieldExpr(e.fieldExpr(1)))}visitExprCompare(e){const r=e.compareOp().text,i=this.getFieldExpr(e.fieldExpr(0)),s=this.getFieldExpr(e.fieldExpr(1));if(ie.isEquality(r)){const o=this.rangeFromContext(e);return s instanceof ie.ExprNULL&&(r==="="?this.warnWithReplacement("sql-is-null","Use 'is null' to check for NULL instead of '= null'",o,`${this.getSourceCode(e.fieldExpr(0))} is null`):r==="!="&&this.warnWithReplacement("sql-is-not-null","Use 'is not null' to check for NULL instead of '!= null'",o,`${this.getSourceCode(e.fieldExpr(0))} is not null`)),this.astAt(new ie.ExprEquality(i,r,s),e)}else if(ie.isComparison(r))return this.astAt(new ie.ExprCompare(i,r,s),e);throw this.internalError(e,`untranslatable comparison operator '${r}'`)}visitExprUngroup(e){const r=e.fieldName().map(s=>this.getFieldName(s)),i=e.ungroup().text.toLowerCase();return this.astAt(new ie.ExprUngroup(i==="all"?i:"exclude",this.getFieldExpr(e.fieldExpr()),r),e)}symmetricAggregateUsageError(e){return`Symmetric aggregate function \`${e}\` must be written as \`${e}(expression)\` or \`path.to.field.${e}()\``}asymmetricAggregateUsageError(e){return`Asymmetric aggregate function \`${e}\` must be written as \`path.to.field.${e}()\`, \`path.to.join.${e}(expression)\`, or \`${e}(expression)\``}visitExprAggregate(e){const r=e.fieldPath(),i=this.getFieldPath(r,ie.ExpressionFieldReference),s=r&&i?this.astAt(i,r):void 0,o=e.aggregate().text.toLowerCase(),u=e.fieldExpr();if(e.aggregate().COUNT())return u&&this.contextError(u,"count-expression-with-locality","Expression illegal inside path.count()"),new ie.ExprCount(s);const a=u?this.getFieldExpr(u):void 0;if(o==="min"||o==="max")if(a)this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(o));else{const l=this.astAt(new ie.ExprIdReference(i),r);return o==="min"?new ie.ExprMin(l):new ie.ExprMax(l)}else{if(o==="avg")return new ie.ExprAvg(a,s);if(o==="sum")return new ie.ExprSum(a,s);this.contextError(e,"aggregate-parse-error",`Cannot parse aggregate function ${o}`)}return new ie.ExprNULL}visitExprPathlessAggregate(e){const r=e.fieldExpr(),i=r?this.getFieldExpr(r):void 0,s=void 0,o=e.aggregate().text.toLowerCase();if(o==="count")return this.astAt(i?new ie.ExprCountDistinct(i):new ie.ExprCount,e);if(o==="min"){if(i)return new ie.ExprMin(i);this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(o))}else if(o==="max"){if(i)return new ie.ExprMax(i);this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(o))}else{if(i===void 0)return this.contextError(e,"invalid-asymmetric-aggregate",this.asymmetricAggregateUsageError(o)),new ie.ExprNULL;const u=e.SOURCE_KW()!==void 0;if(o==="avg")return new ie.ExprAvg(i,s,u);if(o==="sum")return new ie.ExprSum(i,s,u)}return new ie.ExprNULL}visitExprApply(e){return new ie.Apply(this.getFieldExpr(e.fieldExpr()),this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprRange(e){return new ie.Range(this.getFieldExpr(e.fieldExpr(0)),this.getFieldExpr(e.fieldExpr(1)))}visitExprCast(e){const r=this.getMalloyOrSQLType(e.malloyOrSQLType());return new ie.ExprCast(this.getFieldExpr(e.fieldExpr()),r)}getMalloyType(e){const r=e.text;if((0,yT.isCastType)(r))return r;throw this.internalError(e,`unknown type '${r}'`)}getMalloyOrSQLType(e){const r=e.malloyType();if(r)return this.getMalloyType(r);const i=e.string();if(i)return{raw:this.getPlainStringFrom({string:()=>i})};throw this.internalError(e,"Expected Malloy or SQL type to either be a Malloy type or a string")}visitExprSafeCast(e){const r=this.getMalloyOrSQLType(e.malloyOrSQLType());return new ie.ExprCast(this.getFieldExpr(e.fieldExpr()),r,!0)}visitExprTimeTrunc(e){return new ie.ExprGranularTime(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text,!0)}visitTimeframe(e){return new ie.Timeframe(e.text)}visitExprForRange(e){const r=this.getFieldExpr(e._startAt),i=this.getFieldExpr(e._duration),s=this.visitTimeframe(e.timeframe());return new ie.ForRange(r,i,s)}visitExprAggFunc(e){const r=e.argumentList(),i=r?this.allFieldExpressions(r.fieldExpr()):[],s=(0,Yn.getId)(e),o=e.fieldPath(),u=o?this.getFieldPath(o,ie.ExpressionFieldReference):void 0,a=o&&u?this.astAt(u,o):void 0;return ie.ExprTimeExtract.extractor(s)?this.astAt(new ie.ExprTimeExtract(s,i),e):this.astAt(new ie.ExprFunc(s,i,!1,void 0,a),e)}visitExprFunc(e){var r,i;const s=e.argumentList(),o=s?this.allFieldExpressions(s.fieldExpr()):[],u=e.EXCLAM()!==void 0,a=(r=e.malloyType())===null||r===void 0?void 0:r.text;let l;a&&((0,yT.isCastType)(a)?l=a:(this.contextError(e,"unexpected-malloy-type",`'#' assertion for unknown type '${a}'`),l=void 0));let c=(0,Yn.getOptionalId)(e)||((i=e.timeframe())===null||i===void 0?void 0:i.text);return c===void 0&&(this.contextError(e,"failed-to-parse-function-name","Function name error"),c="FUNCTION_NAME_ERROR"),ie.ExprTimeExtract.extractor(c)?this.astAt(new ie.ExprTimeExtract(c,o),e):this.astAt(new ie.ExprFunc(c,o,u,l),e)}visitExprDuration(e){return new ie.ExprDuration(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text)}visitCaseStatement(e){const r=e._valueExpr,i=r?this.getFieldExpr(r):void 0,s=e.caseWhen(),o=s.map(l=>new ie.CaseWhen(this.getFieldExpr(l._condition),this.getFieldExpr(l._result))),u=e._caseElse,a=u?this.getFieldExpr(u):void 0;return this.warnWithReplacement("sql-case","Use a `pick` statement instead of `case`",this.rangeFromContext(e),`${[...r?[`${this.getSourceCode(r)} ?`]:[],...s.map(l=>`pick ${this.getSourceCode(l._result)} when ${this.getSourceCode(l._condition)}`),u?`else ${u.text}`:"else null"].join(" ")}`),new ie.Case(i,o,a)}visitPickStatement(e){const r=e.pick().map(i=>{let s;return i._pickValue&&(s=this.getFieldExpr(i._pickValue)),new ie.PickWhen(s,this.getFieldExpr(i._pickWhen))});return e.ELSE()?new ie.Pick(r,this.getFieldExpr(e._pickElse)):new ie.Pick(r)}visitExprFieldProps(e){const r=this.only(e.fieldProperties().fieldPropertyStatement().map(i=>this.visit(i)),i=>ie.isFieldPropStatement(i)&&i,"field property statement");return new ie.ExprProps(this.getFieldExpr(e.fieldExpr()),r)}visitPartitionByStatement(e){return this.astAt(new ie.PartitionBy(e.id().map(r=>this.astAt(new ie.PartitionByFieldReference([this.astAt(new ie.FieldName((0,Yn.idToStr)(r)),r)]),r))),e)}visitLiteralTimestamp(e){return this.parseTime(e,ie.LiteralTimestamp.parse)}visitLiteralHour(e){return this.parseTime(e,ie.LiteralHour.parse)}visitLiteralDay(e){return this.parseTime(e,ie.LiteralDay.parse)}visitLiteralWeek(e){return this.parseTime(e,ie.LiteralWeek.parse)}visitLiteralMonth(e){return this.parseTime(e,ie.LiteralMonth.parse)}visitLiteralQuarter(e){return this.parseTime(e,ie.LiteralQuarter.parse)}visitLiteralYear(e){return this.parseTime(e,ie.LiteralYear.parse)}visitImportStatement(e){const r=this.getPlainStringFrom(e.importURL()),i=this.astAt(new ie.ImportStatement(r,this.parseInfo.importBaseURL),e),s=e.importSelect();if(s)for(const o of s.importItem()){const u=o.id(),a=u[1]?this.astAt(new ie.ImportSourceName((0,Yn.idToStr)(u[1])),u[1]):void 0;i.push(this.astAt(new ie.ImportSelect((0,Yn.idToStr)(u[0]),a),u[0]))}return i}visitDebugExpr(e){return this.getFieldExpr(e.fieldExpr())}visitSampleStatement(e){const r=e.sampleSpec().INTEGER_LITERAL();if(r)return new ie.SampleProperty({rows:this.getNumber(r)});const i=e.sampleSpec().PERCENT_LITERAL();if(i)return new ie.SampleProperty({percent:this.getNumber(i)});const s=e.sampleSpec().TRUE()!==void 0;return new ie.SampleProperty({enable:s})}visitDocAnnotations(e){const r=e.DOC_ANNOTATION().map(s=>({text:s.text,at:this.getLocation(e)})),i=new ie.ModelAnnotation(r);return this.compilerFlags=i.getCompilerFlags(this.compilerFlags,this.msgLog),i}visitIgnoredObjectAnnotations(e){return this.contextError(e,"orphaned-object-annotation","Object annotation not connected to any object"),new Ek(e.text)}visitIgnoredModelAnnotations(e){return this.contextError(e,"misplaced-model-annotation","Model annotations not allowed at this scope"),new Ek(e.text)}visitDefExploreAnnotation(e){const r=this.getNotes(e);return new ie.ObjectAnnotation(r)}getSQArgument(e){const r=e.argumentId(),i=r?this.astAt(new ie.PartitionByFieldReference([this.astAt(new ie.FieldName((0,Yn.idToStr)(r.id())),r)]),r):void 0;return this.astAt(new ie.Argument({id:i,value:this.getFieldExpr(e.fieldExpr())}),e)}getSQArguments(e){if(e!==void 0)return this.inExperiment("parameters",e),e.sourceArgument().map(r=>this.getSQArgument(r))}visitSQID(e){const r=this.getModelEntryName(e),i=this.getSQArguments(e.sourceArguments());return this.astAt(new ie.SQReference(r,i),e.id())}getSqExpr(e){const r=this.visit(e);return r instanceof ie.SourceQueryElement?r:(this.contextError(e,"unexpected-non-source-query-expression-node",`Expected a source/query expression, not '${r.elementType}'`),new H0e)}visitSQExtendedSource(e){const r=this.getSqExpr(e.sqExpr()),i=e.includeBlock(),s=i?this.getIncludeItems(i):void 0,o=new ie.SQExtend(r,this.getSourceExtensions(e.exploreProperties()),s);return this.astAt(o,e)}getIncludeItems(e){return this.inExperiment("access_modifiers",e),e.includeItem().map(r=>this.getIncludeItem(r)).filter(q0e.isNotUndefined)}getIncludeItem(e){var r;const i=e.tags(),s=i?this.getNotes(i):[],o=e.includeExceptList();if(o){i&&s.length>0&&this.contextError(i,"cannot-tag-include-except","Tags on `except:` are ignored",{severity:"warn"});const u=this.getExcludeList(o);return this.astAt(new ie.IncludeExceptItem(u),e)}else{const u=e.includeList();if(u===void 0){this.contextError((r=e.orphanedAnnotation())!==null&&r!==void 0?r:e,"orphaned-object-annotation","This tag is not attached to anything",{severity:"warn"});return}const a=this.getAccessLabelProp(e.accessLabelProp()),l=this.getIncludeList(u),c=this.astAt(new ie.IncludeAccessItem(a,l),e);return c.extendNote({blockNotes:s}),c}}getIncludeList(e){const r=e.includeField();if(r===void 0)throw this.internalError(e,"Expected a field name list");return r.map(i=>this.getIncludeListItem(i))}getExcludeList(e){return e.includeExceptListItem().map(r=>{r.tags().ANNOTATION().length>0&&this.contextError(r.tags(),"cannot-tag-include-except","Tags on `except:` are ignored",{severity:"warn"});const i=r.fieldName();if(i)return this.astAt(new ie.AccessModifierFieldReference([this.astAt(this.getFieldName(i),r)]),i);const s=r.collectionWildCard();if(s)return this.astAt(this.visitCollectionWildCard(s),s);throw this.internalError(r,"Expected a field name or wildcard")})}getIncludeListItem(e){const r=e.collectionWildCard(),i=r?this.visitCollectionWildCard(r):void 0,s=e._as?e._as.text:void 0,o=e.tags(),u=o?this.getNotes(o):[],a=e.isDefine(),l=a?this.getIsNotes(a):[],c=[...u,...l],f=e._name?this.astAt(new ie.AccessModifierFieldReference([this.astAt(this.getFieldName(e._name),e._name)]),e._name):void 0,x=f??i;if(x===void 0)throw this.internalError(e,"Expected a field name or wildcard");const h=this.astAt(new ie.IncludeListItem(x,s),e);return h.extendNote({notes:c}),h}visitSQParens(e){const r=this.getSqExpr(e.sqExpr());return this.astAt(r,e)}visitSQCompose(e){const r=e.sqExpr().map(i=>this.getSqExpr(i));return this.inExperiment("composite_sources",e),this.astAt(new ie.SQCompose(r),e)}visitSQArrow(e){const r=this.getSqExpr(e.sqExpr()),i=e.segExpr(),s=new ie.SQArrow(r,this.getVExpr(i));return this.astAt(s,e)}getVExpr(e){const r=this.visit(e);if(r instanceof ie.View)return r;throw this.internalError(e,`Expected view, got a '${r.elementType}'`)}visitSegField(e){return new ie.ReferenceView(this.getFieldPath(e.fieldPath(),ie.ViewOrScalarFieldReference))}visitSegOps(e){return new ie.QOpDescView(this.visitQueryProperties(e.queryProperties()))}visitSegParen(e){return this.visit(e.vExpr())}visitVSeg(e){return this.visit(e.segExpr())}visitSegRefine(e){return new ie.ViewRefine(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitVArrow(e){return new ie.ViewArrow(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitSQRefinedQuery(e){const r=this.getSqExpr(e.sqExpr()),i=e.segExpr(),s=new ie.SQRefine(r,this.getVExpr(i));return this.astAt(s,e)}visitSQTable(e){const r=this.visit(e.exploreTable());if(r instanceof _ct.TableSource){const i=new ie.SQSource(r);return this.astAt(i,e)}return new H0e}visitSQSQL(e){const r=new ie.SQSource(this.visitSqlSource(e.sqlSource()));return this.astAt(r,e)}visitExperimentalStatementForTesting(e){return this.inExperiment("compilerTestExperimentParse",e),this.astAt(new ie.ExperimentalExperiment("compilerTestExperimentTranslate"),e)}visitRecordRef(e){const r=new ie.ExprIdReference(this.getFieldPath(e.fieldPath(),ie.ExpressionFieldReference));return this.astAt(new ie.RecordElement({path:r}),e)}visitRecordExpr(e){const r=this.getFieldExpr(e.fieldExpr()),i=e.recordKey(),s=i?{key:(0,Yn.getId)(i),value:r}:{value:r};return this.astAt(new ie.RecordElement(s),e)}visitExprLiteralRecord(e){const r=this.only(e.recordElement().map(i=>this.astAt(this.visit(i),i)),i=>i instanceof ie.RecordElement&&i,"a legal record property description");return new ie.RecordLiteral(r)}visitExprArrayLiteral(e){const r=e.fieldExpr().map(s=>this.getFieldExpr(s)),i=new ie.ArrayLiteral(r);return this.astAt(i,e)}visitExprWarnLike(e){let r="~";const i=e.fieldExpr(0),s=e.fieldExpr(1),o=this.rangeFromContext(e);return e.NOT()?(r="!~",this.warnWithReplacement("sql-not-like","Use Malloy operator '!~' instead of 'NOT LIKE'",o,`${this.getSourceCode(i)} !~ ${this.getSourceCode(s)}`)):this.warnWithReplacement("sql-like","Use Malloy operator '~' instead of 'LIKE'",o,`${this.getSourceCode(i)} ~ ${this.getSourceCode(s)}`),this.astAt(new ie.ExprCompare(this.getFieldExpr(i),r,this.getFieldExpr(s)),e)}visitExprNullCheck(e){const r=e.fieldExpr();return this.astAt(new ie.ExprIsNull(this.getFieldExpr(r),e.NOT()?"!=":"="),e)}visitExprWarnIn(e){const r=this.getFieldExpr(e.fieldExpr()),i=!!e.NOT(),s=e.fieldExprList().fieldExpr(),o=this.astAt(new ie.ExprLegacyIn(r,i,s.map(u=>this.getFieldExpr(u))),e);return this.warnWithReplacement("sql-in",`Use = (a|b|c) instead of${i?" NOT":""} IN (a,b,c)`,this.rangeFromContext(e),`${this.getSourceCode(e.fieldExpr())} ${i?"!=":"="} (${s.map(u=>this.getSourceCode(u)).join(" | ")})`),o}visitTickFilterString(e){const r=e.text.slice(1).trimStart();if(r[r.length-1]===`
1162
- `){const u=r[0]==="'"?'"':"'";this.contextError(e,"literal-string-newline",`Missing $${u}${r[0]}${u} before end-of-line`)}const s=r.slice(1,-1),o=new ie.ExprFilterExpression(s);return this.astAt(o,e)}visitTripFilterString(e){const i=e.text.slice(1).trimStart().slice(3,-3),s=new ie.ExprFilterExpression(i);return this.astAt(s,e)}}gT.MalloyToAST=bct;var ET={};Object.defineProperty(ET,"__esModule",{value:!0}),ET.Zone=void 0;class Tct{constructor(){this.location={},this.zone=new Map}get(e){const r=this.zone.get(e);if((r==null?void 0:r.status)==="present")return r.value}getEntry(e){const r=this.zone.get(e);return r?r.firstReference||!this.location[e]?r:{...r,firstReference:this.location[e]}:{status:"error",message:"import reference failure"}}define(e,r){this.zone.set(e,{status:"present",value:r})}reference(e,r){const i=this.zone.get(e);(i==null?void 0:i.status)===void 0&&(this.zone.set(e,{status:"reference",firstReference:r}),this.location[e]=r)}getUndefined(){const e=[];for(const[r,i]of this.zone)i.status==="reference"&&e.push(r);return e.length>0?e:void 0}updateFrom(e,r){if(e)for(const[i,s]of Object.entries(e))s!==void 0&&this.define(i,s);if(r)for(const[i,s]of Object.entries(r))this.zone.set(i,{status:"error",message:s})}}ET.Zone=Tct;var AT={};Object.defineProperty(AT,"__esModule",{value:!0}),AT.walkForDocumentSymbols=void 0;const Rct=uc,Dct=Bn;class Oct{constructor(e,r,i,s){this.translator=e,this.tokens=r,this.scopes=i,this.symbols=s}popScope(){return this.scopes.pop()}peekScope(){return this.scopes[this.scopes.length-1]}enterTopLevelQueryDefs(e){const r=this.translator.rangeFromContext(e);e.topLevelQueryDef().length===1&&(this.blockRange=r)}enterTopLevelQueryDef(e){this.symbols.push({range:this.translator.rangeFromContext(e),name:e.queryName().text,type:"query",children:[],lensRange:this.blockRange}),this.blockRange=void 0}enterRunStatement(e){this.symbols.push({range:this.translator.rangeFromContext(e.topLevelAnonQueryDef()),name:"unnamed_query",type:"unnamed_query",children:[],lensRange:this.translator.rangeFromContext(e)})}enterDefineSourceStatement(e){const r=this.translator.rangeFromContext(e);e.sourcePropertyList().sourceDefinition().length===1&&(this.blockRange=r)}enterSourceDefinition(e){const r=this.translator.rangeFromContext(e);this.scopes.push({range:r,name:e.sourceNameDef().id().text,type:"explore",children:[],lensRange:this.blockRange}),this.blockRange=void 0}exitSourceDefinition(e){const r=this.popScope();r&&this.symbols.push(r)}enterDefExploreQuery(e){const r=this.translator.rangeFromContext(e);e.subQueryDefList().exploreQueryDef().length===1&&(this.blockRange=r)}enterExploreQueryDef(e){const r={range:this.translator.rangeFromContext(e),name:e.exploreQueryNameDef().id().text,type:"query",children:[],lensRange:this.blockRange},i=this.peekScope();i&&i.children.push(r),this.scopes.push(r),this.blockRange=void 0}exitExploreQueryDef(e){this.popScope()}getNestDefName(e){const r=e.queryName();if(r)return r.id().text;let i,s=!1;const o={enterVArrow(a){a.vExpr().enterRule(o)},enterVSeg(a){a.segExpr().enterRule(u)}},u={enterSegField(a){const l=a.fieldPath().fieldName();s||(i??(i=l[l.length-1].id().text))},enterSegParen(a){a.vExpr().enterRule(o)},enterSegRefine(a){a._lhs.enterRule(u)},enterSegOps(){i=void 0,s=!0}};return e.vExpr().enterRule(o),i}handleNestEntry(e){const r=this.getNestDefName(e);if(r===void 0)return;const i={range:this.translator.rangeFromContext(e),name:r,type:"query",children:[]},s=this.peekScope();return s&&s.children.push(i),i}enterNestDef(e){const r=this.handleNestEntry(e);r&&this.scopes.push(r)}exitNestDef(e){this.popScope()}enterFieldDef(e){const r={range:this.translator.rangeFromContext(e),name:e.fieldNameDef().id().text,type:"field",children:[]},i=this.peekScope();i&&i.children.push(r)}enterQueryFieldEntry(e){var r;const i=(r=e.taggedRef())===null||r===void 0?void 0:r.fieldPath();if(i===void 0)return;const s={range:this.translator.rangeFromContext(e),name:i.text,type:"field",children:[]},o=this.peekScope();o&&o.children.push(s)}enterExploreRenameDef(e){const r={range:this.translator.rangeFromContext(e),name:e.fieldName()[0].text,type:"field",children:[]},i=this.peekScope();i&&i.children.push(r)}enterJoinWith(e){this.handleJoinDef(e)}enterJoinOn(e){this.handleJoinDef(e)}handleJoinDef(e){const r={range:this.translator.rangeFromContext(e),name:e.joinFrom().joinNameDef().id().text,type:"join",children:[]},i=this.peekScope();i&&i.children.push(r)}enterImportStatement(e){const r=(0,Dct.getStringIfShort)(e.importURL());r&&this.scopes.push({range:this.translator.rangeFromContext(e),name:r,type:"import",children:[]})}exitImportStatement(){const e=this.popScope();e&&this.symbols.push(e)}enterImportSelect(e){const r=this.peekScope();if(r)for(const i of e.importItem()){const s={range:this.translator.rangeFromContext(e),name:i.text,type:"import_item",children:[]};r.children.push(s)}}}function Fct(t,e,r){const i=new Oct(t,e,[],[]),s=i;return Rct.ParseTreeWalker.DEFAULT.walk(s,r),i.symbols}AT.walkForDocumentSymbols=Fct;var _T={};Object.defineProperty(_T,"__esModule",{value:!0}),_T.walkForDocumentCompletions=void 0;const wct=uc,Nct=["dimension","measure","join_one","join_many","join_cross","where","primary_key","rename","accept","except","query","declare"],Lct=["group_by","project","index","aggregate","top","limit","order_by","where","having","nest","declare"],Ict=["source","explore","query","sql"];class Bct{constructor(e,r,i){this.tokens=e,this.completions=r,this.position=i}rangeOf(e){const r=e.stop||e.start;return{start:{line:e.start.line-1,character:e.start.charPositionInLine},end:{line:r.line-1,character:r.stopIndex-(r.startIndex-r.charPositionInLine)+1}}}inRange(e){const{start:r,end:i}=e,s=this.position.line>r.line||this.position.line===r.line&&this.position.character>=r.character,o=this.position.line<i.line||this.position.line===i.line&&this.position.character<=i.character;return s&&o}enterExploreProperties(e){if(this.inRange(this.rangeOf(e))){let r=!1;for(const i of e.exploreStatement())this.inRange(this.rangeOf(i))&&(r=!0);if(!r)for(const i of Nct)this.completions.push({type:"explore_property",text:`${i}: `})}}enterQueryProperties(e){if(this.inRange(this.rangeOf(e))){let r=!1;for(const i of e.queryStatement())this.inRange(this.rangeOf(i))&&(r=!0);if(!r)for(const i of Lct)this.completions.push({type:"query_property",text:`${i}: `})}}enterMalloyDocument(e){if(this.inRange(this.rangeOf(e))){let r=!1;for(const i of e.malloyStatement())this.inRange(this.rangeOf(i))&&(r=!0);if(!r)for(const i of Ict)this.completions.push({type:"model_property",text:`${i}: `})}}}function $ct(t,e,r){const i=new Bct(t,[],r),s=i;return wct.ParseTreeWalker.DEFAULT.walk(s,e),i.completions}_T.walkForDocumentCompletions=$ct;var vT={};Object.defineProperty(vT,"__esModule",{value:!0}),vT.walkForDocumentHelpContext=void 0;const kct=qL;class Mct extends kct.AbstractParseTreeVisitor{constructor(e){super(),this.position=e,this.type=""}rangeOf(e){const r=e.stop||e.start;return{start:{line:e.start.line-1,character:e.start.charPositionInLine},end:{line:r.line-1,character:r.stopIndex-(r.startIndex-r.charPositionInLine)+1}}}inRange(e){return e.start.line<=this.position.line&&e.end.line>=this.position.line&&(this.position.line!==e.start.line||this.position.character>=e.start.character)&&(this.position.line!==e.end.line||this.position.character<=e.end.character)}defaultResult(){}visitChildren(e){let r=this.defaultResult();if(this.inRange(this.rangeOf(e))){r={type:this.type,token:e.start.text};const i=e.childCount;for(let s=0;s<i;s++){const u=e.getChild(s).accept(this);u&&(r=this.aggregateResult(r,u))}}return r}visitMalloyDocument(e){return this.inRange(this.rangeOf(e))?(this.type="model_property",this.visitChildren(e)):this.defaultResult()}visitExploreProperties(e){return this.inRange(this.rangeOf(e))?(this.type="explore_property",this.visitChildren(e)):this.defaultResult()}visitQueryProperties(e){return this.inRange(this.rangeOf(e))?(this.type="query_property",this.visitChildren(e)):this.defaultResult()}aggregateResult(e,r){return r}}function Pct(t,e){return new Mct(e).visit(t)}vT.walkForDocumentHelpContext=Pct;var CT={};Object.defineProperty(CT,"__esModule",{value:!0}),CT.ReferenceList=void 0;const Uct=Vn;class jct{constructor(e){this.sourceURL=e,this.references=[]}findIndexBefore(e){let r=0,i=this.references.length;for(;r<i;){const s=Math.floor((r+i)/2),o=this.references[s].location.range.end;o.line<e.line||o.line===e.line&&o.character<e.character?r=s+1:i=s}return r}add(e){if(e.location.url!==this.sourceURL)return;const r=this.findIndexBefore(e.location.range.end);r<this.references.length&&this.isPositionEqual(e,this.references[r])||this.references.splice(r,0,e)}isPositionEqual(e,r){const i=e.location.range,s=r.location.range;return i.start.line===s.start.line&&i.start.character===s.start.character&&i.end.line===s.end.line&&i.end.character===s.end.character}find(e){const r=this.findIndexBefore(e);if(r===this.references.length)return;const i=this.references[r];if((0,Uct.locationContainsPosition)(i.location,e))return i}}CT.ReferenceList=jct;var ST={};Object.defineProperty(ST,"__esModule",{value:!0}),ST.isNeedResponse=void 0;function qct(t){return!!t&&(t.tables||t.urls||t.compileSQL)!==void 0}ST.isNeedResponse=qct;var bT={};Object.defineProperty(bT,"__esModule",{value:!0}),bT.walkForModelAnnotation=void 0;const Hct=uc;class Qct{constructor(e,r,i){this.translator=e,this.tokens=r,this.parseInfo=i,this.notes=[]}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.translator.rangeFromContext(e)}}enterDocAnnotations(e){const r=e.DOC_ANNOTATION().map(i=>({text:i.text,at:this.getLocation(e)}));this.notes.push(...r)}get annotation(){return{notes:this.notes}}}function zct(t,e,r){const i=new Qct(t,e,r),s=i;return Hct.ParseTreeWalker.DEFAULT.walk(s,r.root),i.annotation}bT.walkForModelAnnotation=zct;var TT={};Object.defineProperty(TT,"__esModule",{value:!0}),TT.walkForTablePath=void 0;const Q0e=Bn,Gct=uc;class Wct{constructor(e,r){this.translator=e,this.tokens=r,this.pathInfos=[]}enterExploreTable(e){const r=(0,Q0e.getId)(e.connectionId()),[i,s]=(0,Q0e.getPlainString)(e.tablePath(),!0);i!==void 0&&this.pathInfos.push({connectionId:r,tablePath:i,range:this.translator.rangeFromContext(e)})}}function Vct(t,e,r){const i=new Wct(t,e),s=i;return Gct.ParseTreeWalker.DEFAULT.walk(s,r.root),i.pathInfos}TT.walkForTablePath=Vct;var aE={},RT={},Yct=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Kct=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Jct=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Yct(e,t,r);return Kct(e,t),e};Object.defineProperty(RT,"__esModule",{value:!0}),RT.MalloyLexer=void 0;const Xct=Sp(),Zct=Ml(),eft=Xg(),tft=Fs,z0e=Jct(Sn);class se extends Zct.Lexer{get vocabulary(){return se.VOCABULARY}constructor(e){super(e),this._interp=new eft.LexerATNSimulator(se._ATN,this)}get grammarFileName(){return"MalloyLexer.g4"}get ruleNames(){return se.ruleNames}get serializedATN(){return se._serializedATN}get channelNames(){return se.channelNames}get modeNames(){return se.modeNames}static get _ATN(){return se.__ATN||(se.__ATN=new Xct.ATNDeserializer().deserialize(z0e.toCharArray(se._serializedATN))),se.__ATN}}RT.MalloyLexer=se,se.ACCEPT=1,se.AGGREGATE=2,se.CALCULATE=3,se.CALCULATION=4,se.CONNECTION=5,se.DECLARE=6,se.DIMENSION=7,se.EXCEPT=8,se.EXTENDQ=9,se.GROUP_BY=10,se.HAVING=11,se.INDEX=12,se.INTERNAL=13,se.JOIN_CROSS=14,se.JOIN_ONE=15,se.JOIN_MANY=16,se.LIMIT=17,se.MEASURE=18,se.NEST=19,se.ORDER_BY=20,se.PARTITION_BY=21,se.PRIMARY_KEY=22,se.PRIVATE=23,se.PROJECT=24,se.PUBLIC=25,se.QUERY=26,se.RENAME=27,se.RUN=28,se.SAMPLE=29,se.SELECT=30,se.SOURCE=31,se.TOP=32,se.WHERE=33,se.VIEW=34,se.TIMEZONE=35,se.ALL=36,se.AND=37,se.AS=38,se.ASC=39,se.AVG=40,se.BOOLEAN=41,se.BY=42,se.CASE=43,se.CAST=44,se.CONDITION=45,se.COUNT=46,se.COMPOSE=47,se.DATE=48,se.DAY=49,se.DESC=50,se.DISTINCT=51,se.ELSE=52,se.END=53,se.EXCLUDE=54,se.EXTEND=55,se.FALSE=56,se.FILTER=57,se.FULL=58,se.FOR=59,se.FROM=60,se.HAS=61,se.HOUR=62,se.IMPORT=63,se.INCLUDE=64,se.INNER=65,se.IS=66,se.IN=67,se.INTERNAL_KW=68,se.JSON=69,se.LAST=70,se.LEFT=71,se.LIKE=72,se.MAX=73,se.MIN=74,se.MINUTE=75,se.MONTH=76,se.NOT=77,se.NOW=78,se.NULL=79,se.NUMBER=80,se.ON=81,se.OR=82,se.PICK=83,se.PRIVATE_KW=84,se.PUBLIC_KW=85,se.QUARTER=86,se.RIGHT=87,se.SECOND=88,se.STRING=89,se.SOURCE_KW=90,se.SUM=91,se.SQL=92,se.TABLE=93,se.THEN=94,se.THIS=95,se.TIMESTAMP=96,se.TO=97,se.TRUE=98,se.TURTLE=99,se.WEEK=100,se.WHEN=101,se.WITH=102,se.YEAR=103,se.UNGROUPED=104,se.HACKY_REGEX=105,se.RAW_SQ=106,se.RAW_DQ=107,se.SQ3_FILTER=108,se.SQ_FILTER=109,se.DQ3_FILTER=110,se.DQ_FILTER=111,se.BQ3_FILTER=112,se.BQ_FILTER=113,se.SQ_STRING=114,se.DQ_STRING=115,se.BQ_STRING=116,se.DOC_ANNOTATION=117,se.ANNOTATION=118,se.AMPER=119,se.ARROW=120,se.FAT_ARROW=121,se.OPAREN=122,se.CPAREN=123,se.OBRACK=124,se.CBRACK=125,se.OCURLY=126,se.CCURLY=127,se.DOUBLECOLON=128,se.TRIPLECOLON=129,se.EXCLAM=130,se.COLON=131,se.COMMA=132,se.DOT=133,se.LT=134,se.GT=135,se.EQ=136,se.NE=137,se.LTE=138,se.GTE=139,se.PLUS=140,se.MINUS=141,se.STAR=142,se.STARSTAR=143,se.SLASH=144,se.BAR=145,se.SEMI=146,se.NOT_MATCH=147,se.MATCH=148,se.PERCENT=149,se.DOUBLE_QMARK=150,se.QMARK=151,se.LITERAL_TIMESTAMP=152,se.LITERAL_HOUR=153,se.LITERAL_DAY=154,se.LITERAL_QUARTER=155,se.LITERAL_MONTH=156,se.LITERAL_WEEK=157,se.LITERAL_YEAR=158,se.IDENTIFIER=159,se.PERCENT_LITERAL=160,se.NUMERIC_LITERAL=161,se.INTEGER_LITERAL=162,se.BLOCK_COMMENT=163,se.COMMENT_TO_EOL=164,se.WHITE_SPACE=165,se.SQL_BEGIN=166,se.UNWATED_CHARS_TRAILING_NUMBERS=167,se.UNEXPECTED_CHAR=168,se.OPEN_CODE=169,se.SQL_END=170,se.SQL_MODE=1,se.channelNames=["DEFAULT_TOKEN_CHANNEL","HIDDEN"],se.modeNames=["DEFAULT_MODE","SQL_MODE"],se.ruleNames=["SPACE_CHAR","ACCEPT","AGGREGATE","CALCULATE","CALCULATION","CONNECTION","DECLARE","DIMENSION","EXCEPT","EXTENDQ","GROUP_BY","HAVING","INDEX","INTERNAL","JOIN_CROSS","JOIN_ONE","JOIN_MANY","LIMIT","MEASURE","NEST","ORDER_BY","PARTITION_BY","PRIMARY_KEY","PRIVATE","PROJECT","PUBLIC","QUERY","RENAME","RUN","SAMPLE","SELECT","SOURCE","TOP","WHERE","VIEW","TIMEZONE","ALL","AND","AS","ASC","AVG","BOOLEAN","BY","CASE","CAST","CONDITION","COUNT","COMPOSE","DATE","DAY","DESC","DISTINCT","ELSE","END","EXCLUDE","EXTEND","FALSE","FILTER","FULL","FOR","FROM","HAS","HOUR","IMPORT","INCLUDE","INNER","IS","IN","INTERNAL_KW","JSON","LAST","LEFT","LIKE","MAX","MIN","MINUTE","MONTH","NOT","NOW","NULL","NUMBER","ON","OR","PICK","PRIVATE_KW","PUBLIC_KW","QUARTER","RIGHT","SECOND","STRING","SOURCE_KW","SUM","SQL","TABLE","THEN","THIS","TIMESTAMP","TO","TRUE","TURTLE","WEEK","WHEN","WITH","YEAR","UNGROUPED","SQ","BQ","DQ","SQ3","DQ3","BQ3","RAW_CHAR","RAW3_CHAR","F_PREFIX","S_PREFIX","HACKY_REGEX","RAW_SQ","RAW_DQ","SQ3_FILTER","SQ_FILTER","DQ3_FILTER","DQ_FILTER","BQ3_FILTER","BQ_FILTER","HEX","UNICODE","SAFE_NON_QUOTE","ESCAPED","STR_CHAR","SQ_STRING","DQ_STRING","BQ_STRING","F_TO_EOL","DOC_ANNOTATION","ANNOTATION","AMPER","ARROW","FAT_ARROW","OPAREN","CPAREN","OBRACK","CBRACK","OCURLY","CCURLY","DOUBLECOLON","TRIPLECOLON","EXCLAM","COLON","COMMA","DOT","LT","GT","EQ","NE","LTE","GTE","PLUS","MINUS","STAR","STARSTAR","SLASH","BAR","SEMI","NOT_MATCH","MATCH","PERCENT","DOUBLE_QMARK","QMARK","F_YEAR","F_DD","F_TZ","LITERAL_TIMESTAMP","LITERAL_HOUR","LITERAL_DAY","LITERAL_QUARTER","LITERAL_MONTH","LITERAL_WEEK","LITERAL_YEAR","IDENTIFIER","PERCENT_LITERAL","EXPONENT","NUMERIC_LITERAL","INTEGER_LITERAL","ID_CHAR","DIGIT","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","BLOCK_COMMENT","COMMENT_TO_EOL","WHITE_SPACE","SQL_BEGIN","UNWATED_CHARS_TRAILING_NUMBERS","UNEXPECTED_CHAR","SQL_CHAR","OPEN_CODE","SQL_END"],se._LITERAL_NAMES=[void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,"'&'","'->'","'=>'","'('","')'","'['","']'","'{'","'}'","'::'","':::'","'!'","':'","','","'.'","'<'","'>'","'='","'!='","'<='","'>='","'+'","'-'","'*'","'**'","'/'","'|'","';'","'!~'","'~'","'%'","'??'","'?'",void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,`'"""'`],se._SYMBOLIC_NAMES=[void 0,"ACCEPT","AGGREGATE","CALCULATE","CALCULATION","CONNECTION","DECLARE","DIMENSION","EXCEPT","EXTENDQ","GROUP_BY","HAVING","INDEX","INTERNAL","JOIN_CROSS","JOIN_ONE","JOIN_MANY","LIMIT","MEASURE","NEST","ORDER_BY","PARTITION_BY","PRIMARY_KEY","PRIVATE","PROJECT","PUBLIC","QUERY","RENAME","RUN","SAMPLE","SELECT","SOURCE","TOP","WHERE","VIEW","TIMEZONE","ALL","AND","AS","ASC","AVG","BOOLEAN","BY","CASE","CAST","CONDITION","COUNT","COMPOSE","DATE","DAY","DESC","DISTINCT","ELSE","END","EXCLUDE","EXTEND","FALSE","FILTER","FULL","FOR","FROM","HAS","HOUR","IMPORT","INCLUDE","INNER","IS","IN","INTERNAL_KW","JSON","LAST","LEFT","LIKE","MAX","MIN","MINUTE","MONTH","NOT","NOW","NULL","NUMBER","ON","OR","PICK","PRIVATE_KW","PUBLIC_KW","QUARTER","RIGHT","SECOND","STRING","SOURCE_KW","SUM","SQL","TABLE","THEN","THIS","TIMESTAMP","TO","TRUE","TURTLE","WEEK","WHEN","WITH","YEAR","UNGROUPED","HACKY_REGEX","RAW_SQ","RAW_DQ","SQ3_FILTER","SQ_FILTER","DQ3_FILTER","DQ_FILTER","BQ3_FILTER","BQ_FILTER","SQ_STRING","DQ_STRING","BQ_STRING","DOC_ANNOTATION","ANNOTATION","AMPER","ARROW","FAT_ARROW","OPAREN","CPAREN","OBRACK","CBRACK","OCURLY","CCURLY","DOUBLECOLON","TRIPLECOLON","EXCLAM","COLON","COMMA","DOT","LT","GT","EQ","NE","LTE","GTE","PLUS","MINUS","STAR","STARSTAR","SLASH","BAR","SEMI","NOT_MATCH","MATCH","PERCENT","DOUBLE_QMARK","QMARK","LITERAL_TIMESTAMP","LITERAL_HOUR","LITERAL_DAY","LITERAL_QUARTER","LITERAL_MONTH","LITERAL_WEEK","LITERAL_YEAR","IDENTIFIER","PERCENT_LITERAL","NUMERIC_LITERAL","INTEGER_LITERAL","BLOCK_COMMENT","COMMENT_TO_EOL","WHITE_SPACE","SQL_BEGIN","UNWATED_CHARS_TRAILING_NUMBERS","UNEXPECTED_CHAR","OPEN_CODE","SQL_END"],se.VOCABULARY=new tft.VocabularyImpl(se._LITERAL_NAMES,se._SYMBOLIC_NAMES,[]),se._serializedATNSegments=4,se._serializedATNSegment0=`줝쪺֍꾺体؇쉁¬ފ\b\b     \x07 \x07\b \b 
1159
+ QUERY: ${(0,fle.inspect)(r,{breakLength:72,depth:1/0})}`)}return xle.ErrorFactory.structDef}ks.opOutputStruct=dle;function Int(t,e,r){for(const i of r)e=dle(t,e,i);return e}ks.getFinalStruct=Int;function Bnt(t,e){return t.fields.find(r=>(r.as||r.name)===e)}ks.getStructFieldDef=Bnt,Object.defineProperty(a2,"__esModule",{value:!0}),a2.QueryRefine=void 0;const $nt=Pr,knt=ks,Mnt=$y;class Pnt extends Mnt.QueryBase{constructor(e,r){super({base:e,refinement:r}),this.base=e,this.refinement=r,this.elementType="query-refine"}queryComp(e){const r=this.base.queryComp(e),i=new $nt.StaticSourceSpace(r.inputStruct),s=this.refinement.refine(i,r.query.pipeline,void 0),o={...r.query,pipeline:s},u=this.resolveCompositeSource(r.inputStruct,o);return{query:{...o,compositeResolvedSourceDef:u},outputStruct:(0,knt.getFinalStruct)(this.refinement,r.inputStruct,s),inputStruct:r.inputStruct}}}a2.QueryRefine=Pnt;var ky={},l2={},ds={};Object.defineProperty(ds,"__esModule",{value:!0}),ds.mkTimeResult=ds.resolution=ds.castTo=ds.timeOffset=void 0;const O$=Xe;function Unt(t,e,r,i,s){return{node:"delta",kids:{base:(0,O$.mkTemporal)(e,t),delta:i},op:r,units:s}}ds.timeOffset=Unt;function jnt(t,e,r,i=!1){let s;return typeof t!="string"?s={node:"cast",dstSQLType:t.raw,e,safe:i}:s={node:"cast",dstType:{type:t},e,safe:i},(0,O$.isCastType)(r)&&(s.srcType={type:r}),s}ds.castTo=jnt;function qnt(t){switch(t){case"hour":case"minute":case"second":case"microsecond":case"millisecond":return"timestamp"}return"date"}ds.resolution=qnt;function Hnt(t,e){if(e){if(t.type==="timestamp")return{...t,timeframe:e};if((0,O$.isDateUnit)(e))return{...t,timeframe:e}}return t}ds.mkTimeResult=Hnt;var ed={},ct={},Gt={};Object.defineProperty(Gt,"__esModule",{value:!0}),Gt.literalTimeResult=Gt.literalExprValue=Gt.computedErrorExprValue=Gt.computedTimeResult=Gt.computedExprValue=void 0;const hle=Pi,F$=lt;function My({value:t,dataType:e,from:r}){return{...e,value:t,expressionType:(0,hle.maxOfExpressionTypes)(r.map(i=>i.expressionType)),evalSpace:(0,hle.mergeEvalSpaces)(...r.map(i=>i.evalSpace)),compositeFieldUsage:(0,F$.mergeCompositeFieldUsage)(...r.map(i=>i.compositeFieldUsage))}}Gt.computedExprValue=My;function Qnt({value:t,dataType:e,from:r,timeframe:i}){const s=My({value:t,dataType:e,from:r}),o={...e,expressionType:s.expressionType,evalSpace:s.evalSpace,value:s.value,compositeFieldUsage:(0,F$.mergeCompositeFieldUsage)(...r.map(u=>u.compositeFieldUsage))};return i&&(o.timeframe=i),o}Gt.computedTimeResult=Qnt;function znt({dataType:t,from:e,error:r}){return My({dataType:t??{type:"error"},value:{node:"error",message:r},from:e})}Gt.computedErrorExprValue=znt;function Gnt(t){return My({...t,from:[]})}Gt.literalExprValue=Gnt;function Wnt({value:t,dataType:e,timeframe:r}){const i=My({value:t,dataType:e,from:[]}),s={...e,expressionType:i.expressionType,evalSpace:i.evalSpace,value:i.value,compositeFieldUsage:(0,F$.emptyCompositeFieldUsage)()};return r&&(s.timeframe=r),s}Gt.literalTimeResult=Wnt;var c2={};Object.defineProperty(c2,"__esModule",{value:!0}),c2.isGranularResult=void 0;function Vnt(t){return t.type==="date"||t.type==="timestamp"?t.timeframe!==void 0:!1}c2.isGranularResult=Vnt;var pu={};Object.defineProperty(pu,"__esModule",{value:!0}),pu.isComparison=pu.isEquality=pu.getExprNode=void 0;function Ynt(t){switch(t){case"~":return"like";case"!~":return"!like"}return t}pu.getExprNode=Ynt;function ple(t){return t==="="||t==="!="||t==="~"||t==="!~"}pu.isEquality=ple;function Knt(t){return ple(t)||t===">="||t==="<="||t===">"||t==="<"}pu.isComparison=Knt;var Jnt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Xnt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Znt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Jnt(e,t,r);return Xnt(e,t),e};Object.defineProperty(ct,"__esModule",{value:!0}),ct.checkFilterExpression=ct.applyBinary=ct.getMorphicValue=ct.ExprDuration=ct.ExpressionDef=ct.ATNodeType=void 0;const Lc=Xe,td=Znt(Zt),w$=Bs,Vl=Gt,ert=ds,mle=c2,trt=Je,Py=pu,Uy=Cy;class nrt extends Error{}var N$;(function(t){t[t.And=0]="And",t[t.Or=1]="Or",t[t.Value=2]="Value",t[t.Partial=3]="Partial"})(N$||(ct.ATNodeType=N$={}));class gle extends trt.MalloyElement{constructor(){super(...arguments),this.legalChildTypes=td.anyAtomicT}granular(){return!1}requestExpression(e){return this.getExpression(e)}defaultFieldName(){}typeCheck(e,r){return r.type!=="error"&&!td.any(r,this.legalChildTypes)?(r.type==="sql native"?e.logError("sql-native-not-allowed-in-expression",{rawType:r.rawType}):e.logError("expression-type-error",`'${this.elementType}' Can't use type ${td.inspect(r)}`),!1):!0}apply(e,r,i,s=!1){return _le(e,i,r,this)}canSupportPartitionBy(){return!1}canSupportOrderBy(){return!1}canSupportLimit(){return!1}supportsWhere(e){return(0,Lc.expressionIsAggregate)(e.expressionType)}atNodeType(){return N$.Value}atExpr(){return this}}ct.ExpressionDef=gle;class L$ extends gle{constructor(e,r){super({n:e}),this.n=e,this.timeframe=r,this.elementType="duration",this.legalChildTypes=[td.timestampT,td.dateT]}apply(e,r,i){const s=i.getExpression(e);if(this.typeCheck(this,s),(0,Lc.isTemporalType)(s.type)&&(r==="+"||r==="-")){const o=this.n.getExpression(e);if(!td.typeEq(o,td.numberT))return this.logError("invalid-duration-quantity",`Duration quantity needs number not '${o.type}`),(0,w$.errorFor)("illegal unit expression");let u;return(0,mle.isGranularResult)(s)&&s.timeframe===this.timeframe&&(u=s.timeframe),s.type==="date"&&!(0,Lc.isDateUnit)(this.timeframe)?this.loggedErrorExpr("invalid-timeframe-for-time-offset",`Cannot offset date by ${this.timeframe}`):(0,Vl.computedTimeResult)({dataType:{type:s.type},value:(0,ert.timeOffset)(s.type,s.value,r,o.value,this.timeframe),timeframe:u,from:[s,o]})}return super.apply(e,r,i)}getExpression(e){const r=this.n.getExpression(e);return(0,Vl.computedErrorExprValue)({dataType:{type:"duration"},error:"Duration is not a value",from:[r]})}}ct.ExprDuration=L$;function yle(t,e){return t.type===e?t.value:t.morphic&&t.morphic[e]}function rrt(t,e){if(t.type===e)return t;if(t.morphic&&t.morphic[e])return(0,Vl.computedExprValue)({dataType:{type:e},value:t.morphic[e],from:[t]})}ct.getMorphicValue=rrt;function Ele(t,e,r,i){const s=(0,Lc.isTemporalType)(e.type),o=(0,Lc.isTemporalType)(i.type),u=(0,Py.getExprNode)(r);if(s&&o)if(e.type!==i.type){const a=yle(e,"timestamp"),l=yle(i,"timestamp");if(a&&l)return{node:u,kids:{left:a,right:a}}}else return{node:u,kids:{left:e.value,right:i.value}};if((s||o)&&e.type!=="null"&&i.type!=="null")return t.logError("time-comparison-type-mismatch",`Cannot compare a ${e.type} to a ${i.type}`),{node:"false"}}function irt(t,e){if(t.type==="string"){if(e.type==="regular expression")return{node:"regexpMatch",kids:{expr:t.value,regex:e.value}}}else if(e.type==="string"&&t.type==="regular expression")return{node:"regexpMatch",kids:{expr:e.value,regex:t.value}}}function srt(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=(0,Py.getExprNode)(r),a=jy("boolean",s,o);if(a)return a;const l=Lc.TD.isSQL(s)?s.rawType||"typeless-left":void 0,c=Lc.TD.isSQL(o)?o.rawType||"typeless-right":void 0;if((l||c)&&!(s.type==="null"||o.type==="null"||l===c)){const h=qy(e,s,i,o);if(h)return{...h,type:"boolean"}}let f;if(o.type==="filter expression"){if(r!=="~"&&r!=="!~")return i.loggedErrorExpr("filter-expression-error",`Cannot use the '${r}' operator with a filter expression`);if((0,Uy.isFilterable)(s.type)){let x=o.value;for(;x.node==="()";)x=x.e;x.node!=="parameter"&&vle(i,s.type,x);const h={node:"filterMatch",dataType:s.type,kids:{filterExpr:o.value,expr:s.value}};r==="!~"&&(h.notMatch=!0),f=h}else return e.loggedErrorExpr("filter-expression-type",`Cannot use filter expressions with type '${s.type}'`)}else if(f=Ele(e,s,r,o)||{node:u,kids:{left:s.value,right:o.value}},s.type!=="error"&&o.type!=="error"&&(r==="~"||r==="!~")&&(s.type!=="string"||o.type!=="string")){let x=irt(s,o);if(x)r[0]==="!"&&(x={node:"not",e:{...x}});else throw new nrt("Incompatible types for match('~') operator");f=x}return(0,Vl.computedExprValue)({dataType:{type:"boolean"},value:f,from:[s,o]})}function ort(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=jy("boolean",s,o);if(u)return u;const a=qy(e,s,i,o);if(a)return{...a,type:"boolean"};const l=Ele(e,s,r,o)||{node:(0,Py.getExprNode)(r),kids:{left:s.value,right:o.value}};return(0,Vl.computedExprValue)({dataType:{type:"boolean"},value:l,from:[s,o]})}function Ale(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=jy("number",s,o);if(u)return u;const a=qy(e,s,i,o);if(a)return a;if(s.type!=="number")e.logError("arithmetic-operation-type-mismatch",`The '${r}' operator requires a number, not a '${s.type}'`);else if(o.type!=="number")i.logError("arithmetic-operation-type-mismatch",`The '${r}' operator requires a number, not a '${o.type}'`);else return(0,Vl.computedExprValue)({dataType:{type:"number"},value:{node:r,kids:{left:s.value,right:o.value}},from:[s,o]});return(0,w$.errorFor)("numbers required")}function urt(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=qy(e,s,i,o);if(u)return u;const a=(0,Lc.isTemporalType)(s.type),l=jy(a?"error":"number",s,o);if(l)return l;if(a){let c=i;if(o.type!=="duration")if((0,mle.isGranularResult)(s))c=new L$(i,s.timeframe);else if(s.type==="date")c=new L$(i,"day");else return e.loggedErrorExpr("time-offset-type-mismatch",`Can not offset time by '${o.type}'`);return c.apply(t,r,e)}return Ale(t,e,r,i)}function _le(t,e,r,i){if((0,Py.isEquality)(r))return srt(t,e,r,i);if((0,Py.isComparison)(r))return ort(t,e,r,i);if(r==="+"||r==="-")return urt(t,e,r,i);if(r==="*")return Ale(t,e,r,i);if(r==="/"||r==="%"){const s=e.getExpression(t),o=i.getExpression(t),u=qy(e,s,i,o);if(u)return u;const a=jy("number",s,o);if(a)return a;if(s.type!=="number")e.logError("arithmetic-operation-type-mismatch","Numerator must be a number");else if(o.type!=="number")i.logError("arithmetic-operation-type-mismatch","Denominator must be a number");else{const l={node:r,kids:{left:s.value,right:o.value}};return(0,Vl.computedExprValue)({dataType:{type:"number"},value:l,from:[s,o]})}return(0,w$.errorFor)("divide type mismatch")}return e.loggedErrorExpr("unexpected-binary-operator",`Cannot use ${r} operator here`)}ct.applyBinary=_le;function jy(t,...e){if(e.some(r=>r.type==="error"))return(0,Vl.computedExprValue)({dataType:{type:t},value:{node:"error",message:"cascading error"},from:e})}function qy(t,e,r,i){const s=(0,Vl.computedExprValue)({dataType:e,value:{node:"error",message:"sql-native unsupported"},from:[e,i]});if(e.type==="sql native")return t.logError("sql-native-not-allowed-in-expression",{rawType:e.rawType}),s.type=i.type,s;if(i.type==="sql native")return r.logError("sql-native-not-allowed-in-expression",{rawType:i.rawType}),s}function vle(t,e,r){for(var i,s,o,u;r.node==="()";)r=r.e;if(r.node!=="filterLiteral"){t.logError("filter-expression-error","Expected a filter expression literal here");return}const a=r.filterSrc;let l;e==="date"||e==="timestamp"?l=(i=Uy.TemporalFilterExpression.parse(a).log[0])===null||i===void 0?void 0:i.message:e==="string"?l=(s=Uy.StringFilterExpression.parse(a).log[0])===null||s===void 0?void 0:s.message:e==="number"?l=(o=Uy.NumberFilterExpression.parse(a).log[0])===null||o===void 0?void 0:o.message:e==="boolean"?l=(u=Uy.BooleanFilterExpression.parse(a).log[0])===null||u===void 0?void 0:u.message:t.logError("filter-expression-type",`Cannot apply filter expression to type ${e}`),l!==void 0&&t.logError("filter-expression-error",`Filter syntax error: ${l}`)}ct.checkFilterExpression=vle,Object.defineProperty(ed,"__esModule",{value:!0}),ed.ExprIdReference=void 0;const art=Xe,lrt=ct,crt=lt;class frt extends lrt.ExpressionDef{constructor(e){super(),this.fieldReference=e,this.elementType="ExpressionIdReference",this.has({fieldPath:e})}get refString(){return this.fieldReference.refString}getExpression(e){const r=this.fieldReference.getField(e),i=this.fieldReference.list.map(s=>s.name).slice(0,-1);if(r.found){const s=r.found.typeDesc(),o=(0,crt.joinedCompositeFieldUsage)(i,s.compositeFieldUsage);if(r.isOutputField)return{...s,evalSpace:s.evalSpace==="constant"?"constant":"output",value:{node:"outputField",name:this.refString},compositeFieldUsage:o};const u={node:r.found.refType,path:this.fieldReference.path},a=(0,art.expressionIsAggregate)(s.expressionType)?"output":s.evalSpace;return{...s,value:u,evalSpace:a,compositeFieldUsage:o}}return this.loggedErrorExpr(r.error.code,r.error.message)}}ed.ExprIdReference=frt,Object.defineProperty(l2,"__esModule",{value:!0}),l2.NamedSource=void 0;const I$=Xe,xrt=Eo,drt=ai,hrt=ds,Cle=Je,prt=ed,mrt=n2,grt=ct;class yrt extends xrt.Source{constructor(e,r,i){super(),this.ref=e,this.sourceArguments=r,this.args=i,this.elementType="namedSource",i&&this.has({args:i}),e instanceof Cle.ModelEntryReference&&this.has({ref:e})}get refName(){return this.ref instanceof Cle.ModelEntryReference?this.ref.name:this.ref}structRef(e){const r=this.modelEntry(this.ref);return r&&!r.exported?{structRef:this.getSourceDef(e)}:{structRef:this.refName,sourceArguments:this.evaluateArgumentsForRef(e)}}refLogError(e,r,i){typeof this.ref=="string"?this.logError(e,r,i):this.ref.logError(e,r,i)}modelStruct(){var e;const r=this.modelEntry(this.ref),i=r==null?void 0:r.entry;if(!i){this.refLogError("source-not-found",`Undefined source '${this.refName}'`);return}if(i.type==="query"){this.logError("invalid-source-from-query",`Cannot construct a source from query '${this.refName}'`);return}else if(i.type==="function"){this.logError("invalid-source-from-function",`Cannot construct a source from a function '${this.refName}'`);return}else if(i.type==="connection"){this.logError("invalid-source-from-connection",`Cannot construct a source from a connection '${this.refName}'`);return}else if((e=this.document())===null||e===void 0||e.checkExperimentalDialect(this,i.dialect),(0,I$.isSourceDef)(i))return{...i};this.logError("invalid-source-source","Cannot construct a source from a never type")}evaluateArgumentsForRef(e){const r=this.modelStruct();return r===void 0?{}:this.evaluateArguments(e,r.parameters,[])}evaluateArguments(e,r,i){var s,o;const u={...this.sourceArguments},a=new Set;for(const l of(s=this.args)!==null&&s!==void 0?s:[]){const c=(o=l.id)!==null&&o!==void 0?o:l.value instanceof prt.ExprIdReference?l.value.fieldReference:void 0;if(c===void 0){l.value.logError("unnamed-source-argument","Parameterized source arguments must be named with `parameter_name is`");continue}const f=c.outputName;if(a.has(f)){l.logError("duplicate-source-argument",`Cannot pass argument for \`${f}\` more than once`);continue}a.add(f);const x=(r??{})[f];if(!x)c.logError("source-parameter-not-found",`\`${this.refName}\` has no declared parameter named \`${c.refString}\``);else{const h=e??new mrt.ParameterSpace(i??[]),p=l.value.getExpression(h);let m=p.value;p.type==="filter expression"&&x.type==="filter expression"&&x.filterType&&(0,grt.checkFilterExpression)(l.value,x.filterType,m),p.type!==x.type&&(0,I$.isCastType)(x.type)&&(m=(0,hrt.castTo)(x.type,p.value,p.type,!0)),u[f]={...x,value:m}}}for(const l in r)l in u||((0,I$.paramHasValue)(r[l])?u[l]={...r[l]}:this.refLogError("missing-source-argument",`Argument not provided for required parameter \`${l}\``));return u}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,r){var i;const s=this.modelStruct();if(!s){const l=drt.ErrorFactory.structDef,c=`${this.refName}-undefined`;return l.name=l.name+c,l.dialect=l.dialect+c,l}const o={};for(const l of r??[]){const c=l.parameter();o[c.name]=c}const u=this.evaluateArguments(e,s.parameters,r),a={...s,parameters:o,arguments:u};return(i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(a),a}}l2.NamedSource=yrt;var Hy={},eb={};Object.defineProperty(eb,"__esModule",{value:!0}),eb.QueryHeadStruct=void 0;const Ert=Xe,Art=Eo,_rt=l2;class vrt extends Art.Source{constructor(e,r){super(),this.fromRef=e,this.sourceArguments=r,this.elementType="internalOnlyQueryHead"}structRef(){return{structRef:this.fromRef}}getSourceDef(e){if((0,Ert.refIsStructDef)(this.fromRef))return this.fromRef;const r=new _rt.NamedSource(this.fromRef,this.sourceArguments,void 0);return this.has({exploreReference:r}),r.getSourceDef(e)}}eb.QueryHeadStruct=vrt,Object.defineProperty(Hy,"__esModule",{value:!0}),Hy.QueryReference=void 0;const B$=ai,Crt=Je,Srt=eb,brt=Xe,Trt=ks;class Rrt extends Crt.MalloyElement{constructor(e){super(),this.name=e,this.elementType="query-reference"}queryComp(e){const r=this.modelEntry(this.name),i=r==null?void 0:r.entry,s=function(){return{inputStruct:B$.ErrorFactory.structDef,outputStruct:B$.ErrorFactory.structDef,query:B$.ErrorFactory.query}};if(!i)return this.logError("query-reference-not-found",`Reference to undefined query '${this.name.refString}'`),s();if(i.type==="query"){const o=new Srt.QueryHeadStruct(i.structRef,i.sourceArguments);this.has({queryHead:o});const u=o.getSourceDef(void 0),a=(0,Trt.getFinalStruct)(this,u,i.pipeline);return{query:e||(0,brt.refIsStructDef)(i.structRef)?i:{...i,structRef:u},outputStruct:a,inputStruct:u}}return this.logError("non-query-used-as-query",`Illegal reference to '${this.name}', query expected`),s()}query(){return this.queryComp(!0).query}}Hy.QueryReference=Rrt,Object.defineProperty(ky,"__esModule",{value:!0}),ky.SQReference=void 0;const Drt=hu,Ort=Zx,Frt=l2,Sle=Hy,ble=Pi;class wrt extends Drt.SourceQueryElement{constructor(e,r){super({ref:e}),this.ref=e,this.args=r,this.elementType="sq-reference",r!==void 0&&this.has({args:r})}getQuery(){const e=this.ref.getNamed();if(e)if(e.type==="query"){const r=new Sle.QueryReference(this.ref);return this.has({query:r}),r}else this.sqLog("cannot-use-as-query",`Illegal reference to '${e.as||e.name}', query expected`);else this.ref.logError("source-or-query-not-found",`Reference to undefined object '${this.ref.refString}'`),this.errored=!0}isSource(){const e=this.ref.getNamed();return e!==void 0&&(0,ble.isSourceDef)(e)}getSource(){if(this.asSource)return this.asSource;const e=this.ref.getNamed();if(!e){this.ref.logError("source-not-found",`Reference to undefined object '${this.ref.refString}'`),this.errored=!0;return}if(e.type==="query"){this.args!==void 0&&this.ref.logError("illegal-query-argument","Arguments cannot be passed to queries");const r=new Sle.QueryReference(this.ref);this.asSource=new Ort.QuerySource(r)}else if((0,ble.isSourceDef)(e))this.asSource=new Frt.NamedSource(this.ref,void 0,this.args);else{this.sqLog("cannot-use-struct-as-source",`Expected '${this.ref.refString}' to be of type query or source, not '${e.type}'`);return}return this.has({asSource:this.asSource}),this.asSource}}ky.SQReference=wrt,Object.defineProperty(X4,"__esModule",{value:!0}),X4.SQRefine=void 0;const Nrt=hu,Lrt=Zx,Irt=a2,Brt=ky;class $rt extends Nrt.SourceQueryElement{constructor(e,r){super({toRefine:e,refine:r}),this.toRefine=e,this.refine=r,this.elementType="sq-refine"}getQuery(){if(this.toRefine.isSource()){this.toRefine instanceof Brt.SQReference?this.sqLog("illegal-refinement-of-source",`Cannot add view refinements to '${this.toRefine.ref.refString}' because it is a source`):this.sqLog("illegal-refinement-of-source","Cannot add view refinements to a source");return}const e=this.toRefine.getQuery();if(e){const r=new Irt.QueryRefine(e,this.refine);return this.has({query:r}),r}}getSource(){const e=this.getQuery();if(e){const r=new Lrt.QuerySource(e);return this.has({queryAsSource:r}),r}}}X4.SQRefine=$rt;var tb={},Qy={};Object.defineProperty(Qy,"__esModule",{value:!0}),Qy.QueryRaw=void 0;const krt=Xe,Mrt=Je;class Prt extends Mrt.MalloyElement{constructor(e){super({source:e}),this.source=e,this.elementType="query-raw"}queryComp(e){const r=e?this.source.structRef(void 0):{structRef:this.source.getSourceDef(void 0)},i=(0,krt.refIsStructDef)(r.structRef)?r.structRef:this.source.getSourceDef(void 0);return{query:{type:"query",...r,pipeline:[{type:"raw",fields:[]}],location:this.location},outputStruct:i,inputStruct:i}}query(){return this.queryComp(!0).query}}Qy.QueryRaw=Prt;var zy={},Yl={};Object.defineProperty(Yl,"__esModule",{value:!0}),Yl.sqlKey=Yl.compileSQLInterpolation=void 0;const Urt=Ls,jrt=Xe,qrt=Bt;function Hrt(t,e,r){let i,s="",o=!1;for(const u of t)if((0,jrt.isSegmentSQL)(u))s+=u.sql,o=u.sql.match(/\(\s*$/)!==null;else{if(!i){if(!r)throw new Error("Internal error: Partial model missing when compiling SQL block");i=new Urt.QueryModel(r)}const a=i.compileQuery(u,{defaultRowLimit:void 0},!1).sql;s+=o?a:`(${a})`,o=!1}return{connection:e,selectStr:s}}Yl.compileSQLInterpolation=Hrt;function Qrt(t,e){return`sql://${t}/${(0,qrt.generateHash)(e)}`}Yl.sqlKey=Qrt,Object.defineProperty(zy,"__esModule",{value:!0}),zy.SQLSource=void 0;const $$=Yl,zrt=Eo,Gy=ai;class Grt extends zrt.Source{constructor(e,r){super({connectionName:e,select:r}),this.connectionName=e,this.select=r,this.elementType="sqlSource",this.connectionNameInvalid=!1}sqlSourceRequest(e){const r=this.select.containsQueries?e.modelDef():void 0;return(0,$$.compileSQLInterpolation)(this.select.sqlPhrases(),this.connectionName.refString,r)}structRef(){return{structRef:this.getSourceDef()}}validateConnectionName(){var e;const r=this.modelEntry(this.connectionName),i=this.connectionName.refString;if(this.connectionNameInvalid)return!1;if(r===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(i,{entry:{type:"connection",name:i},exported:!0},!0);else if(r.entry.type!=="connection")return this.connectionName.logError("invalid-connection-for-sql-source",`${this.connectionName.refString} is not a connection`),this.connectionNameInvalid=!0,!1;return!0}needs(e){var r;if(!this.validateConnectionName())return;const i=super.needs(e);if(i)return i;this.requestBlock===void 0&&(this.requestBlock=this.sqlSourceRequest(e));const s=this.requestBlock,o=(r=this.translator())===null||r===void 0?void 0:r.root.sqlQueryZone;if(!o){this.logError("failed-to-fetch-sql-source-schema","Cant't look up schema for sql block");return}const u=(0,$$.sqlKey)(s.connection,s.selectStr);o.reference(u,this.location);const a=o.getEntry(u);if(a.status==="reference")return{compileSQL:s};a.status==="present"&&e.checkExperimentalDialect(this,a.value.dialect)}getSourceDef(){var e;if(!this.validateConnectionName())return Gy.ErrorFactory.structDef;const r=(e=this.translator())===null||e===void 0?void 0:e.root.sqlQueryZone;if(!r)return this.logError("failed-to-fetch-sql-source-schema","Cant't look up schema for sql block"),Gy.ErrorFactory.structDef;if(this.requestBlock===void 0)return this.logError("failed-to-fetch-sql-source-schema","Expected to have already compiled the sql block"),Gy.ErrorFactory.structDef;const i=this.requestBlock,s=(0,$$.sqlKey)(i.connection,i.selectStr);r.reference(s,this.location);const o=r.getEntry(s);if(o.status==="error"){const u=o.message.split(/\r?\n/);return this.select.logError("invalid-sql-source","Invalid SQL, "+u.join(`
1160
+ `)),Gy.ErrorFactory.structDef}else if(o.status==="present"){const u=this.select.location,a={...o.value,fields:o.value.fields.map(f=>({...f,location:u})),location:this.location},l=this.document(),c=l==null?void 0:l.currentModelAnnotation();return c&&(a.modelAnnotation=c),a}else return this.logError("non-top-level-sql-source","`connection_name.sql(...)` can currently only be used in top level source/query definitions"),Gy.ErrorFactory.structDef}}zy.SQLSource=Grt,Object.defineProperty(tb,"__esModule",{value:!0}),tb.SQSource=void 0;const Wrt=hu,Vrt=Qy,Yrt=zy;class Krt extends Wrt.SourceQueryElement{constructor(e){super({theSource:e}),this.theSource=e,this.elementType="sq-source"}isSource(){return!0}getSource(){return this.theSource}getQuery(){if(this.theSource instanceof Yrt.SQLSource){const e=new Vrt.QueryRaw(this.theSource);return this.has({rawQuery:e}),e}else this.sqLog("invalid-source-as-query","This source cannot be used as a query")}}tb.SQSource=Krt;var nb={};Object.defineProperty(nb,"__esModule",{value:!0}),nb.SQExtend=void 0;const Jrt=Fy,Xrt=hu;class Zrt extends Xrt.SourceQueryElement{constructor(e,r,i){super({sqSrc:e,extend:r}),this.sqSrc=e,this.extend=r,this.includeList=i,this.elementType="sq-extend"}getSource(){if(this.asSource)return this.asSource;const e=this.sqSrc.getSource();if(e)return this.asSource=new Jrt.RefinedSource(e,this.extend,this.includeList),this.has({asSource:this.asSource}),this.asSource;this.sqLog("failed-to-compute-source-to-extend","Could not compute source to extend")}isSource(){return!0}}nb.SQExtend=Zrt;var rb={},ib={};Object.defineProperty(ib,"__esModule",{value:!0}),ib.CompositeSource=void 0;const eit=Xe,tit=Eo;class nit extends tit.Source{constructor(e){super({sources:e}),this.sources=e,this.elementType="compositeSource"}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,r){const i=this.sources.map(c=>c.withParameters(e,r)),s=i[0].connection,o=i[0].dialect,u="composite_source",a=[],l=new Map;return this.sources.forEach((c,f)=>{var x;const h=i[f];h.connection!==s&&c.logError("composite-source-connection-mismatch",`All sources in a composite source must share the same connection; connection \`${h.connection}\` differs from previous connection \`${s}\``);for(const p of h.fields){if(!(0,eit.isAtomic)(p)){c.logWarning("composite-source-atomic-fields-only",`Only atomic fields are supported in composite sources; field \`${p.name}\` is not atomic and will be ignored`);continue}if(p.accessModifier==="private")continue;const m=(x=p.as)!==null&&x!==void 0?x:p.name,g=l.get(m);if(g===void 0){const y={...p,name:m,as:void 0,e:{node:"compositeField"},compositeFieldUsage:{fields:[m],joinedUsage:{}},code:this.code,location:this.codeLocation};l.set(m,y),a.push(y)}else p.accessModifier==="internal"&&(g.accessModifier="internal")}}),{type:"composite",sources:i,connection:s,fields:a,dialect:o,name:u,parameters:i[0].parameters}}}ib.CompositeSource=nit,Object.defineProperty(rb,"__esModule",{value:!0}),rb.SQCompose=void 0;const rit=ib,iit=hu;class sit extends iit.SourceQueryElement{constructor(e){super({sources:e}),this.sources=e,this.elementType="sq-compose"}getSource(){if(this.asSource)return this.asSource;const e=this.sources.map(r=>r.getSource());if(e.length===0){this.sqLog("empty-composite-source","Composite source must have at least one input source");return}else e.length===1&&this.sqLog("unnecessary-composite-source","A composite source with one input is equivalent to that input",{severity:"warn"});if(oit(e))return this.asSource=new rit.CompositeSource(e),this.has({asSource:this.asSource}),this.asSource;this.sqLog("invalid-composite-source-input","All composite source inputs must be valid sources")}isSource(){return!0}}rb.SQCompose=sit;function oit(t){return t.every(e=>e!==void 0)}var sb={},Kl={},Wy={},uit=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),ait=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),lit=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&uit(e,t,r);return ait(e,t),e};Object.defineProperty(Wy,"__esModule",{value:!0}),Wy.BinaryBoolean=void 0;const cit=Bs,fit=lit(Zt),xit=pu,dit=Gt,hit=ct;class pit extends hit.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="abstract boolean binary",this.legalChildTypes=[fit.boolT]}getExpression(e){const r=this.left.getExpression(e),i=this.right.getExpression(e);return this.typeCheck(this.left,r)&&this.typeCheck(this.right,i)?(0,dit.computedExprValue)({dataType:{type:"boolean"},value:{node:(0,xit.getExprNode)(this.op),kids:{left:r.value,right:i.value}},from:[r,i]}):(0,cit.errorFor)("logical-op expected boolean")}}Wy.BinaryBoolean=pit;var mit=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),git=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),yit=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&mit(e,t,r);return git(e,t),e};Object.defineProperty(Kl,"__esModule",{value:!0}),Kl.ExprLegacyIn=Kl.ExprEquality=Kl.ExprCompare=void 0;const fn=yit(Zt),Eit=Gt,Ait=ct,_it=Wy,vit={"~":[fn.stringT],"!~":[fn.stringT],"<":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT],"<=":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT],"=":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT],"!=":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT],">=":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT],">":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT]};class Tle extends _it.BinaryBoolean{constructor(e,r,i){super(e,r,i),this.elementType="a<=>b",this.legalChildTypes=vit[r]}getExpression(e){return this.right.apply(e,this.op,this.left)}}Kl.ExprCompare=Tle;class Cit extends Tle{constructor(e,r,i){super(e,r,i),this.elementType="a~=b"}getExpression(e){return this.right.apply(e,this.op,this.left,!0)}apply(e,r,i){return super.apply(e,r,i,!0)}}Kl.ExprEquality=Cit;class Sit extends Ait.ExpressionDef{constructor(e,r,i){super(),this.expr=e,this.notIn=r,this.choices=i,this.elementType="in",this.has({expr:e,choices:i})}getExpression(e){const r=this.expr.getExpression(e),i=this.choices.map(s=>s.getExpression(e));return(0,Eit.computedExprValue)({dataType:{type:"boolean"},value:{node:"in",not:this.notIn,kids:{e:r.value,oneOf:i.map(s=>s.value)}},from:[r,...i]})}}Kl.ExprLegacyIn=Sit;var Vy={},f2={};Object.defineProperty(f2,"__esModule",{value:!0}),f2.ExprTime=void 0;const bit=Xe,Tit=Gt,Rit=ct;class k$ extends Rit.ExpressionDef{constructor(e,r,i){super(),this.elementType="timestampOrDate",this.elementType=e,this.translationValue=(0,Tit.computedExprValue)({dataType:{type:e},value:r,from:i??[]})}getExpression(e){return this.translationValue}static fromValue(e,r){let i=r.value;if(e!==r.type){const s={node:"cast",safe:!1,dstType:{type:e},e:r.value};(0,bit.isTemporalType)(r.type)&&(s.srcType={type:r.type}),i=s}return new k$(e,i,[r])}}f2.ExprTime=k$;var Ic={};Object.defineProperty(Ic,"__esModule",{value:!0}),Ic.Range=void 0;const Dit=Bs,Oit=Gt,Fit=ct;class wit extends Fit.ExpressionDef{constructor(e,r){super({first:e,last:r}),this.first=e,this.last=r,this.elementType="range"}apply(e,r,i){switch(r){case"=":case"!=":{const s=r==="="?">=":"<",o=r==="="?"and":"or",u=r==="="?"<":">=",a=this.first.apply(e,s,i),l=this.last.apply(e,u,i);return(0,Oit.computedExprValue)({dataType:{type:"boolean"},value:{node:o,kids:{left:a.value,right:l.value}},from:[a,l]})}case">":return this.last.apply(e,">=",i);case">=":return this.first.apply(e,">=",i);case"<":return this.first.apply(e,"<",i);case"<=":return this.last.apply(e,"<",i)}throw new Error("mysterious error in range computation")}requestExpression(e){}getExpression(e){return this.logError("range-as-value","A Range is not a value"),(0,Dit.errorFor)("a range is not a value")}}Ic.Range=wit;var Nit=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Lit=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Iit=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Nit(e,t,r);return Lit(e,t),e};Object.defineProperty(Vy,"__esModule",{value:!0}),Vy.ExprGranularTime=void 0;const M$=Xe,Bit=Bs,Rle=Iit(Zt),Dle=ds,$it=ct,ob=f2,Ole=Ic;class kit extends $it.ExpressionDef{constructor(e,r,i){super({expr:e}),this.expr=e,this.units=r,this.truncate=i,this.elementType="granularTime",this.legalChildTypes=[Rle.timestampT,Rle.dateT]}granular(){return!0}getExpression(e){const r=this.units,i=this.expr.getExpression(e);if(M$.TD.isTemporal(i)){const o={...i,timeframe:r};return this.truncate&&(o.value={node:"trunc",e:(0,M$.mkTemporal)(i.value,i.type),units:r}),o}i.type!=="error"&&this.logError("unsupported-type-for-time-truncation",`Cannot do time truncation on type '${i.type}'`);const s={...i};return i.type==="error"&&(s.type=(0,M$.isDateUnit)(r)?"date":"timestamp"),{...s,value:(0,Bit.errorFor)("granularity typecheck").value,evalSpace:"constant"}}toRange(e){const r=this.getExpression(e),i={node:"numberLiteral",literal:"1"};if(r.type==="timestamp"){const a=ob.ExprTime.fromValue("timestamp",r),l=new ob.ExprTime("timestamp",(0,Dle.timeOffset)("timestamp",r.value,"+",i,this.units),[r]);return new Ole.Range(a,l)}const s=new ob.ExprTime("date",r.value,[r]),o=(0,Dle.timeOffset)("date",r.value,"+",i,this.units),u=new ob.ExprTime("date",o,[r]);return new Ole.Range(s,u)}}Vy.ExprGranularTime=kit,Object.defineProperty(sb,"__esModule",{value:!0}),sb.Apply=void 0;const Mit=Kl,Pit=c2,Fle=Vy;class Uit extends Mit.ExprCompare{constructor(e,r){super(e,"=",r),this.left=e,this.right=r,this.elementType="apply"}getExpression(e){let r=this.right;if(!this.right.granular()){const i=this.right.requestExpression(e);i&&(0,Pit.isGranularResult)(i)&&(r=new Fle.ExprGranularTime(this.right,i.timeframe,!1))}return r instanceof Fle.ExprGranularTime?r.toRange(e).apply(e,this.op,this.left):super.getExpression(e)}}sb.Apply=Uit;var x2={},jit=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),qit=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Hit=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&jit(e,t,r);return qit(e,t),e};Object.defineProperty(x2,"__esModule",{value:!0}),x2.BinaryNumeric=void 0;const Qit=Hit(Zt),zit=ct;class Git extends zit.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="numeric binary abstract",this.legalChildTypes=[Qit.numberT]}getExpression(e){return this.right.apply(e,this.op,this.left)}}x2.BinaryNumeric=Git;var ub={},Wit=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Vit=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Yit=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Wit(e,t,r);return Vit(e,t),e};Object.defineProperty(ub,"__esModule",{value:!0}),ub.Boolean=void 0;const Kit=ct,Jit=Yit(Zt);let Xit=class extends Kit.ExpressionDef{constructor(e){super(),this.value=e,this.elementType="boolean literal"}getExpression(){return{...Jit.boolT,value:{node:this.value}}}};ub.Boolean=Xit;var d2={};Object.defineProperty(d2,"__esModule",{value:!0}),d2.ConstantExpression=d2.ConstantFieldSpace=void 0;const Zit=ct;class wle{constructor(){this.type="fieldSpace"}structDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}emptyStructDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}lookup(e){return{error:{message:"Only constants allowed in parameter default values",code:"illegal-reference-in-parameter-default"},found:void 0}}entries(){return[]}entry(){}dialectName(){return"~constant-space-unknown-dialect~"}dialectObj(){}isQueryFieldSpace(){return!1}isProtectedAccessSpace(){return!1}}d2.ConstantFieldSpace=wle;class est extends Zit.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="constantExpression"}getExpression(e){return this.constantValue()}get constantFs(){return this.cfs||(this.cfs=new wle),this.cfs}constantValue(){return this.expr.getExpression(this.constantFs)}apply(e,r,i){return this.expr.apply(e,r,i)}requestExpression(e){return this.expr.requestExpression(e)}}d2.ConstantExpression=est;var Bc={};Object.defineProperty(Bc,"__esModule",{value:!0}),Bc.FunctionOrdering=Bc.FunctionOrderBy=void 0;const P$=Xe,Nle=Je,tst=ed;class nst extends Nle.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e&&this.has({field:e})}getAnalyticOrderBy(e){if(!this.field)return this.logError("analytic-order-by-missing-field","analytic `order_by` must specify an aggregate expression or output field reference"),{node:"functionOrderBy",e:{node:"error"},dir:this.dir};const r=this.field.getExpression(e);return(0,P$.expressionIsAggregate)(r.expressionType)||((0,P$.expressionIsScalar)(r.expressionType)?(!(this.field instanceof tst.ExprIdReference)||r.evalSpace==="input")&&this.field.logError("analytic-order-by-not-output","analytic `order_by` must be an aggregate or an output field reference"):this.field.logError("analytic-order-by-not-aggregate-or-output","analytic `order_by` must be scalar or aggregate")),{node:"functionOrderBy",e:r.value,dir:this.dir}}getAggregateOrderBy(e,r){if(this.field){const i=this.field.getExpression(e);return(0,P$.expressionIsScalar)(i.expressionType)||this.field.logError("aggregate-order-by-not-scalar","aggregate `order_by` must be scalar"),r||this.field.logError("aggregate-order-by-expression-not-allowed","`order_by` must be only `asc` or `desc` with no expression"),{node:"functionOrderBy",e:i.value,dir:this.dir}}else return this.dir===void 0?(this.logError("aggregate-order-by-without-field-or-direction","field or order direction must be specified"),{node:"functionDefaultOrderBy",dir:"asc"}):{node:"functionDefaultOrderBy",dir:this.dir}}}Bc.FunctionOrderBy=nst;class rst extends Nle.ListOf{constructor(e){super(e),this.elementType="function-ordering"}getAnalyticOrderBy(e){return this.list.map(r=>r.getAnalyticOrderBy(e))}getAggregateOrderBy(e,r){return this.list.map(i=>i.getAggregateOrderBy(e,r))}}Bc.FunctionOrdering=rst;var ab={};Object.defineProperty(ab,"__esModule",{value:!0}),ab.ExprAddSub=void 0;const ist=x2;class sst extends ist.BinaryNumeric{constructor(){super(...arguments),this.elementType="+-"}}ab.ExprAddSub=sst;var Jl={},ost=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),ust=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),ast=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&ost(e,t,r);return ust(e,t),e};Object.defineProperty(Jl,"__esModule",{value:!0}),Jl.ExprAggregateFunction=void 0;const Yy=Xe,lst=Bt,cst=Bs,Lle=Pr,Ile=ast(Zt),fst=yt,xst=ct,dst=Mr,hst=ed;class pst extends xst.ExpressionDef{constructor(e,r,i){super(),this.func=e,this.legalChildTypes=[Ile.numberT],this.elementType=e,this.explicitSource=i,r&&(this.expr=r,this.has({expr:r}))}getExpression(e){var r,i,s;const o=e.isQueryFieldSpace()?e.inputSpace():e;let u=this.expr,a=(r=this.expr)===null||r===void 0?void 0:r.getExpression(o),l=(i=this.source)===null||i===void 0?void 0:i.path,c=[];if(this.source){const x=this.source.getField(o);if(x.found){c=x.joinPath;const h=x.found,p=h.typeDesc();if(!(h instanceof Lle.StructSpaceField))if((0,Yy.isAtomicFieldType)(p.type)){u=this.source,a={...Ile.atomicDef(p),expressionType:p.expressionType,value:p.evalSpace==="output"?{node:"outputField",name:this.source.refString}:{node:"field",path:this.source.path},evalSpace:p.evalSpace,compositeFieldUsage:p.compositeFieldUsage},l=this.source.path.slice(0,-1);const m=this.getJoinUsage(o);(m.length===1||m.length>1&&m.slice(1).every(y=>mst(y,m[0])))&&(l=m[0].map(y=>y.name),c=m[0])}else return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${p.type}`)}else return this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}if(a===void 0)return this.loggedErrorExpr("missing-aggregate-expression","Missing expression for aggregate function");if((0,Yy.expressionIsAggregate)(a.expressionType))return this.loggedErrorExpr("aggregate-of-aggregate","Aggregate expression cannot be aggregate");if(!(a.type==="error")){const x=this.getJoinUsage(o),h=this.source!==void 0||this.explicitSource;if(u&&!(!this.source&&x.every(m=>m.length===0))&&!this.isSymmetricFunction()){const m=j$(c,x),g=q$(this.elementType,m),y=h?g==null?void 0:g.message:"Join path is required for this calculation";if(y){const E=gst(y,x,u,this.elementType),A=(s=g==null?void 0:g.code)!==null&&s!==void 0?s:"bad-join-usage";g?this.logError(A,E):this.logWarning(A,E)}}}if(this.typeCheck(this.expr||this,{...a,expressionType:"scalar"})){const x={node:"aggregate",function:this.func,e:a.value};return l&&l.length>0&&(x.structPath=l),{...this.returns(a),expressionType:"aggregate",value:x,evalSpace:"output"}}return(0,cst.errorFor)("aggregate type check")}isSymmetricFunction(){return!0}getJoinUsage(e){const r=[];if(this.source&&this.source.getField(e).found){const s={node:"field",path:this.source.path};r.push(...U$(e,s))}if(this.expr){const i=this.expr.getExpression(e).value;r.push(...U$(e,i))}return r}}Jl.ExprAggregateFunction=pst;function mst(t,e){let r=t.length;if(r!==e.length)return!1;for(;r>0;)if(r-=1,t[r].name!==e[r].name)return!1;return!0}function U$(t,e){const r=[],i=(s,o)=>{const u=o[0],a=o.slice(1),l=s.entry(u);if(l===void 0)throw new Error(`Invalid field lookup ${u}`);if(l instanceof Lle.StructSpaceField&&a.length>0){const c=i(l.fieldSpace,a);return{...c,joinPath:[{...l.joinPathElement,name:u},...c.joinPath]}}else if(l instanceof dst.SpaceField){if(a.length!==0)throw new Error(`${u} cannot contain a ${a.join(".")}`);const c=l.fieldDef();if(c)return{fs:s,def:c,joinPath:[]};throw new Error("No field def")}else throw new Error("expected a field def or struct")};for(const s of(0,lst.exprWalk)(e))if(s.node==="field"){const o=i(t,s.path),u=o.def;if((0,Yy.isAtomic)(u)&&!(0,Yy.isJoined)(u))if((0,Yy.hasExpression)(u)){const a=U$(o.fs,u.e);r.push(...a.map(l=>[...o.joinPath,...l]))}else r.push(o.joinPath)}else if(s.node==="source-reference")if(s.path){const o=i(t,s.path);r.push(o.joinPath)}else r.push([]);return r}function j$(t,e){const r=[];for(const i of e){let s=0;for(let l=0;l<t.length&&l<i.length&&t[l].name===i[l].name;l++)s=l+1;const o=t.slice(s),u=i.slice(s),a=[...o.map(l=>({...l,reverse:!0})),...u.map(l=>({...l,reverse:!1}))];r.push(a)}return r}function q$(t,e){for(const r of e)for(const i of r){if(i.joinType==="cross")return{code:"aggregate-traverses-join-cross",message:`Cannot compute \`${t}\` across \`join_cross\` relationship \`${i.name}\``};if(i.joinElementType==="array"&&!i.reverse)return{code:"aggregate-traverses-repeated-relationship",message:`Cannot compute \`${t}\` across repeated relationship \`${i.name}\``};if(i.joinType==="many"&&!i.reverse)return{code:"aggregate-traverses-join-many",message:`Cannot compute \`${t}\` across \`join_many\` relationship \`${i.name}\``}}}function gst(t,e,r,i){if(e.length===0)return t;let s=e[0];for(const m of e.slice(1))for(let g=0;g<s.length;g++){const y=s[g],E=m[g];if(y.name!==E.name){s=s.slice(0,g);break}}const o=j$(s,e),u=q$(i,o),a=s.slice().reverse().findIndex(m=>m.joinType==="many"||m.joinType==="cross"),l=a===-1?0:s.length-a,c=s.slice(0,l),f=j$(c,e),x=q$(i,f),h=s.length>0?s.map(m=>m.name).join("."):"source",p=c.length>0?c.map(m=>m.name).join("."):"source";if(u)return"Aggregated dimensional expression contains multiple join paths; rewrite, for example `sum(first_join.field + second_join.field)` as `first_join.field.sum() + second_join.field.sum()`";{const m=r instanceof fst.FieldReference?`${r.refString}.${i}()`:r instanceof hst.ExprIdReference?`${r.fieldReference.refString}.${i}()`:`${h}.${i}(${r.code})`,g=`${p}.${i}(${r.code})`;let y=`${t}; use \`${m}\``;return x===void 0&&p!==h&&(y+=` or \`${g}\` to get a result weighted with respect to \`${p}\``),y}}var lb={};Object.defineProperty(lb,"__esModule",{value:!0}),lb.ExprAlternationTree=void 0;const Ble=Gt,h2=ct,yst=pu;function H$(t){const e=t.atExpr();switch(e.atNodeType()){case h2.ATNodeType.And:case h2.ATNodeType.Partial:return;case h2.ATNodeType.Or:{if(e instanceof $le){const r=H$(e.left);if(r){const i=H$(e.right);if(i)return[...r,...i]}}return}default:return e.granular()?void 0:[e]}}class $le extends h2.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="alternation",this.elementType=`${r}alternation${r}`}equalityList(){return this.inList===void 0&&(this.inList=H$(this)||[]),this.inList}apply(e,r,i,s){if((0,yst.isEquality)(r)){const a=this.equalityList();if(a.length>0&&(r==="="||r==="!=")){const l=i.getExpression(e),c=a.map(f=>f.getExpression(e));return(0,Ble.computedExprValue)({dataType:{type:"boolean"},value:{node:"in",not:r==="!=",kids:{e:l.value,oneOf:c.map(f=>f.value)}},from:[l,...c]})}a.length===0&&s&&this.logWarning("or-choices-only",`Only | seperated values are legal when used with ${r} operator`)}const o=this.left.apply(e,r,i),u=this.right.apply(e,r,i);return(0,Ble.computedExprValue)({dataType:{type:"boolean"},value:{node:this.op==="&"?"and":"or",kids:{left:o.value,right:u.value}},from:[o,u]})}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("alternation-as-value","Alternation tree has no value")}atNodeType(){return this.op==="|"?h2.ATNodeType.Or:h2.ATNodeType.And}}lb.ExprAlternationTree=$le;var p2={};Object.defineProperty(p2,"__esModule",{value:!0}),p2.ExprAsymmetric=void 0;const Est=Jl;class Ast extends Est.ExprAggregateFunction{constructor(e,r,i,s){super(e,r,s),this.func=e,this.expr=r,this.source=i,this.has({source:i})}isSymmetricFunction(){return!1}returns(e){return e}defaultFieldName(){if(this.source&&this.expr===void 0){const e=this.source.nameString;switch(this.func){case"sum":return`total_${e}`;case"avg":return`avg_${e}`}}}}p2.ExprAsymmetric=Ast;var cb={};Object.defineProperty(cb,"__esModule",{value:!0}),cb.ExprAvg=void 0;const _st=p2;class vst extends _st.ExprAsymmetric{constructor(e,r,i){super("avg",e,r,i),this.has({source:r})}}cb.ExprAvg=vst;var fb={};Object.defineProperty(fb,"__esModule",{value:!0}),fb.ExprCast=void 0;const Cst=ds,Sst=Gt,bst=ct;class Tst extends bst.ExpressionDef{constructor(e,r,i=!1){super({expr:e}),this.expr=e,this.castType=r,this.safe=i,this.elementType="cast"}getExpression(e){const r=this.expr.getExpression(e);let i={type:"error"};if(typeof this.castType=="string")i={type:this.castType};else{const s=e.dialectObj();s&&(s.validateTypeName(this.castType.raw)?i=s.sqlTypeToMalloyType(this.castType.raw):this.logError("invalid-sql-native-type",`Cast type \`${this.castType.raw}\` is invalid for ${s.name} dialect`),this.safe&&!s.supportsSafeCast&&this.logError("dialect-cast-unsafe-only",`The SQL dialect '${e.dialectName()}' does not supply a safe cast operator`))}return(0,Sst.computedExprValue)({dataType:i,value:(0,Cst.castTo)(this.castType,r.value,r.type,this.safe),from:[r]})}}fb.ExprCast=Tst;var xb={},Rst=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Dst=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Ost=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Rst(e,t,r);return Dst(e,t),e};Object.defineProperty(xb,"__esModule",{value:!0}),xb.ExprCoalesce=void 0;const kle=Pi,Mle=Ost(Zt),Fst=ct;class wst extends Fst.ExpressionDef{constructor(e,r){super({expr:e,altExpr:r}),this.expr=e,this.altExpr=r,this.elementType="coalesce expression",this.legalChildTypes=Mle.anyAtomicT}getExpression(e){const r=this.expr.getExpression(e),i=this.altExpr.getExpression(e);return r.type==="null"?i:(Mle.typeEq(r,i)||this.logError("mismatched-coalesce-types",`Mismatched types for coalesce (${r.type}, ${i.type})`),{...r.type==="error"?i:r,expressionType:(0,kle.maxExpressionType)(r.expressionType,i.expressionType),value:{node:"coalesce",kids:{left:r.value,right:i.value}},evalSpace:(0,kle.mergeEvalSpaces)(r.evalSpace,i.evalSpace)})}}xb.ExprCoalesce=wst;var db={};Object.defineProperty(db,"__esModule",{value:!0}),db.ExprCount=void 0;const Nst=lt,Lst=Jl;class Ist extends Lst.ExprAggregateFunction{constructor(e){super("count"),this.source=e,this.elementType="count",this.has({source:e})}defaultFieldName(){if(this.source)return"count_"+this.source.nameString}returns(e){return{type:"number",numberType:"integer",evalSpace:e.evalSpace,expressionType:"aggregate",value:e.value,compositeFieldUsage:e.compositeFieldUsage}}getExpression(e){const r={node:"aggregate",function:"count",e:{node:""}};return this.source&&(r.structPath=this.source.path),{type:"number",numberType:"integer",expressionType:"aggregate",value:r,evalSpace:"output",compositeFieldUsage:(0,Nst.emptyCompositeFieldUsage)()}}}db.ExprCount=Ist;var hb={},Bst=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),$st=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),kst=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Bst(e,t,r);return $st(e,t),e};Object.defineProperty(hb,"__esModule",{value:!0}),hb.ExprCountDistinct=void 0;const pb=kst(Zt),Mst=Jl;class Pst extends Mst.ExprAggregateFunction{constructor(e){super("distinct",e),this.legalChildTypes=[pb.numberT,pb.stringT,pb.dateT,pb.timestampT]}returns(e){return{type:"number",numberType:"integer",evalSpace:e.evalSpace,expressionType:"aggregate",value:e.value,compositeFieldUsage:e.compositeFieldUsage}}}hb.ExprCountDistinct=Pst;var mb={},$c={};Object.defineProperty($c,"__esModule",{value:!0}),$c.Limit=void 0;const Ust=Je,jst=jn;class qst extends Ust.MalloyElement{constructor(e){super(),this.limit=e,this.elementType="limit",this.queryRefinementStage=jst.LegalRefinementStage.Tail,this.forceQueryClass=void 0}}$c.Limit=qst;var m2={};Object.defineProperty(m2,"__esModule",{value:!0}),m2.PartitionBy=void 0;const Hst=Je;class Qst extends Hst.ListOf{constructor(e){super(e),this.partitionFields=e,this.elementType="partition_by"}}m2.PartitionBy=Qst;var Ky={},kc={};Object.defineProperty(kc,"__esModule",{value:!0}),kc.FieldName=void 0;const zst=Je;class Gst extends zst.MalloyElement{constructor(e){super(),this.name=e,this.elementType="fieldName"}get refString(){return this.name}toString(){return this.refString}getField(e){return e.lookup([this])}}kc.FieldName=Gst;var Wst=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Vst=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Yst=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Wst(e,t,r);return Vst(e,t),e};Object.defineProperty(Ky,"__esModule",{value:!0}),Ky.ExprFunc=void 0;const Cr=Xe,Kst=Bs,Jst=Xx,Xst=Gt,Zst=ct,eot=kc,Ple=Bt,Ule=Yst(Zt),tot=lt;class not extends Zst.ExpressionDef{constructor(e,r,i,s,o){super({args:r}),this.name=e,this.args=r,this.isRaw=i,this.rawType=s,this.source=o,this.elementType="function call()",this.has({source:o})}canSupportPartitionBy(){return!0}canSupportOrderBy(){return!0}canSupportLimit(){return!0}getExpression(e){return this.getPropsExpression(e)}findFunctionDef(e){var r,i,s;const o=this.name.toLowerCase(),u=e?(i=(r=this.getDialectNamespace(e))===null||r===void 0?void 0:r.getEntry(o))===null||i===void 0?void 0:i.entry:void 0,a=u??((s=this.modelEntry(o))===null||s===void 0?void 0:s.entry);return a===void 0?(this.logError("function-not-found",`Unknown function '${this.name}'. Use '${this.name}!(...)' to call a SQL function directly.`),{found:void 0,error:"unknown function"}):a.type!=="function"?(this.logError("call-of-non-function",`'${this.name}' (with type ${a.type}) is not a function`),{found:void 0,error:"called non function"}):(a.name!==this.name&&this.logWarning("case-insensitive-function",`Case insensitivity for function names is deprecated, use '${a.name}' instead`),{found:a,error:void 0})}getPropsExpression(e,r){var i,s,o,u;const a=this.args.map(B=>B.getExpression(e));if(this.isRaw){const B=[`${this.name}(`];a.forEach((q,Y)=>{Y!==0&&B.push(","),B.push(q.value)}),B.push(")");const D=(i=a[0])!==null&&i!==void 0?i:{type:"number"},k=this.rawType?{type:this.rawType}:D;return(0,Xst.computedExprValue)({dataType:k,value:(0,Ple.composeSQLExpr)(B),from:a})}const l=(s=e.dialectObj())===null||s===void 0?void 0:s.name,{found:c,error:f}=this.findFunctionDef(l);if(c===void 0)return(0,Kst.errorFor)(f);let x,h=(o=this.source)===null||o===void 0?void 0:o.path;if(this.source){const D=this.source.getField(e).found;if(D){const k=D.typeDesc();if((0,Cr.isAtomicFieldType)(k.type))x={...Ule.atomicDef(k),expressionType:k.expressionType,value:{node:"field",path:this.source.path},evalSpace:k.evalSpace,compositeFieldUsage:k.compositeFieldUsage},h=this.source.path.slice(0,-1);else if(!(D instanceof Jst.StructSpaceFieldBase))return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${k.type}`)}else this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}const p=[...x?[x]:[],...a],m=rot(c,p);if(m===void 0)return this.loggedErrorExpr("no-matching-function-overload",`No matching overload for function ${this.name}(${p.map(B=>B.type).join(", ")})`);const{overload:g,expressionTypeErrors:y,evalSpaceErrors:E,nullabilityErrors:A,returnType:_}=m;for(const B of y){const D=B.argIndex-(x?1:0),k=(0,Cr.expressionIsScalar)(B.maxExpressionType)?"scalar":"scalar or aggregate";this.args[D].logError("invalid-function-argument-expression-type",`Parameter ${B.argIndex+1} ('${B.param.name}') of ${this.name} must be ${k}, but received ${B.actualExpressionType}`)}for(const B of E){const D=B.argIndex-(x?1:0),k=B.maxEvalSpace==="literal"?"literal":B.maxEvalSpace==="constant"?"literal or constant":"literal, constant or output";this.args[D].logError("invalid-function-argument-evaluation-space",`Parameter ${B.argIndex+1} ('${B.param.name}') of ${this.name} must be ${k}, but received ${B.actualEvalSpace}`)}for(const B of A){const D=B.argIndex-(x?1:0);this.args[D].logError("literal-null-function-argument",`Parameter ${B.argIndex+1} ('${B.param.name}') of ${this.name} must not be a literal null`)}m.returnTypeError&&this.logError(m.returnTypeError.code,m.returnTypeError.parameters);const v=g.returnType,C=(0,Cr.maxOfExpressionTypes)([(u=v.expressionType)!==null&&u!==void 0?u:"scalar",...p.map(B=>B.expressionType)]);if(!(0,Cr.expressionIsAggregate)(g.returnType.expressionType)&&this.source!==void 0)return this.loggedErrorExpr("non-aggregate-function-with-source",`Cannot call function ${this.name}(${p.map(B=>B.type).join(", ")}) with source`);const b={node:"function_call",overload:g,name:this.name,kids:{args:p.map(B=>B.value)},expressionType:C,structPath:h};let S=b;if(r!=null&&r.orderBys&&r.orderBys.length>0){const B=(0,Cr.expressionIsAnalytic)(g.returnType.expressionType);if(B||this.inExperiment("aggregate_order_by",!0)||r.orderBys[0].logError("aggregate-order-by-experiment-not-enabled","Enable experiment `aggregate_order_by` to use `order_by` with an aggregate function"),g.supportsOrderBy||B){const D=g.supportsOrderBy!=="only_default",k=r.orderBys.flatMap(q=>B?q.getAnalyticOrderBy(e):q.getAggregateOrderBy(e,D));b.kids.orderBy=k}else r.orderBys[0].logError("function-does-not-support-order-by",`Function \`${this.name}\` does not support \`order_by\``)}if((r==null?void 0:r.limit)!==void 0&&(g.supportsLimit?b.limit=r.limit.limit:this.logError("function-does-not-support-limit",`Function ${this.name} does not support limit`)),r!=null&&r.partitionBys&&r.partitionBys.length>0){const B=[];for(const D of r.partitionBys)for(const k of D.partitionFields){const q=k.getField(e);q.found===void 0?k.logError("partition-by-not-found",`${k.refString} is not defined`):(0,Cr.expressionIsAnalytic)(q.found.typeDesc().expressionType)||(0,Cr.expressionIsUngroupedAggregate)(q.found.typeDesc().expressionType)?k.logError("non-scalar-or-aggregate-partition-by","Partition expression must be scalar or aggregate"):B.push(k.nameString)}b.partitionBy=B}if(["sql_number","sql_string","sql_date","sql_timestamp","sql_boolean"].includes(c.name)){if(!this.inExperiment("sql_functions",!0))return this.loggedErrorExpr("sql-functions-experiment-not-enabled",`Cannot use sql_function \`${c.name}\`; use \`sql_functions\` experiment to enable this behavior`);const B=p[0].value;if(B.node!=="stringLiteral")this.logError("invalid-sql-function-argument",`Invalid string literal for \`${c.name}\``);else{const D=B.literal,k=iot(D),q=k.filter(Q=>Q.type==="interpolation"&&Q.name.includes(".")).map(Q=>Q.type==="interpolation"?`\${${Q.name}}`:`\${${Q.value}}`);if(q.length>0){const Q=q.length===1?`'.' paths are not yet supported in sql interpolations, found ${q.at(0)}`:`'.' paths are not yet supported in sql interpolations, found (${q.join(", ")})`;return this.loggedErrorExpr("unsupported-sql-function-interpolation",Q)}const Y=[];for(const Q of k)if(Q.type==="string")Y.push(Q.value);else if(Q.name==="TABLE")Y.push({node:"source-reference"});else{const X=new eot.FieldName(Q.name);this.has({name:X});const ce=e.lookup([X]);if(ce.found===void 0)return this.loggedErrorExpr("sql-function-interpolation-not-found",`Invalid interpolation: ${ce.error.message}`);if(ce.found.typeDesc().type==="filter expression")return this.loggedErrorExpr("filter-expression-error","Filter expressions cannot be used in sql_ functions");ce.found.refType==="parameter"?Y.push({node:"parameter",path:[Q.name]}):Y.push({node:"field",path:[Q.name]})}S=(0,Ple.composeSQLExpr)(Y)}}const R=(0,Cr.mergeEvalSpaces)(...p.map(B=>B.evalSpace)),O=R==="constant"?"constant":(0,Cr.expressionIsScalar)(C)?R:"output";return{...(0,Cr.isAtomic)(_)?Ule.atomicDef(_):_,expressionType:C,value:S,evalSpace:O,compositeFieldUsage:(0,tot.mergeCompositeFieldUsage)(...p.map(B=>B.compositeFieldUsage))}}}Ky.ExprFunc=not;function rot(t,e){var r;for(const i of t.overloads){const s=new Map;let o=0,u=!0,a=!1;const l=[],c=[],f=[];for(let p=0;p<e.length;p++){const m=e[p],g=i.params[o];if(g===void 0){u=!1;break}if(!g.allowedTypes.some(E=>{var A;const{dataTypeMatch:_,genericsSet:v}=g2(s,(A=i.genericTypes)!==null&&A!==void 0?A:[],m,E);for(const C of v)s.set(C.name,C.type);return E.expressionType&&((0,Cr.isExpressionTypeLEQ)(m.expressionType,E.expressionType)||l.push({argIndex:p,maxExpressionType:E.expressionType,actualExpressionType:m.expressionType,param:g})),(E.evalSpace==="literal"&&m.evalSpace!=="literal"||E.evalSpace==="constant"&&(m.evalSpace==="input"||m.evalSpace==="output")||(0,Cr.expressionIsAnalytic)(i.returnType.expressionType)&&m.evalSpace==="input")&&c.push({argIndex:p,param:g,maxEvalSpace:E.evalSpace,actualEvalSpace:m.evalSpace}),E.evalSpace==="literal"&&m.type==="null"&&f.push({argIndex:p,param:g}),_})){u=!1;break}g.isVariadic?p===e.length-1&&(a=!0):o++}if(!a&&(o!==e.length||o!==i.params.length))continue;const x=gb(i.returnType,s),h=(r=x.returnType)!==null&&r!==void 0?r:{type:"number"};if(u)return{overload:i,expressionTypeErrors:l,evalSpaceErrors:c,nullabilityErrors:f,returnTypeError:x.error,returnType:h}}}function iot(t){const e=[];let r=t;for(;r.length;){const i=r.indexOf("${");if(i===-1){e.push({type:"string",value:r});break}else{const s=r.slice(i).indexOf("}");if(s===-1){e.push({type:"string",value:r});break}i>0&&e.push({type:"string",value:r.slice(0,i)}),e.push({type:"interpolation",name:r.slice(i+2,s+i)}),r=r.slice(s+i+1)}}return e}function g2(t,e,r,i){var s,o,u,a;if(Cr.TD.eq(i,r)||i.type==="any"||i.type!=="generic"&&(r.type==="null"||r.type==="error"))return{dataTypeMatch:!0,genericsSet:[]};if(i.type==="array"&&r.type==="array"){if((0,Cr.isBasicArray)(r))return(0,Cr.isRepeatedRecordFunctionParam)(i)?{dataTypeMatch:!1,genericsSet:[]}:g2(t,e,r.elementTypeDef,i.elementTypeDef);if((0,Cr.isRepeatedRecordFunctionParam)(i)){const l={type:"record",fields:i.fields},c={type:"record",fields:r.fields};return g2(t,e,c,l)}else return{dataTypeMatch:!1,genericsSet:[]}}else if(i.type==="record"&&r.type==="record"){const l=[],c=new Map;for(const f of i.fields)c.set((s=f.as)!==null&&s!==void 0?s:f.name,f);for(const f of r.fields){const x=c.get((o=f.as)!==null&&o!==void 0?o:f.name);if(x===void 0)return{dataTypeMatch:!1,genericsSet:[]};const h=g2(new Map([...t.entries(),...l.map(p=>[p.name,p.type])]),e,f,x);l.push(...h.genericsSet)}return{dataTypeMatch:!0,genericsSet:l}}else if(i.type==="generic"){const l=t.get(i.generic);if(l!==void 0&&l.type!=="null"&&l.type!=="error")return g2(t,e,r,l);const c=(a=(u=e.find(f=>f.name===i.generic))===null||u===void 0?void 0:u.acceptibleTypes)!==null&&a!==void 0?a:[];for(const f of c){const x=g2(t,e,r,f);if(x.dataTypeMatch){if(!(0,Cr.isAtomic)(r)&&r.type!=="null")continue;const h={name:i.generic,type:r};return{dataTypeMatch:!0,genericsSet:[...x.genericsSet,h]}}}}return{dataTypeMatch:!1,genericsSet:[]}}function gb(t,e){switch(t.type){case"array":{if("fields"in t){const s=t.fields.map(o=>{const u=gb(o,e);return{...o,...u}});return{error:void 0,returnType:{type:"array",elementTypeDef:t.elementTypeDef,fields:s}}}const r=gb(t.elementTypeDef,e);if(r.error)return r;const i=r.returnType;return i.type==="record"?{error:void 0,returnType:{type:"array",elementTypeDef:{type:"record_element"},fields:i.fields}}:(0,Cr.isAtomic)(i)?{error:void 0,returnType:{type:"array",elementTypeDef:i}}:{error:{code:"invalid-resolved-type-for-array",parameters:"Invalid resolved type for array; cannot be non-atomic"},returnType:void 0}}case"record":return{error:void 0,returnType:{type:"record",fields:t.fields.map(i=>{const s=gb(i,e);return{...i,...s}})}};case"generic":{const r=e.get(t.generic);return r===void 0?{error:{code:"generic-not-resolved",parameters:`Generic ${t.generic} in return type could not be resolved`},returnType:void 0}:{error:void 0,returnType:r}}default:return{error:void 0,returnType:t}}}var sot=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),oot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),uot=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&sot(e,t,r);return oot(e,t),e};Object.defineProperty(mb,"__esModule",{value:!0}),mb.ExprProps=void 0;const aot=Xe,lot=Bs,cot=uot(Zt),fot=Bc,xot=$c,dot=m2,hot=ct,pot=Ky,mot=lt;class got extends hot.ExpressionDef{constructor(e,r){super({expr:e,statements:r}),this.expr=e,this.statements=r,this.elementType="expression with props",this.legalChildTypes=cot.anyAtomicT}getFilteredExpression(e,r,i){if(i.length>0){if(!this.expr.supportsWhere(r))return this.expr.logError("filter-of-non-aggregate","Filtered expression requires an aggregate computation"),r;const s=[];for(const o of i){const u=o.getFilterList(e);if(u.find(a=>(0,aot.expressionIsCalculation)(a.expressionType)))return o.logError("aggregate-filter-expression-not-scalar","Cannot filter an expresion with an aggregate or analytical computation"),r;s.push(...u)}return this.typeCheck(this.expr,{...r,expressionType:"scalar"})?{...r,compositeFieldUsage:(0,mot.mergeCompositeFieldUsage)(r.compositeFieldUsage,...s.map(o=>o.compositeFieldUsage)),value:{node:"filteredExpr",kids:{e:r.value,filterList:s}}}:(this.expr.logError("filter-of-non-aggregate",`Cannot filter '${r.expressionType}' data`),(0,lot.errorFor)("cannot filter type"))}return r}getExpression(e){const r=[];let i;const s=[],o=[];for(const a of this.statements)a instanceof dot.PartitionBy?this.expr.canSupportPartitionBy()?r.push(a):a.logError("partition-by-of-non-window-function","`partition_by` is not supported for this kind of expression"):a instanceof xot.Limit?i?a.logError("expression-limit-already-specified","limit already specified"):this.expr.canSupportLimit()?i=a:a.logError("limit-of-non-aggregate-function","`limit` is not supported for this kind of expression"):a instanceof fot.FunctionOrdering?this.expr.canSupportOrderBy()?s.push(a):a.logError("order-by-of-non-aggregate-function","`order_by` is not supported for this kind of expression"):o.push(a);const u=this.expr instanceof pot.ExprFunc?this.expr.getPropsExpression(e,{partitionBys:r,limit:i,orderBys:s}):this.expr.getExpression(e);return this.getFilteredExpression(e,u,o)}}mb.ExprProps=got;var yb={},yot=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Eot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Aot=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&yot(e,t,r);return Eot(e,t),e};Object.defineProperty(yb,"__esModule",{value:!0}),yb.ExprLogicalOp=void 0;const _ot=Wy,jle=Aot(Zt);class vot extends _ot.BinaryBoolean{constructor(){super(...arguments),this.elementType="logical operator",this.legalChildTypes=[jle.boolT,jle.aggregateBoolT]}}yb.ExprLogicalOp=vot;var Eb={},Cot=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Sot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),bot=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Cot(e,t,r);return Sot(e,t),e};Object.defineProperty(Eb,"__esModule",{value:!0}),Eb.ExprMax=void 0;const Ab=bot(Zt),Tot=Jl;class Rot extends Tot.ExprAggregateFunction{constructor(e){super("max",e),this.legalChildTypes=[Ab.numberT,Ab.stringT,Ab.dateT,Ab.timestampT]}returns(e){return e}}Eb.ExprMax=Rot;var _b={},Dot=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Oot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Fot=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Dot(e,t,r);return Oot(e,t),e};Object.defineProperty(_b,"__esModule",{value:!0}),_b.ExprMin=void 0;const vb=Fot(Zt),wot=Jl;class Not extends wot.ExprAggregateFunction{constructor(e){super("min",e),this.legalChildTypes=[vb.numberT,vb.stringT,vb.dateT,vb.timestampT]}returns(e){return e}}_b.ExprMin=Not;var Cb={},Lot=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Iot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Bot=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Lot(e,t,r);return Iot(e,t),e};Object.defineProperty(Cb,"__esModule",{value:!0}),Cb.ExprMinus=void 0;const $ot=Bs,qle=Bot(Zt),kot=ct;class Mot extends kot.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="unary minus",this.legalChildTypes=[qle.numberT]}getExpression(e){const r=this.expr.getExpression(e);return qle.typeIn(r,this.legalChildTypes)?{...r,type:"number",value:{node:"unary-",e:r.value}}:(0,$ot.errorFor)("negate requires number")}}Cb.ExprMinus=Mot;var Sb={};Object.defineProperty(Sb,"__esModule",{value:!0}),Sb.ExprMulDiv=void 0;const Pot=x2;class Uot extends Pot.BinaryNumeric{constructor(){super(...arguments),this.elementType="*/%"}}Sb.ExprMulDiv=Uot;var bb={},Jy={};Object.defineProperty(Jy,"__esModule",{value:!0}),Jy.Unary=void 0;const jot=ct;class qot extends jot.ExpressionDef{constructor(e){super({expr:e}),this.expr=e}}Jy.Unary=qot;var Hot=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Qot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),zot=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Hot(e,t,r);return Qot(e,t),e};Object.defineProperty(bb,"__esModule",{value:!0}),bb.ExprNot=void 0;const Q$=zot(Zt),Got=Jy;class Wot extends Got.Unary{constructor(e){super(e),this.elementType="not",this.legalChildTypes=[Q$.boolT,Q$.nullT]}getExpression(e){var r;const i=this.expr.getExpression(e);!((r=e.dialectObj())===null||r===void 0)&&r.booleanAsNumbers&&this.legalChildTypes.find(o=>o.type==="number")===void 0&&this.legalChildTypes.push(Q$.numberT);const s=this.typeCheck(this.expr,i);return{...i,type:"boolean",value:{node:"not",e:s?i.value:{node:"false"}}}}}bb.ExprNot=Wot;var Tb={};Object.defineProperty(Tb,"__esModule",{value:!0}),Tb.ExprNow=void 0;const Vot=ct,Yot=lt;class Kot extends Vot.ExpressionDef{constructor(){super(...arguments),this.elementType="timestamp"}getExpression(e){return{type:"timestamp",expressionType:"scalar",evalSpace:"constant",value:{node:"now",typeDef:{type:"timestamp"}},compositeFieldUsage:(0,Yot.emptyCompositeFieldUsage)()}}}Tb.ExprNow=Kot;var Mc={};Object.defineProperty(Mc,"__esModule",{value:!0}),Mc.ExprIsNull=Mc.PartialIsNull=Mc.ExprNULL=void 0;const Jot=Gt,Rb=ct;function z$(t,e,r){const i=r.getExpression(t);return i.type="boolean",i.value={node:e==="="?"is-null":"is-not-null",e:i.value},i}class Xot extends Rb.ExpressionDef{constructor(){super(...arguments),this.elementType="NULL"}getExpression(){return(0,Jot.literalExprValue)({dataType:{type:"null"},value:{node:"null"}})}apply(e,r,i){return r==="!="||r==="="?z$(e,r,i):super.apply(e,r,i,!0)}}Mc.ExprNULL=Xot;class Zot extends Rb.ExpressionDef{constructor(e){super(),this.op=e,this.elementType="<=> NULL"}apply(e,r,i){return z$(e,this.op,i)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("partial-as-value","Partial null check does not have a value")}atNodeType(){return Rb.ATNodeType.Partial}}Mc.PartialIsNull=Zot;class eut extends Rb.ExpressionDef{constructor(e,r){super(),this.expr=e,this.op=r,this.elementType="is null",this.has({expr:e})}getExpression(e){return z$(e,this.op,this.expr)}}Mc.ExprIsNull=eut;var Db={};Object.defineProperty(Db,"__esModule",{value:!0}),Db.ExprNumber=void 0;const tut=Gt,nut=ct;class rut extends nut.ExpressionDef{constructor(e){super(),this.n=e,this.elementType="numeric literal"}getExpression(e){return this.constantExpression()}constantExpression(){const e=Number(this.n),r=Number.isNaN(e)?{type:"number"}:{type:"number",numberType:Number.isInteger(e)?"integer":"float"};return(0,tut.literalExprValue)({dataType:r,value:{node:"numberLiteral",literal:this.n}})}}Db.ExprNumber=rut;var Ob={};Object.defineProperty(Ob,"__esModule",{value:!0}),Ob.ExprParens=void 0;const G$=ct;class iut extends G$.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="(expression)"}requestExpression(e){return this.expr.requestExpression(e)}getExpression(e){const r=this.expr.getExpression(e);return{...r,value:{node:"()",e:r.value}}}apply(e,r,i,s){return this.expr.atNodeType()===G$.ATNodeType.Or?this.expr.apply(e,r,i,s):(0,G$.applyBinary)(e,i,r,this)}atNodeType(){return this.expr.atNodeType()}atExpr(){return this.expr}}Ob.ExprParens=iut;var Fb={};Object.defineProperty(Fb,"__esModule",{value:!0}),Fb.ExprFilterExpression=void 0;const sut=ct;class out extends sut.ExpressionDef{constructor(e){super(),this.filterText=e,this.elementType="filter expression literal"}getExpression(){return{type:"filter expression",value:{node:"filterLiteral",filterSrc:this.filterText},expressionType:"scalar",evalSpace:"constant",compositeFieldUsage:{fields:[],joinedUsage:{}}}}}Fb.ExprFilterExpression=out;var wb={};Object.defineProperty(wb,"__esModule",{value:!0}),wb.ExprRegEx=void 0;const uut=Gt,aut=ct;class lut extends aut.ExpressionDef{constructor(e){super(),this.regex=e,this.elementType="regular expression literal"}getExpression(){return(0,uut.literalExprValue)({dataType:{type:"regular expression"},value:{node:"regexpLiteral",literal:this.regex}})}}wb.ExprRegEx=lut;var Nb={};Object.defineProperty(Nb,"__esModule",{value:!0}),Nb.ExprString=void 0;const cut=ct,fut=Gt;class xut extends cut.ExpressionDef{constructor(e){super(),this.elementType="string literal",this.value=e}getExpression(e){return(0,fut.literalExprValue)({dataType:{type:"string"},value:{node:"stringLiteral",literal:this.value}})}}Nb.ExprString=xut;var Lb={};Object.defineProperty(Lb,"__esModule",{value:!0}),Lb.ExprSum=void 0;const dut=p2;class hut extends dut.ExprAsymmetric{constructor(e,r,i){super("sum",e,r,i),this.has({source:r})}}Lb.ExprSum=hut;var Ib={};Object.defineProperty(Ib,"__esModule",{value:!0}),Ib.ExprTimeExtract=void 0;const Xl=Xe,Bb=Gt,W$=ct,put=Ic;class Xy extends W$.ExpressionDef{static extractor(e){const r=Xy.pluralMap[e];if(r)return r;if((0,Xl.isExtractUnit)(e))return e}constructor(e,r){super({args:r}),this.extractText=e,this.args=r,this.elementType="timeExtract"}getExpression(e){const r=Xy.extractor(this.extractText);if(r){if(this.args.length!==1)return this.loggedErrorExpr("too-many-arguments-for-time-extraction",`Extraction function ${r} requires one argument`);const i=this.args[0];if(i instanceof put.Range){let s=i.first.getExpression(e),o=i.last.getExpression(e);if(s.type==="error"||o.type==="error")return(0,Bb.computedErrorExprValue)({dataType:{type:"number"},error:"extract from error",from:[s,o]});if(!(0,Xl.isTemporalType)(s.type))return i.first.loggedErrorExpr("invalid-type-for-time-extraction",`Can't extract ${r} from '${s.type}'`);if(!(0,Xl.isTemporalType)(o.type))return i.last.loggedErrorExpr("invalid-type-for-time-extraction",`Cannot extract ${r} from '${o.type}'`);let u=s.type;if(!Xl.TD.eq(s,o)){let a=!0;if(u="timestamp",s.type==="date"){const l=(0,W$.getMorphicValue)(s,"timestamp");l&&(s=l,a=!1)}else{const l=(0,W$.getMorphicValue)(o,"timestamp");l&&(o=l,a=!1)}if(a)return i.first.loggedErrorExpr("invalid-types-for-time-measurement",`Cannot measure from ${s.type} to ${o.type}`)}return["week","month","quarter","year"].includes(r)?this.loggedErrorExpr("invalid-timeframe-for-time-measurement",`Cannot measure interval using '${r}'`):(0,Xl.isTimestampUnit)(r)?(0,Bb.computedExprValue)({dataType:{type:"number",numberType:"integer"},value:{node:"timeDiff",units:r,kids:{left:(0,Xl.mkTemporal)(s.value,u),right:(0,Xl.mkTemporal)(o.value,u)}},from:[s,o]}):this.loggedErrorExpr("invalid-time-extraction-unit",`Cannot extract ${r} from a range`)}else{const s=i.getExpression(e);return(0,Xl.isTemporalType)(s.type)?(0,Bb.computedExprValue)({dataType:{type:"number",numberType:"integer"},value:{node:"extract",e:(0,Xl.mkTemporal)(s.value,s.type),units:r},from:[s]}):(s.type!=="error"&&this.logError("unsupported-type-for-time-extraction",`${this.extractText}() requires time type, not '${s.type}'`),(0,Bb.computedErrorExprValue)({dataType:{type:"number",numberType:"integer"},error:`${this.extractText} bad type ${s.type}`,from:[s]}))}}throw this.internalError(`Illegal extraction unit '${this.extractText}'`)}}Ib.ExprTimeExtract=Xy,Xy.pluralMap={years:"year",quarters:"quarter",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second"};var $b={},mu={},kb={};Object.defineProperty(kb,"__esModule",{value:!0}),kb.QueryInputSpace=void 0;const mut=xs,gut=e2;class yut extends gut.RefinedSpace{constructor(e,r,i){super(e),this.queryOutput=r,this._isProtectedAccessSpace=i,this.extendList=[]}extendSource(e){this.pushFields(e),e instanceof mut.Join?this.extendList.push(e.name.refString):this.extendList.push(e.defineName)}isQueryFieldSpace(){return!0}outputSpace(){return this.queryOutput}inputSpace(){return this}isProtectedAccessSpace(){return this._isProtectedAccessSpace}}kb.QueryInputSpace=yut;var Eut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Aut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_ut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Eut(e,t,r);return Aut(e,t),e};Object.defineProperty(mu,"__esModule",{value:!0}),mu.ReduceFieldSpace=mu.QuerySpace=mu.QueryOperationSpace=void 0;const Mb=_ut(Xe),V$=Dc,Hle=kc,Qle=Mr,vut=yt,Cut=e2,Sut=Ny,but=Pr,Tut=kb,Da=lt,Rut=Xx;class zle extends Cut.RefinedSpace{get compositeFieldUsage(){if(this._compositeFieldUsage===void 0)throw new Error("Composite field usage accessed before computed");return this._compositeFieldUsage}constructor(e,r,i,s){super(e.emptyStructDef()),this.queryInputSpace=e,this.nestParent=i,this.astEl=s,this.expandedWild={},this.compositeFieldUsers=[],this._compositeFieldUsage=void 0,this.exprSpace=new Tut.QueryInputSpace(e.structDef(),this,e.isProtectedAccessSpace()),r&&this.addRefineFromFields(r)}logError(e,r,i){return this.astEl&&this.astEl.logError(e,r,i),e}inputSpace(){return this.exprSpace}outputSpace(){return this}addWild(e){var r;let i=this.exprSpace;const s=[];if(e.joinPath)for(const a of e.joinPath.list){const l=a.refString;s.push(l);const c=i.entry(l);if(c)if(c instanceof but.StructSpaceField)i=c.fieldSpace;else{a.logError("invalid-wildcard-source",`Field '${l}' does not contain rows and cannot be expanded with '*'`);return}else{a.logError("wildcard-source-not-defined",`No such field as '${l}'`);return}}const o=this.dialectObj(),u=[];for(const[a,l]of i.entries())if(!e.except.has(a)&&l.refType!=="parameter")if(this.entry(a)){const c=(r=this.expandedWild[a])===null||r===void 0?void 0:r.path.join(".");e.logError("name-conflict-in-wildcard-expansion",`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${c?` (conflicts with ${c})`:""}`)}else{const c=l.typeDesc();Mb.TD.isAtomic(c)&&Mb.expressionIsScalar(c.expressionType)&&(o===void 0||!o.ignoreInProject(a))&&(u.push({name:a,entry:l}),this.expandedWild[a]={path:s.concat(a),entry:l})}for(const a of u.sort((l,c)=>l.name.localeCompare(c.name)))this.newEntry(a.name,e,a.entry)}addValidatedCompositeFieldUserFromEntry(e,r){r instanceof Qle.SpaceField&&this.compositeFieldUsers.push({type:"field",name:e,field:r,logTo:void 0})}getJoinOnCompositeFieldUsage(e){var r;const i=e.map(o=>new Hle.FieldName(o));this.astEl.has({reference:i});const s=this.exprSpace.lookup(i);if(s.found&&s.found instanceof Rut.StructSpaceFieldBase)return(0,Da.joinedCompositeFieldUsage)(e.slice(0,-1),(r=s.found.fieldDef().onCompositeFieldUsage)!==null&&r!==void 0?r:(0,Da.emptyCompositeFieldUsage)());throw new Error("Unexpected join lookup was not found or not a struct")}getCompositeFieldUsageIncludingJoinOns(e){let r=e;const i=(0,Da.compositeFieldUsageJoinPaths)(e);for(const s of i)r=(0,Da.mergeCompositeFieldUsage)(this.getJoinOnCompositeFieldUsage(s),r);return r}addCompositeFieldUserFromFilter(e,r){e.compositeFieldUsage!==void 0&&this.compositeFieldUsers.push({type:"filter",filter:e,logTo:r})}newEntry(e,r,i){i instanceof Qle.SpaceField&&this.compositeFieldUsers.push({type:"field",name:e,field:i,logTo:r}),super.newEntry(e,r,i)}applyNextCompositeFieldUsage(e,r,i,s,o){if(s){const u=this.getCompositeFieldUsageIncludingJoinOns((0,Da.compositeFieldUsageDifference)(s,r));if(r=(0,Da.mergeCompositeFieldUsage)(r,u),!(0,Da.isEmptyCompositeFieldUsage)(u)){const a=(0,Da.narrowCompositeFieldResolution)(e,r,i);a.error?(o??this).logError("invalid-composite-field-usage",{newUsage:u,allUsage:r}):i=a.narrowedCompositeFieldResolution}}return{compositeFieldUsage:r,narrowedCompositeFieldResolution:i}}}mu.QueryOperationSpace=zle;class Gle extends zle{addRefineFromFields(e){var r;if(Mb.isQuerySegment(e)){if(e!=null&&e.extendSource)for(const i of e.extendSource)this.exprSpace.addFieldDef(i);for(const i of e.queryFields)if(i.type==="fieldref"){const s=this.exprSpace.lookup(i.path.map(o=>new Hle.FieldName(o)));if(s.found){const o=i.path[i.path.length-1];this.setEntry(o,s.found),this.addValidatedCompositeFieldUserFromEntry(o,s.found)}}else if(i.type!=="turtle"){const s=new Sut.ColumnSpaceField(i),o=(r=i.as)!==null&&r!==void 0?r:i.name;this.setEntry(o,s),this.addValidatedCompositeFieldUserFromEntry(o,s)}}}pushFields(...e){for(const r of e)r instanceof vut.WildcardFieldReference?this.addWild(r):super.pushFields(r)}canContain(e){return!0}queryFieldDefs(){const e=[];let r=(0,Da.emptyCompositeFieldUsage)(),i=(0,Da.emptyNarrowedCompositeFieldResolution)();const s=this.inputSpace().structDef();for(const o of this.compositeFieldUsers){let u;if(o.type==="filter")o.filter.compositeFieldUsage&&(u=o.filter.compositeFieldUsage);else{const{name:l,field:c}=o,f=this.expandedWild[l];if(f)e.push({type:"fieldref",path:f.path}),u=f.entry.typeDesc().compositeFieldUsage;else{const x=c.getQueryFieldDef(this.exprSpace);if(x){const h=c.typeDesc();u=h.compositeFieldUsage,h&&h.type!=="error"&&this.canContain(h)&&!Out(x)&&e.push(x)}}}const a=this.applyNextCompositeFieldUsage(s,r,i,u,o.logTo);r=a.compositeFieldUsage,i=a.narrowedCompositeFieldResolution}return this._compositeFieldUsage=r,e}getQuerySegment(e){const r=this.getPipeSegment(e);if(Mb.isQuerySegment(r))return r;throw new Error("TODO NOT POSSIBLE")}getPipeSegment(e){if(this.segmentType==="index")return this.logError("unexpected-index-segment","internal error generating index segment from non index query"),{type:"reduce",queryFields:[]};const r={type:this.segmentType,queryFields:this.queryFieldDefs()};if(r.queryFields=(0,V$.mergeFields)(e==null?void 0:e.queryFields,r.queryFields),e!=null&&e.extendSource&&(r.extendSource=e.extendSource),this.exprSpace.extendList.length>0){const i=[],s=this.exprSpace.structDef();for(const o of this.exprSpace.extendList){const u=s.fields.find(a=>(0,V$.nameFromDef)(a)===o);u&&i.push(u)}r.extendSource=(0,V$.mergeFields)(r.extendSource,i)}return this.newTimezone&&(r.queryTimezone=this.newTimezone),r}lookup(e){const r=super.lookup(e);return r.found?{...r,isOutputField:!0}:this.exprSpace.lookup(e)}isQueryFieldSpace(){return!0}}mu.QuerySpace=Gle;class Dut extends Gle{constructor(){super(...arguments),this.segmentType="reduce"}}mu.ReduceFieldSpace=Dut;function Out(t){return typeof t!="string"&&t.type==="turtle"&&t.pipeline.length===0}var Fut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),wut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Nut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Fut(e,t,r);return wut(e,t),e};Object.defineProperty($b,"__esModule",{value:!0}),$b.ExprUngroup=void 0;const Wle=Xe,Lut=mu,Vle=Nut(Zt),Iut=ct;class But extends Iut.ExpressionDef{constructor(e,r,i){super({expr:r,fields:i}),this.control=e,this.expr=r,this.fields=i,this.legalChildTypes=Vle.anyAtomicT,this.elementType="ungroup"}getExpression(e){const r=this.expr.getExpression(e);if(!(0,Wle.expressionIsAggregate)(r.expressionType))return this.expr.loggedErrorExpr("ungroup-of-non-aggregate",`${this.control}() expression must be an aggregate`);if((0,Wle.expressionIsUngroupedAggregate)(r.expressionType))return this.expr.loggedErrorExpr("ungroup-of-ungrouped-aggregate",`${this.control}() expression must not already be ungrouped`);const i={node:this.control,e:r.value};if(this.typeCheck(this.expr,{...r,expressionType:"scalar"})){if(e.isQueryFieldSpace()&&this.fields.length>0){const s=[],o=this.control==="exclude";for(const u of this.fields){let a=e.outputSpace(),l=!0;for(;a;){const c=a.lookup([u]);if(c.found&&c.isOutputField)s.push(u.refString),l=!1;else if(a instanceof Lut.QuerySpace){a=a.nestParent;continue}break}if(l){const c=o?"exclude()":"all()";u.logError("ungroup-field-not-in-output",`${c} '${u.refString}' is missing from query output`)}}i.fields=s}return{...Vle.atomicDef(r),expressionType:"ungrouped_aggregate",value:i,evalSpace:"output",compositeFieldUsage:r.compositeFieldUsage}}return this.loggedErrorExpr("ungroup-with-non-scalar",`${this.control}() incompatible type`)}}$b.ExprUngroup=But;var Pb={},$ut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),kut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Mut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&$ut(e,t,r);return kut(e,t),e};Object.defineProperty(Pb,"__esModule",{value:!0}),Pb.ForRange=void 0;const Put=Bs,Yle=Mut(Zt),Ub=ds,Uut=Gt,jut=ct,jb=f2,Kle=Ic;class qut extends jut.ExpressionDef{constructor(e,r,i){super({from:e,duration:r,timeframe:i}),this.from=e,this.duration=r,this.timeframe=i,this.elementType="forRange",this.legalChildTypes=[Yle.timestampT,Yle.dateT]}apply(e,r,i){const s=this.from.getExpression(e),o=i.getExpression(e);if(!this.typeCheck(i,o))return(0,Put.errorFor)("no time for range");const u=this.duration.getExpression(e);if(u.type!=="number")return u.type!=="error"&&this.logError("invalid-duration-quantity",`FOR duration count must be a number, not '${u.type}'`),(0,Uut.computedErrorExprValue)({dataType:{type:"boolean"},error:"for not number",from:[s,o]});const a=this.timeframe.text;let l=(0,Ub.resolution)(a);if(s.type==="timestamp"&&(l="timestamp"),o.type==="date"&&l==="date"){const m=this.from,g=(0,Ub.timeOffset)("date",s.value,"+",u.value,a),y=new jb.ExprTime("date",g);return new Kle.Range(m,y).apply(e,r,i)}const c=jb.ExprTime.fromValue("timestamp",o);let f=this.from,x=s.value;if(s.type==="date"){const m=s.morphic&&s.morphic.timestamp;m?x=m:x=(0,Ub.castTo)("timestamp",x,"date"),f=new jb.ExprTime("timestamp",x,[s])}const h=(0,Ub.timeOffset)("timestamp",x,"+",u.value,a),p=new jb.ExprTime("timestamp",h,[s,u]);return new Kle.Range(f,p).apply(e,r,c)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("range-as-value","A Range is not a value")}}Pb.ForRange=qut;var Sr={};Object.defineProperty(Sr,"__esModule",{value:!0}),Sr.LiteralYear=Sr.LiteralQuarter=Sr.LiteralMonth=Sr.LiteralWeek=Sr.LiteralDay=Sr.LiteralHour=Sr.LiteralTimestamp=Sr.TimeFormatError=void 0;const Pc=by,Hut=Xe,Qut=Gt,zut=Ic,Jle=f2,Y$=ct;class Gut extends Error{}Sr.TimeFormatError=Gut;function nd(t,e){const r=t.slice(1);if(e){const i=r.match(/\[[^\]]+]$/);if(i)return{tzSpec:i[0].slice(1,-1),text:r.slice(0,-i[0].length)}}return{text:r}}const Xle="yyyy",Zle=`${Xle}-LL`,Ao=`${Zle}-dd`,e0e=`${Ao} HH`,t0e=`${e0e}:mm`,K$=`${t0e}:ss`;class n0e extends Y$.ExpressionDef{constructor(e,r,i){super(),this.units=r,this.timeType=i,this.literalPart=e.text,e.tzSpec&&(this.timeZone=e.tzSpec)}makeLiteral(e,r){const i={node:"timeLiteral",literal:e,typeDef:{type:r}};return this.timeZone&&(i.timezone=this.timeZone),i}makeValue(e,r){const i=this.makeLiteral(e,r);return(0,Qut.literalTimeResult)({value:i,dataType:{type:r},timeframe:this.units})}getExpression(e){return this.makeValue(this.literalPart,this.timeType)}getNext(){if(this.nextLit)return this.makeValue(this.nextLit,this.timeType)}granular(){return this.nextLit!==void 0}}class J$ extends n0e{constructor(e,r){super(e,r,"timestamp"),this.elementType="literal:timestamp"}static parse(e){let r;const i=nd(e,!0);e=i.text,e[10]==="T"&&(e=e.slice(0,10)+" "+e.slice(11),i.text=e);const s=e.match(/^([^.,]+)[,.](\d+)$/);s&&(e=s[1]);let o=Pc.DateTime.fromFormat(e,K$);if(o.isValid)return new J$(i,r);if(o=Pc.DateTime.fromFormat(e,t0e),o.isValid){i.text=i.text+":00",r="minute";const u=o.plus({minute:1}).toFormat(K$);return new X$(i,r,"timestamp",u)}}}Sr.LiteralTimestamp=J$;class X$ extends n0e{constructor(e,r,i,s){super(e,r,i),this.nextLit=s,this.elementType="granularTimeLiteral"}apply(e,r,i){let s=this.getExpression(e),o=this.getNext();if(o){const u=i.getExpression(e);if(u.type==="timestamp"){const a=(0,Y$.getMorphicValue)(s,"timestamp"),l=(0,Y$.getMorphicValue)(o,"timestamp");if(a&&l)s=a,o=l;else return super.apply(e,r,i)}if(o&&(0,Hut.isTemporalType)(u.type)){const a=u.type;return new zut.Range(new Jle.ExprTime(a,s.value),new Jle.ExprTime(a,o.value)).apply(e,r,i)}}return super.apply(e,r,i)}}class Z$ extends X${constructor(e,r){super(e,"hour","timestamp",r),this.elementType="literal:hour"}static parse(e){const r=nd(e,!1);let i=r.text;const s=Pc.DateTime.fromFormat(r.text,e0e);if(s.isValid)return r.text=r.text+":00:00",i=s.plus({hour:1}).toFormat(K$),new Z$(r,i)}}Sr.LiteralHour=Z$;class Zy extends X${constructor(e,r,i){super(e,r,"date",i)}getExpression(e){const r=this.makeValue(this.literalPart,"date"),i=this.makeLiteral(`${this.literalPart} 00:00:00`,"timestamp");return{...r,morphic:{timestamp:i},evalSpace:"literal"}}getNext(){const e=this.makeValue(this.nextLit,"date"),r=this.makeLiteral(`${this.nextLit} 00:00:00`,"timestamp");return{...e,morphic:{timestamp:r}}}}class ek extends Zy{constructor(e,r){super(e,"day",r),this.elementType="literal:day"}static parse(e){const r=nd(e,!1);let i=r.text;const s=Pc.DateTime.fromFormat(r.text,Ao);if(s.isValid)return i=s.plus({day:1}).toFormat(Ao),new ek(r,i)}}Sr.LiteralDay=ek;class tk extends Zy{constructor(e,r){super(e,"week",r),this.elementType="literal:week"}static parse(e){const r=nd(e,!1);let i=r.text;const s=r.text.slice(0,10),o=Pc.DateTime.fromFormat(s,Ao);if(o.isValid&&o.weekday===7){const a=o.plus({days:7});return r.text=o.toFormat(Ao),i=a.toFormat(Ao),new tk(r,i)}}}Sr.LiteralWeek=tk;class nk extends Zy{constructor(e,r){super(e,"month",r),this.elementType="literal:month"}static parse(e){const r=nd(e,!1);let i=r.text;const s=Pc.DateTime.fromFormat(r.text,Zle);if(s.isValid){const o=s.plus({months:1});return r.text=s.toFormat(Ao),i=o.toFormat(Ao),new nk(r,i)}}}Sr.LiteralMonth=nk;class rk extends Zy{constructor(e,r){super(e,"quarter",r),this.elementType="literal:quarter"}static parse(e){const r=nd(e,!1);let i=r.text;const s=r.text.match(/(^\d{4})-[qQ](\d)$/);if(s){const o=Number.parseInt(s[2])-1;let u=Pc.DateTime.fromFormat(s[1],"yyyy");o>0&&(u=u.plus({quarters:o}));const a=u.plus({quarter:1});return r.text=u.toFormat(Ao),i=a.toFormat(Ao),new rk(r,i)}}}Sr.LiteralQuarter=rk;class ik extends Zy{constructor(e,r){super(e,"year",r),this.elementType="literal:year"}static parse(e){const r=nd(e,!1);let i=r.text;const s=Pc.DateTime.fromFormat(r.text,Xle);if(s.isValid){const o=s.plus({year:1});return r.text=s.toFormat(Ao),i=o.toFormat(Ao),new ik(r,i)}}}Sr.LiteralYear=ik;var qb={};Object.defineProperty(qb,"__esModule",{value:!0}),qb.PartialCompare=void 0;const r0e=ct;class Wut extends r0e.ExpressionDef{constructor(e,r){super({right:r}),this.op=e,this.right=r,this.elementType="<=> a"}granular(){return this.right.granular()}apply(e,r,i){return this.right.apply(e,this.op,i)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("partial-as-value","Partial comparison does not have a value")}atNodeType(){return r0e.ATNodeType.Partial}}qb.PartialCompare=Wut;var y2={},Vut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Yut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Kut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Vut(e,t,r);return Yut(e,t),e};Object.defineProperty(y2,"__esModule",{value:!0}),y2.PickWhen=y2.Pick=void 0;const E2=Kut(Zt),i0e=Gt,Jut=ct,Xut=Je;function Hb(t,e){return t===void 0||t.type==="null"||t.type==="error"?e:t}class Zut extends Jut.ExpressionDef{constructor(e,r){super({choices:e}),this.choices=e,this.elsePick=r,this.elementType="pick",this.has({elsePick:r})}requestExpression(e){if(this.elsePick!==void 0){for(const r of this.choices){if(r.pick===void 0)return;const i=r.when.requestExpression(e);if(i===void 0||i.type!=="boolean")return}return this.getExpression(e)}}apply(e,r,i){var s;const o={node:"case",kids:{caseWhen:[],caseThen:[]}};let u;const a=[];for(const h of this.choices){const p=h.when.apply(e,"=",i),m=h.pick?h.pick.getExpression(e):i.getExpression(e);if(a.push(p,m),u&&!E2.typeEq(u,m,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:m.type,returnType:u.type});u=Hb(u,m),o.kids.caseWhen.push(p.value),o.kids.caseThen.push(m.value)}const l=(s=this.elsePick)===null||s===void 0?void 0:s.getExpression(e),c=i.getExpression(e);a.push(c),l&&a.push(l);const f=l??c,x=Hb(u,f);return E2.typeEq(x,f,!0)?x.type==="filter expression"?this.loggedErrorExpr("filter-expression-error","Pick statments cannot have filter expression values"):(o.kids.caseElse=f.value,(0,i0e.computedExprValue)({dataType:x,value:o,from:a})):this.elsePick?this.loggedErrorExpr("pick-else-type-does-not-match",{elseType:f.type,returnType:x.type}):this.loggedErrorExpr("pick-default-type-does-not-match",{defaultType:f.type,returnType:x.type})}getExpression(e){const r={node:"case",kids:{caseWhen:[],caseThen:[]}};if(this.elsePick===void 0)return this.loggedErrorExpr("pick-missing-else","pick incomplete, missing 'else'");const i=[],s=[];for(const l of this.choices){if(l.pick===void 0)return this.loggedErrorExpr("pick-missing-value","pick with no value can only be used with apply");l.when.requestExpression(e)===void 0&&this.loggedErrorExpr("pick-illegal-partial","pick with partial when can only be used with apply");const f=l.pick.getExpression(e),x=l.when.getExpression(e);i.push({pick:f,when:x}),s.push(f,x)}let o;for(const l of i){if(!E2.typeEq(l.when,E2.boolT))return this.loggedErrorExpr("pick-when-must-be-boolean",{whenType:l.when.type});if(o&&!E2.typeEq(o,l.pick,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:l.pick.type,returnType:o.type});o=Hb(o,l.pick),r.kids.caseWhen.push(l.when.value),r.kids.caseThen.push(l.pick.value)}const u=this.elsePick.getExpression(e);s.push(u);const a=Hb(o,u);return E2.typeEq(a,u,!0)?a.type==="filter expression"?this.loggedErrorExpr("filter-expression-error","Pick statments cannot have filter expression values"):(r.kids.caseElse=u.value,(0,i0e.computedExprValue)({dataType:a,value:r,from:s})):this.elsePick.loggedErrorExpr("pick-else-type-does-not-match",{elseType:u.type,returnType:a.type})}}y2.Pick=Zut;class eat extends Xut.MalloyElement{constructor(e,r){super({when:r}),this.pick=e,this.when=r,this.elementType="caseWhen",this.has({pick:e})}}y2.PickWhen=eat;var A2={},tat=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),nat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),rat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&tat(e,t,r);return nat(e,t),e};Object.defineProperty(A2,"__esModule",{value:!0}),A2.CaseWhen=A2.Case=void 0;const iat=Gt,sat=ct,oat=Je,_2=rat(Zt);function s0e(t,e){return t===void 0||t.type==="null"||t.type==="error"?e:t}class uat extends sat.ExpressionDef{constructor(e,r,i){super({choices:r}),this.value=e,this.choices=r,this.elseValue=i,this.elementType="case",this.has({elseValue:i,value:e})}getExpression(e){const r={node:"case",kids:{caseWhen:[],caseThen:[]}},i=[];let s;if(this.value){const a=this.value.getExpression(e);i.push(a),r.kids.caseValue=a.value,s=a}const o=[];for(const a of this.choices){const l=a.when.getExpression(e),c=a.then.getExpression(e);o.push({when:l,then:c}),i.push(l,c)}let u;for(const a of o){if(s!==void 0){if(!_2.typeEq(a.when,s))return this.loggedErrorExpr("case-when-type-does-not-match",{whenType:a.when.type,valueType:s.type})}else if(!_2.typeEq(a.when,_2.boolT))return this.loggedErrorExpr("case-when-must-be-boolean",{whenType:a.when.type});if(u&&!_2.typeEq(u,a.then,!0))return this.loggedErrorExpr("case-then-type-does-not-match",{thenType:a.then.type,returnType:u.type});u=s0e(u,a.then),r.kids.caseWhen.push(a.when.value),r.kids.caseThen.push(a.then.value)}if(this.elseValue){const a=this.elseValue.getExpression(e);if(u&&!_2.typeEq(u,a,!0))return this.loggedErrorExpr("case-else-type-does-not-match",{elseType:a.type,returnType:u.type});u=s0e(u,a),i.push(a),r.kids.caseElse=a.value}return(0,iat.computedExprValue)({value:r,dataType:u?_2.atomicDef(u):{type:"null"},from:i})}}A2.Case=uat;class aat extends oat.MalloyElement{constructor(e,r){super({when:e,then:r}),this.when=e,this.then=r,this.elementType="caseWhen"}}A2.CaseWhen=aat;var Qb={},rd={},lat=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),cat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),fat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&lat(e,t,r);return cat(e,t),e};Object.defineProperty(rd,"__esModule",{value:!0}),rd.RecordLiteral=rd.RecordElement=void 0;const o0e=Pi,xat=Gt,dat=ct,hat=Je,pat=fat(Zt);class mat extends hat.MalloyElement{constructor(e){if(super(),this.elementType="record element","value"in e)this.value=e.value,this.has({value:e.value}),e.key&&(this.key=e.key);else{this.has({path:e.path}),this.value=e.path;const r=e.path.fieldReference.path;this.key=r[r.length-1]}}}rd.RecordElement=mat;class gat extends dat.ExpressionDef{constructor(e){super(),this.pairs=e,this.elementType="record literal",this.has({pairs:e})}getExpression(e){return this.getRecord(e,[])}getRecord(e,r){var i;const s={node:"recordLiteral",kids:{},typeDef:{type:"record",fields:[]}},o=[];let u=0;for(const a of this.pairs){const l=(i=a.key)!==null&&i!==void 0?i:r[u];if(u+=1,l===void 0){a.logError("record-literal-needs-keys","Anonymous record element not legal here");continue}const c=a.value.getExpression(e);o0e.TD.isAtomic(c)?(o.push(c),s.kids[l]=c.value,s.typeDef.fields.push((0,o0e.mkFieldDef)(pat.atomicDef(c),l))):a.value.logError("illegal-record-property-type",`Record property '${a.key} is type '${c.type}', which is not a legal property value type`)}return(0,xat.computedExprValue)({value:s,dataType:s.typeDef,from:o})}getNextElement(e,r){const i=r.value;return i.node==="recordLiteral"?this.getRecord(e,Object.keys(i.kids)):this.getRecord(e,[])}}rd.RecordLiteral=gat;var yat=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Eat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Aat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&yat(e,t,r);return Eat(e,t),e};Object.defineProperty(Qb,"__esModule",{value:!0}),Qb.ArrayLiteral=void 0;const _at=Gt,vat=ct,u0e=Aat(Zt),Cat=rd;class Sat extends vat.ExpressionDef{constructor(e){super(),this.elements=e,this.elementType="array literal",this.has({elements:e})}getExpression(e){const r=[],i=[];let s;if(this.elements.length>0)for(const l of this.elements){const c=s&&l instanceof Cat.RecordLiteral?l.getNextElement(e,s):l.getExpression(e);if(i.push(c),c.type!=="error"){if(s){if(c.type!=="null"&&!u0e.typeEq(s,c)){l.logError("array-values-incompatible","All array elements must be same type");continue}}else c.type!=="null"&&(s=c);r.push(c.value)}}const o=u0e.atomicDef(s||{type:"number"}),u=o.type==="record"?{type:"array",elementTypeDef:{type:"record_element"},fields:o.fields}:{type:"array",elementTypeDef:o},a={node:"arrayLiteral",kids:{values:r},typeDef:u};return(0,_at.computedExprValue)({dataType:u,value:a,from:i})}}Qb.ArrayLiteral=Sat;var zb={};Object.defineProperty(zb,"__esModule",{value:!0}),zb.Timeframe=void 0;const bat=Xe,Tat=Je;class Rat extends Tat.MalloyElement{constructor(e){super(),this.elementType="timeframe";let r=e.toLowerCase();r.endsWith("s")&&(r=r.slice(0,-1)),this.text=(0,bat.isTimestampUnit)(r)?r:"second"}}zb.Timeframe=Rat;var Uc={};Object.defineProperty(Uc,"__esModule",{value:!0}),Uc.ImportStatement=Uc.ImportSelect=Uc.ImportSourceName=void 0;const sk=Je;class Dat extends sk.MalloyElement{constructor(e){super(),this.text=e,this.elementType="importSourceName"}}Uc.ImportSourceName=Dat;class Oat extends sk.MalloyElement{constructor(e,r){super(),this.text=e,this.from=r,this.elementType="importName",r&&this.has({from:r})}}Uc.ImportSelect=Oat;class Fat extends sk.ListOf{constructor(e,r){super([]),this.url=e,this.elementType="import statement";try{this.fullURL=decodeURI(new URL(e,r).toString())}catch{this.logError("invalid-import-url","Invalid URL in import statement")}}needs(){const e=this.translator();if(e&&this.fullURL&&e.root.importZone.getEntry(this.fullURL).status==="present"){const i=e.childRequest(this.fullURL);if(i)return i}}execute(e){const r=this.translator();if(!r)this.logError("no-translator-for-import","Cannot import without translation context");else if(this.fullURL){const i=r.root.pretranslatedModels.get(this.fullURL),s=r.root.importZone.getEntry(this.fullURL);if(i||s.status==="present"){const o=r.getChildExports(this.fullURL);if(this.notEmpty())for(const u of this.list){const a=u.from||u;if(e.getEntry(u.text))u.logError("name-conflict-on-selective-import",`Cannot redefine '${u.text}'`);else if(o[a.text]){const l={...o[a.text]};u.from&&(l.as=u.text),e.setEntry(u.text,{entry:l,exported:!1})}else a.logError("selective-import-not-found",`Cannot find '${a.text}', not imported`)}else for(const[u,a]of Object.entries(r.getChildExports(this.fullURL)))e.getEntry(u)?this.logError("name-conflict-on-indiscriminate-import",`Cannot redefine '${u}'`):e.setEntry(u,{entry:a,exported:!1})}else s.status==="error"?this.logError("failed-import",`import failed: '${s.message}'`):this.logError("failed-import",`import failed with status: '${s.status}'`)}}}Uc.ImportStatement=Fat;var eE={};Object.defineProperty(eE,"__esModule",{value:!0}),eE.ExtendBlock=void 0;const wat=Je,Nat=jn;class Lat extends wat.ListOf{constructor(){super(...arguments),this.elementType="extendBlock",this.forceQueryClass=void 0,this.queryRefinementStage=Nat.LegalRefinementStage.Single}queryExecute(e){for(const r of this.list)for(const i of r.list)e.inputFS.extendSource(i)}}eE.ExtendBlock=Lat;var Gb={};Object.defineProperty(Gb,"__esModule",{value:!0}),Gb.Argument=void 0;const Iat=Je;class Bat extends Iat.MalloyElement{constructor(e){super({...e}),this.elementType="Argument",this.id=e.id,this.value=e.value}}Gb.Argument=Bat;var Wb={};Object.defineProperty(Wb,"__esModule",{value:!0}),Wb.HasParameter=void 0;const a0e=Xe,$at=Je,kat=ct;class Mat extends $at.MalloyElement{constructor(e){super(),this.elementType="hasParameter",this.name=e.name,e.type&&(0,a0e.isParameterType)(e.type)&&(this.type=e.type),e.default&&(this.default=e.default,this.has({default:this.default})),e.filterType&&(this.filterType=e.filterType)}parameter(){var e;let r;if(this.default!==void 0){const i=this.default.constantValue();if(this.type&&this.type!==i.type&&i.type!=="null"&&i.type!=="error"&&this.default.logError("parameter-default-does-not-match-declared-type",`Default value for parameter does not match declared type \`${this.type}\``),i.type==="null")return this.type?{type:this.type,value:i.value,name:this.name}:(this.default.logError("parameter-null-default-without-declared-type","Default value cannot have type `null` unless parameter type is also specified"),{value:i.value,name:this.name,type:"error"});if(i.type==="filter expression")return this.type!=="filter expression"&&this.logError("parameter-missing-default-or-type",`Filter expression parameters must have expicit filter type, for example '${this.name}::filter<string>'`),this.filterType&&(0,kat.checkFilterExpression)(this,this.filterType,i.value),{value:i.value,name:this.name,type:i.type};if(!(0,a0e.isCastType)(i.type)&&i.type!=="error")return this.default.logError("parameter-illegal-default-type",`Default value cannot have type \`${i.type}\``),{value:i.value,name:this.name,type:"error"};r={value:i.value,name:this.name,type:i.type}}else this.type===void 0&&this.logError("parameter-missing-default-or-type","Parameter must have default value or declared type"),r={value:null,name:this.name,type:(e=this.type)!==null&&e!==void 0?e:"error"};return r.type==="filter expression"&&this.filterType&&(r.filterType=this.filterType),r}}Wb.HasParameter=Mat;var Vb={};Object.defineProperty(Vb,"__esModule",{value:!0}),Vb.AnonymousQuery=void 0;const Pat=Je,Uat=kr;class jat extends Pat.MalloyElement{constructor(e){super(),this.queryExpr=e,this.elementType="anonymousQuery",this.isNoteableObj=!0,this.extendNote=Uat.extendNoteMethod,this.has({queryExpr:e})}execute(e){const r=this.queryExpr.getQuery();if(!r){this.queryExpr.sqLog("non-query-used-as-query","Cannot run this object as a query");return}const i={...r.query()},s=this.note||{};i.annotation&&(s.inherits=i.annotation),(s.notes||s.blockNotes||s.inherits)&&(i.annotation=s),e.queryList.push(i)}}Vb.AnonymousQuery=jat;var jc={};Object.defineProperty(jc,"__esModule",{value:!0}),jc.View=void 0;const qat=Je;class Hat extends qat.MalloyElement{pipeline(e,r){return this.pipelineComp(e,r).pipeline}}jc.View=Hat;var Yb={};Object.defineProperty(Yb,"__esModule",{value:!0}),Yb.ViewArrow=void 0;const Qat=Pr,zat=jc;class Gat extends zat.View{constructor(e,r){super({base:e,operation:r}),this.base=e,this.operation=r,this.elementType="viewArrow"}pipelineComp(e){const r=this.base.pipelineComp(e),i=new Qat.StaticSourceSpace(r.outputStruct),s=this.operation.pipelineComp(i);return{pipeline:[...r.pipeline,...s.pipeline],outputStruct:s.outputStruct}}refine(e,r,i){return this.logError("refinement-with-multistage-view","A multi-segment view cannot be used as a refinement"),[]}getImplicitName(){return this.operation.getImplicitName()}}Yb.ViewArrow=Gat;var Kb={},tE={};Object.defineProperty(tE,"__esModule",{value:!0}),tE.refine=void 0;const ok=Pi,Wat=lt,uk=Dc;function Vat(t,e,r){var i,s;if(e.length!==1)return t.logError("refinement-with-multistage-view","Named refinements of multi-stage views are not supported"),e;const o={...e[0]},u=r;if((0,ok.isRawSegment)(o))t.logError("refinement-of-raw-query","Cannot refine raw query, must add an explicit query stage");else if(o.type==="partial"&&u.type!=="index"&&u.type!=="raw"?o.type=u.type:u.type!==o.type&&t.logError("mismatched-view-types-for-refinement",`cannot refine ${o.type} view with ${u.type} view`),u.type!=="index"&&o.type!=="index"&&u.type!=="raw"&&(u.orderBy!==void 0&&!u.defaultOrderBy&&(o.orderBy===void 0||o.defaultOrderBy?o.orderBy=u.orderBy:t.logError("ordering-overridden-in-refinement","refinement cannot override existing ordering")),u.limit!==void 0&&(o.limit===void 0?o.limit=u.limit:t.logError("limit-overridden-in-refinement","refinement cannot override existing limit"))),o.filterList=o.filterList!==void 0||u.filterList!==void 0?[...(i=o.filterList)!==null&&i!==void 0?i:[],...(s=u.filterList)!==null&&s!==void 0?s:[]]:void 0,(0,ok.isQuerySegment)(u)&&(0,ok.isQuerySegment)(o)){const a=[],l=[],c=new Map(o.queryFields.map(f=>[(0,uk.nameFromDef)(f),f]));for(const f of u.queryFields)c.has((0,uk.nameFromDef)(f))?a.push(f):l.push(f);o.queryFields=[...o.queryFields,...l],a.length>0&&t.logError("name-conflict-in-refinement",`overlapping fields in refinement: ${a.map(uk.nameFromDef)}`),o.compositeFieldUsage=(0,Wat.mergeCompositeFieldUsage)(o.compositeFieldUsage,u.compositeFieldUsage)}else u.type==="index"&&o.type==="index"&&(o.indexFields=[...u.indexFields,...o.indexFields]);return[o]}tE.refine=Vat,Object.defineProperty(Kb,"__esModule",{value:!0}),Kb.ViewRefine=void 0;const Yat=ai,Kat=ks,Jat=tE,Xat=jc;class Zat extends Xat.View{constructor(e,r){super({base:e,refinement:r}),this.base=e,this.refinement=r,this.elementType="refine"}pipelineComp(e,r){const i=this.base.pipelineComp(e),s=this.refinement.refine(e,i.pipeline,r);return{pipeline:s,annotation:i.annotation,outputStruct:s.length>0?(0,Kat.getFinalStruct)(this.refinement,e.structDef(),s):Yat.ErrorFactory.structDef}}refine(e,r,i){const s=this.pipeline(e,i);return s.length!==1?(this.refinement.logError("refinement-with-multistage-view","refinement must have exactly one stage"),r):(0,Jat.refine)(this,r,s[0])}getImplicitName(){return this.base.getImplicitName()}}Kb.ViewRefine=Zat;var Jb={};Object.defineProperty(Jb,"__esModule",{value:!0}),Jb.ReferenceView=void 0;const ak=Xe,l0e=ai,elt=ks,tlt=Mr,nlt=tE,rlt=jc;class ilt extends rlt.View{constructor(e){super({reference:e}),this.reference=e,this.elementType="reference-view"}pipelineComp(e,r){return this._pipelineComp(e)}_pipelineComp(e,{forRefinement:r}={forRefinement:!1}){const i=this.reference.getField(e),s=function(){return{inputStruct:l0e.ErrorFactory.structDef,outputStruct:l0e.ErrorFactory.structDef,pipeline:[],error:!0}};if(!i.found)return this.reference.logError(i.error.code,i.error.message),s();if(!(i.found instanceof tlt.SpaceField))throw new Error("Expected space field");const o=i.found.fieldDef();if(o===void 0)throw new Error("Expected field to have definition");if((0,ak.isAtomic)(o)){const u={type:"reduce",queryFields:[this.reference.refToField],compositeFieldUsage:o.compositeFieldUsage},a=this.reference.nameString,l={...(0,ak.sourceBase)(e.structDef()),type:"query_result",name:a,fields:[o]};return{pipeline:[u],name:a,outputStruct:l}}else return(0,ak.isTurtle)(o)?this.reference.list.length>1?(r?this.logError("refinement-with-joined-view","Cannot use view from join as refinement"):this.logError("nest-of-joined-view","Cannot use view from join"),s()):{pipeline:[...o.pipeline],name:o.name,annotation:o.annotation,outputStruct:(0,elt.getFinalStruct)(this.reference,e.structDef(),o.pipeline)}:(r?this.reference.logError("refinement-with-source",`named refinement \`${this.reference.refString}\` must be a view, found a ${o.type}`):this.reference.logError("nest-of-source","This operation is not supported"),s())}getRefinementSegment(e){const{pipeline:r,error:i}=this._pipelineComp(e,{forRefinement:!0});if(!i){if(r.length!==1){this.reference.logError("refinement-with-multistage-view",`named refinement \`${this.reference.refString}\` must have exactly one stage`);return}return r[0]}}refine(e,r,i){const s=this.getRefinementSegment(e);return s?(0,nlt.refine)(this,r,s):r}getImplicitName(){return this.reference.nameString}}Jb.ReferenceView=ilt;var Xb={},nE={},Zb={},rE={};Object.defineProperty(rE,"__esModule",{value:!0}),rE.Index=void 0;const slt=Je,olt=jn;class ult extends slt.MalloyElement{constructor(e){super({fields:e}),this.fields=e,this.elementType="index",this.forceQueryClass=olt.QueryClass.Index,this.queryRefinementStage=void 0}useWeight(e){this.has({weightBy:e}),this.weightBy=e}}rE.Index=ult;var iE={};Object.defineProperty(iE,"__esModule",{value:!0}),iE.SampleProperty=void 0;const alt=Je,c0e=jn;class llt extends alt.MalloyElement{constructor(e){super(),this.sample=e,this.elementType="sampleProperty",this.queryRefinementStage=c0e.LegalRefinementStage.Tail,this.forceQueryClass=c0e.QueryClass.Index}sampling(){return this.sample}}iE.SampleProperty=llt;var eT={};Object.defineProperty(eT,"__esModule",{value:!0}),eT.IndexFieldSpace=void 0;const f0e=lt,x0e=Xe,lk=yt,clt=Mr,flt=mu,xlt=By,dlt=Pr;class hlt extends flt.QueryOperationSpace{constructor(){super(...arguments),this.segmentType="index"}pushFields(...e){for(const r of e)r instanceof lk.FieldReference?super.pushFields(r):r instanceof lk.WildcardFieldReference?this.addWild(r):r.logError("invalid-field-in-index-query","Internal error, not expected in index query")}getPipeSegment(e){if(e)return this.logError("refinement-of-index-segment","index query operations cannot be refined"),{type:"index",indexFields:[]};let r=(0,f0e.emptyCompositeFieldUsage)(),i=(0,f0e.emptyNarrowedCompositeFieldResolution)();const s=[],o=this.inputSpace().structDef();for(const[u,a]of this.entries())if(a instanceof clt.SpaceField){let l,c;const f=this.expandedWild[u];if(f)s.push({type:"fieldref",path:f.path}),l=f.entry.typeDesc().compositeFieldUsage;else if(a instanceof xlt.ReferenceField){const h=a.fieldRef,p=h.getField(this.exprSpace);p.error?h.logError(p.error.code,p.error.message):(s.push(h.refToField),l=p.found.typeDesc().compositeFieldUsage,c=h)}const x=this.applyNextCompositeFieldUsage(o,r,i,l,c);r=x.compositeFieldUsage,i=x.narrowedCompositeFieldResolution}return this._compositeFieldUsage=r,{type:"index",indexFields:s}}addRefineFromFields(e){}addWild(e){var r;let i=this.exprSpace;const s=[];if(e.joinPath)for(const a of e.joinPath.list){const l=a.refString;s.push(l);const c=i.entry(l);if(c)if(c instanceof dlt.StructSpaceField)i=c.fieldSpace;else{a.logError("invalid-wildcard-source",`Field '${l}' does not contain rows and cannot be expanded with '*'`);return}else{a.logError("wildcard-source-not-found",`No such field as '${l}'`);return}}const o=this.dialectObj(),u=[];for(const[a,l]of i.entries()){if(e.except.has(a)||l.refType==="parameter")continue;const c=lk.IndexFieldReference.indexOutputName([...s,a]);if(this.entry(c)){const f=(r=this.expandedWild[c].path)===null||r===void 0?void 0:r.join(".");e.logError("name-conflict-in-wildcard-expansion",`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${f?` (conflicts with ${f})`:""}`)}else{const f=l.typeDesc();x0e.TD.isBasicAtomic(f)&&(0,x0e.expressionIsScalar)(f.expressionType)&&(o===void 0||!o.ignoreInProject(a))&&(u.push({name:c,entry:l}),this.expandedWild[c]={path:s.concat(a),entry:l})}}for(const a of u.sort((l,c)=>l.name.localeCompare(c.name)))this.setEntry(a.name,a.entry)}}eT.IndexFieldSpace=hlt,Object.defineProperty(Zb,"__esModule",{value:!0}),Zb.IndexBuilder=void 0;const ck=Xe,plt=ai,mlt=Ra,glt=rE,ylt=$c,Elt=iE,Alt=eT,fk=lt;class _lt{constructor(e,r,i,s){this.filters=[],this.alwaysJoins=[],this.type="index",this.resultFS=new Alt.IndexFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}execute(e){e instanceof mlt.Filter?e.queryExecute(this):e instanceof ylt.Limit?(this.limit&&this.limit.logError("index-limit-already-specified","Ignored, too many limit: statements"),this.limit=e):e instanceof glt.Index?(this.resultFS.pushFields(...e.fields.list),e.weightBy&&(this.indexOn&&this.indexOn.logError("index-by-already-specified","Ignoring previous BY"),this.indexOn=e.weightBy)):e instanceof Elt.SampleProperty?this.sample=e.sampling():e.logError("illegal-operation-for-index","Not legal in an index query operation")}get compositeFieldUsage(){return this.resultFS.compositeFieldUsage}finalize(e){var r;if(e&&!(0,ck.isIndexSegment)(e)&&!(0,ck.isPartialSegment)(e))return this.resultFS.logError("refinement-of-index-segment",`Can't refine index with ${e.type}`),plt.ErrorFactory.indexSegment;const i=this.resultFS.getPipeSegment(e),s=(e==null?void 0:e.filterList)||[];this.filters.length>0&&!s?i.filterList=this.filters:s&&(i.filterList=[...s,...this.filters]),e!=null&&e.limit&&(i.limit=e.limit),this.limit&&(i.limit=this.limit.limit),this.indexOn&&(i.weightMeasure=this.indexOn.refString),e&&(0,ck.isIndexSegment)(e)&&(e!=null&&e.sample)&&(i.sample=e.sample),this.sample&&(i.sample=this.sample),this.alwaysJoins.length>0&&(i.alwaysJoins=[...this.alwaysJoins]);const o=e&&e.type==="index"&&(r=e.compositeFieldUsage)!==null&&r!==void 0?r:(0,fk.emptyCompositeFieldUsage)();return i.compositeFieldUsage=(0,fk.mergeCompositeFieldUsage)(o,this.compositeFieldUsage),i}}Zb.IndexBuilder=_lt;var tT={},sE={};Object.defineProperty(sE,"__esModule",{value:!0}),sE.GroupBy=void 0;const vlt=$s,d0e=jn;class Clt extends vlt.DefinitionList{constructor(){super(...arguments),this.elementType="groupBy",this.queryRefinementStage=d0e.LegalRefinementStage.Single,this.forceQueryClass=d0e.QueryClass.Grouping}}sE.GroupBy=Clt;var nT={};Object.defineProperty(nT,"__esModule",{value:!0}),nT.ProjectFieldSpace=void 0;const rT=Xe,Slt=mu;class blt extends Slt.QuerySpace{constructor(){super(...arguments),this.segmentType="project"}canContain(e){return e===void 0||!rT.TD.isAtomic(e)||(0,rT.expressionIsAggregate)(e.expressionType)?!1:(0,rT.expressionInvolvesAggregate)(e.expressionType)&&(0,rT.expressionIsAnalytic)(e.expressionType)?(this.logError("aggregate-analytic-in-select","Cannot add aggregate analyics to select"),!1):!0}}nT.ProjectFieldSpace=blt;var qc={},id={};Object.defineProperty(id,"__esModule",{value:!0}),id.Ordering=id.OrderBy=void 0;const Tlt=Xe,h0e=kc,p0e=Je,Rlt=jn;class Dlt extends p0e.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e instanceof h0e.FieldName&&this.has({field:e})}get modelField(){return typeof this.field=="number"?this.field:this.field.refString}getOrderBy(e){var r;if(this.field instanceof h0e.FieldName&&e.isQueryFieldSpace()){const s=e.outputSpace(),o=this.field.getField(s);o.error&&this.field.logError(o.error.code,o.error.message),(!o.found||!o.isOutputField)&&this.logError("order-by-not-found-in-output",`Unknown field ${this.field.refString} in output space`),(0,Tlt.expressionIsAnalytic)((r=o.found)===null||r===void 0?void 0:r.typeDesc().expressionType)&&this.logError("order-by-analytic",`Illegal order by of analytic field ${this.field.refString}`)}const i={field:this.modelField};return this.dir&&(i.dir=this.dir),i}}id.OrderBy=Dlt;class Olt extends p0e.ListOf{constructor(e){super(e),this.elementType="ordering",this.queryRefinementStage=Rlt.LegalRefinementStage.Tail,this.forceQueryClass=void 0}getOrderBy(e){return this.list.map(r=>r.getOrderBy(e))}}id.Ordering=Olt,Object.defineProperty(qc,"__esModule",{value:!0}),qc.ReduceBuilder=qc.QuerySegmentBuilder=void 0;const gu=Xe,Flt=ai,wlt=kc,Nlt=$c,Llt=id,Ilt=mu,Blt=$s,xk=lt;function m0e(t){return t.type==="fieldref"?t.path[t.path.length-1]:t.name}class g0e{constructor(){this.alwaysJoins=[],this.filters=[]}execute(e){if(e.queryExecute){e.queryExecute(this);return}e instanceof Blt.DefinitionList?this.resultFS.pushFields(...e.list):e instanceof Nlt.Limit?this.limit?e.logError("limit-already-specified","Query operation already limited"):this.limit=e.limit:e instanceof Llt.Ordering&&(this.order?e.logError("ordering-already-specified","Query operation already sorted"):this.order=e)}get compositeFieldUsage(){return this.resultFS.compositeFieldUsage}refineFrom(e,r){var i;e&&e.type!=="index"&&e.type!=="raw"&&(!this.limit&&e.orderBy&&!e.defaultOrderBy&&(r.orderBy=e.orderBy),!this.limit&&e.limit&&(r.limit=e.limit)),this.order&&(r.orderBy=this.order.getOrderBy(this.inputFS),delete r.defaultOrderBy),this.limit&&(r.limit=this.limit);const s=(e==null?void 0:e.filterList)||[];this.filters.length>0&&!s?r.filterList=this.filters:s&&(r.filterList=[...s,...this.filters]),this.alwaysJoins.length>0&&(r.alwaysJoins=[...this.alwaysJoins]);const o=e&&(0,gu.isQuerySegment)(e)&&(i=e.compositeFieldUsage)!==null&&i!==void 0?i:(0,xk.emptyCompositeFieldUsage)();r.compositeFieldUsage=(0,xk.mergeCompositeFieldUsage)(o,this.compositeFieldUsage)}}qc.QuerySegmentBuilder=g0e;class $lt extends g0e{constructor(e,r,i,s){super(),this.type="grouping",this.resultFS=new Ilt.ReduceFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}finalize(e){let r;if(e)if((0,gu.isReduceSegment)(e)||(0,gu.isPartialSegment)(e))r=e;else return this.resultFS.logError("incompatible-segment-for-reduce-refinement",`Can't refine reduce with ${e.type}`),Flt.ErrorFactory.reduceSegment;const i=this.resultFS.getQuerySegment(r);if(this.refineFrom(r,i),i.orderBy){for(const s of i.orderBy)if(typeof s.field=="number"){const o=i.queryFields[s.field-1];s.field=m0e(o)}}if(i.orderBy===void 0||i.defaultOrderBy){let s;for(const o of i.queryFields){let u=!1,a=!1,l;const c=m0e(o);if(o.type==="fieldref"){const f=o.path.map(h=>new wlt.FieldName(h)),x=this.inputFS.lookup(f).found;if(x){const h=x.typeDesc();l=h.type,u=(0,gu.expressionIsAggregate)(h.expressionType),a=(0,gu.expressionIsAnalytic)(h.expressionType)}else continue}else l=o.type,u=(0,gu.hasExpression)(o)&&(0,gu.expressionIsAggregate)(o.expressionType),a=(0,gu.hasExpression)(o)&&(0,gu.expressionIsAnalytic)(o.expressionType);if((0,gu.isTemporalType)(l)||u){i.defaultOrderBy=!0,i.orderBy=[{field:c,dir:"desc"}],s=void 0;break}(0,gu.canOrderBy)(l)&&!a&&!s&&(s=c)}s&&(i.defaultOrderBy=!0,i.orderBy=[{field:s,dir:"asc"}])}return i}}qc.ReduceBuilder=$lt,Object.defineProperty(tT,"__esModule",{value:!0}),tT.ProjectBuilder=void 0;const y0e=Xe,klt=ai,Mlt=sE,Plt=nT,Ult=qc;class jlt extends Ult.QuerySegmentBuilder{constructor(e,r,i,s){super(),this.type="project",this.resultFS=new Plt.ProjectFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}execute(e){e.elementType==="having"||e instanceof Mlt.GroupBy?e.logError("illegal-operation-in-select-segment","Illegal statement in a select query operation"):super.execute(e)}finalize(e){let r;if(e)if((0,y0e.isProjectSegment)(e)||(0,y0e.isPartialSegment)(e))r=e;else return this.resultFS.logError("incompatible-segment-for-select-refinement",`Can't refine select with ${e.type}`),klt.ErrorFactory.projectSegment;const i=this.resultFS.getQuerySegment(r);return this.refineFrom(r,i),i}}tT.ProjectBuilder=jlt;var iT={};Object.defineProperty(iT,"__esModule",{value:!0}),iT.PartialBuilder=void 0;const qlt=Pi,Hlt=qc;class Qlt extends Hlt.ReduceBuilder{finalize(e){const r=super.finalize(e);if((0,qlt.isQuerySegment)(r))return{...r,type:"partial"};throw new Error(`Partial Builder cannot finalize from ${r.type}`)}}iT.PartialBuilder=Qlt,Object.defineProperty(nE,"__esModule",{value:!0}),nE.QOpDesc=void 0;const zlt=Zb,Glt=tT,Wlt=qc,Vlt=Je,Ylt=ks,Klt=Pr,sd=jn,Jlt=iT;class Xlt extends Vlt.ListOf{constructor(){super(...arguments),this.elementType="queryOperation"}computeType(){var e;let r,i=!1;this.refineThis&&(this.refineThis.type==="reduce"?r=sd.QueryClass.Grouping:this.refineThis.type==="project"?r=sd.QueryClass.Project:this.refineThis.type==="index"&&(r=sd.QueryClass.Index));for(const s of this.list)s.forceQueryClass&&(r?r!==s.forceQueryClass&&s.logError(`illegal-${r}-operation`,`Not legal in ${r} query`):r=s.forceQueryClass),i||(i=(e=s.needsExplicitQueryClass)!==null&&e!==void 0?e:!1);return r===void 0&&i&&(this.logError("ambiguous-view-type",{}),r=sd.QueryClass.Project),this.opClass=r,r}refineFrom(e){this.refineThis=e}getBuilder(e,r,i){switch(this.computeType()){case sd.QueryClass.Grouping:return new Wlt.ReduceBuilder(e,this.refineThis,r,i);case sd.QueryClass.Project:return new Glt.ProjectBuilder(e,this.refineThis,r,i);case sd.QueryClass.Index:return new zlt.IndexBuilder(e,this.refineThis,r,i);case void 0:return new Jlt.PartialBuilder(e,this.refineThis,r,i)}}getOp(e,r){const i=this.getBuilder(e,r,this);for(const o of this.list)i.execute(o);const s=i.finalize(this.refineThis);return{segment:s,outputSpace:()=>new Klt.StaticSourceSpace((0,Ylt.opOutputStruct)(this,e.structDef(),s))}}}nE.QOpDesc=Xlt,Object.defineProperty(Xb,"__esModule",{value:!0}),Xb.QOpDescView=void 0;const Zlt=Xe,e0t=Pr,E0e=nE,t0t=ks,dk=jn,n0t=jc;class r0t extends n0t.View{constructor(e){super({operation:e}),this.operation=e,this.elementType="qopdesc-view"}pipelineComp(e,r){const i=this.operation.getOp(e,r);return{pipeline:[i.segment],outputStruct:i.outputSpace().structDef()}}getOp(e,r,i,s){return(0,Zlt.isRawSegment)(s)?(this.logError("refinement-of-raw-query","A raw query cannot be refined"),s):(i.refineFrom(s),i.getOp(e,r).segment)}refine(e,r,i){const s=[...r];if(s.length===0)return s;if(s.length===1)return this.operation.refineFrom(s[0]),[this.getOp(e,i,this.operation,s[0])];const o=new E0e.QOpDesc([]),u=new E0e.QOpDesc([]);for(const a of this.operation.list)switch(a.queryRefinementStage){case dk.LegalRefinementStage.Head:o.push(a);break;case dk.LegalRefinementStage.Single:a.logError("illegal-multistage-refinement-operation","Illegal in refinement of a query with more than one stage");break;case dk.LegalRefinementStage.Tail:u.push(a);break;default:a.logError("illegal-refinement-operation","Illegal query refinement")}if(o.notEmpty()&&(this.has({headRefinements:o}),s[0]=this.getOp(e,void 0,o,s[0])),u.notEmpty()){const a=s.length-1;this.has({tailRefinements:u});const l=(0,t0t.getFinalStruct)(this,e.structDef(),s.slice(-1));s[a]=this.getOp(new e0t.StaticSourceSpace(l),void 0,u,s[a])}return s}getImplicitName(){}}Xb.QOpDescView=r0t;var Rn={},i0t=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),s0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&i0t(e,t,r);return s0t(e,t),e};Object.defineProperty(Rn,"__esModule",{value:!0}),Rn.FieldDefinitionValue=Rn.DefSpace=Rn.DimensionFieldDeclaration=Rn.MeasureFieldDeclaration=Rn.DeclareFieldDeclaration=Rn.ProjectFieldDeclaration=Rn.GroupByFieldDeclaration=Rn.AggregateFieldDeclaration=Rn.CalculateFieldDeclaration=Rn.AtomicFieldDeclaration=void 0;const hk=Xe,A0e=o0t(Zt),u0t=c2,a0t=Je,od=sr,l0t=kr,c0t=Mr;class Hc extends a0t.MalloyElement{constructor(e,r,i){super({expr:e}),this.expr=e,this.defineName=r,this.exprSrc=i,this.isNoteableObj=!0,this.extendNote=l0t.extendNoteMethod}getName(){return this.defineName}fieldDef(e,r){return this.queryFieldDef(new pk(e,this),r)}executesInOutputSpace(){return!1}queryFieldDef(e,r){let i;function s(){if(e.isQueryFieldSpace())return e.outputSpace();throw new Error("must be in a query -- weird internal error")}try{const u=this.executesInOutputSpace()?s():e;i=this.expr.getExpression(u)}catch(u){return this.logError("failed-field-definition",`Cannot define '${r}', ${u.message}`),{name:r,type:"error"}}if(i.type==="null"&&(this.expr.logWarning("null-typed-field-definition",'null value defaults to type number, use "null::TYPE" to specify correct type'),i={type:"number",value:i.value,expressionType:i.expressionType,evalSpace:i.evalSpace,compositeFieldUsage:i.compositeFieldUsage}),(0,hk.isAtomicFieldType)(i.type)&&i.type!=="error"){this.typecheckExprValue(i);const u=(0,hk.mkFieldDef)(A0e.atomicDef(i),r);return(u.type==="date"||u.type==="timestamp")&&(0,u0t.isGranularResult)(i)&&(u.timeframe=i.timeframe),u.location=this.location,u.e=i.value,u.compositeFieldUsage=i.compositeFieldUsage,i.expressionType&&(u.expressionType=i.expressionType),this.exprSrc&&(u.code=this.exprSrc),this.note&&(u.annotation=this.note),u}if(!(e instanceof pk&&e.foundCircle)&&i.type!=="error"){const u=A0e.inspect(i);this.logError("invalid-type-for-field-definition",`Cannot define '${r}', unexpected type: ${u}`)}return{name:r,type:"error"}}makeEntry(e){e.newEntry(this.defineName,this,new _0e(e,this))}}Rn.AtomicFieldDeclaration=Hc;class f0t extends Hc{constructor(){super(...arguments),this.elementType="calculateFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckCalculate)(e,this)}executesInOutputSpace(){return!0}}Rn.CalculateFieldDeclaration=f0t;class x0t extends Hc{constructor(){super(...arguments),this.elementType="aggregateFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckAggregate)(e,this)}}Rn.AggregateFieldDeclaration=x0t;class d0t extends Hc{constructor(){super(...arguments),this.elementType="groupByFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckGroupBy)(e,this)}}Rn.GroupByFieldDeclaration=d0t;class h0t extends Hc{constructor(){super(...arguments),this.elementType="projectFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckProject)(e,this)}}Rn.ProjectFieldDeclaration=h0t;class p0t extends Hc{constructor(){super(...arguments),this.elementType="declareFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckDeclare)(e,this)}}Rn.DeclareFieldDeclaration=p0t;class m0t extends Hc{constructor(){super(...arguments),this.elementType="measureFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckMeasure)(e,this)}}Rn.MeasureFieldDeclaration=m0t;class g0t extends Hc{constructor(){super(...arguments),this.elementType="dimensionFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckDimension)(e,this)}}Rn.DimensionFieldDeclaration=g0t;class pk{constructor(e,r){this.realFS=e,this.circular=r,this.type="fieldSpace",this.foundCircle=!1}structDef(){return this.realFS.structDef()}emptyStructDef(){return this.realFS.emptyStructDef()}entry(e){return this.realFS.entry(e)}lookup(e){return e[0]&&e[0].refString===this.circular.defineName?(this.foundCircle=!0,{error:{message:`Circular reference to '${this.circular.defineName}' in definition`,code:"circular-reference-in-field-definition"},found:void 0}):this.realFS.lookup(e)}entries(){return this.realFS.entries()}dialectName(){return this.realFS.dialectName()}dialectObj(){return this.realFS.dialectObj()}isQueryFieldSpace(){return this.realFS.isQueryFieldSpace()}outputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.outputSpace();throw new Error("Not a query field space")}inputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.inputSpace();throw new Error("Not a query field space")}isProtectedAccessSpace(){return!0}}Rn.DefSpace=pk;class _0e extends c0t.SpaceField{constructor(e,r){super(),this.space=e,this.exprDef=r,this.fieldName=r.defineName}get name(){return this.fieldName}fieldDef(){var e;const r=(e=this.defInSource)!==null&&e!==void 0?e:this.exprDef.fieldDef(this.space,this.name);return this.defInSource=r,r}getQueryFieldDef(e){if(!this.defInQuery){const r=this.exprDef.queryFieldDef(e,this.name);this.defInQuery=r}return this.defInQuery}typeDesc(){const e=this.defInQuery||this.fieldDef();if((0,hk.isAtomic)(e))return this.fieldTypeFromFieldDef(e);throw new Error(`Can't get typeDesc for ${e.type}`)}}Rn.FieldDefinitionValue=_0e;var sT={};Object.defineProperty(sT,"__esModule",{value:!0}),sT.Aggregate=void 0;const y0t=$s,v0e=jn;class E0t extends y0t.DefinitionList{constructor(){super(...arguments),this.elementType="aggregateList",this.queryRefinementStage=v0e.LegalRefinementStage.Single,this.forceQueryClass=v0e.QueryClass.Grouping}}sT.Aggregate=E0t;var oT={};Object.defineProperty(oT,"__esModule",{value:!0}),oT.Calculate=void 0;const A0t=$s,_0t=jn;class v0t extends A0t.DefinitionList{constructor(){super(...arguments),this.elementType="calculate",this.forceQueryClass=void 0,this.needsExplicitQueryClass=!0,this.queryRefinementStage=_0t.LegalRefinementStage.Single}}oT.Calculate=v0t;var oE={};Object.defineProperty(oE,"__esModule",{value:!0}),oE.Dimensions=void 0;const C0t=Oc;class S0t extends C0t.DeclareFields{constructor(){super(...arguments),this.elementType="dimensionList"}}oE.Dimensions=S0t;var uE={};Object.defineProperty(uE,"__esModule",{value:!0}),uE.Measures=void 0;const b0t=Oc;class T0t extends b0t.DeclareFields{constructor(){super(...arguments),this.elementType="measureList"}}uE.Measures=T0t;var uT={};Object.defineProperty(uT,"__esModule",{value:!0}),uT.Nests=void 0;const R0t=$s,C0e=jn;class D0t extends R0t.DefinitionList{constructor(e){super(e),this.elementType="nestedQueries",this.queryRefinementStage=C0e.LegalRefinementStage.Single,this.forceQueryClass=C0e.QueryClass.Grouping}}uT.Nests=D0t;var aT={};Object.defineProperty(aT,"__esModule",{value:!0}),aT.ProjectStatement=void 0;const O0t=$s,S0e=jn;class F0t extends O0t.DefinitionList{constructor(){super(...arguments),this.elementType="projectStatement",this.forceQueryClass=S0e.QueryClass.Project,this.queryRefinementStage=S0e.LegalRefinementStage.Single}queryExecute(e){e.type==="project"&&e.resultFS.pushFields(...this.list)}}aT.ProjectStatement=F0t;var Qc={},Zl={},Bn={};Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.getPlainString=Bn.unIndent=Bn.getOptionalId=Bn.idToStr=Bn.getId=Bn.getStringParts=Bn.getStringIfShort=Bn.getShortString=void 0;const b0e=Zo;function T0e(t){var e,r;const i=((e=t.DQ_STRING())===null||e===void 0?void 0:e.text)||((r=t.SQ_STRING())===null||r===void 0?void 0:r.text);return i?b0e.ParseUtil.parseString(i,i[0]):""}Bn.getShortString=T0e;function R0e(t){const e=t.string().shortString();if(e)return T0e(e)}Bn.getStringIfShort=R0e;function*D0e(t){var e;if(t){for(const i of t.sqlInterpolation()){const s=i.OPEN_CODE().text;s.length>2&&(yield s.slice(0,s.length-2)),i.sqExpr()&&(yield i.sqExpr())}const r=(e=t.SQL_END())===null||e===void 0?void 0:e.text.slice(0,-3);r&&r.length>0&&(yield r)}}Bn.getStringParts=D0e;function O0e(t){return F0e(t.id())}Bn.getId=O0e;function F0e(t){const e=t.BQ_STRING();return e?b0e.ParseUtil.parseString(e.text,"`"):t.text}Bn.idToStr=F0e;function w0t(t){function e(r){return"id"in r}if(e(t)&&t.id())return O0e(t)}Bn.getOptionalId=w0t;function*w0e(t){for(;t.length>0;){const e=t.match(/^.*?\r?\n/);let r=t;e&&(r=e[0]),yield r,t=t.slice(r.length)}}function N0t(t){let e;for(const r of w0e(t)){const i=r.match(/^( *).*[^\s]/);if(i){const s=i[1].length;(e===void 0||s<e)&&(e=s)}}return e}function N0e(t){let e;for(const r of t)if(typeof r=="string"){const i=N0t(r);i!==void 0&&(e===void 0||i<e)&&(e=i)}if(e)for(let r=0;r<=t.length;r+=1){const i=t[r];if(typeof i=="string"){let s="";for(let o of w0e(i))o[0]===" "&&(o=o.slice(e)),s+=o;t[r]=s}}}Bn.unIndent=N0e;function L0t(t,e=!1){const r=[],i=R0e(t);if(i)return[i,r];const s=[],o=t.string().sqlString();if(o){for(const u of D0e(o))if(typeof u=="string")s.push(u);else if(r.push(u),e)return[void 0,r];return N0e(s),[s.join(""),r]}return["",r]}Bn.getPlainString=L0t,Object.defineProperty(Zl,"__esModule",{value:!0}),Zl.findReferences=Zl.deprecatedParseTableURI=Zl.constructTableKey=void 0;const I0t=uc,mk=Bn;function L0e(t){const e=(0,mk.getStringIfShort)(t);if(e)return e;const r=[],i=t.string().sqlString();if(i){for(const s of(0,mk.getStringParts)(i))typeof s=="string"&&r.push(s);return r.join("")}return""}class B0t{constructor(e,r){this.trans=e,this.tokens=r,this.needTables={},this.needImports={}}registerTableReference(e,r,i){const s=I0e(e,r);this.needTables[s]||(this.needTables[s]={connectionName:e,tablePath:r,firstReference:i})}enterExploreTable(e){const r=(0,mk.getId)(e.connectionId()),i=L0e(e.tablePath()),s=this.trans.rangeFromContext(e);this.registerTableReference(r,i,s)}enterImportURL(e){const r=L0e(e);this.needImports[r]||(this.needImports[r]=this.trans.rangeFromContext(e))}}function I0e(t,e){return t===void 0?e:`${t}:${e}`}Zl.constructTableKey=I0e;function $0t(t){const e=t.match(/^([^:]*):(.*)$/);if(e){const[,r,i]=e;return{connectionName:r,tablePath:i}}else return{tablePath:t}}Zl.deprecatedParseTableURI=$0t;function k0t(t,e,r){const i=new B0t(t,e),s=i;return I0t.ParseTreeWalker.DEFAULT.walk(s,r),{tables:i.needTables,urls:i.needImports}}Zl.findReferences=k0t,Object.defineProperty(Qc,"__esModule",{value:!0}),Qc.TableFunctionSource=Qc.TableMethodSource=Qc.TableSource=void 0;const B0e=Zl,M0t=Eo,$0e=ai;class gk extends M0t.Source{getSourceDef(){var e,r,i;const s=this.getTableInfo();if(s===void 0)return $0e.ErrorFactory.structDef;const{tablePath:o,connectionName:u}=s,a=(0,B0e.constructTableKey)(u,o),l=(e=this.translator())===null||e===void 0?void 0:e.root.schemaZone.getEntry(a);let c=`Schema read failure for table '${o}' for connection '${u}'`;if(l){if(l.status==="present"){(r=this.document())===null||r===void 0||r.checkExperimentalDialect(this,l.value.dialect),l.value.location=this.location,l.value.fields.forEach(x=>{x.location=this.location});const f={...l.value,fields:l.value.fields.map(x=>({...x,location:this.location})),location:this.location};return(i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(f),f}l.status==="error"&&(c=l.message)}return this.logError("failed-to-fetch-table-schema",c),$0e.ErrorFactory.structDef}}Qc.TableSource=gk;class P0t extends gk{constructor(e,r){super(),this.connectionName=e,this.tablePath=r,this.elementType="tableMethodSource",this.has({connectionName:e})}getTableInfo(){var e;const r=this.modelEntry(this.connectionName),i=this.connectionName.refString;if(r===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(i,{entry:{type:"connection",name:i},exported:!0},!0);else if(r.entry.type!=="connection"){this.connectionName.logError("invalid-connection-for-table-source",`${this.connectionName.refString} is not a connection`);return}return{tablePath:this.tablePath,connectionName:this.connectionName.refString}}}Qc.TableMethodSource=P0t;class U0t extends gk{constructor(e){super(),this.tableURI=e,this.elementType="tableFunctionSource"}getTableInfo(){return(0,B0e.deprecatedParseTableURI)(this.tableURI)}}Qc.TableFunctionSource=U0t;var lT={};Object.defineProperty(lT,"__esModule",{value:!0}),lT.SQLString=void 0;const j0t=Je,k0e=hu;class q0t extends j0t.MalloyElement{constructor(){super(...arguments),this.elementType="sqlString",this.elements=[],this.containsQueries=!1}complete(){this.has({queries:this.elements.filter(H0t)})}push(e){typeof e=="string"?e.length>0&&this.elements.push(e):e instanceof k0e.SourceQueryElement?(this.elements.push(e),this.containsQueries=!0,e.parent=this):e.logError("invalid-sql-source-interpolation","This element is not legal inside an SQL string")}sqlPhrases(){const e=[];for(const r of this.elements)if(typeof r=="string")e.push({sql:r});else{const i=r.getQuery();i?e.push(i.query()):r.sqLog("failed-to-expand-sql-source","Cannot expand into a query")}return e}}lT.SQLString=q0t;function H0t(t){return t instanceof k0e.SourceQueryElement}var cT={};Object.defineProperty(cT,"__esModule",{value:!0}),cT.SourceDesc=void 0;const Q0t=Je;class z0t extends Q0t.ListOf{constructor(){super(...arguments),this.elementType="sourceDescription"}}cT.SourceDesc=z0t;var fT={};Object.defineProperty(fT,"__esModule",{value:!0}),fT.isSourceProperty=void 0;const G0t=Ra,W0t=Oc,V0t=r2,Y0t=wc,K0t=i2,J0t=s2,X0t=o2,Z0t=Fc,ect=xs;function tct(t){return t instanceof G0t.Filter||t instanceof ect.JoinStatement||t instanceof W0t.DeclareFields||t instanceof V0t.FieldListEdit||t instanceof Y0t.Renames||t instanceof K0t.PrimaryKey||t instanceof Z0t.ObjectAnnotation||t instanceof J0t.Views||t instanceof X0t.TimezoneStatement}fT.isSourceProperty=tct;var xT={};Object.defineProperty(xT,"__esModule",{value:!0}),xT.isFieldCollectionMember=void 0;const nct=Rn,M0e=yt;function rct(t){return t instanceof M0e.FieldReference||t instanceof M0e.WildcardFieldReference||t instanceof nct.AtomicFieldDeclaration}xT.isFieldCollectionMember=rct;var dT={};Object.defineProperty(dT,"__esModule",{value:!0}),dT.isQueryElement=void 0;const ict=u2,sct=a2,oct=Hy,uct=Qy;function act(t){return t instanceof ict.QueryArrow||t instanceof sct.QueryRefine||t instanceof oct.QueryReference||t instanceof uct.QueryRaw}dT.isQueryElement=act;var P0e={};Object.defineProperty(P0e,"__esModule",{value:!0});var hT={};Object.defineProperty(hT,"__esModule",{value:!0}),hT.isQueryProperty=void 0;function lct(t){return"queryRefinementStage"in t&&"forceQueryClass"in t}hT.isQueryProperty=lct;var pT={};Object.defineProperty(pT,"__esModule",{value:!0}),pT.isQueryExtendProperty=void 0;const cct=oE,fct=xs,xct=uE;function dct(t){return t instanceof cct.Dimensions||t instanceof xct.Measures||t instanceof fct.JoinStatement}pT.isQueryExtendProperty=dct;var mT={};Object.defineProperty(mT,"__esModule",{value:!0}),mT.isFieldPropStatement=void 0;const hct=Bc,pct=Ra,mct=$c,gct=m2;function yct(t){return t instanceof pct.Filter||t instanceof mct.Limit||t instanceof gct.PartitionBy||t instanceof hct.FunctionOrdering}mT.isFieldPropStatement=yct,function(t){var e=T&&T.__createBinding||(Object.create?function(i,s,o,u){u===void 0&&(u=o);var a=Object.getOwnPropertyDescriptor(s,o);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,u,a)}:function(i,s,o,u){u===void 0&&(u=o),i[u]=s[o]}),r=T&&T.__exportStar||function(i,s){for(var o in i)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,i,o)};Object.defineProperty(t,"__esModule",{value:!0}),r(Ry,t),r(Xp,t),r(Zp,t),r(Eo,t),r(Fy,t),r(hu,t),r(J4,t),r(X4,t),r(tb,t),r(ky,t),r(nb,t),r(rb,t),r(du,t),r(r2,t),r(i2,t),r(wc,t),r(s2,t),r(o2,t),r(sb,t),r(x2,t),r(ub,t),r(d2,t),r(Bc,t),r(ab,t),r(Jl,t),r(lb,t),r(p2,t),r(cb,t),r(fb,t),r(xb,t),r(Kl,t),r(db,t),r(hb,t),r(mb,t),r(Ky,t),r(Vy,t),r(ed,t),r(yb,t),r(Eb,t),r(_b,t),r(Cb,t),r(Sb,t),r(bb,t),r(Tb,t),r(Mc,t),r(Db,t),r(Ob,t),r(Fb,t),r(wb,t),r(Nb,t),r(Lb,t),r(Ib,t),r($b,t),r(Pb,t),r(Sr,t),r(qb,t),r(m2,t),r(y2,t),r(A2,t),r(Qb,t),r(rd,t),r(Ic,t),r(zb,t),r(Jy,t),r(Uc,t),r(eE,t),r(Gb,t),r(Wb,t),r(Vb,t),r(a2,t),r(u2,t),r(jc,t),r(Yb,t),r(Kb,t),r(Jb,t),r(Xb,t),r(Rn,t),r(yt,t),r(sT,t),r(oT,t),r(Oc,t),r(oE,t),r(eE,t),r(Ra,t),r(sE,t),r(rE,t),r(xs,t),r(Dy,t),r($c,t),r(uE,t),r(Ry,t),r(uT,t),r(id,t),r(aT,t),r(nE,t),r(iE,t),r(l2,t),r(Zx,t),r(zy,t),r(Qc,t),r(lT,t),r(Fc,t),r(pu,t),r(cT,t),r(fT,t),r(ct,t),r(xT,t),r(kc,t),r(Je,t),r(dT,t),r(P0e,t),r(hT,t),r(pT,t),r(mT,t)}(Q4);var gT={},Ect=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Act=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_ct=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Ect(e,t,r);return Act(e,t),e};Object.defineProperty(gT,"__esModule",{value:!0}),gT.MalloyToAST=void 0;const U0e=py,vct=Kh,ie=_ct(Q4),yk=Yp,j0e=Er,Cct=Q4,Yn=Bn,yT=Xe,Sct=Zo,q0e=Vn,bct=Cy;class H0e extends ie.SourceQueryElement{constructor(){super(...arguments),this.elementType="parseErrorSourceQuery"}}class Ek extends ie.MalloyElement{constructor(e){super(),this.elementType="ignoredByParser",this.malloySrc=e}}const Tct=[];class Rct extends vct.AbstractParseTreeVisitor{constructor(e,r,i){super(),this.parseInfo=e,this.msgLog=r,this.compilerFlags=i;for(const s of Tct){const o=Sct.Tag.fromTagLine(s,0,this.compilerFlags);this.compilerFlags=o.tag}}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}astError(e,r,i,s){this.msgLog.log((0,yk.makeLogMessage)(r,i,{at:e.location,...s}))}rangeFromContext(e){return(0,q0e.rangeFromContext)(this.parseInfo.sourceInfo,e)}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.rangeFromContext(e)}}getSourceString(e){return this.parseInfo.sourceStream.getText(new j0e.Interval(e.start.startIndex,e.stop?e.stop.stopIndex:e.start.startIndex))}contextError(e,r,i,s){this.msgLog.log((0,yk.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}warnWithReplacement(e,r,i,s){this.msgLog.log((0,yk.makeLogMessage)(e,r,{at:{url:this.parseInfo.sourceURL,range:i},severity:"warn",replacement:s}))}inExperiment(e,r){const i=this.compilerFlags.tag("experimental");return i&&(i.bare()||i.has(e))?!0:(this.contextError(r,"experiment-not-enabled",{experimentId:e}),!1)}only(e,r,i){const s=[];for(const o of e){const u=r(o);u?s.push(u):o instanceof Ek||this.astError(o,"unexpected-statement-in-translation",`Parser enountered unexpected statement type '${o.elementType}' when it needed '${i}'`)}return s}getNumber(e){return Number.parseInt(e.text)}getFieldName(e){return this.astAt(new ie.FieldName((0,Yn.getId)(e)),e.id())}getModelEntryName(e){return this.astAt(new ie.ModelEntryReference((0,Yn.getId)(e)),e.id())}defaultResult(){return new ie.Unimplemented}astAt(e,r){return e.location={url:this.parseInfo.sourceURL,range:this.rangeFromContext(r)},e}getSourceCode(e){const r=e.start.startIndex,i=e.stop||e.start,s=new j0e.Interval(r,i.stopIndex);return this.parseInfo.sourceStream.getText(s)}getFilterElement(e){const r=this.getFieldExpr(e),i=new ie.FilterElement(r,this.getSourceCode(e));return this.astAt(i,e)}getFieldDefs(e,r){return e.map(i=>this.getFieldDef(i,r))}getFieldExpr(e){const r=this.visit(e);if(r instanceof ie.ExpressionDef)return this.astAt(r,e);throw this.internalError(e,`expression node unknown type '${r.elementType}'`)}getPlainStringFrom(e){const[r,i]=(0,Yn.getPlainString)(e);for(const s of i)s instanceof U0e.ParserRuleContext&&this.contextError(s,"illegal-query-interpolation-outside-sql-block","%{ query } illegal in this string");return r||""}makeSqlString(e,r){for(const i of(0,Yn.getStringParts)(e))i instanceof U0e.ParserRuleContext?r.push(this.visit(i)):r.push(i);r.complete(),this.astAt(r,e)}parseTime(e,r){let i=r(e.text);return i||(this.contextError(e,"failed-to-parse-time-literal","Time data parse error"),i=new ie.LiteralTimestamp({text:e.text})),this.astAt(i,e)}getNotes(e){return e.ANNOTATION().map(r=>({text:r.text,at:this.getLocation(e)}))}getIsNotes(e){return this.getNotes(e._beforeIs).concat(this.getNotes(e._afterIs))}visitMalloyDocument(e){const r=this.only(e.malloyStatement().map(i=>this.visit(i)),i=>ie.isDocStatementOrDocStatementList(i)&&i,"statement");return new ie.Document(r)}visitDefineSourceStatement(e){const i=e.sourcePropertyList().sourceDefinition().map(u=>this.visitSourceDefinition(u)),s=this.getNotes(e.tags()),o=new ie.DefineSourceList(i);return o.extendNote({blockNotes:s}),o}getSourceParameter(e){const r=(0,Yn.getId)(e.parameterNameDef());let i,s;const o=e.legalParamType();if(o){const l=o.malloyType();if(l){const f=this.getMalloyType(l);(0,bct.isFilterable)(f)?s=f:this.contextError(o,"parameter-illegal-default-type",`Unknown filter type ${f}`)}const c=o.FILTER()?"filter expression":o.text.toLowerCase();if(!(0,yT.isParameterType)(c))return this.contextError(o,"parameter-illegal-default-type",`Unknown parameter type ${c}`),null;i=c}const u=e.fieldExpr();let a;if(u){const l=new ie.ConstantExpression(this.getFieldExpr(u));a=this.astAt(l,u)}return this.astAt(new ie.HasParameter({name:r,type:i,default:a,filterType:s}),e)}getSourceParameters(e){if(e===void 0)return[];this.inExperiment("parameters",e);function r(i){return i!==null}return e.sourceParameter().map(i=>this.getSourceParameter(i)).filter(r)}visitSourceDefinition(e){const r=this.visit(e.sqExplore()),i=this.getSourceParameters(e.sourceParameters()),s=new ie.DefineSource((0,Yn.getId)(e.sourceNameDef()),r instanceof ie.SourceQueryElement?r:void 0,!0,i),o=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return s.extendNote({notes:o}),this.astAt(s,e)}getSourceExtensions(e){return this.astAt(this.visitExploreProperties(e),e)}visitExploreProperties(e){const r=this.only(e.exploreStatement().map(s=>this.visit(s)),s=>ie.isSourceProperty(s)&&s,"source property");return new ie.SourceDesc(r)}visitExploreTable(e){const r=e.connectionId(),i=this.astAt(this.getModelEntryName(r),r),s=this.getPlainStringFrom(e.tablePath());return this.astAt(new ie.TableMethodSource(i,s),e)}visitSqlSource(e){const r=e.connectionId(),i=this.astAt(this.getModelEntryName(r),r),s=new ie.SQLString,o=e.sqlString();o&&this.makeSqlString(o,s);const u=e.shortString();u&&s.push((0,Yn.getShortString)(u));const a=new ie.SQLSource(i,s);return this.astAt(a,e)}visitDefJoinMany(e){const r=this.getAccessLabel(e.accessLabel()),i=[];for(const o of e.joinList().joinDef()){const u=this.visit(o);u instanceof ie.Join&&(i.push(u),u instanceof ie.ExpressionJoin?(u.joinType="many",u.joinOn===void 0&&this.contextError(e,"missing-on-in-join-many","join_many: requires ON expression")):u instanceof ie.KeyJoin&&this.contextError(e,"foreign-key-in-join-many","Foreign key join not legal in join_many:"))}const s=new ie.JoinStatement(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),s}visitDefJoinOne(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getJoinList(e.joinList()),s=[];for(const u of i)u instanceof ie.Join&&(s.push(u),u instanceof ie.ExpressionJoin&&(u.joinType="one"));const o=new ie.JoinStatement(s,r);return o.extendNote({blockNotes:this.getNotes(e.tags())}),o}visitDefJoinCross(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getJoinList(e.joinList()),s=[];for(const u of i)u instanceof ie.Join&&(s.push(u),u instanceof ie.ExpressionJoin?u.joinType="cross":u.logError("foreign-key-in-join-cross","Foreign key join not legal in join_cross:"));const o=new ie.JoinStatement(s,r);return o.extendNote({blockNotes:this.getNotes(e.tags())}),o}getJoinList(e){return this.only(e.joinDef().map(r=>this.visit(r)),r=>r instanceof ie.Join&&r,"join")}getJoinFrom(e){const r=e.isExplore(),i=this.getModelEntryName(e.joinNameDef());if(r){const o=this.getSqExpr(r.sqExpr()),u=this.getNotes(r._before_is).concat(this.getNotes(r._after_is));return{joinFrom:o,notes:u,joinAs:i}}const s=e.sourceArguments();return s?{joinFrom:this.astAt(new ie.SQReference(i,this.getSQArguments(s)),e),notes:[],joinAs:i}:{joinAs:i,joinFrom:new ie.SQReference(i),notes:[]}}visitQueryJoinStatement(e){return this.astAt(this.visit(e.joinStatement()),e)}visitJoinOn(e){var r;const{joinAs:i,joinFrom:s,notes:o}=this.getJoinFrom(e.joinFrom()),u=new ie.ExpressionJoin(i,s),a=e.joinExpression(),l=((r=e.matrixOperation())===null||r===void 0?void 0:r.text.toLocaleLowerCase())||"left";return(0,yT.isMatrixOperation)(l)?u.matrixOperation=l:this.contextError(e,"unknown-matrix-operation","Internal Error: Unknown matrixOperation"),a&&(u.joinOn=this.getFieldExpr(a)),u.extendNote({notes:this.getNotes(e).concat(o)}),this.astAt(u,e)}visitJoinWith(e){const{joinAs:r,joinFrom:i,notes:s}=this.getJoinFrom(e.joinFrom()),o=this.getFieldExpr(e.fieldExpr()),u=new ie.KeyJoin(r,i,o);return u.extendNote({notes:this.getNotes(e).concat(s)}),this.astAt(u,e)}getFieldDef(e,r){const i=e.fieldExpr(),s=(0,Yn.getId)(e.fieldNameDef()),o=this.getFieldExpr(i),u=new r(o,s,this.getSourceCode(i)),a=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return u.extendNote({notes:a}),this.astAt(u,e)}visitDefDimensions(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getFieldDefs(e.defList().fieldDef(),ie.DimensionFieldDeclaration),s=new ie.Dimensions(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(s,e)}getAccessLabel(e){if(e!==void 0){if(e.INTERNAL_KW())return"internal";if(e.PRIVATE_KW())return"private";if(e.PUBLIC_KW())return"public";throw this.internalError(e,`Unknown access modifier label ${e.text}`)}}getAccessLabelProp(e){if(e!==void 0){if(e.INTERNAL())return"internal";if(e.PRIVATE())return"private";if(e.PUBLIC())return"public";throw this.internalError(e,`Unknown access modifier label ${e.text}`)}}visitDefMeasures(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getFieldDefs(e.defList().fieldDef(),ie.MeasureFieldDeclaration),s=new ie.Measures(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(s,e)}visitQueryExtend(e){const r=[],i=e.queryExtendStatementList().queryExtendStatement().map(o=>this.visit(o));for(const o of i)if(ie.isQueryExtendProperty(o))r.push(o);else throw this.internalError(e,`Query extend matched, but ${o.elementType} found`);const s=new ie.ExtendBlock(r);return this.astAt(s,e)}visitExploreRenameDef(e){const r=e.fieldName(0),i=e.fieldName(1),s=new ie.RenameField((0,Yn.getId)(r),this.getFieldName(i));return this.astAt(s,e)}visitDefExploreRename(e){const r=this.getAccessLabel(e.accessLabel()),s=e.renameList().exploreRenameDef().map(u=>this.visitExploreRenameDef(u)),o=new ie.Renames(s,r);return this.astAt(o,e)}visitFilterClauseList(e){return new ie.Filter(e.fieldExpr().map(r=>this.getFilterElement(r)))}visitWhereStatement(e){const r=this.visitFilterClauseList(e.filterClauseList());return r.having=!1,this.astAt(r,e)}visitHavingStatement(e){const r=this.visitFilterClauseList(e.filterClauseList());return r.having=!0,this.astAt(r,e)}visitDefExploreQuery(e){const r=this.getAccessLabel(e.accessLabel()),i=e.subQueryDefList().exploreQueryDef().map(u=>this.visitExploreQueryDef(u)),s=new ie.Views(i,r),o=this.getNotes(e.tags());return s.extendNote({blockNotes:o}),s}visitDefExplorePrimaryKey(e){const r=new ie.PrimaryKey(this.getFieldName(e.fieldName()));return this.astAt(r,e)}getFieldNameList(e,r){const i=e.fieldName().map(s=>this.astAt(new r([this.getFieldName(s)]),s));return new ie.FieldReferences(i)}visitDefExploreEditField(e){const r=e.ACCEPT()?"accept":"except";return new ie.FieldListEdit(r,this.getFieldNameList(e.fieldNameList(),ie.AcceptExceptFieldReference))}visitSQInclude(e){const r=this.getSqExpr(e.sqExpr()),i=e.includeBlock(),s=i?this.getIncludeItems(i):void 0,o=new ie.SQExtend(r,new ie.SourceDesc([]),s);return this.astAt(o,e)}visitDefExploreTimezone(e){return this.visitTimezoneStatement(e.timezoneStatement())}visitTimezoneStatement(e){const r=this.getPlainStringFrom(e),i=this.astAt(new ie.TimezoneStatement(r),e.string());return i.isValid||this.astError(i,"invalid-timezone",{timezone:i.tz}),this.astAt(i,e)}visitQueryProperties(e){const r=this.only(e.queryStatement().map(i=>this.astAt(this.visit(i),i)),i=>ie.isQueryProperty(i)&&i,"query statement");return new ie.QOpDesc(r)}getFieldPath(e,r){const i=e.fieldName().map(s=>this.getFieldName(s));return this.astAt(new r(i),e)}getQueryFieldDef(e,r){const i=this.getFieldDef(e,r);return this.astAt(i,e)}getQueryFieldEntry(e,r,i){const s=e.taggedRef();if(s)return this.getTaggedRef(s,r,i);const o=e.fieldDef();if(o)return this.getQueryFieldDef(o,r);throw new Error("Expected query field entry to be a field reference or definition")}getQueryItems(e,r,i){return this.only(e.queryFieldEntry().map(s=>this.getQueryFieldEntry(s,r,i)),s=>s instanceof ie.FieldReference||s instanceof ie.AtomicFieldDeclaration?s:!1,"view field")}visitAggregateStatement(e){const r=new ie.Aggregate(this.getQueryItems(e.queryFieldList(),ie.AggregateFieldDeclaration,ie.AggregateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitGroupByStatement(e){const r=new ie.GroupBy(this.getQueryItems(e.queryFieldList(),ie.GroupByFieldDeclaration,ie.GroupByFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCalculateStatement(e){const r=new ie.Calculate(this.getQueryItems(e.queryFieldList(),ie.CalculateFieldDeclaration,ie.CalculateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}getTaggedRef(e,r,i){const s=e.refExpr();if(s){const u=this.getFieldPath(e.fieldPath(),ie.ExpressionFieldReference);let a;const l=s.timeframe();l&&(a=new ie.ExprGranularTime(new ie.ExprIdReference(u),this.visitTimeframe(l).text,!0));const c=s.aggregate();if(c){const x=c.text.toLowerCase();if(x==="sum")a=new ie.ExprSum(void 0,u);else return this.contextError(c,"invalid-reference-only-aggregation",`\`${x}\` is not legal in a reference-only aggregation`),u}const f=new r(a,u.outputName);return f.extendNote({notes:this.getNotes(e.tags())}),f}const o=this.getFieldPath(e.fieldPath(),i);return o.extendNote({notes:this.getNotes(e.tags())}),o}getFieldCollectionMember(e,r,i){const s=e.fieldDef();if(s)return this.getFieldDef(s,r);const o=e.taggedRef();if(o)return this.getTaggedRef(o,r,i);const u=e.collectionWildCard();if(u)return this.visitCollectionWildCard(u);throw this.internalError(e,"Unexpected element in fieldCollectionMember")}visitFieldCollection(e){const r=e.collectionMember().map(i=>this.getFieldCollectionMember(i,ie.ProjectFieldDeclaration,ie.ProjectFieldReference));return this.astAt(new ie.ProjectStatement(r),e)}visitProjectStatement(e){const r=this.visitFieldCollection(e.fieldCollection());return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCollectionWildCard(e){var r;const i=e.fieldPath(),s=i?this.getFieldPath(i,ie.ProjectFieldReference):void 0,o=this.astAt(new ie.WildcardFieldReference(s),e),u=((r=e.starQualified())===null||r===void 0?void 0:r.fieldNameList())||[];for(const a of u)for(const l of a.fieldName())o.except.add((0,Yn.getId)(l));return o}visitIndexFields(e){const r=e.indexElement().map(i=>{const s=i.fieldPath();if(!s)return this.astAt(new ie.WildcardFieldReference(void 0),e);const o=this.getFieldPath(s,ie.IndexFieldReference);return i.STAR()?this.astAt(new ie.WildcardFieldReference(o),e):this.astAt(o,e)});return new ie.FieldReferences(r)}visitIndexStatement(e){const r=this.visitIndexFields(e.indexFields()),i=new ie.Index(r),s=e.fieldName();return s&&i.useWeight(this.getFieldName(s)),this.astAt(i,e)}visitFieldPropertyLimitStatement(e){return this.inExperiment("aggregate_limit",e),this.visitLimitStatement(e.limitStatement())}visitLimitStatement(e){return new ie.Limit(this.getNumber(e.INTEGER_LITERAL()))}visitAggregateOrderBySpec(e){const r=e.ASC()?"asc":e.DESC()?"desc":void 0,i=e.fieldExpr(),s=i?this.getFieldExpr(i):void 0;return this.astAt(new ie.FunctionOrderBy(s,r),e)}visitAggregateOrderByStatement(e){return this.visitAggregateOrdering(e.aggregateOrdering())}visitAggregateOrdering(e){const r=e.aggregateOrderBySpec().map(i=>this.visitAggregateOrderBySpec(i));return this.astAt(new ie.FunctionOrdering(r),e)}visitOrderBySpec(e){const r=e.ASC()?"asc":e.DESC()?"desc":void 0,i=e.INTEGER_LITERAL();if(i)return new ie.OrderBy(this.getNumber(i),r);const s=e.fieldName();if(s)return new ie.OrderBy(this.getFieldName(s),r);throw this.internalError(e,"can't parse order_by specification")}visitOrdering(e){const r=e.orderBySpec().map(i=>this.visitOrderBySpec(i));return this.astAt(new ie.Ordering(r),e)}visitTopStatement(e){const r=this.getNumber(e.INTEGER_LITERAL());return this.astAt(new ie.Limit(r),e)}visitTopLevelQueryDefs(e){const r=e.topLevelQueryDef().map(o=>this.visitTopLevelQueryDef(o)),i=this.getNotes(e.tags()),s=new ie.DefineQueryList(r);return s.extendNote({blockNotes:i}),s}visitTopLevelQueryDef(e){const r=(0,Yn.getId)(e.queryName()),i=this.visit(e.sqExpr()),s=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));if(i instanceof ie.SourceQueryElement){const o=new ie.DefineQuery(r,i);return o.extendNote({notes:s}),this.astAt(o,e)}throw this.internalError(e,`Expected query definition, got a '${i.elementType}'`)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getSqExpr(r.sqExpr()),s=this.astAt(new ie.AnonymousQuery(i),r),o=this.getNotes(e.topLevelAnonQueryDef().tags()),u=this.getNotes(e.tags());return s.extendNote({notes:o,blockNotes:u}),this.astAt(s,e)}visitNestStatement(e){const r=this.visitNestedQueryList(e.nestedQueryList());return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitNestedQueryList(e){return new ie.Nests(this.only(e.nestEntry().map(r=>this.visit(r)),r=>r instanceof ie.NestFieldDeclaration&&r,"query"))}visitNestDef(e){const r=e.queryName();let i;const s=this.getVExpr(e.vExpr());if(r)i=(0,Yn.getId)(r);else{const a=s.getImplicitName();a===void 0&&this.contextError(e,"anonymous-nest","`nest:` view requires a name (add `nest_name is ...`)"),i=a??"__unnamed__"}const o=new ie.NestFieldDeclaration(i,s),u=e.isDefine();return o.extendNote({notes:this.getNotes(e.tags()).concat(u?this.getIsNotes(u):[])}),this.astAt(o,e)}visitExploreQueryDef(e){const r=(0,Yn.getId)(e.exploreQueryNameDef()),i=new ie.ViewFieldDeclaration(r,this.getVExpr(e.vExpr())),s=this.getNotes(e).concat(this.getIsNotes(e.isDefine()));return i.extendNote({notes:s}),this.astAt(i,e)}visitExprNot(e){return new ie.ExprNot(this.getFieldExpr(e.fieldExpr()))}visitExprBool(e){return new ie.Boolean(e.TRUE()?"true":"false")}allFieldExpressions(e){return e.map(r=>this.getFieldExpr(r))}visitExprLogicalOr(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1));return new ie.ExprLogicalOp(r,"or",i)}visitExprLogicalAnd(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1));return new ie.ExprLogicalOp(r,"and",i)}visitExprOrTree(e){const r=this.getFieldExpr(e.fieldExpr()),i=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new ie.ExprAlternationTree(r,"|",i),e)}visitExprAndTree(e){const r=this.getFieldExpr(e.fieldExpr()),i=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new ie.ExprAlternationTree(r,"&",i),e)}visitExprCoalesce(e){const r=this.getFieldExpr(e.fieldExpr()[0]),i=this.getFieldExpr(e.fieldExpr()[1]);return this.astAt(new ie.ExprCoalesce(r,i),e)}visitPartialCompare(e){const r=e.compareOp().text;if(ie.isComparison(r))return this.astAt(new ie.PartialCompare(r,this.getFieldExpr(e.fieldExpr())),e);throw this.internalError(e,`partial comparison '${r}' not recognized`)}visitPartialTest(e){const r=e.partialCompare();return r?this.visitPartialCompare(r):this.astAt(new ie.PartialIsNull(e.NOT()?"!=":"="),e)}visitPartialAllowedFieldExpr(e){const r=e.fieldExpr();if(r)return this.getFieldExpr(r);const i=e.partialTest();if(i)return this.visitPartialTest(i);throw this.internalError(e,"impossible partial")}visitExprString(e){const r=this.getPlainStringFrom(e);return new ie.ExprString(r)}visitRawString(e){const r=e.text.slice(1).trimStart();if(r[r.length-1]===`
1161
+ `){const o=r[0]==="'"?'"':"'";this.contextError(e,"literal-string-newline",`Missing ${o}${r[0]}${o} before end-of-line`)}const s=new ie.ExprString(r.slice(1,-1));return this.astAt(s,e)}visitExprRegex(e){const r=e.HACKY_REGEX().text;return new ie.ExprRegEx(r.slice(2,-1))}visitExprNow(e){return new ie.ExprNow}visitExprNumber(e){return new ie.ExprNumber(e.text)}visitExprFieldPath(e){const r=new ie.ExprIdReference(this.getFieldPath(e.fieldPath(),ie.ExpressionFieldReference));return this.astAt(r,e)}visitExprNULL(e){return new ie.ExprNULL}visitExprExpr(e){return new ie.ExprParens(this.getFieldExpr(e.fieldExpr()))}visitExprMinus(e){return new ie.ExprMinus(this.getFieldExpr(e.fieldExpr()))}visitExprAddSub(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1)),s=e.PLUS()?"+":"-";return new ie.ExprAddSub(r,s,i)}visitExprMulDiv(e){const r=e.STAR()?"*":e.SLASH()?"/":"%";return new ie.ExprMulDiv(this.getFieldExpr(e.fieldExpr(0)),r,this.getFieldExpr(e.fieldExpr(1)))}visitExprCompare(e){const r=e.compareOp().text,i=this.getFieldExpr(e.fieldExpr(0)),s=this.getFieldExpr(e.fieldExpr(1));if(ie.isEquality(r)){const o=this.rangeFromContext(e);return s instanceof ie.ExprNULL&&(r==="="?this.warnWithReplacement("sql-is-null","Use 'is null' to check for NULL instead of '= null'",o,`${this.getSourceCode(e.fieldExpr(0))} is null`):r==="!="&&this.warnWithReplacement("sql-is-not-null","Use 'is not null' to check for NULL instead of '!= null'",o,`${this.getSourceCode(e.fieldExpr(0))} is not null`)),this.astAt(new ie.ExprEquality(i,r,s),e)}else if(ie.isComparison(r))return this.astAt(new ie.ExprCompare(i,r,s),e);throw this.internalError(e,`untranslatable comparison operator '${r}'`)}visitExprUngroup(e){const r=e.fieldName().map(s=>this.getFieldName(s)),i=e.ungroup().text.toLowerCase();return this.astAt(new ie.ExprUngroup(i==="all"?i:"exclude",this.getFieldExpr(e.fieldExpr()),r),e)}symmetricAggregateUsageError(e){return`Symmetric aggregate function \`${e}\` must be written as \`${e}(expression)\` or \`path.to.field.${e}()\``}asymmetricAggregateUsageError(e){return`Asymmetric aggregate function \`${e}\` must be written as \`path.to.field.${e}()\`, \`path.to.join.${e}(expression)\`, or \`${e}(expression)\``}visitExprAggregate(e){const r=e.fieldPath(),i=this.getFieldPath(r,ie.ExpressionFieldReference),s=r&&i?this.astAt(i,r):void 0,o=e.aggregate().text.toLowerCase(),u=e.fieldExpr();if(e.aggregate().COUNT())return u&&this.contextError(u,"count-expression-with-locality","Expression illegal inside path.count()"),new ie.ExprCount(s);const a=u?this.getFieldExpr(u):void 0;if(o==="min"||o==="max")if(a)this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(o));else{const l=this.astAt(new ie.ExprIdReference(i),r);return o==="min"?new ie.ExprMin(l):new ie.ExprMax(l)}else{if(o==="avg")return new ie.ExprAvg(a,s);if(o==="sum")return new ie.ExprSum(a,s);this.contextError(e,"aggregate-parse-error",`Cannot parse aggregate function ${o}`)}return new ie.ExprNULL}visitExprPathlessAggregate(e){const r=e.fieldExpr(),i=r?this.getFieldExpr(r):void 0,s=void 0,o=e.aggregate().text.toLowerCase();if(o==="count")return this.astAt(i?new ie.ExprCountDistinct(i):new ie.ExprCount,e);if(o==="min"){if(i)return new ie.ExprMin(i);this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(o))}else if(o==="max"){if(i)return new ie.ExprMax(i);this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(o))}else{if(i===void 0)return this.contextError(e,"invalid-asymmetric-aggregate",this.asymmetricAggregateUsageError(o)),new ie.ExprNULL;const u=e.SOURCE_KW()!==void 0;if(o==="avg")return new ie.ExprAvg(i,s,u);if(o==="sum")return new ie.ExprSum(i,s,u)}return new ie.ExprNULL}visitExprApply(e){return new ie.Apply(this.getFieldExpr(e.fieldExpr()),this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprRange(e){return new ie.Range(this.getFieldExpr(e.fieldExpr(0)),this.getFieldExpr(e.fieldExpr(1)))}visitExprCast(e){const r=this.getMalloyOrSQLType(e.malloyOrSQLType());return new ie.ExprCast(this.getFieldExpr(e.fieldExpr()),r)}getMalloyType(e){const r=e.text;if((0,yT.isCastType)(r))return r;throw this.internalError(e,`unknown type '${r}'`)}getMalloyOrSQLType(e){const r=e.malloyType();if(r)return this.getMalloyType(r);const i=e.string();if(i)return{raw:this.getPlainStringFrom({string:()=>i})};throw this.internalError(e,"Expected Malloy or SQL type to either be a Malloy type or a string")}visitExprSafeCast(e){const r=this.getMalloyOrSQLType(e.malloyOrSQLType());return new ie.ExprCast(this.getFieldExpr(e.fieldExpr()),r,!0)}visitExprTimeTrunc(e){return new ie.ExprGranularTime(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text,!0)}visitTimeframe(e){return new ie.Timeframe(e.text)}visitExprForRange(e){const r=this.getFieldExpr(e._startAt),i=this.getFieldExpr(e._duration),s=this.visitTimeframe(e.timeframe());return new ie.ForRange(r,i,s)}visitExprAggFunc(e){const r=e.argumentList(),i=r?this.allFieldExpressions(r.fieldExpr()):[],s=(0,Yn.getId)(e),o=e.fieldPath(),u=o?this.getFieldPath(o,ie.ExpressionFieldReference):void 0,a=o&&u?this.astAt(u,o):void 0;return ie.ExprTimeExtract.extractor(s)?this.astAt(new ie.ExprTimeExtract(s,i),e):this.astAt(new ie.ExprFunc(s,i,!1,void 0,a),e)}visitExprFunc(e){var r,i;const s=e.argumentList(),o=s?this.allFieldExpressions(s.fieldExpr()):[],u=e.EXCLAM()!==void 0,a=(r=e.malloyType())===null||r===void 0?void 0:r.text;let l;a&&((0,yT.isCastType)(a)?l=a:(this.contextError(e,"unexpected-malloy-type",`'#' assertion for unknown type '${a}'`),l=void 0));let c=(0,Yn.getOptionalId)(e)||((i=e.timeframe())===null||i===void 0?void 0:i.text);return c===void 0&&(this.contextError(e,"failed-to-parse-function-name","Function name error"),c="FUNCTION_NAME_ERROR"),ie.ExprTimeExtract.extractor(c)?this.astAt(new ie.ExprTimeExtract(c,o),e):this.astAt(new ie.ExprFunc(c,o,u,l),e)}visitExprDuration(e){return new ie.ExprDuration(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text)}visitCaseStatement(e){const r=e._valueExpr,i=r?this.getFieldExpr(r):void 0,s=e.caseWhen(),o=s.map(l=>new ie.CaseWhen(this.getFieldExpr(l._condition),this.getFieldExpr(l._result))),u=e._caseElse,a=u?this.getFieldExpr(u):void 0;return this.warnWithReplacement("sql-case","Use a `pick` statement instead of `case`",this.rangeFromContext(e),`${[...r?[`${this.getSourceCode(r)} ?`]:[],...s.map(l=>`pick ${this.getSourceCode(l._result)} when ${this.getSourceCode(l._condition)}`),u?`else ${u.text}`:"else null"].join(" ")}`),new ie.Case(i,o,a)}visitPickStatement(e){const r=e.pick().map(i=>{let s;return i._pickValue&&(s=this.getFieldExpr(i._pickValue)),new ie.PickWhen(s,this.getFieldExpr(i._pickWhen))});return e.ELSE()?new ie.Pick(r,this.getFieldExpr(e._pickElse)):new ie.Pick(r)}visitExprFieldProps(e){const r=this.only(e.fieldProperties().fieldPropertyStatement().map(i=>this.visit(i)),i=>ie.isFieldPropStatement(i)&&i,"field property statement");return new ie.ExprProps(this.getFieldExpr(e.fieldExpr()),r)}visitPartitionByStatement(e){return this.astAt(new ie.PartitionBy(e.id().map(r=>this.astAt(new ie.PartitionByFieldReference([this.astAt(new ie.FieldName((0,Yn.idToStr)(r)),r)]),r))),e)}visitLiteralTimestamp(e){return this.parseTime(e,ie.LiteralTimestamp.parse)}visitLiteralHour(e){return this.parseTime(e,ie.LiteralHour.parse)}visitLiteralDay(e){return this.parseTime(e,ie.LiteralDay.parse)}visitLiteralWeek(e){return this.parseTime(e,ie.LiteralWeek.parse)}visitLiteralMonth(e){return this.parseTime(e,ie.LiteralMonth.parse)}visitLiteralQuarter(e){return this.parseTime(e,ie.LiteralQuarter.parse)}visitLiteralYear(e){return this.parseTime(e,ie.LiteralYear.parse)}visitImportStatement(e){const r=this.getPlainStringFrom(e.importURL()),i=this.astAt(new ie.ImportStatement(r,this.parseInfo.importBaseURL),e),s=e.importSelect();if(s)for(const o of s.importItem()){const u=o.id(),a=u[1]?this.astAt(new ie.ImportSourceName((0,Yn.idToStr)(u[1])),u[1]):void 0;i.push(this.astAt(new ie.ImportSelect((0,Yn.idToStr)(u[0]),a),u[0]))}return i}visitDebugExpr(e){return this.getFieldExpr(e.fieldExpr())}visitSampleStatement(e){const r=e.sampleSpec().INTEGER_LITERAL();if(r)return new ie.SampleProperty({rows:this.getNumber(r)});const i=e.sampleSpec().PERCENT_LITERAL();if(i)return new ie.SampleProperty({percent:this.getNumber(i)});const s=e.sampleSpec().TRUE()!==void 0;return new ie.SampleProperty({enable:s})}visitDocAnnotations(e){const r=e.DOC_ANNOTATION().map(s=>({text:s.text,at:this.getLocation(e)})),i=new ie.ModelAnnotation(r);return this.compilerFlags=i.getCompilerFlags(this.compilerFlags,this.msgLog),i}visitIgnoredObjectAnnotations(e){return this.contextError(e,"orphaned-object-annotation","Object annotation not connected to any object"),new Ek(e.text)}visitIgnoredModelAnnotations(e){return this.contextError(e,"misplaced-model-annotation","Model annotations not allowed at this scope"),new Ek(e.text)}visitDefExploreAnnotation(e){const r=this.getNotes(e);return new ie.ObjectAnnotation(r)}getSQArgument(e){const r=e.argumentId(),i=r?this.astAt(new ie.PartitionByFieldReference([this.astAt(new ie.FieldName((0,Yn.idToStr)(r.id())),r)]),r):void 0;return this.astAt(new ie.Argument({id:i,value:this.getFieldExpr(e.fieldExpr())}),e)}getSQArguments(e){if(e!==void 0)return this.inExperiment("parameters",e),e.sourceArgument().map(r=>this.getSQArgument(r))}visitSQID(e){const r=this.getModelEntryName(e),i=this.getSQArguments(e.sourceArguments());return this.astAt(new ie.SQReference(r,i),e.id())}getSqExpr(e){const r=this.visit(e);return r instanceof ie.SourceQueryElement?r:(this.contextError(e,"unexpected-non-source-query-expression-node",`Expected a source/query expression, not '${r.elementType}'`),new H0e)}visitSQExtendedSource(e){const r=this.getSqExpr(e.sqExpr()),i=e.includeBlock(),s=i?this.getIncludeItems(i):void 0,o=new ie.SQExtend(r,this.getSourceExtensions(e.exploreProperties()),s);return this.astAt(o,e)}getIncludeItems(e){return this.inExperiment("access_modifiers",e),e.includeItem().map(r=>this.getIncludeItem(r)).filter(q0e.isNotUndefined)}getIncludeItem(e){var r;const i=e.tags(),s=i?this.getNotes(i):[],o=e.includeExceptList();if(o){i&&s.length>0&&this.contextError(i,"cannot-tag-include-except","Tags on `except:` are ignored",{severity:"warn"});const u=this.getExcludeList(o);return this.astAt(new ie.IncludeExceptItem(u),e)}else{const u=e.includeList();if(u===void 0){this.contextError((r=e.orphanedAnnotation())!==null&&r!==void 0?r:e,"orphaned-object-annotation","This tag is not attached to anything",{severity:"warn"});return}const a=this.getAccessLabelProp(e.accessLabelProp()),l=this.getIncludeList(u),c=this.astAt(new ie.IncludeAccessItem(a,l),e);return c.extendNote({blockNotes:s}),c}}getIncludeList(e){const r=e.includeField();if(r===void 0)throw this.internalError(e,"Expected a field name list");return r.map(i=>this.getIncludeListItem(i))}getExcludeList(e){return e.includeExceptListItem().map(r=>{r.tags().ANNOTATION().length>0&&this.contextError(r.tags(),"cannot-tag-include-except","Tags on `except:` are ignored",{severity:"warn"});const i=r.fieldName();if(i)return this.astAt(new ie.AccessModifierFieldReference([this.astAt(this.getFieldName(i),r)]),i);const s=r.collectionWildCard();if(s)return this.astAt(this.visitCollectionWildCard(s),s);throw this.internalError(r,"Expected a field name or wildcard")})}getIncludeListItem(e){const r=e.collectionWildCard(),i=r?this.visitCollectionWildCard(r):void 0,s=e._as?e._as.text:void 0,o=e.tags(),u=o?this.getNotes(o):[],a=e.isDefine(),l=a?this.getIsNotes(a):[],c=[...u,...l],f=e._name?this.astAt(new ie.AccessModifierFieldReference([this.astAt(this.getFieldName(e._name),e._name)]),e._name):void 0,x=f??i;if(x===void 0)throw this.internalError(e,"Expected a field name or wildcard");const h=this.astAt(new ie.IncludeListItem(x,s),e);return h.extendNote({notes:c}),h}visitSQParens(e){const r=this.getSqExpr(e.sqExpr());return this.astAt(r,e)}visitSQCompose(e){const r=e.sqExpr().map(i=>this.getSqExpr(i));return this.inExperiment("composite_sources",e),this.astAt(new ie.SQCompose(r),e)}visitSQArrow(e){const r=this.getSqExpr(e.sqExpr()),i=e.segExpr(),s=new ie.SQArrow(r,this.getVExpr(i));return this.astAt(s,e)}getVExpr(e){const r=this.visit(e);if(r instanceof ie.View)return r;throw this.internalError(e,`Expected view, got a '${r.elementType}'`)}visitSegField(e){return new ie.ReferenceView(this.getFieldPath(e.fieldPath(),ie.ViewOrScalarFieldReference))}visitSegOps(e){return new ie.QOpDescView(this.visitQueryProperties(e.queryProperties()))}visitSegParen(e){return this.visit(e.vExpr())}visitVSeg(e){return this.visit(e.segExpr())}visitSegRefine(e){return new ie.ViewRefine(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitVArrow(e){return new ie.ViewArrow(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitSQRefinedQuery(e){const r=this.getSqExpr(e.sqExpr()),i=e.segExpr(),s=new ie.SQRefine(r,this.getVExpr(i));return this.astAt(s,e)}visitSQTable(e){const r=this.visit(e.exploreTable());if(r instanceof Cct.TableSource){const i=new ie.SQSource(r);return this.astAt(i,e)}return new H0e}visitSQSQL(e){const r=new ie.SQSource(this.visitSqlSource(e.sqlSource()));return this.astAt(r,e)}visitExperimentalStatementForTesting(e){return this.inExperiment("compilerTestExperimentParse",e),this.astAt(new ie.ExperimentalExperiment("compilerTestExperimentTranslate"),e)}visitRecordRef(e){const r=new ie.ExprIdReference(this.getFieldPath(e.fieldPath(),ie.ExpressionFieldReference));return this.astAt(new ie.RecordElement({path:r}),e)}visitRecordExpr(e){const r=this.getFieldExpr(e.fieldExpr()),i=e.recordKey(),s=i?{key:(0,Yn.getId)(i),value:r}:{value:r};return this.astAt(new ie.RecordElement(s),e)}visitExprLiteralRecord(e){const r=this.only(e.recordElement().map(i=>this.astAt(this.visit(i),i)),i=>i instanceof ie.RecordElement&&i,"a legal record property description");return new ie.RecordLiteral(r)}visitExprArrayLiteral(e){const r=e.fieldExpr().map(s=>this.getFieldExpr(s)),i=new ie.ArrayLiteral(r);return this.astAt(i,e)}visitExprWarnLike(e){let r="~";const i=e.fieldExpr(0),s=e.fieldExpr(1),o=this.rangeFromContext(e);return e.NOT()?(r="!~",this.warnWithReplacement("sql-not-like","Use Malloy operator '!~' instead of 'NOT LIKE'",o,`${this.getSourceCode(i)} !~ ${this.getSourceCode(s)}`)):this.warnWithReplacement("sql-like","Use Malloy operator '~' instead of 'LIKE'",o,`${this.getSourceCode(i)} ~ ${this.getSourceCode(s)}`),this.astAt(new ie.ExprCompare(this.getFieldExpr(i),r,this.getFieldExpr(s)),e)}visitExprNullCheck(e){const r=e.fieldExpr();return this.astAt(new ie.ExprIsNull(this.getFieldExpr(r),e.NOT()?"!=":"="),e)}visitExprWarnIn(e){const r=this.getFieldExpr(e.fieldExpr()),i=!!e.NOT(),s=e.fieldExprList().fieldExpr(),o=this.astAt(new ie.ExprLegacyIn(r,i,s.map(u=>this.getFieldExpr(u))),e);return this.warnWithReplacement("sql-in",`Use = (a|b|c) instead of${i?" NOT":""} IN (a,b,c)`,this.rangeFromContext(e),`${this.getSourceCode(e.fieldExpr())} ${i?"!=":"="} (${s.map(u=>this.getSourceCode(u)).join(" | ")})`),o}visitTickFilterString(e){const r=e.text.slice(1).trimStart();if(r[r.length-1]===`
1162
+ `){const u=r[0]==="'"?'"':"'";this.contextError(e,"literal-string-newline",`Missing $${u}${r[0]}${u} before end-of-line`)}const s=r.slice(1,-1),o=new ie.ExprFilterExpression(s);return this.astAt(o,e)}visitTripFilterString(e){const i=e.text.slice(1).trimStart().slice(3,-3),s=new ie.ExprFilterExpression(i);return this.astAt(s,e)}}gT.MalloyToAST=Rct;var ET={};Object.defineProperty(ET,"__esModule",{value:!0}),ET.Zone=void 0;class Dct{constructor(){this.location={},this.zone=new Map}get(e){const r=this.zone.get(e);if((r==null?void 0:r.status)==="present")return r.value}getEntry(e){const r=this.zone.get(e);return r?r.firstReference||!this.location[e]?r:{...r,firstReference:this.location[e]}:{status:"error",message:"import reference failure"}}define(e,r){this.zone.set(e,{status:"present",value:r})}reference(e,r){const i=this.zone.get(e);(i==null?void 0:i.status)===void 0&&(this.zone.set(e,{status:"reference",firstReference:r}),this.location[e]=r)}getUndefined(){const e=[];for(const[r,i]of this.zone)i.status==="reference"&&e.push(r);return e.length>0?e:void 0}updateFrom(e,r){if(e)for(const[i,s]of Object.entries(e))s!==void 0&&this.define(i,s);if(r)for(const[i,s]of Object.entries(r))this.zone.set(i,{status:"error",message:s})}}ET.Zone=Dct;var AT={};Object.defineProperty(AT,"__esModule",{value:!0}),AT.walkForDocumentSymbols=void 0;const Oct=uc,Fct=Bn;class wct{constructor(e,r,i,s){this.translator=e,this.tokens=r,this.scopes=i,this.symbols=s}popScope(){return this.scopes.pop()}peekScope(){return this.scopes[this.scopes.length-1]}enterTopLevelQueryDefs(e){const r=this.translator.rangeFromContext(e);e.topLevelQueryDef().length===1&&(this.blockRange=r)}enterTopLevelQueryDef(e){this.symbols.push({range:this.translator.rangeFromContext(e),name:e.queryName().text,type:"query",children:[],lensRange:this.blockRange}),this.blockRange=void 0}enterRunStatement(e){this.symbols.push({range:this.translator.rangeFromContext(e.topLevelAnonQueryDef()),name:"unnamed_query",type:"unnamed_query",children:[],lensRange:this.translator.rangeFromContext(e)})}enterDefineSourceStatement(e){const r=this.translator.rangeFromContext(e);e.sourcePropertyList().sourceDefinition().length===1&&(this.blockRange=r)}enterSourceDefinition(e){const r=this.translator.rangeFromContext(e);this.scopes.push({range:r,name:e.sourceNameDef().id().text,type:"explore",children:[],lensRange:this.blockRange}),this.blockRange=void 0}exitSourceDefinition(e){const r=this.popScope();r&&this.symbols.push(r)}enterDefExploreQuery(e){const r=this.translator.rangeFromContext(e);e.subQueryDefList().exploreQueryDef().length===1&&(this.blockRange=r)}enterExploreQueryDef(e){const r={range:this.translator.rangeFromContext(e),name:e.exploreQueryNameDef().id().text,type:"query",children:[],lensRange:this.blockRange},i=this.peekScope();i&&i.children.push(r),this.scopes.push(r),this.blockRange=void 0}exitExploreQueryDef(e){this.popScope()}getNestDefName(e){const r=e.queryName();if(r)return r.id().text;let i,s=!1;const o={enterVArrow(a){a.vExpr().enterRule(o)},enterVSeg(a){a.segExpr().enterRule(u)}},u={enterSegField(a){const l=a.fieldPath().fieldName();s||(i??(i=l[l.length-1].id().text))},enterSegParen(a){a.vExpr().enterRule(o)},enterSegRefine(a){a._lhs.enterRule(u)},enterSegOps(){i=void 0,s=!0}};return e.vExpr().enterRule(o),i}handleNestEntry(e){const r=this.getNestDefName(e);if(r===void 0)return;const i={range:this.translator.rangeFromContext(e),name:r,type:"query",children:[]},s=this.peekScope();return s&&s.children.push(i),i}enterNestDef(e){const r=this.handleNestEntry(e);r&&this.scopes.push(r)}exitNestDef(e){this.popScope()}enterFieldDef(e){const r={range:this.translator.rangeFromContext(e),name:e.fieldNameDef().id().text,type:"field",children:[]},i=this.peekScope();i&&i.children.push(r)}enterQueryFieldEntry(e){var r;const i=(r=e.taggedRef())===null||r===void 0?void 0:r.fieldPath();if(i===void 0)return;const s={range:this.translator.rangeFromContext(e),name:i.text,type:"field",children:[]},o=this.peekScope();o&&o.children.push(s)}enterExploreRenameDef(e){const r={range:this.translator.rangeFromContext(e),name:e.fieldName()[0].text,type:"field",children:[]},i=this.peekScope();i&&i.children.push(r)}enterJoinWith(e){this.handleJoinDef(e)}enterJoinOn(e){this.handleJoinDef(e)}handleJoinDef(e){const r={range:this.translator.rangeFromContext(e),name:e.joinFrom().joinNameDef().id().text,type:"join",children:[]},i=this.peekScope();i&&i.children.push(r)}enterImportStatement(e){const r=(0,Fct.getStringIfShort)(e.importURL());r&&this.scopes.push({range:this.translator.rangeFromContext(e),name:r,type:"import",children:[]})}exitImportStatement(){const e=this.popScope();e&&this.symbols.push(e)}enterImportSelect(e){const r=this.peekScope();if(r)for(const i of e.importItem()){const s={range:this.translator.rangeFromContext(e),name:i.text,type:"import_item",children:[]};r.children.push(s)}}}function Nct(t,e,r){const i=new wct(t,e,[],[]),s=i;return Oct.ParseTreeWalker.DEFAULT.walk(s,r),i.symbols}AT.walkForDocumentSymbols=Nct;var _T={};Object.defineProperty(_T,"__esModule",{value:!0}),_T.walkForDocumentCompletions=void 0;const Lct=uc,Ict=["dimension","measure","join_one","join_many","join_cross","where","primary_key","rename","accept","except","query","declare"],Bct=["group_by","project","index","aggregate","top","limit","order_by","where","having","nest","declare"],$ct=["source","explore","query","sql"];class kct{constructor(e,r,i){this.tokens=e,this.completions=r,this.position=i}rangeOf(e){const r=e.stop||e.start;return{start:{line:e.start.line-1,character:e.start.charPositionInLine},end:{line:r.line-1,character:r.stopIndex-(r.startIndex-r.charPositionInLine)+1}}}inRange(e){const{start:r,end:i}=e,s=this.position.line>r.line||this.position.line===r.line&&this.position.character>=r.character,o=this.position.line<i.line||this.position.line===i.line&&this.position.character<=i.character;return s&&o}enterExploreProperties(e){if(this.inRange(this.rangeOf(e))){let r=!1;for(const i of e.exploreStatement())this.inRange(this.rangeOf(i))&&(r=!0);if(!r)for(const i of Ict)this.completions.push({type:"explore_property",text:`${i}: `})}}enterQueryProperties(e){if(this.inRange(this.rangeOf(e))){let r=!1;for(const i of e.queryStatement())this.inRange(this.rangeOf(i))&&(r=!0);if(!r)for(const i of Bct)this.completions.push({type:"query_property",text:`${i}: `})}}enterMalloyDocument(e){if(this.inRange(this.rangeOf(e))){let r=!1;for(const i of e.malloyStatement())this.inRange(this.rangeOf(i))&&(r=!0);if(!r)for(const i of $ct)this.completions.push({type:"model_property",text:`${i}: `})}}}function Mct(t,e,r){const i=new kct(t,[],r),s=i;return Lct.ParseTreeWalker.DEFAULT.walk(s,e),i.completions}_T.walkForDocumentCompletions=Mct;var vT={};Object.defineProperty(vT,"__esModule",{value:!0}),vT.walkForDocumentHelpContext=void 0;const Pct=qL;class Uct extends Pct.AbstractParseTreeVisitor{constructor(e){super(),this.position=e,this.type=""}rangeOf(e){const r=e.stop||e.start;return{start:{line:e.start.line-1,character:e.start.charPositionInLine},end:{line:r.line-1,character:r.stopIndex-(r.startIndex-r.charPositionInLine)+1}}}inRange(e){return e.start.line<=this.position.line&&e.end.line>=this.position.line&&(this.position.line!==e.start.line||this.position.character>=e.start.character)&&(this.position.line!==e.end.line||this.position.character<=e.end.character)}defaultResult(){}visitChildren(e){let r=this.defaultResult();if(this.inRange(this.rangeOf(e))){r={type:this.type,token:e.start.text};const i=e.childCount;for(let s=0;s<i;s++){const u=e.getChild(s).accept(this);u&&(r=this.aggregateResult(r,u))}}return r}visitMalloyDocument(e){return this.inRange(this.rangeOf(e))?(this.type="model_property",this.visitChildren(e)):this.defaultResult()}visitExploreProperties(e){return this.inRange(this.rangeOf(e))?(this.type="explore_property",this.visitChildren(e)):this.defaultResult()}visitQueryProperties(e){return this.inRange(this.rangeOf(e))?(this.type="query_property",this.visitChildren(e)):this.defaultResult()}aggregateResult(e,r){return r}}function jct(t,e){return new Uct(e).visit(t)}vT.walkForDocumentHelpContext=jct;var CT={};Object.defineProperty(CT,"__esModule",{value:!0}),CT.ReferenceList=void 0;const qct=Vn;class Hct{constructor(e){this.sourceURL=e,this.references=[]}findIndexBefore(e){let r=0,i=this.references.length;for(;r<i;){const s=Math.floor((r+i)/2),o=this.references[s].location.range.end;o.line<e.line||o.line===e.line&&o.character<e.character?r=s+1:i=s}return r}add(e){if(e.location.url!==this.sourceURL)return;const r=this.findIndexBefore(e.location.range.end);r<this.references.length&&this.isPositionEqual(e,this.references[r])||this.references.splice(r,0,e)}isPositionEqual(e,r){const i=e.location.range,s=r.location.range;return i.start.line===s.start.line&&i.start.character===s.start.character&&i.end.line===s.end.line&&i.end.character===s.end.character}find(e){const r=this.findIndexBefore(e);if(r===this.references.length)return;const i=this.references[r];if((0,qct.locationContainsPosition)(i.location,e))return i}}CT.ReferenceList=Hct;var ST={};Object.defineProperty(ST,"__esModule",{value:!0}),ST.isNeedResponse=void 0;function Qct(t){return!!t&&(t.tables||t.urls||t.compileSQL)!==void 0}ST.isNeedResponse=Qct;var bT={};Object.defineProperty(bT,"__esModule",{value:!0}),bT.walkForModelAnnotation=void 0;const zct=uc;class Gct{constructor(e,r,i){this.translator=e,this.tokens=r,this.parseInfo=i,this.notes=[]}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.translator.rangeFromContext(e)}}enterDocAnnotations(e){const r=e.DOC_ANNOTATION().map(i=>({text:i.text,at:this.getLocation(e)}));this.notes.push(...r)}get annotation(){return{notes:this.notes}}}function Wct(t,e,r){const i=new Gct(t,e,r),s=i;return zct.ParseTreeWalker.DEFAULT.walk(s,r.root),i.annotation}bT.walkForModelAnnotation=Wct;var TT={};Object.defineProperty(TT,"__esModule",{value:!0}),TT.walkForTablePath=void 0;const Q0e=Bn,Vct=uc;class Yct{constructor(e,r){this.translator=e,this.tokens=r,this.pathInfos=[]}enterExploreTable(e){const r=(0,Q0e.getId)(e.connectionId()),[i,s]=(0,Q0e.getPlainString)(e.tablePath(),!0);i!==void 0&&this.pathInfos.push({connectionId:r,tablePath:i,range:this.translator.rangeFromContext(e)})}}function Kct(t,e,r){const i=new Yct(t,e),s=i;return Vct.ParseTreeWalker.DEFAULT.walk(s,r.root),i.pathInfos}TT.walkForTablePath=Kct;var aE={},RT={},Jct=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Xct=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Zct=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Jct(e,t,r);return Xct(e,t),e};Object.defineProperty(RT,"__esModule",{value:!0}),RT.MalloyLexer=void 0;const eft=Sp(),tft=Ml(),nft=Xg(),rft=Fs,z0e=Zct(Sn);class se extends tft.Lexer{get vocabulary(){return se.VOCABULARY}constructor(e){super(e),this._interp=new nft.LexerATNSimulator(se._ATN,this)}get grammarFileName(){return"MalloyLexer.g4"}get ruleNames(){return se.ruleNames}get serializedATN(){return se._serializedATN}get channelNames(){return se.channelNames}get modeNames(){return se.modeNames}static get _ATN(){return se.__ATN||(se.__ATN=new eft.ATNDeserializer().deserialize(z0e.toCharArray(se._serializedATN))),se.__ATN}}RT.MalloyLexer=se,se.ACCEPT=1,se.AGGREGATE=2,se.CALCULATE=3,se.CALCULATION=4,se.CONNECTION=5,se.DECLARE=6,se.DIMENSION=7,se.EXCEPT=8,se.EXTENDQ=9,se.GROUP_BY=10,se.HAVING=11,se.INDEX=12,se.INTERNAL=13,se.JOIN_CROSS=14,se.JOIN_ONE=15,se.JOIN_MANY=16,se.LIMIT=17,se.MEASURE=18,se.NEST=19,se.ORDER_BY=20,se.PARTITION_BY=21,se.PRIMARY_KEY=22,se.PRIVATE=23,se.PROJECT=24,se.PUBLIC=25,se.QUERY=26,se.RENAME=27,se.RUN=28,se.SAMPLE=29,se.SELECT=30,se.SOURCE=31,se.TOP=32,se.WHERE=33,se.VIEW=34,se.TIMEZONE=35,se.ALL=36,se.AND=37,se.AS=38,se.ASC=39,se.AVG=40,se.BOOLEAN=41,se.BY=42,se.CASE=43,se.CAST=44,se.CONDITION=45,se.COUNT=46,se.COMPOSE=47,se.DATE=48,se.DAY=49,se.DESC=50,se.DISTINCT=51,se.ELSE=52,se.END=53,se.EXCLUDE=54,se.EXTEND=55,se.FALSE=56,se.FILTER=57,se.FULL=58,se.FOR=59,se.FROM=60,se.HAS=61,se.HOUR=62,se.IMPORT=63,se.INCLUDE=64,se.INNER=65,se.IS=66,se.IN=67,se.INTERNAL_KW=68,se.JSON=69,se.LAST=70,se.LEFT=71,se.LIKE=72,se.MAX=73,se.MIN=74,se.MINUTE=75,se.MONTH=76,se.NOT=77,se.NOW=78,se.NULL=79,se.NUMBER=80,se.ON=81,se.OR=82,se.PICK=83,se.PRIVATE_KW=84,se.PUBLIC_KW=85,se.QUARTER=86,se.RIGHT=87,se.SECOND=88,se.STRING=89,se.SOURCE_KW=90,se.SUM=91,se.SQL=92,se.TABLE=93,se.THEN=94,se.THIS=95,se.TIMESTAMP=96,se.TO=97,se.TRUE=98,se.TURTLE=99,se.WEEK=100,se.WHEN=101,se.WITH=102,se.YEAR=103,se.UNGROUPED=104,se.HACKY_REGEX=105,se.RAW_SQ=106,se.RAW_DQ=107,se.SQ3_FILTER=108,se.SQ_FILTER=109,se.DQ3_FILTER=110,se.DQ_FILTER=111,se.BQ3_FILTER=112,se.BQ_FILTER=113,se.SQ_STRING=114,se.DQ_STRING=115,se.BQ_STRING=116,se.DOC_ANNOTATION=117,se.ANNOTATION=118,se.AMPER=119,se.ARROW=120,se.FAT_ARROW=121,se.OPAREN=122,se.CPAREN=123,se.OBRACK=124,se.CBRACK=125,se.OCURLY=126,se.CCURLY=127,se.DOUBLECOLON=128,se.TRIPLECOLON=129,se.EXCLAM=130,se.COLON=131,se.COMMA=132,se.DOT=133,se.LT=134,se.GT=135,se.EQ=136,se.NE=137,se.LTE=138,se.GTE=139,se.PLUS=140,se.MINUS=141,se.STAR=142,se.STARSTAR=143,se.SLASH=144,se.BAR=145,se.SEMI=146,se.NOT_MATCH=147,se.MATCH=148,se.PERCENT=149,se.DOUBLE_QMARK=150,se.QMARK=151,se.LITERAL_TIMESTAMP=152,se.LITERAL_HOUR=153,se.LITERAL_DAY=154,se.LITERAL_QUARTER=155,se.LITERAL_MONTH=156,se.LITERAL_WEEK=157,se.LITERAL_YEAR=158,se.IDENTIFIER=159,se.PERCENT_LITERAL=160,se.NUMERIC_LITERAL=161,se.INTEGER_LITERAL=162,se.BLOCK_COMMENT=163,se.COMMENT_TO_EOL=164,se.WHITE_SPACE=165,se.SQL_BEGIN=166,se.UNWATED_CHARS_TRAILING_NUMBERS=167,se.UNEXPECTED_CHAR=168,se.OPEN_CODE=169,se.SQL_END=170,se.SQL_MODE=1,se.channelNames=["DEFAULT_TOKEN_CHANNEL","HIDDEN"],se.modeNames=["DEFAULT_MODE","SQL_MODE"],se.ruleNames=["SPACE_CHAR","ACCEPT","AGGREGATE","CALCULATE","CALCULATION","CONNECTION","DECLARE","DIMENSION","EXCEPT","EXTENDQ","GROUP_BY","HAVING","INDEX","INTERNAL","JOIN_CROSS","JOIN_ONE","JOIN_MANY","LIMIT","MEASURE","NEST","ORDER_BY","PARTITION_BY","PRIMARY_KEY","PRIVATE","PROJECT","PUBLIC","QUERY","RENAME","RUN","SAMPLE","SELECT","SOURCE","TOP","WHERE","VIEW","TIMEZONE","ALL","AND","AS","ASC","AVG","BOOLEAN","BY","CASE","CAST","CONDITION","COUNT","COMPOSE","DATE","DAY","DESC","DISTINCT","ELSE","END","EXCLUDE","EXTEND","FALSE","FILTER","FULL","FOR","FROM","HAS","HOUR","IMPORT","INCLUDE","INNER","IS","IN","INTERNAL_KW","JSON","LAST","LEFT","LIKE","MAX","MIN","MINUTE","MONTH","NOT","NOW","NULL","NUMBER","ON","OR","PICK","PRIVATE_KW","PUBLIC_KW","QUARTER","RIGHT","SECOND","STRING","SOURCE_KW","SUM","SQL","TABLE","THEN","THIS","TIMESTAMP","TO","TRUE","TURTLE","WEEK","WHEN","WITH","YEAR","UNGROUPED","SQ","BQ","DQ","SQ3","DQ3","BQ3","RAW_CHAR","RAW3_CHAR","F_PREFIX","S_PREFIX","HACKY_REGEX","RAW_SQ","RAW_DQ","SQ3_FILTER","SQ_FILTER","DQ3_FILTER","DQ_FILTER","BQ3_FILTER","BQ_FILTER","HEX","UNICODE","SAFE_NON_QUOTE","ESCAPED","STR_CHAR","SQ_STRING","DQ_STRING","BQ_STRING","F_TO_EOL","DOC_ANNOTATION","ANNOTATION","AMPER","ARROW","FAT_ARROW","OPAREN","CPAREN","OBRACK","CBRACK","OCURLY","CCURLY","DOUBLECOLON","TRIPLECOLON","EXCLAM","COLON","COMMA","DOT","LT","GT","EQ","NE","LTE","GTE","PLUS","MINUS","STAR","STARSTAR","SLASH","BAR","SEMI","NOT_MATCH","MATCH","PERCENT","DOUBLE_QMARK","QMARK","F_YEAR","F_DD","F_TZ","LITERAL_TIMESTAMP","LITERAL_HOUR","LITERAL_DAY","LITERAL_QUARTER","LITERAL_MONTH","LITERAL_WEEK","LITERAL_YEAR","IDENTIFIER","PERCENT_LITERAL","EXPONENT","NUMERIC_LITERAL","INTEGER_LITERAL","ID_CHAR","DIGIT","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","BLOCK_COMMENT","COMMENT_TO_EOL","WHITE_SPACE","SQL_BEGIN","UNWATED_CHARS_TRAILING_NUMBERS","UNEXPECTED_CHAR","SQL_CHAR","OPEN_CODE","SQL_END"],se._LITERAL_NAMES=[void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,"'&'","'->'","'=>'","'('","')'","'['","']'","'{'","'}'","'::'","':::'","'!'","':'","','","'.'","'<'","'>'","'='","'!='","'<='","'>='","'+'","'-'","'*'","'**'","'/'","'|'","';'","'!~'","'~'","'%'","'??'","'?'",void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,`'"""'`],se._SYMBOLIC_NAMES=[void 0,"ACCEPT","AGGREGATE","CALCULATE","CALCULATION","CONNECTION","DECLARE","DIMENSION","EXCEPT","EXTENDQ","GROUP_BY","HAVING","INDEX","INTERNAL","JOIN_CROSS","JOIN_ONE","JOIN_MANY","LIMIT","MEASURE","NEST","ORDER_BY","PARTITION_BY","PRIMARY_KEY","PRIVATE","PROJECT","PUBLIC","QUERY","RENAME","RUN","SAMPLE","SELECT","SOURCE","TOP","WHERE","VIEW","TIMEZONE","ALL","AND","AS","ASC","AVG","BOOLEAN","BY","CASE","CAST","CONDITION","COUNT","COMPOSE","DATE","DAY","DESC","DISTINCT","ELSE","END","EXCLUDE","EXTEND","FALSE","FILTER","FULL","FOR","FROM","HAS","HOUR","IMPORT","INCLUDE","INNER","IS","IN","INTERNAL_KW","JSON","LAST","LEFT","LIKE","MAX","MIN","MINUTE","MONTH","NOT","NOW","NULL","NUMBER","ON","OR","PICK","PRIVATE_KW","PUBLIC_KW","QUARTER","RIGHT","SECOND","STRING","SOURCE_KW","SUM","SQL","TABLE","THEN","THIS","TIMESTAMP","TO","TRUE","TURTLE","WEEK","WHEN","WITH","YEAR","UNGROUPED","HACKY_REGEX","RAW_SQ","RAW_DQ","SQ3_FILTER","SQ_FILTER","DQ3_FILTER","DQ_FILTER","BQ3_FILTER","BQ_FILTER","SQ_STRING","DQ_STRING","BQ_STRING","DOC_ANNOTATION","ANNOTATION","AMPER","ARROW","FAT_ARROW","OPAREN","CPAREN","OBRACK","CBRACK","OCURLY","CCURLY","DOUBLECOLON","TRIPLECOLON","EXCLAM","COLON","COMMA","DOT","LT","GT","EQ","NE","LTE","GTE","PLUS","MINUS","STAR","STARSTAR","SLASH","BAR","SEMI","NOT_MATCH","MATCH","PERCENT","DOUBLE_QMARK","QMARK","LITERAL_TIMESTAMP","LITERAL_HOUR","LITERAL_DAY","LITERAL_QUARTER","LITERAL_MONTH","LITERAL_WEEK","LITERAL_YEAR","IDENTIFIER","PERCENT_LITERAL","NUMERIC_LITERAL","INTEGER_LITERAL","BLOCK_COMMENT","COMMENT_TO_EOL","WHITE_SPACE","SQL_BEGIN","UNWATED_CHARS_TRAILING_NUMBERS","UNEXPECTED_CHAR","OPEN_CODE","SQL_END"],se.VOCABULARY=new rft.VocabularyImpl(se._LITERAL_NAMES,se._SYMBOLIC_NAMES,[]),se._serializedATNSegments=4,se._serializedATNSegment0=`줝쪺֍꾺体؇쉁¬ފ\b\b     \x07 \x07\b \b 
1163
1163
 
1164
1164
  \v \v\f \f\r \r             \x1B \x1B     ! !" "# #$ $% %& &' '( () )* *+ +, ,- -. ./ /0 01 12 23 34 45 56 67 78 89 9: :; ;< <= => >? ?@ @A AB BC CD DE EF FG GH HI IJ JK KL LM MN NO OP PQ QR RS ST TU UV VW WX XY YZ Z[ [\\ \\] ]^ ^_ _\` \`a ab bc cd de ef fg gh hi ij jk kl lm mn no op pq qr rs st tu uv vw wx xy yz z{ {| |} }~ ~ € € ‚ ‚ƒ ƒ„ „… …† †‡ ‡ˆ ˆ‰ ‰Š Š‹ ‹Œ Œ Ž Ž  ‘ ‘’ ’“ “” ”• •– –— —˜ ˜™ ™š š› ›œ œ ž žŸ Ÿ   ¡ ¡¢ ¢£ £¤ ¤¥ ¥¦ ¦§ §¨ ¨© ©ª ª« «¬ ¬­ ­® ®¯ ¯° °± ±² ²³ ³´ ´µ µ¶ ¶· ·¸ ¸¹ ¹º º» »¼ ¼½ ½¾ ¾¿ ¿À ÀÁ Á Âà ÃÄ ÄÅ ÅÆ ÆÇ ÇÈ ÈÉ ÉÊ ÊË ËÌ ÌÍ ÍÎ ÎÏ ÏÐ ÐÑ ÑÒ ÒÓ ÓÔ ÔÕ ÕÖ Ö× ×Ø ØÙ ÙÚ ÚÛ ÛÜ ÜÝ Ý\x07dž
1165
1165
  \flj\v\x07Ǘ
@@ -1277,7 +1277,7 @@ z\fzzֻ\vzzz{{{\x07{ׂ
1277
1277
  +ݩݪ\x07$ݪݲ
1278
1278
  ,ݫݬ\x07$ݬݭ\x07$ݭݮݮݲ
1279
1279
  ,ݯݰ\x07'ݰݲ
1280
- -ݱݦݱݨݱݩݱݫݱݯݲƷݳݵƶÛݴݳݵݸݶݷݶݴݷݹݸݶݹݺ\x07'ݺݻ\x07}ݻݼݼݽ\bÜݽƹݾހƶÛݿݾހރށނށݿނބރށބޅ\x07$ޅކ\x07$ކއ\x07$އވވމ\bÝމƻcLJǘǩǼȎȨȶɄɔɢɯɿʛʬʹˈ˔ˤ˸̷̩̋̈́͒ͫ̚͝͹·ΒΟΫλЉѕҞҦӞӭԳՄեժհշջց֋֐ֲֹ֣֭֗֜׃׈׏ימײ׷׹؁؃؋؍ؙؕ؝ڃڅښڜڞڡێې۪ۭۖۜۡۤ۲۷ܷ݃ݖݛݟݡݱݶށ\x07\x07\b\x07`,se._serializedATN=z0e.join([se._serializedATNSegment0,se._serializedATNSegment1,se._serializedATNSegment2,se._serializedATNSegment3],"");var w={},nft=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),rft=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),ift=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&nft(e,t,r);return rft(e,t),e};Object.defineProperty(w,"__esModule",{value:!0}),w.AccessLabelContext=w.DefIgnoreModel_stubContext=w.DefExploreAnnotationContext=w.DefExploreTimezoneContext=w.DefExploreQueryContext=w.DefExploreEditFieldContext=w.DefExploreRenameContext=w.DefExplorePrimaryKeyContext=w.DefExploreWhere_stubContext=w.DefJoin_stubContext=w.DefExploreMeasure_stubContext=w.DefExploreDimension_stubContext=w.ExploreStatementContext=w.ExplorePropertiesContext=w.SourceNameDefContext=w.ParameterNameDefContext=w.SourceParameterContext=w.LegalParamTypeContext=w.SourceParametersContext=w.SqExploreContext=w.SourceDefinitionContext=w.SourcePropertyListContext=w.QueryNameContext=w.QueryPropertiesContext=w.ConnectionIdContext=w.ExploreTableContext=w.SqlSourceContext=w.TurtleNameContext=w.RefineOperatorContext=w.TopLevelQueryDefContext=w.TopLevelQueryDefsContext=w.IgnoredModelAnnotationsContext=w.IgnoredObjectAnnotationsContext=w.DocAnnotationsContext=w.ImportURLContext=w.ImportItemContext=w.ImportSelectContext=w.ImportStatementContext=w.SqlInterpolationContext=w.SqlStringContext=w.RunStatementContext=w.IsDefineContext=w.TagsContext=w.TopLevelAnonQueryDefContext=w.Use_top_level_query_defsContext=w.DefineQueryContext=w.DefineSourceStatementContext=w.MalloyStatementContext=w.MalloyDocumentContext=w.MalloyParser=void 0,w.MatrixOperationContext=w.IsExploreContext=w.JoinListContext=w.QueryExtendStatementListContext=w.QueryExtendStatementContext=w.VArrowContext=w.VSegContext=w.VExprContext=w.SegRefineContext=w.SegParenContext=w.SegOpsContext=w.SegFieldContext=w.SegExprContext=w.IncludeFieldContext=w.IncludeListContext=w.IncludeExceptListItemContext=w.IncludeExceptListContext=w.AccessLabelPropContext=w.OrphanedAnnotationContext=w.IncludeItemContext=w.IncludeBlockContext=w.SQSQLContext=w.SQTableContext=w.SQIncludeContext=w.SQExtendedSourceContext=w.SQArrowContext=w.SQRefinedQueryContext=w.SQComposeContext=w.SQParensContext=w.SQIDContext=w.SqExprContext=w.SourceArgumentContext=w.ArgumentIdContext=w.SourceArgumentsContext=w.ModEitherContext=w.QueryExtendContext=w.DefJoinCrossContext=w.DefJoinManyContext=w.DefJoinOneContext=w.JoinStatementContext=w.DeclareStatementContext=w.JoinNameDefContext=w.FieldNameDefContext=w.FieldDefContext=w.DefListContext=w.ExploreRenameDefContext=w.RenameListContext=w.DefDimensionsContext=w.DefMeasuresContext=w.AccessModifierListContext=void 0,w.RawStringContext=w.ShortStringContext=w.StringContext=w.CompareOpContext=w.MalloyTypeContext=w.AggregateContext=w.SampleSpecContext=w.QueryAnnotationContext=w.TimezoneStatementContext=w.SampleStatementContext=w.IndexStatementContext=w.IndexFieldsContext=w.IndexElementContext=w.TopStatementContext=w.BySpecContext=w.LimitStatementContext=w.OrderBySpecContext=w.OrderingContext=w.OrderByStatementContext=w.PartitionByStatementContext=w.ProjectStatementContext=w.CalculateStatementContext=w.AggregateStatementContext=w.NestDefContext=w.NestEntryContext=w.NestedQueryListContext=w.NestStatementContext=w.QueryFieldEntryContext=w.QueryFieldListContext=w.GroupByStatementContext=w.QueryJoinStatementContext=w.QueryStatementContext=w.ExploreQueryDefContext=w.ExploreQueryNameDefContext=w.SubQueryDefListContext=w.HavingStatementContext=w.WhereStatementContext=w.FilterClauseListContext=w.FieldPropertyStatementContext=w.FieldPropertyLimitStatementContext=w.AggregateOrderByStatementContext=w.AggregateOrderBySpecContext=w.AggregateOrderingContext=w.FieldPropertiesContext=w.FilterStatementContext=w.JoinExpressionContext=w.JoinOnContext=w.JoinWithContext=w.JoinDefContext=w.JoinFromContext=void 0,w.ExprLogicalOrContext=w.ExprLogicalAndContext=w.ExprNotContext=w.ExprApplyContext=w.ExprWarnInContext=w.ExprNullCheckContext=w.ExprWarnLikeContext=w.ExprCompareContext=w.ExprOrTreeContext=w.ExprAndTreeContext=w.ExprForRangeContext=w.ExprRangeContext=w.ExprAddSubContext=w.ExprMulDivContext=w.ExprMinusContext=w.ExprSafeCastContext=w.ExprCastContext=w.ExprTimeTruncContext=w.ExprDurationContext=w.ExprFieldPropsContext=w.ExprLiteralRecordContext=w.ExprArrayLiteralContext=w.ExprLiteralContext=w.ExprFieldPathContext=w.FieldExprContext=w.MalloyOrSQLTypeContext=w.UngroupContext=w.TimeframeContext=w.IdContext=w.TableURIContext=w.TablePathContext=w.LiteralYearContext=w.LiteralQuarterContext=w.LiteralMonthContext=w.LiteralWeekContext=w.LiteralDayContext=w.LiteralHourContext=w.LiteralTimestampContext=w.DateLiteralContext=w.ExprNowContext=w.FilterString_stubContext=w.ExprRegexContext=w.ExprBoolContext=w.ExprNULLContext=w.ExprTimeContext=w.ExprNumberContext=w.Stub_rawStringContext=w.ExprStringContext=w.LiteralContext=w.NumericLiteralContext=void 0,w.ExperimentalStatementForTestingContext=w.DebugPartialContext=w.DebugExprContext=w.FilterStringContext=w.TickFilterStringContext=w.TripFilterStringContext=w.ConnectionNameContext=w.NameSQLBlockContext=w.SqlExploreNameRefContext=w.FieldNameContext=w.JoinNameContext=w.FieldPathContext=w.CollectionMemberContext=w.RefExprContext=w.TaggedRefContext=w.StarQualifiedContext=w.CollectionWildCardContext=w.FieldCollectionContext=w.FieldNameListContext=w.ArgumentListContext=w.RecordExprContext=w.RecordRefContext=w.RecordElementContext=w.RecordKeyContext=w.CaseWhenContext=w.CaseStatementContext=w.PickContext=w.PickStatementContext=w.FieldExprListContext=w.PartialAllowedFieldExprContext=w.PartialTestContext=w.PartialCompareContext=w.ExprUngroupContext=w.ExprCaseContext=w.ExprPickContext=w.ExprFuncContext=w.ExprAggFuncContext=w.ExprExprContext=w.ExprAggregateContext=w.ExprPathlessAggregateContext=w.ExprCoalesceContext=void 0;const en=uu(),sft=Sp(),oft=gc,tn=C3(),uft=Dp(),pe=ho(),aft=vp(),me=xo,qn=sn,lft=Fs,G0e=ift(Sn);class d extends uft.Parser{get vocabulary(){return d.VOCABULARY}get grammarFileName(){return"MalloyParser.g4"}get ruleNames(){return d.ruleNames}get serializedATN(){return d._serializedATN}createFailedPredicateException(e,r){return new oft.FailedPredicateException(this,e,r)}constructor(e){super(e),this._interp=new aft.ParserATNSimulator(d._ATN,this)}malloyDocument(){let e=new W0e(this._ctx,this.state);this.enterRule(e,0,d.RULE_malloyDocument);let r;try{this.enterOuterAlt(e,1);{for(this.state=316,this._errHandler.sync(this),r=this._input.LA(1);!(r&-32)&&1<<r&(1<<d.AGGREGATE|1<<d.CALCULATE|1<<d.DIMENSION|1<<d.EXCEPT|1<<d.GROUP_BY|1<<d.INTERNAL|1<<d.JOIN_CROSS|1<<d.JOIN_ONE|1<<d.JOIN_MANY|1<<d.MEASURE|1<<d.NEST|1<<d.PRIVATE|1<<d.PUBLIC|1<<d.QUERY|1<<d.RUN|1<<d.SELECT|1<<d.SOURCE)||!(r-34&-32)&&1<<r-34&(1<<d.VIEW-34|1<<d.ALL-34|1<<d.AVG-34|1<<d.CASE-34|1<<d.CAST-34|1<<d.COUNT-34|1<<d.COMPOSE-34|1<<d.DAY-34|1<<d.EXCLUDE-34|1<<d.FALSE-34|1<<d.HOUR-34|1<<d.IMPORT-34)||!(r-66&-32)&&1<<r-66&(1<<d.IS-66|1<<d.INTERNAL_KW-66|1<<d.MAX-66|1<<d.MIN-66|1<<d.MINUTE-66|1<<d.MONTH-66|1<<d.NOT-66|1<<d.NOW-66|1<<d.NULL-66|1<<d.PICK-66|1<<d.PRIVATE_KW-66|1<<d.PUBLIC_KW-66|1<<d.QUARTER-66|1<<d.SECOND-66|1<<d.SOURCE_KW-66|1<<d.SUM-66)||!(r-98&-32)&&1<<r-98&(1<<d.TRUE-98|1<<d.WEEK-98|1<<d.YEAR-98|1<<d.HACKY_REGEX-98|1<<d.RAW_SQ-98|1<<d.RAW_DQ-98|1<<d.SQ3_FILTER-98|1<<d.SQ_FILTER-98|1<<d.DQ3_FILTER-98|1<<d.DQ_FILTER-98|1<<d.BQ3_FILTER-98|1<<d.BQ_FILTER-98|1<<d.SQ_STRING-98|1<<d.DQ_STRING-98|1<<d.BQ_STRING-98|1<<d.DOC_ANNOTATION-98|1<<d.ANNOTATION-98|1<<d.OPAREN-98|1<<d.OBRACK-98|1<<d.OCURLY-98)||!(r-141&-32)&&1<<r-141&(1<<d.MINUS-141|1<<d.STAR-141|1<<d.SEMI-141|1<<d.LITERAL_TIMESTAMP-141|1<<d.LITERAL_HOUR-141|1<<d.LITERAL_DAY-141|1<<d.LITERAL_QUARTER-141|1<<d.LITERAL_MONTH-141|1<<d.LITERAL_WEEK-141|1<<d.LITERAL_YEAR-141|1<<d.IDENTIFIER-141|1<<d.NUMERIC_LITERAL-141|1<<d.INTEGER_LITERAL-141|1<<d.SQL_BEGIN-141);){switch(this.state=314,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,0,this._ctx)){case 1:this.state=312,this.malloyStatement();break;case 2:this.state=313,this.match(d.SEMI);break}this.state=318,this._errHandler.sync(this),r=this._input.LA(1)}this.state=319,this.match(d.EOF)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}malloyStatement(){let e=new DT(this._ctx,this.state);this.enterRule(e,2,d.RULE_malloyStatement);try{switch(this.state=328,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,2,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=321,this.defineSourceStatement();break;case 2:this.enterOuterAlt(e,2),this.state=322,this.defineQuery();break;case 3:this.enterOuterAlt(e,3),this.state=323,this.importStatement();break;case 4:this.enterOuterAlt(e,4),this.state=324,this.runStatement();break;case 5:this.enterOuterAlt(e,5),this.state=325,this.docAnnotations();break;case 6:this.enterOuterAlt(e,6),this.state=326,this.ignoredObjectAnnotations();break;case 7:this.enterOuterAlt(e,7),this.state=327,this.experimentalStatementForTesting();break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}defineSourceStatement(){let e=new Ak(this._ctx,this.state);this.enterRule(e,4,d.RULE_defineSourceStatement);try{this.enterOuterAlt(e,1),this.state=330,this.tags(),this.state=331,this.match(d.SOURCE),this.state=332,this.sourcePropertyList()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}defineQuery(){let e=new OT(this._ctx,this.state);this.enterRule(e,6,d.RULE_defineQuery);try{e=new V0e(e),this.enterOuterAlt(e,1),this.state=334,this.topLevelQueryDefs()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}topLevelAnonQueryDef(){let e=new _k(this._ctx,this.state);this.enterRule(e,8,d.RULE_topLevelAnonQueryDef);try{this.enterOuterAlt(e,1),this.state=336,this.tags(),this.state=337,this.sqExpr(0)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}tags(){let e=new Yt(this._ctx,this.state);this.enterRule(e,10,d.RULE_tags);let r;try{for(this.enterOuterAlt(e,1),this.state=342,this._errHandler.sync(this),r=this._input.LA(1);r===d.ANNOTATION;)this.state=339,this.match(d.ANNOTATION),this.state=344,this._errHandler.sync(this),r=this._input.LA(1)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}isDefine(){let e=new e0(this._ctx,this.state);this.enterRule(e,12,d.RULE_isDefine);try{this.enterOuterAlt(e,1),this.state=345,e._beforeIs=this.tags(),this.state=346,this.match(d.IS),this.state=347,e._afterIs=this.tags()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}runStatement(){let e=new vk(this._ctx,this.state);this.enterRule(e,14,d.RULE_runStatement);try{this.enterOuterAlt(e,1),this.state=349,this.tags(),this.state=350,this.match(d.RUN),this.state=351,this.topLevelAnonQueryDef()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sqlString(){let e=new FT(this._ctx,this.state);this.enterRule(e,16,d.RULE_sqlString);let r;try{this.enterOuterAlt(e,1);{for(this.state=353,this.match(d.SQL_BEGIN),this.state=357,this._errHandler.sync(this),r=this._input.LA(1);r===d.OPEN_CODE;)this.state=354,this.sqlInterpolation(),this.state=359,this._errHandler.sync(this),r=this._input.LA(1);this.state=360,this.match(d.SQL_END)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}sqlInterpolation(){let e=new wT(this._ctx,this.state);this.enterRule(e,18,d.RULE_sqlInterpolation);try{this.enterOuterAlt(e,1),this.state=362,this.match(d.OPEN_CODE),this.state=363,this.sqExpr(0),this.state=364,this.match(d.CCURLY)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}importStatement(){let e=new Ck(this._ctx,this.state);this.enterRule(e,20,d.RULE_importStatement);let r;try{this.enterOuterAlt(e,1),this.state=366,this.match(d.IMPORT),this.state=368,this._errHandler.sync(this),r=this._input.LA(1),r===d.OCURLY&&(this.state=367,this.importSelect()),this.state=370,this.importURL()}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}importSelect(){let e=new Sk(this._ctx,this.state);this.enterRule(e,22,d.RULE_importSelect);let r;try{this.enterOuterAlt(e,1);{for(this.state=372,this.match(d.OCURLY),this.state=373,this.importItem(),this.state=378,this._errHandler.sync(this),r=this._input.LA(1);r===d.COMMA;)this.state=374,this.match(d.COMMA),this.state=375,this.importItem(),this.state=380,this._errHandler.sync(this),r=this._input.LA(1);this.state=381,this.match(d.CCURLY),this.state=382,this.match(d.FROM)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}importItem(){let e=new NT(this._ctx,this.state);this.enterRule(e,24,d.RULE_importItem);let r;try{this.enterOuterAlt(e,1),this.state=384,this.id(),this.state=387,this._errHandler.sync(this),r=this._input.LA(1),r===d.IS&&(this.state=385,this.match(d.IS),this.state=386,this.id())}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}importURL(){let e=new bk(this._ctx,this.state);this.enterRule(e,26,d.RULE_importURL);try{this.enterOuterAlt(e,1),this.state=389,this.string()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}docAnnotations(){let e=new Tk(this._ctx,this.state);this.enterRule(e,28,d.RULE_docAnnotations);try{let r;this.enterOuterAlt(e,1);{this.state=392,this._errHandler.sync(this),r=1;do{switch(r){case 1:this.state=391,this.match(d.DOC_ANNOTATION);break;default:throw new tn.NoViableAltException(this)}this.state=394,this._errHandler.sync(this),r=this.interpreter.adaptivePredict(this._input,8,this._ctx)}while(r!==2&&r!==en.ATN.INVALID_ALT_NUMBER)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}ignoredObjectAnnotations(){let e=new Rk(this._ctx,this.state);this.enterRule(e,30,d.RULE_ignoredObjectAnnotations);try{let r;this.enterOuterAlt(e,1);{this.state=397,this._errHandler.sync(this),r=1;do{switch(r){case 1:this.state=396,this.match(d.ANNOTATION);break;default:throw new tn.NoViableAltException(this)}this.state=399,this._errHandler.sync(this),r=this.interpreter.adaptivePredict(this._input,9,this._ctx)}while(r!==2&&r!==en.ATN.INVALID_ALT_NUMBER)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}ignoredModelAnnotations(){let e=new LT(this._ctx,this.state);this.enterRule(e,32,d.RULE_ignoredModelAnnotations);try{let r;this.enterOuterAlt(e,1);{this.state=402,this._errHandler.sync(this),r=1;do{switch(r){case 1:this.state=401,this.match(d.DOC_ANNOTATION);break;default:throw new tn.NoViableAltException(this)}this.state=404,this._errHandler.sync(this),r=this.interpreter.adaptivePredict(this._input,10,this._ctx)}while(r!==2&&r!==en.ATN.INVALID_ALT_NUMBER)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}topLevelQueryDefs(){let e=new Dk(this._ctx,this.state);this.enterRule(e,34,d.RULE_topLevelQueryDefs);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=406,this.tags(),this.state=407,this.match(d.QUERY),this.state=408,this.topLevelQueryDef(),this.state=415,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,12,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=410,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=409,this.match(d.COMMA)),this.state=412,this.topLevelQueryDef()),this.state=417,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,12,this._ctx);this.state=419,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=418,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}topLevelQueryDef(){let e=new IT(this._ctx,this.state);this.enterRule(e,36,d.RULE_topLevelQueryDef);try{this.enterOuterAlt(e,1),this.state=421,this.tags(),this.state=422,this.queryName(),this.state=423,this.isDefine(),this.state=424,this.sqExpr(0)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}refineOperator(){let e=new Y0e(this._ctx,this.state);this.enterRule(e,38,d.RULE_refineOperator);try{this.enterOuterAlt(e,1),this.state=426,this.match(d.PLUS)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}turtleName(){let e=new K0e(this._ctx,this.state);this.enterRule(e,40,d.RULE_turtleName);try{this.enterOuterAlt(e,1),this.state=428,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sqlSource(){let e=new Ok(this._ctx,this.state);this.enterRule(e,42,d.RULE_sqlSource);try{this.enterOuterAlt(e,1);{switch(this.state=430,this.connectionId(),this.state=431,this.match(d.DOT),this.state=432,this.match(d.SQL),this.state=433,this.match(d.OPAREN),this.state=436,this._errHandler.sync(this),this._input.LA(1)){case d.SQL_BEGIN:this.state=434,this.sqlString();break;case d.SQ_STRING:case d.DQ_STRING:this.state=435,this.shortString();break;default:throw new tn.NoViableAltException(this)}this.state=438,this.match(d.CPAREN)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}exploreTable(){let e=new Fk(this._ctx,this.state);this.enterRule(e,44,d.RULE_exploreTable);try{this.enterOuterAlt(e,1),this.state=440,this.connectionId(),this.state=441,this.match(d.DOT),this.state=442,this.match(d.TABLE),this.state=443,this.match(d.OPAREN),this.state=444,this.tablePath(),this.state=445,this.match(d.CPAREN)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}connectionId(){let e=new BT(this._ctx,this.state);this.enterRule(e,46,d.RULE_connectionId);try{this.enterOuterAlt(e,1),this.state=447,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}queryProperties(){let e=new wk(this._ctx,this.state);this.enterRule(e,48,d.RULE_queryProperties);let r;try{this.enterOuterAlt(e,1);{for(this.state=449,this.match(d.OCURLY),this.state=454,this._errHandler.sync(this),r=this._input.LA(1);!(r&-32)&&1<<r&(1<<d.AGGREGATE|1<<d.CALCULATE|1<<d.DECLARE|1<<d.DIMENSION|1<<d.EXCEPT|1<<d.EXTENDQ|1<<d.GROUP_BY|1<<d.HAVING|1<<d.INDEX|1<<d.INTERNAL|1<<d.JOIN_CROSS|1<<d.JOIN_ONE|1<<d.JOIN_MANY|1<<d.LIMIT|1<<d.MEASURE|1<<d.NEST|1<<d.ORDER_BY|1<<d.PRIVATE|1<<d.PUBLIC|1<<d.QUERY|1<<d.RUN|1<<d.SAMPLE|1<<d.SELECT|1<<d.SOURCE)||!(r-32&-32)&&1<<r-32&(1<<d.TOP-32|1<<d.WHERE-32|1<<d.VIEW-32|1<<d.TIMEZONE-32|1<<d.ALL-32|1<<d.AVG-32|1<<d.CASE-32|1<<d.CAST-32|1<<d.COUNT-32|1<<d.COMPOSE-32|1<<d.DAY-32|1<<d.EXCLUDE-32|1<<d.FALSE-32|1<<d.HOUR-32)||!(r-66&-32)&&1<<r-66&(1<<d.IS-66|1<<d.INTERNAL_KW-66|1<<d.MAX-66|1<<d.MIN-66|1<<d.MINUTE-66|1<<d.MONTH-66|1<<d.NOT-66|1<<d.NOW-66|1<<d.NULL-66|1<<d.PICK-66|1<<d.PRIVATE_KW-66|1<<d.PUBLIC_KW-66|1<<d.QUARTER-66|1<<d.SECOND-66|1<<d.SOURCE_KW-66|1<<d.SUM-66)||!(r-98&-32)&&1<<r-98&(1<<d.TRUE-98|1<<d.WEEK-98|1<<d.YEAR-98|1<<d.HACKY_REGEX-98|1<<d.RAW_SQ-98|1<<d.RAW_DQ-98|1<<d.SQ3_FILTER-98|1<<d.SQ_FILTER-98|1<<d.DQ3_FILTER-98|1<<d.DQ_FILTER-98|1<<d.BQ3_FILTER-98|1<<d.BQ_FILTER-98|1<<d.SQ_STRING-98|1<<d.DQ_STRING-98|1<<d.BQ_STRING-98|1<<d.DOC_ANNOTATION-98|1<<d.ANNOTATION-98|1<<d.OPAREN-98|1<<d.OBRACK-98|1<<d.OCURLY-98)||!(r-141&-32)&&1<<r-141&(1<<d.MINUS-141|1<<d.STAR-141|1<<d.SEMI-141|1<<d.LITERAL_TIMESTAMP-141|1<<d.LITERAL_HOUR-141|1<<d.LITERAL_DAY-141|1<<d.LITERAL_QUARTER-141|1<<d.LITERAL_MONTH-141|1<<d.LITERAL_WEEK-141|1<<d.LITERAL_YEAR-141|1<<d.IDENTIFIER-141|1<<d.NUMERIC_LITERAL-141|1<<d.INTEGER_LITERAL-141|1<<d.SQL_BEGIN-141);){switch(this.state=452,this._errHandler.sync(this),this._input.LA(1)){case d.AGGREGATE:case d.CALCULATE:case d.DECLARE:case d.DIMENSION:case d.EXCEPT:case d.EXTENDQ:case d.GROUP_BY:case d.HAVING:case d.INDEX:case d.INTERNAL:case d.JOIN_CROSS:case d.JOIN_ONE:case d.JOIN_MANY:case d.LIMIT:case d.MEASURE:case d.NEST:case d.ORDER_BY:case d.PRIVATE:case d.PUBLIC:case d.QUERY:case d.RUN:case d.SAMPLE:case d.SELECT:case d.SOURCE:case d.TOP:case d.WHERE:case d.VIEW:case d.TIMEZONE:case d.ALL:case d.AVG:case d.CASE:case d.CAST:case d.COUNT:case d.COMPOSE:case d.DAY:case d.EXCLUDE:case d.FALSE:case d.HOUR:case d.IS:case d.INTERNAL_KW:case d.MAX:case d.MIN:case d.MINUTE:case d.MONTH:case d.NOT:case d.NOW:case d.NULL:case d.PICK:case d.PRIVATE_KW:case d.PUBLIC_KW:case d.QUARTER:case d.SECOND:case d.SOURCE_KW:case d.SUM:case d.TRUE:case d.WEEK:case d.YEAR:case d.HACKY_REGEX:case d.RAW_SQ:case d.RAW_DQ:case d.SQ3_FILTER:case d.SQ_FILTER:case d.DQ3_FILTER:case d.DQ_FILTER:case d.BQ3_FILTER:case d.BQ_FILTER:case d.SQ_STRING:case d.DQ_STRING:case d.BQ_STRING:case d.DOC_ANNOTATION:case d.ANNOTATION:case d.OPAREN:case d.OBRACK:case d.OCURLY:case d.MINUS:case d.STAR:case d.LITERAL_TIMESTAMP:case d.LITERAL_HOUR:case d.LITERAL_DAY:case d.LITERAL_QUARTER:case d.LITERAL_MONTH:case d.LITERAL_WEEK:case d.LITERAL_YEAR:case d.IDENTIFIER:case d.NUMERIC_LITERAL:case d.INTEGER_LITERAL:case d.SQL_BEGIN:this.state=450,this.queryStatement();break;case d.SEMI:this.state=451,this.match(d.SEMI);break;default:throw new tn.NoViableAltException(this)}this.state=456,this._errHandler.sync(this),r=this._input.LA(1)}this.state=457,this.match(d.CCURLY)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}queryName(){let e=new $T(this._ctx,this.state);this.enterRule(e,50,d.RULE_queryName);try{this.enterOuterAlt(e,1),this.state=459,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sourcePropertyList(){let e=new Nk(this._ctx,this.state);this.enterRule(e,52,d.RULE_sourcePropertyList);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=461,this.sourceDefinition(),this.state=468,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,18,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=463,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=462,this.match(d.COMMA)),this.state=465,this.sourceDefinition()),this.state=470,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,18,this._ctx);this.state=472,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=471,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}sourceDefinition(){let e=new kT(this._ctx,this.state);this.enterRule(e,54,d.RULE_sourceDefinition);try{this.enterOuterAlt(e,1);{switch(this.state=474,this.tags(),this.state=475,this.sourceNameDef(),this.state=477,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,20,this._ctx)){case 1:this.state=476,this.sourceParameters();break}this.state=479,this.isDefine(),this.state=480,this.sqExplore()}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sqExplore(){let e=new Lk(this._ctx,this.state);this.enterRule(e,56,d.RULE_sqExplore);try{this.enterOuterAlt(e,1),this.state=482,this.sqExpr(0)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sourceParameters(){let e=new Ik(this._ctx,this.state);this.enterRule(e,58,d.RULE_sourceParameters);let r;try{switch(this.state=497,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,22,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=484,this.match(d.OPAREN),this.state=485,this.match(d.CPAREN);break;case 2:this.enterOuterAlt(e,2);{for(this.state=486,this.match(d.OPAREN),this.state=487,this.sourceParameter(),this.state=492,this._errHandler.sync(this),r=this._input.LA(1);r===d.COMMA;)this.state=488,this.match(d.COMMA),this.state=489,this.sourceParameter(),this.state=494,this._errHandler.sync(this),r=this._input.LA(1);this.state=495,this.match(d.CPAREN)}break}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}legalParamType(){let e=new Bk(this._ctx,this.state);this.enterRule(e,60,d.RULE_legalParamType);try{switch(this.state=505,this._errHandler.sync(this),this._input.LA(1)){case d.BOOLEAN:case d.DATE:case d.NUMBER:case d.STRING:case d.TIMESTAMP:this.enterOuterAlt(e,1),this.state=499,this.malloyType();break;case d.FILTER:this.enterOuterAlt(e,2),this.state=500,this.match(d.FILTER),this.state=501,this.match(d.LT),this.state=502,this.malloyType(),this.state=503,this.match(d.GT);break;default:throw new tn.NoViableAltException(this)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sourceParameter(){let e=new MT(this._ctx,this.state);this.enterRule(e,62,d.RULE_sourceParameter);let r;try{this.enterOuterAlt(e,1),this.state=507,this.parameterNameDef(),this.state=510,this._errHandler.sync(this),r=this._input.LA(1),r===d.DOUBLECOLON&&(this.state=508,this.match(d.DOUBLECOLON),this.state=509,this.legalParamType()),this.state=514,this._errHandler.sync(this),r=this._input.LA(1),r===d.IS&&(this.state=512,this.match(d.IS),this.state=513,this.fieldExpr(0))}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}parameterNameDef(){let e=new $k(this._ctx,this.state);this.enterRule(e,64,d.RULE_parameterNameDef);try{this.enterOuterAlt(e,1),this.state=516,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sourceNameDef(){let e=new kk(this._ctx,this.state);this.enterRule(e,66,d.RULE_sourceNameDef);try{this.enterOuterAlt(e,1),this.state=518,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}exploreProperties(){let e=new Mk(this._ctx,this.state);this.enterRule(e,68,d.RULE_exploreProperties);let r;try{this.enterOuterAlt(e,1);{for(this.state=520,this.match(d.OCURLY),this.state=525,this._errHandler.sync(this),r=this._input.LA(1);!(r&-32)&&1<<r&(1<<d.ACCEPT|1<<d.AGGREGATE|1<<d.CALCULATE|1<<d.DIMENSION|1<<d.EXCEPT|1<<d.GROUP_BY|1<<d.INTERNAL|1<<d.JOIN_CROSS|1<<d.JOIN_ONE|1<<d.JOIN_MANY|1<<d.MEASURE|1<<d.NEST|1<<d.PRIMARY_KEY|1<<d.PRIVATE|1<<d.PUBLIC|1<<d.QUERY|1<<d.RENAME|1<<d.RUN|1<<d.SELECT|1<<d.SOURCE)||!(r-33&-32)&&1<<r-33&(1<<d.WHERE-33|1<<d.VIEW-33|1<<d.TIMEZONE-33|1<<d.ALL-33|1<<d.AVG-33|1<<d.CASE-33|1<<d.CAST-33|1<<d.COUNT-33|1<<d.COMPOSE-33|1<<d.DAY-33|1<<d.EXCLUDE-33|1<<d.FALSE-33|1<<d.HOUR-33)||!(r-66&-32)&&1<<r-66&(1<<d.IS-66|1<<d.INTERNAL_KW-66|1<<d.MAX-66|1<<d.MIN-66|1<<d.MINUTE-66|1<<d.MONTH-66|1<<d.NOT-66|1<<d.NOW-66|1<<d.NULL-66|1<<d.PICK-66|1<<d.PRIVATE_KW-66|1<<d.PUBLIC_KW-66|1<<d.QUARTER-66|1<<d.SECOND-66|1<<d.SOURCE_KW-66|1<<d.SUM-66)||!(r-98&-32)&&1<<r-98&(1<<d.TRUE-98|1<<d.WEEK-98|1<<d.YEAR-98|1<<d.HACKY_REGEX-98|1<<d.RAW_SQ-98|1<<d.RAW_DQ-98|1<<d.SQ3_FILTER-98|1<<d.SQ_FILTER-98|1<<d.DQ3_FILTER-98|1<<d.DQ_FILTER-98|1<<d.BQ3_FILTER-98|1<<d.BQ_FILTER-98|1<<d.SQ_STRING-98|1<<d.DQ_STRING-98|1<<d.BQ_STRING-98|1<<d.DOC_ANNOTATION-98|1<<d.ANNOTATION-98|1<<d.OPAREN-98|1<<d.OBRACK-98|1<<d.OCURLY-98)||!(r-141&-32)&&1<<r-141&(1<<d.MINUS-141|1<<d.STAR-141|1<<d.SEMI-141|1<<d.LITERAL_TIMESTAMP-141|1<<d.LITERAL_HOUR-141|1<<d.LITERAL_DAY-141|1<<d.LITERAL_QUARTER-141|1<<d.LITERAL_MONTH-141|1<<d.LITERAL_WEEK-141|1<<d.LITERAL_YEAR-141|1<<d.IDENTIFIER-141|1<<d.NUMERIC_LITERAL-141|1<<d.INTEGER_LITERAL-141|1<<d.SQL_BEGIN-141);){switch(this.state=523,this._errHandler.sync(this),this._input.LA(1)){case d.ACCEPT:case d.AGGREGATE:case d.CALCULATE:case d.DIMENSION:case d.EXCEPT:case d.GROUP_BY:case d.INTERNAL:case d.JOIN_CROSS:case d.JOIN_ONE:case d.JOIN_MANY:case d.MEASURE:case d.NEST:case d.PRIMARY_KEY:case d.PRIVATE:case d.PUBLIC:case d.QUERY:case d.RENAME:case d.RUN:case d.SELECT:case d.SOURCE:case d.WHERE:case d.VIEW:case d.TIMEZONE:case d.ALL:case d.AVG:case d.CASE:case d.CAST:case d.COUNT:case d.COMPOSE:case d.DAY:case d.EXCLUDE:case d.FALSE:case d.HOUR:case d.IS:case d.INTERNAL_KW:case d.MAX:case d.MIN:case d.MINUTE:case d.MONTH:case d.NOT:case d.NOW:case d.NULL:case d.PICK:case d.PRIVATE_KW:case d.PUBLIC_KW:case d.QUARTER:case d.SECOND:case d.SOURCE_KW:case d.SUM:case d.TRUE:case d.WEEK:case d.YEAR:case d.HACKY_REGEX:case d.RAW_SQ:case d.RAW_DQ:case d.SQ3_FILTER:case d.SQ_FILTER:case d.DQ3_FILTER:case d.DQ_FILTER:case d.BQ3_FILTER:case d.BQ_FILTER:case d.SQ_STRING:case d.DQ_STRING:case d.BQ_STRING:case d.DOC_ANNOTATION:case d.ANNOTATION:case d.OPAREN:case d.OBRACK:case d.OCURLY:case d.MINUS:case d.STAR:case d.LITERAL_TIMESTAMP:case d.LITERAL_HOUR:case d.LITERAL_DAY:case d.LITERAL_QUARTER:case d.LITERAL_MONTH:case d.LITERAL_WEEK:case d.LITERAL_YEAR:case d.IDENTIFIER:case d.NUMERIC_LITERAL:case d.INTEGER_LITERAL:case d.SQL_BEGIN:this.state=521,this.exploreStatement();break;case d.SEMI:this.state=522,this.match(d.SEMI);break;default:throw new tn.NoViableAltException(this)}this.state=527,this._errHandler.sync(this),r=this._input.LA(1)}this.state=528,this.match(d.CCURLY)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}exploreStatement(){let e=new qi(this._ctx,this.state);this.enterRule(e,70,d.RULE_exploreStatement);let r;try{let i;switch(this.state=557,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,31,this._ctx)){case 1:e=new J0e(e),this.enterOuterAlt(e,1),this.state=530,this.defDimensions();break;case 2:e=new X0e(e),this.enterOuterAlt(e,2),this.state=531,this.defMeasures();break;case 3:e=new Z0e(e),this.enterOuterAlt(e,3),this.state=532,this.joinStatement();break;case 4:e=new ece(e),this.enterOuterAlt(e,4),this.state=533,this.whereStatement();break;case 5:e=new tce(e),this.enterOuterAlt(e,5),this.state=534,this.match(d.PRIMARY_KEY),this.state=535,this.fieldName();break;case 6:e=new nce(e),this.enterOuterAlt(e,6),this.state=537,this._errHandler.sync(this),r=this._input.LA(1),!(r-68&-32)&&1<<r-68&(1<<d.INTERNAL_KW-68|1<<d.PRIVATE_KW-68|1<<d.PUBLIC_KW-68)&&(this.state=536,this.accessLabel()),this.state=539,this.match(d.RENAME),this.state=540,this.renameList();break;case 7:e=new rce(e),this.enterOuterAlt(e,7),this.state=541,r=this._input.LA(1),r===d.ACCEPT||r===d.EXCEPT?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this),this.state=542,this.fieldNameList();break;case 8:e=new ice(e),this.enterOuterAlt(e,8),this.state=543,this.tags(),this.state=545,this._errHandler.sync(this),r=this._input.LA(1),!(r-68&-32)&&1<<r-68&(1<<d.INTERNAL_KW-68|1<<d.PRIVATE_KW-68|1<<d.PUBLIC_KW-68)&&(this.state=544,this.accessLabel()),this.state=547,this.match(d.VIEW),this.state=548,this.subQueryDefList();break;case 9:e=new sce(e),this.enterOuterAlt(e,9),this.state=550,this.timezoneStatement();break;case 10:e=new oce(e),this.enterOuterAlt(e,10);{this.state=552,this._errHandler.sync(this),i=1;do{switch(i){case 1:this.state=551,this.match(d.ANNOTATION);break;default:throw new tn.NoViableAltException(this)}this.state=554,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,30,this._ctx)}while(i!==2&&i!==en.ATN.INVALID_ALT_NUMBER)}break;case 11:e=new uce(e),this.enterOuterAlt(e,11),this.state=556,this.ignoredModelAnnotations();break}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}accessLabel(){let e=new Oa(this._ctx,this.state);this.enterRule(e,72,d.RULE_accessLabel);let r;try{this.enterOuterAlt(e,1),this.state=559,r=this._input.LA(1),!(r-68&-32)&&1<<r-68&(1<<d.INTERNAL_KW-68|1<<d.PRIVATE_KW-68|1<<d.PUBLIC_KW-68)?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}accessModifierList(){let e=new ace(this._ctx,this.state);this.enterRule(e,74,d.RULE_accessModifierList);let r;try{switch(this.state=566,this._errHandler.sync(this),this._input.LA(1)){case d.BQ_STRING:case d.IDENTIFIER:this.enterOuterAlt(e,1),this.state=561,this.fieldNameList();break;case d.STAR:this.enterOuterAlt(e,2),this.state=562,this.match(d.STAR),this.state=564,this._errHandler.sync(this),r=this._input.LA(1),r===d.OCURLY&&(this.state=563,this.starQualified());break;default:throw new tn.NoViableAltException(this)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}defMeasures(){let e=new PT(this._ctx,this.state);this.enterRule(e,76,d.RULE_defMeasures);let r;try{this.enterOuterAlt(e,1),this.state=568,this.tags(),this.state=570,this._errHandler.sync(this),r=this._input.LA(1),!(r-68&-32)&&1<<r-68&(1<<d.INTERNAL_KW-68|1<<d.PRIVATE_KW-68|1<<d.PUBLIC_KW-68)&&(this.state=569,this.accessLabel()),this.state=572,this.match(d.MEASURE),this.state=573,this.defList()}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}defDimensions(){let e=new UT(this._ctx,this.state);this.enterRule(e,78,d.RULE_defDimensions);let r;try{this.enterOuterAlt(e,1),this.state=575,this.tags(),this.state=577,this._errHandler.sync(this),r=this._input.LA(1),!(r-68&-32)&&1<<r-68&(1<<d.INTERNAL_KW-68|1<<d.PRIVATE_KW-68|1<<d.PUBLIC_KW-68)&&(this.state=576,this.accessLabel()),this.state=579,this.match(d.DIMENSION),this.state=580,this.defList()}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}renameList(){let e=new Pk(this._ctx,this.state);this.enterRule(e,80,d.RULE_renameList);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=582,this.exploreRenameDef(),this.state=589,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,37,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=584,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=583,this.match(d.COMMA)),this.state=586,this.exploreRenameDef()),this.state=591,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,37,this._ctx);this.state=593,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=592,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}exploreRenameDef(){let e=new jT(this._ctx,this.state);this.enterRule(e,82,d.RULE_exploreRenameDef);try{this.enterOuterAlt(e,1),this.state=595,this.fieldName(),this.state=596,this.isDefine(),this.state=597,this.fieldName()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}defList(){let e=new lE(this._ctx,this.state);this.enterRule(e,84,d.RULE_defList);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=599,this.fieldDef(),this.state=606,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,40,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=601,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=600,this.match(d.COMMA)),this.state=603,this.fieldDef()),this.state=608,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,40,this._ctx);this.state=610,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=609,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}fieldDef(){let e=new v2(this._ctx,this.state);this.enterRule(e,86,d.RULE_fieldDef);try{this.enterOuterAlt(e,1),this.state=612,this.tags(),this.state=613,this.fieldNameDef(),this.state=614,this.isDefine(),this.state=615,this.fieldExpr(0)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}fieldNameDef(){let e=new Uk(this._ctx,this.state);this.enterRule(e,88,d.RULE_fieldNameDef);try{this.enterOuterAlt(e,1),this.state=617,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}joinNameDef(){let e=new jk(this._ctx,this.state);this.enterRule(e,90,d.RULE_joinNameDef);try{this.enterOuterAlt(e,1),this.state=619,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}declareStatement(){let e=new qT(this._ctx,this.state);this.enterRule(e,92,d.RULE_declareStatement);try{this.enterOuterAlt(e,1);{switch(this.state=621,this.match(d.DECLARE),this.state=623,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,42,this._ctx)){case 1:this.state=622,this.accessLabel();break}this.state=625,this.defList()}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}joinStatement(){let e=new t0(this._ctx,this.state);this.enterRule(e,94,d.RULE_joinStatement);let r;try{switch(this.state=648,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,46,this._ctx)){case 1:e=new lce(e),this.enterOuterAlt(e,1),this.state=627,this.tags(),this.state=629,this._errHandler.sync(this),r=this._input.LA(1),!(r-68&-32)&&1<<r-68&(1<<d.INTERNAL_KW-68|1<<d.PRIVATE_KW-68|1<<d.PUBLIC_KW-68)&&(this.state=628,this.accessLabel()),this.state=631,this.match(d.JOIN_ONE),this.state=632,this.joinList();break;case 2:e=new cce(e),this.enterOuterAlt(e,2),this.state=634,this.tags(),this.state=636,this._errHandler.sync(this),r=this._input.LA(1),!(r-68&-32)&&1<<r-68&(1<<d.INTERNAL_KW-68|1<<d.PRIVATE_KW-68|1<<d.PUBLIC_KW-68)&&(this.state=635,this.accessLabel()),this.state=638,this.match(d.JOIN_MANY),this.state=639,this.joinList();break;case 3:e=new fce(e),this.enterOuterAlt(e,3),this.state=641,this.tags(),this.state=643,this._errHandler.sync(this),r=this._input.LA(1),!(r-68&-32)&&1<<r-68&(1<<d.INTERNAL_KW-68|1<<d.PRIVATE_KW-68|1<<d.PUBLIC_KW-68)&&(this.state=642,this.accessLabel()),this.state=645,this.match(d.JOIN_CROSS),this.state=646,this.joinList();break}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}queryExtend(){let e=new qk(this._ctx,this.state);this.enterRule(e,96,d.RULE_queryExtend);try{this.enterOuterAlt(e,1),this.state=650,this.match(d.EXTENDQ),this.state=651,this.queryExtendStatementList()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}modEither(){let e=new xce(this._ctx,this.state);this.enterRule(e,98,d.RULE_modEither);try{switch(this.state=656,this._errHandler.sync(this),this._input.LA(1)){case d.AGGREGATE:case d.CALCULATE:case d.DIMENSION:case d.EXCEPT:case d.GROUP_BY:case d.INTERNAL:case d.JOIN_CROSS:case d.JOIN_ONE:case d.JOIN_MANY:case d.MEASURE:case d.NEST:case d.PRIVATE:case d.PUBLIC:case d.QUERY:case d.RUN:case d.SELECT:case d.SOURCE:case d.VIEW:case d.ALL:case d.AVG:case d.CASE:case d.CAST:case d.COUNT:case d.COMPOSE:case d.DAY:case d.EXCLUDE:case d.FALSE:case d.HOUR:case d.IS:case d.INTERNAL_KW:case d.MAX:case d.MIN:case d.MINUTE:case d.MONTH:case d.NOT:case d.NOW:case d.NULL:case d.PICK:case d.PRIVATE_KW:case d.PUBLIC_KW:case d.QUARTER:case d.SECOND:case d.SOURCE_KW:case d.SUM:case d.TRUE:case d.WEEK:case d.YEAR:case d.HACKY_REGEX:case d.RAW_SQ:case d.RAW_DQ:case d.SQ3_FILTER:case d.SQ_FILTER:case d.DQ3_FILTER:case d.DQ_FILTER:case d.BQ3_FILTER:case d.BQ_FILTER:case d.SQ_STRING:case d.DQ_STRING:case d.BQ_STRING:case d.ANNOTATION:case d.OPAREN:case d.OBRACK:case d.OCURLY:case d.MINUS:case d.STAR:case d.LITERAL_TIMESTAMP:case d.LITERAL_HOUR:case d.LITERAL_DAY:case d.LITERAL_QUARTER:case d.LITERAL_MONTH:case d.LITERAL_WEEK:case d.LITERAL_YEAR:case d.IDENTIFIER:case d.NUMERIC_LITERAL:case d.INTEGER_LITERAL:case d.SQL_BEGIN:this.enterOuterAlt(e,1),this.state=653,this.joinStatement();break;case d.WHERE:this.enterOuterAlt(e,2),this.state=654,this.whereStatement();break;case d.DECLARE:this.enterOuterAlt(e,3),this.state=655,this.declareStatement();break;default:throw new tn.NoViableAltException(this)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sourceArguments(){let e=new HT(this._ctx,this.state);this.enterRule(e,100,d.RULE_sourceArguments);let r;try{switch(this.state=671,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,49,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=658,this.match(d.OPAREN),this.state=659,this.match(d.CPAREN);break;case 2:this.enterOuterAlt(e,2);{for(this.state=660,this.match(d.OPAREN),this.state=661,this.sourceArgument(),this.state=666,this._errHandler.sync(this),r=this._input.LA(1);r===d.COMMA;)this.state=662,this.match(d.COMMA),this.state=663,this.sourceArgument(),this.state=668,this._errHandler.sync(this),r=this._input.LA(1);this.state=669,this.match(d.CPAREN)}break}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}argumentId(){let e=new Hk(this._ctx,this.state);this.enterRule(e,102,d.RULE_argumentId);try{this.enterOuterAlt(e,1),this.state=673,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sourceArgument(){let e=new QT(this._ctx,this.state);this.enterRule(e,104,d.RULE_sourceArgument);try{this.enterOuterAlt(e,1);{switch(this.state=678,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,50,this._ctx)){case 1:this.state=675,this.argumentId(),this.state=676,this.match(d.IS);break}this.state=680,this.fieldExpr(0)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sqExpr(e){e===void 0&&(e=0);let r=this._ctx,i=this.state,s=new un(this._ctx,i),o=s,u=106;this.enterRecursionRule(s,106,d.RULE_sqExpr,e);let a;try{let l;this.enterOuterAlt(s,1);{switch(this.state=706,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,54,this._ctx)){case 1:switch(s=new dce(s),this._ctx=s,o=s,this.state=683,this.id(),this.state=685,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,51,this._ctx)){case 1:this.state=684,this.sourceArguments();break}break;case 2:s=new hce(s),this._ctx=s,o=s,this.state=687,this.match(d.OPAREN),this.state=688,this.sqExpr(0),this.state=689,this.match(d.CPAREN);break;case 3:{if(s=new pce(s),this._ctx=s,o=s,this.state=691,this.match(d.COMPOSE),this.state=692,this.match(d.OPAREN),this.state=701,this._errHandler.sync(this),a=this._input.LA(1),a===d.COMPOSE||a===d.BQ_STRING||a===d.OPAREN||a===d.IDENTIFIER)for(this.state=693,this.sqExpr(0),this.state=698,this._errHandler.sync(this),a=this._input.LA(1);a===d.COMMA;)this.state=694,this.match(d.COMMA),this.state=695,this.sqExpr(0),this.state=700,this._errHandler.sync(this),a=this._input.LA(1);this.state=703,this.match(d.CPAREN)}break;case 4:s=new Ace(s),this._ctx=s,o=s,this.state=704,this.exploreTable();break;case 5:s=new _ce(s),this._ctx=s,o=s,this.state=705,this.sqlSource();break}for(this._ctx._stop=this._input.tryLT(-1),this.state=726,this._errHandler.sync(this),l=this.interpreter.adaptivePredict(this._input,57,this._ctx);l!==2&&l!==en.ATN.INVALID_ALT_NUMBER;){if(l===1)switch(this._parseListeners!=null&&this.triggerExitRuleEvent(),o=s,this.state=724,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,56,this._ctx)){case 1:{if(s=new mce(new un(r,i)),this.pushNewRecursionContext(s,u,d.RULE_sqExpr),this.state=708,!this.precpred(this._ctx,6))throw this.createFailedPredicateException("this.precpred(this._ctx, 6)");this.state=709,this.match(d.PLUS),this.state=710,this.segExpr(0)}break;case 2:{if(s=new gce(new un(r,i)),this.pushNewRecursionContext(s,u,d.RULE_sqExpr),this.state=711,!this.precpred(this._ctx,5))throw this.createFailedPredicateException("this.precpred(this._ctx, 5)");this.state=712,this.match(d.ARROW),this.state=713,this.segExpr(0)}break;case 3:{if(s=new yce(new un(r,i)),this.pushNewRecursionContext(s,u,d.RULE_sqExpr),this.state=714,!this.precpred(this._ctx,4))throw this.createFailedPredicateException("this.precpred(this._ctx, 4)");this.state=717,this._errHandler.sync(this),a=this._input.LA(1),a===d.INCLUDE&&(this.state=715,this.match(d.INCLUDE),this.state=716,this.includeBlock()),this.state=719,this.match(d.EXTEND),this.state=720,this.exploreProperties()}break;case 4:{if(s=new Ece(new un(r,i)),this.pushNewRecursionContext(s,u,d.RULE_sqExpr),this.state=721,!this.precpred(this._ctx,3))throw this.createFailedPredicateException("this.precpred(this._ctx, 3)");this.state=722,this.match(d.INCLUDE),this.state=723,this.includeBlock()}break}this.state=728,this._errHandler.sync(this),l=this.interpreter.adaptivePredict(this._input,57,this._ctx)}}}catch(l){if(l instanceof me.RecognitionException)s.exception=l,this._errHandler.reportError(this,l),this._errHandler.recover(this,l);else throw l}finally{this.unrollRecursionContexts(r)}return s}includeBlock(){let e=new zT(this._ctx,this.state);this.enterRule(e,108,d.RULE_includeBlock);let r;try{this.enterOuterAlt(e,1);{for(this.state=729,this.match(d.OCURLY),this.state=734,this._errHandler.sync(this),r=this._input.LA(1);!(r&-32)&&1<<r&(1<<d.AGGREGATE|1<<d.CALCULATE|1<<d.DIMENSION|1<<d.EXCEPT|1<<d.GROUP_BY|1<<d.INTERNAL|1<<d.JOIN_CROSS|1<<d.JOIN_ONE|1<<d.JOIN_MANY|1<<d.MEASURE|1<<d.NEST|1<<d.PRIVATE|1<<d.PUBLIC|1<<d.QUERY|1<<d.RUN|1<<d.SELECT|1<<d.SOURCE)||!(r-34&-32)&&1<<r-34&(1<<d.VIEW-34|1<<d.ALL-34|1<<d.AVG-34|1<<d.CASE-34|1<<d.CAST-34|1<<d.COUNT-34|1<<d.COMPOSE-34|1<<d.DAY-34|1<<d.EXCLUDE-34|1<<d.FALSE-34|1<<d.HOUR-34)||!(r-66&-32)&&1<<r-66&(1<<d.IS-66|1<<d.INTERNAL_KW-66|1<<d.MAX-66|1<<d.MIN-66|1<<d.MINUTE-66|1<<d.MONTH-66|1<<d.NOT-66|1<<d.NOW-66|1<<d.NULL-66|1<<d.PICK-66|1<<d.PRIVATE_KW-66|1<<d.PUBLIC_KW-66|1<<d.QUARTER-66|1<<d.SECOND-66|1<<d.SOURCE_KW-66|1<<d.SUM-66)||!(r-98&-32)&&1<<r-98&(1<<d.TRUE-98|1<<d.WEEK-98|1<<d.YEAR-98|1<<d.HACKY_REGEX-98|1<<d.RAW_SQ-98|1<<d.RAW_DQ-98|1<<d.SQ3_FILTER-98|1<<d.SQ_FILTER-98|1<<d.DQ3_FILTER-98|1<<d.DQ_FILTER-98|1<<d.BQ3_FILTER-98|1<<d.BQ_FILTER-98|1<<d.SQ_STRING-98|1<<d.DQ_STRING-98|1<<d.BQ_STRING-98|1<<d.ANNOTATION-98|1<<d.OPAREN-98|1<<d.OBRACK-98|1<<d.OCURLY-98)||!(r-141&-32)&&1<<r-141&(1<<d.MINUS-141|1<<d.STAR-141|1<<d.SEMI-141|1<<d.LITERAL_TIMESTAMP-141|1<<d.LITERAL_HOUR-141|1<<d.LITERAL_DAY-141|1<<d.LITERAL_QUARTER-141|1<<d.LITERAL_MONTH-141|1<<d.LITERAL_WEEK-141|1<<d.LITERAL_YEAR-141|1<<d.IDENTIFIER-141|1<<d.NUMERIC_LITERAL-141|1<<d.INTEGER_LITERAL-141|1<<d.SQL_BEGIN-141);){switch(this.state=732,this._errHandler.sync(this),this._input.LA(1)){case d.AGGREGATE:case d.CALCULATE:case d.DIMENSION:case d.EXCEPT:case d.GROUP_BY:case d.INTERNAL:case d.JOIN_CROSS:case d.JOIN_ONE:case d.JOIN_MANY:case d.MEASURE:case d.NEST:case d.PRIVATE:case d.PUBLIC:case d.QUERY:case d.RUN:case d.SELECT:case d.SOURCE:case d.VIEW:case d.ALL:case d.AVG:case d.CASE:case d.CAST:case d.COUNT:case d.COMPOSE:case d.DAY:case d.EXCLUDE:case d.FALSE:case d.HOUR:case d.IS:case d.INTERNAL_KW:case d.MAX:case d.MIN:case d.MINUTE:case d.MONTH:case d.NOT:case d.NOW:case d.NULL:case d.PICK:case d.PRIVATE_KW:case d.PUBLIC_KW:case d.QUARTER:case d.SECOND:case d.SOURCE_KW:case d.SUM:case d.TRUE:case d.WEEK:case d.YEAR:case d.HACKY_REGEX:case d.RAW_SQ:case d.RAW_DQ:case d.SQ3_FILTER:case d.SQ_FILTER:case d.DQ3_FILTER:case d.DQ_FILTER:case d.BQ3_FILTER:case d.BQ_FILTER:case d.SQ_STRING:case d.DQ_STRING:case d.BQ_STRING:case d.ANNOTATION:case d.OPAREN:case d.OBRACK:case d.OCURLY:case d.MINUS:case d.STAR:case d.LITERAL_TIMESTAMP:case d.LITERAL_HOUR:case d.LITERAL_DAY:case d.LITERAL_QUARTER:case d.LITERAL_MONTH:case d.LITERAL_WEEK:case d.LITERAL_YEAR:case d.IDENTIFIER:case d.NUMERIC_LITERAL:case d.INTEGER_LITERAL:case d.SQL_BEGIN:this.state=730,this.includeItem();break;case d.SEMI:this.state=731,this.match(d.SEMI);break;default:throw new tn.NoViableAltException(this)}this.state=736,this._errHandler.sync(this),r=this._input.LA(1)}this.state=737,this.match(d.CCURLY)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}includeItem(){let e=new GT(this._ctx,this.state);this.enterRule(e,110,d.RULE_includeItem);try{switch(this.state=749,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,60,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=739,this.tags(),this.state=740,this.accessLabelProp(),this.state=741,this.includeList();break;case 2:this.enterOuterAlt(e,2),this.state=743,this.includeList();break;case 3:this.enterOuterAlt(e,3),this.state=744,this.tags(),this.state=745,this.match(d.EXCEPT),this.state=746,this.includeExceptList();break;case 4:this.enterOuterAlt(e,4),this.state=748,this.orphanedAnnotation();break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}orphanedAnnotation(){let e=new Qk(this._ctx,this.state);this.enterRule(e,112,d.RULE_orphanedAnnotation);try{this.enterOuterAlt(e,1),this.state=751,this.match(d.ANNOTATION)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}accessLabelProp(){let e=new zk(this._ctx,this.state);this.enterRule(e,114,d.RULE_accessLabelProp);let r;try{this.enterOuterAlt(e,1),this.state=753,r=this._input.LA(1),!(r&-32)&&1<<r&(1<<d.INTERNAL|1<<d.PRIVATE|1<<d.PUBLIC)?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}includeExceptList(){let e=new Gk(this._ctx,this.state);this.enterRule(e,116,d.RULE_includeExceptList);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=755,this.includeExceptListItem(),this.state=762,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,62,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=757,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=756,this.match(d.COMMA)),this.state=759,this.includeExceptListItem()),this.state=764,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,62,this._ctx);this.state=766,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=765,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}includeExceptListItem(){let e=new WT(this._ctx,this.state);this.enterRule(e,118,d.RULE_includeExceptListItem);try{switch(this.state=774,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,64,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=768,this.tags(),this.state=769,this.fieldName();break;case 2:this.enterOuterAlt(e,2),this.state=771,this.tags(),this.state=772,this.collectionWildCard();break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}includeList(){let e=new Wk(this._ctx,this.state);this.enterRule(e,120,d.RULE_includeList);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=776,this.includeField(),this.state=783,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,66,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=778,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=777,this.match(d.COMMA)),this.state=780,this.includeField()),this.state=785,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,66,this._ctx);this.state=787,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=786,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}includeField(){let e=new VT(this._ctx,this.state);this.enterRule(e,122,d.RULE_includeField);try{switch(this.state=803,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,69,this._ctx)){case 1:this.enterOuterAlt(e,1);{switch(this.state=789,this.tags(),this.state=793,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,68,this._ctx)){case 1:this.state=790,e._as=this.fieldName(),this.state=791,this.isDefine();break}this.state=795,e._name=this.fieldName()}break;case 2:this.enterOuterAlt(e,2),this.state=797,this.tags(),this.state=798,e._name=this.fieldName();break;case 3:this.enterOuterAlt(e,3),this.state=800,this.tags(),this.state=801,this.collectionWildCard();break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}segExpr(e){e===void 0&&(e=0);let r=this._ctx,i=this.state,s=new Ms(this._ctx,i),o=s,u=124;this.enterRecursionRule(s,124,d.RULE_segExpr,e);try{let a;this.enterOuterAlt(s,1);{switch(this.state=812,this._errHandler.sync(this),this._input.LA(1)){case d.BQ_STRING:case d.IDENTIFIER:s=new vce(s),this._ctx=s,o=s,this.state=806,this.fieldPath();break;case d.OCURLY:s=new Cce(s),this._ctx=s,o=s,this.state=807,this.queryProperties();break;case d.OPAREN:s=new Sce(s),this._ctx=s,o=s,this.state=808,this.match(d.OPAREN),this.state=809,this.vExpr(),this.state=810,this.match(d.CPAREN);break;default:throw new tn.NoViableAltException(this)}for(this._ctx._stop=this._input.tryLT(-1),this.state=819,this._errHandler.sync(this),a=this.interpreter.adaptivePredict(this._input,71,this._ctx);a!==2&&a!==en.ATN.INVALID_ALT_NUMBER;){if(a===1){this._parseListeners!=null&&this.triggerExitRuleEvent(),o=s;{if(s=new bce(new Ms(r,i)),s._lhs=o,this.pushNewRecursionContext(s,u,d.RULE_segExpr),this.state=814,!this.precpred(this._ctx,1))throw this.createFailedPredicateException("this.precpred(this._ctx, 1)");this.state=815,this.match(d.PLUS),this.state=816,s._rhs=this.segExpr(2)}}this.state=821,this._errHandler.sync(this),a=this.interpreter.adaptivePredict(this._input,71,this._ctx)}}}catch(a){if(a instanceof me.RecognitionException)s.exception=a,this._errHandler.reportError(this,a),this._errHandler.recover(this,a);else throw a}finally{this.unrollRecursionContexts(r)}return s}vExpr(){let e=new zc(this._ctx,this.state);this.enterRule(e,126,d.RULE_vExpr);try{switch(this.state=827,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,72,this._ctx)){case 1:e=new Tce(e),this.enterOuterAlt(e,1),this.state=822,this.segExpr(0);break;case 2:e=new Rce(e),this.enterOuterAlt(e,2),this.state=823,e._lhs=this.segExpr(0),this.state=824,this.match(d.ARROW),this.state=825,e._rhs=this.vExpr();break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}queryExtendStatement(){let e=new YT(this._ctx,this.state);this.enterRule(e,128,d.RULE_queryExtendStatement);try{switch(this.state=832,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,73,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=829,this.defDimensions();break;case 2:this.enterOuterAlt(e,2),this.state=830,this.defMeasures();break;case 3:this.enterOuterAlt(e,3),this.state=831,this.joinStatement();break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}queryExtendStatementList(){let e=new Vk(this._ctx,this.state);this.enterRule(e,130,d.RULE_queryExtendStatementList);let r;try{this.enterOuterAlt(e,1);{for(this.state=834,this.match(d.OCURLY),this.state=839,this._errHandler.sync(this),r=this._input.LA(1);!(r&-32)&&1<<r&(1<<d.AGGREGATE|1<<d.CALCULATE|1<<d.DIMENSION|1<<d.EXCEPT|1<<d.GROUP_BY|1<<d.INTERNAL|1<<d.JOIN_CROSS|1<<d.JOIN_ONE|1<<d.JOIN_MANY|1<<d.MEASURE|1<<d.NEST|1<<d.PRIVATE|1<<d.PUBLIC|1<<d.QUERY|1<<d.RUN|1<<d.SELECT|1<<d.SOURCE)||!(r-34&-32)&&1<<r-34&(1<<d.VIEW-34|1<<d.ALL-34|1<<d.AVG-34|1<<d.CASE-34|1<<d.CAST-34|1<<d.COUNT-34|1<<d.COMPOSE-34|1<<d.DAY-34|1<<d.EXCLUDE-34|1<<d.FALSE-34|1<<d.HOUR-34)||!(r-66&-32)&&1<<r-66&(1<<d.IS-66|1<<d.INTERNAL_KW-66|1<<d.MAX-66|1<<d.MIN-66|1<<d.MINUTE-66|1<<d.MONTH-66|1<<d.NOT-66|1<<d.NOW-66|1<<d.NULL-66|1<<d.PICK-66|1<<d.PRIVATE_KW-66|1<<d.PUBLIC_KW-66|1<<d.QUARTER-66|1<<d.SECOND-66|1<<d.SOURCE_KW-66|1<<d.SUM-66)||!(r-98&-32)&&1<<r-98&(1<<d.TRUE-98|1<<d.WEEK-98|1<<d.YEAR-98|1<<d.HACKY_REGEX-98|1<<d.RAW_SQ-98|1<<d.RAW_DQ-98|1<<d.SQ3_FILTER-98|1<<d.SQ_FILTER-98|1<<d.DQ3_FILTER-98|1<<d.DQ_FILTER-98|1<<d.BQ3_FILTER-98|1<<d.BQ_FILTER-98|1<<d.SQ_STRING-98|1<<d.DQ_STRING-98|1<<d.BQ_STRING-98|1<<d.ANNOTATION-98|1<<d.OPAREN-98|1<<d.OBRACK-98|1<<d.OCURLY-98)||!(r-141&-32)&&1<<r-141&(1<<d.MINUS-141|1<<d.STAR-141|1<<d.SEMI-141|1<<d.LITERAL_TIMESTAMP-141|1<<d.LITERAL_HOUR-141|1<<d.LITERAL_DAY-141|1<<d.LITERAL_QUARTER-141|1<<d.LITERAL_MONTH-141|1<<d.LITERAL_WEEK-141|1<<d.LITERAL_YEAR-141|1<<d.IDENTIFIER-141|1<<d.NUMERIC_LITERAL-141|1<<d.INTEGER_LITERAL-141|1<<d.SQL_BEGIN-141);){switch(this.state=837,this._errHandler.sync(this),this._input.LA(1)){case d.AGGREGATE:case d.CALCULATE:case d.DIMENSION:case d.EXCEPT:case d.GROUP_BY:case d.INTERNAL:case d.JOIN_CROSS:case d.JOIN_ONE:case d.JOIN_MANY:case d.MEASURE:case d.NEST:case d.PRIVATE:case d.PUBLIC:case d.QUERY:case d.RUN:case d.SELECT:case d.SOURCE:case d.VIEW:case d.ALL:case d.AVG:case d.CASE:case d.CAST:case d.COUNT:case d.COMPOSE:case d.DAY:case d.EXCLUDE:case d.FALSE:case d.HOUR:case d.IS:case d.INTERNAL_KW:case d.MAX:case d.MIN:case d.MINUTE:case d.MONTH:case d.NOT:case d.NOW:case d.NULL:case d.PICK:case d.PRIVATE_KW:case d.PUBLIC_KW:case d.QUARTER:case d.SECOND:case d.SOURCE_KW:case d.SUM:case d.TRUE:case d.WEEK:case d.YEAR:case d.HACKY_REGEX:case d.RAW_SQ:case d.RAW_DQ:case d.SQ3_FILTER:case d.SQ_FILTER:case d.DQ3_FILTER:case d.DQ_FILTER:case d.BQ3_FILTER:case d.BQ_FILTER:case d.SQ_STRING:case d.DQ_STRING:case d.BQ_STRING:case d.ANNOTATION:case d.OPAREN:case d.OBRACK:case d.OCURLY:case d.MINUS:case d.STAR:case d.LITERAL_TIMESTAMP:case d.LITERAL_HOUR:case d.LITERAL_DAY:case d.LITERAL_QUARTER:case d.LITERAL_MONTH:case d.LITERAL_WEEK:case d.LITERAL_YEAR:case d.IDENTIFIER:case d.NUMERIC_LITERAL:case d.INTEGER_LITERAL:case d.SQL_BEGIN:this.state=835,this.queryExtendStatement();break;case d.SEMI:this.state=836,this.match(d.SEMI);break;default:throw new tn.NoViableAltException(this)}this.state=841,this._errHandler.sync(this),r=this._input.LA(1)}this.state=842,this.match(d.CCURLY)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}joinList(){let e=new cE(this._ctx,this.state);this.enterRule(e,132,d.RULE_joinList);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=844,this.joinDef(),this.state=851,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,77,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=846,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=845,this.match(d.COMMA)),this.state=848,this.joinDef()),this.state=853,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,77,this._ctx);this.state=855,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=854,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}isExplore(){let e=new Yk(this._ctx,this.state);this.enterRule(e,134,d.RULE_isExplore);try{this.enterOuterAlt(e,1),this.state=857,e._before_is=this.tags(),this.state=858,this.match(d.IS),this.state=859,e._after_is=this.tags(),this.state=860,this.sqExpr(0)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}matrixOperation(){let e=new KT(this._ctx,this.state);this.enterRule(e,136,d.RULE_matrixOperation);let r;try{this.enterOuterAlt(e,1),this.state=862,r=this._input.LA(1),!(r-58&-32)&&1<<r-58&(1<<d.FULL-58|1<<d.INNER-58|1<<d.LEFT-58|1<<d.RIGHT-58)?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}joinFrom(){let e=new JT(this._ctx,this.state);this.enterRule(e,138,d.RULE_joinFrom);try{switch(this.state=871,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,79,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=864,this.joinNameDef();break;case 2:this.enterOuterAlt(e,2),this.state=865,this.joinNameDef(),this.state=866,this.sourceArguments();break;case 3:this.enterOuterAlt(e,3),this.state=868,this.joinNameDef(),this.state=869,this.isExplore();break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}joinDef(){let e=new C2(this._ctx,this.state);this.enterRule(e,140,d.RULE_joinDef);let r;try{switch(this.state=900,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,85,this._ctx)){case 1:e=new Dce(e),this.enterOuterAlt(e,1);{for(this.state=876,this._errHandler.sync(this),r=this._input.LA(1);r===d.ANNOTATION;)this.state=873,this.match(d.ANNOTATION),this.state=878,this._errHandler.sync(this),r=this._input.LA(1);this.state=879,this.joinFrom(),this.state=881,this._errHandler.sync(this),r=this._input.LA(1),!(r-58&-32)&&1<<r-58&(1<<d.FULL-58|1<<d.INNER-58|1<<d.LEFT-58|1<<d.RIGHT-58)&&(this.state=880,this.matrixOperation()),this.state=883,this.match(d.WITH),this.state=884,this.fieldExpr(0)}break;case 2:e=new Oce(e),this.enterOuterAlt(e,2);{for(this.state=889,this._errHandler.sync(this),r=this._input.LA(1);r===d.ANNOTATION;)this.state=886,this.match(d.ANNOTATION),this.state=891,this._errHandler.sync(this),r=this._input.LA(1);this.state=892,this.joinFrom(),this.state=898,this._errHandler.sync(this),r=this._input.LA(1),!(r-58&-32)&&1<<r-58&(1<<d.FULL-58|1<<d.INNER-58|1<<d.LEFT-58|1<<d.ON-58|1<<d.RIGHT-58)&&(this.state=894,this._errHandler.sync(this),r=this._input.LA(1),!(r-58&-32)&&1<<r-58&(1<<d.FULL-58|1<<d.INNER-58|1<<d.LEFT-58|1<<d.RIGHT-58)&&(this.state=893,this.matrixOperation()),this.state=896,this.match(d.ON),this.state=897,this.joinExpression())}break}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}joinExpression(){let e=new Kk(this._ctx,this.state);this.enterRule(e,142,d.RULE_joinExpression);try{this.enterOuterAlt(e,1),this.state=902,this.fieldExpr(0)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}filterStatement(){let e=new Fce(this._ctx,this.state);this.enterRule(e,144,d.RULE_filterStatement);try{switch(this.state=906,this._errHandler.sync(this),this._input.LA(1)){case d.WHERE:this.enterOuterAlt(e,1),this.state=904,this.whereStatement();break;case d.HAVING:this.enterOuterAlt(e,2),this.state=905,this.havingStatement();break;default:throw new tn.NoViableAltException(this)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}fieldProperties(){let e=new Jk(this._ctx,this.state);this.enterRule(e,146,d.RULE_fieldProperties);let r;try{this.enterOuterAlt(e,1);{for(this.state=908,this.match(d.OCURLY),this.state=913,this._errHandler.sync(this),r=this._input.LA(1);!(r-17&-32)&&1<<r-17&(1<<d.LIMIT-17|1<<d.ORDER_BY-17|1<<d.PARTITION_BY-17|1<<d.WHERE-17)||r===d.SEMI;){switch(this.state=911,this._errHandler.sync(this),this._input.LA(1)){case d.LIMIT:case d.ORDER_BY:case d.PARTITION_BY:case d.WHERE:this.state=909,this.fieldPropertyStatement();break;case d.SEMI:this.state=910,this.match(d.SEMI);break;default:throw new tn.NoViableAltException(this)}this.state=915,this._errHandler.sync(this),r=this._input.LA(1)}this.state=916,this.match(d.CCURLY)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}aggregateOrdering(){let e=new Xk(this._ctx,this.state);this.enterRule(e,148,d.RULE_aggregateOrdering);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=918,this.aggregateOrderBySpec(),this.state=923,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,89,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=919,this.match(d.COMMA),this.state=920,this.aggregateOrderBySpec()),this.state=925,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,89,this._ctx);this.state=927,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=926,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}aggregateOrderBySpec(){let e=new XT(this._ctx,this.state);this.enterRule(e,150,d.RULE_aggregateOrderBySpec);let r;try{switch(this.state=935,this._errHandler.sync(this),this._input.LA(1)){case d.ALL:case d.AVG:case d.CASE:case d.CAST:case d.COUNT:case d.DAY:case d.EXCLUDE:case d.FALSE:case d.HOUR:case d.MAX:case d.MIN:case d.MINUTE:case d.MONTH:case d.NOT:case d.NOW:case d.NULL:case d.PICK:case d.QUARTER:case d.SECOND:case d.SOURCE_KW:case d.SUM:case d.TRUE:case d.WEEK:case d.YEAR:case d.HACKY_REGEX:case d.RAW_SQ:case d.RAW_DQ:case d.SQ3_FILTER:case d.SQ_FILTER:case d.DQ3_FILTER:case d.DQ_FILTER:case d.BQ3_FILTER:case d.BQ_FILTER:case d.SQ_STRING:case d.DQ_STRING:case d.BQ_STRING:case d.OPAREN:case d.OBRACK:case d.OCURLY:case d.MINUS:case d.LITERAL_TIMESTAMP:case d.LITERAL_HOUR:case d.LITERAL_DAY:case d.LITERAL_QUARTER:case d.LITERAL_MONTH:case d.LITERAL_WEEK:case d.LITERAL_YEAR:case d.IDENTIFIER:case d.NUMERIC_LITERAL:case d.INTEGER_LITERAL:case d.SQL_BEGIN:this.enterOuterAlt(e,1),this.state=929,this.fieldExpr(0),this.state=931,this._errHandler.sync(this),r=this._input.LA(1),(r===d.ASC||r===d.DESC)&&(this.state=930,r=this._input.LA(1),r===d.ASC||r===d.DESC?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this));break;case d.ASC:this.enterOuterAlt(e,2),this.state=933,this.match(d.ASC);break;case d.DESC:this.enterOuterAlt(e,3),this.state=934,this.match(d.DESC);break;default:throw new tn.NoViableAltException(this)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}aggregateOrderByStatement(){let e=new Zk(this._ctx,this.state);this.enterRule(e,152,d.RULE_aggregateOrderByStatement);try{this.enterOuterAlt(e,1),this.state=937,this.match(d.ORDER_BY),this.state=938,this.aggregateOrdering()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}fieldPropertyLimitStatement(){let e=new eM(this._ctx,this.state);this.enterRule(e,154,d.RULE_fieldPropertyLimitStatement);try{this.enterOuterAlt(e,1),this.state=940,this.limitStatement()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}fieldPropertyStatement(){let e=new ZT(this._ctx,this.state);this.enterRule(e,156,d.RULE_fieldPropertyStatement);try{switch(this.state=946,this._errHandler.sync(this),this._input.LA(1)){case d.WHERE:this.enterOuterAlt(e,1),this.state=942,this.whereStatement();break;case d.PARTITION_BY:this.enterOuterAlt(e,2),this.state=943,this.partitionByStatement();break;case d.ORDER_BY:this.enterOuterAlt(e,3),this.state=944,this.aggregateOrderByStatement();break;case d.LIMIT:this.enterOuterAlt(e,4),this.state=945,this.fieldPropertyLimitStatement();break;default:throw new tn.NoViableAltException(this)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}filterClauseList(){let e=new eR(this._ctx,this.state);this.enterRule(e,158,d.RULE_filterClauseList);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=948,this.fieldExpr(0),this.state=953,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,94,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=949,this.match(d.COMMA),this.state=950,this.fieldExpr(0)),this.state=955,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,94,this._ctx);this.state=957,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=956,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}whereStatement(){let e=new ud(this._ctx,this.state);this.enterRule(e,160,d.RULE_whereStatement);try{this.enterOuterAlt(e,1),this.state=959,this.match(d.WHERE),this.state=960,this.filterClauseList()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}havingStatement(){let e=new tR(this._ctx,this.state);this.enterRule(e,162,d.RULE_havingStatement);try{this.enterOuterAlt(e,1),this.state=962,this.match(d.HAVING),this.state=963,this.filterClauseList()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}subQueryDefList(){let e=new tM(this._ctx,this.state);this.enterRule(e,164,d.RULE_subQueryDefList);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=965,this.exploreQueryDef(),this.state=972,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,97,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=967,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=966,this.match(d.COMMA)),this.state=969,this.exploreQueryDef()),this.state=974,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,97,this._ctx);this.state=976,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=975,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}exploreQueryNameDef(){let e=new nM(this._ctx,this.state);this.enterRule(e,166,d.RULE_exploreQueryNameDef);try{this.enterOuterAlt(e,1),this.state=978,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}exploreQueryDef(){let e=new nR(this._ctx,this.state);this.enterRule(e,168,d.RULE_exploreQueryDef);let r;try{this.enterOuterAlt(e,1);{for(this.state=983,this._errHandler.sync(this),r=this._input.LA(1);r===d.ANNOTATION;)this.state=980,this.match(d.ANNOTATION),this.state=985,this._errHandler.sync(this),r=this._input.LA(1);this.state=986,this.exploreQueryNameDef(),this.state=987,this.isDefine(),this.state=988,this.vExpr()}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}queryStatement(){let e=new rR(this._ctx,this.state);this.enterRule(e,170,d.RULE_queryStatement);try{switch(this.state=1008,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,100,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=990,this.groupByStatement();break;case 2:this.enterOuterAlt(e,2),this.state=991,this.declareStatement();break;case 3:this.enterOuterAlt(e,3),this.state=992,this.queryJoinStatement();break;case 4:this.enterOuterAlt(e,4),this.state=993,this.queryExtend();break;case 5:this.enterOuterAlt(e,5),this.state=994,this.projectStatement();break;case 6:this.enterOuterAlt(e,6),this.state=995,this.indexStatement();break;case 7:this.enterOuterAlt(e,7),this.state=996,this.aggregateStatement();break;case 8:this.enterOuterAlt(e,8),this.state=997,this.calculateStatement();break;case 9:this.enterOuterAlt(e,9),this.state=998,this.topStatement();break;case 10:this.enterOuterAlt(e,10),this.state=999,this.limitStatement();break;case 11:this.enterOuterAlt(e,11),this.state=1e3,this.orderByStatement();break;case 12:this.enterOuterAlt(e,12),this.state=1001,this.whereStatement();break;case 13:this.enterOuterAlt(e,13),this.state=1002,this.havingStatement();break;case 14:this.enterOuterAlt(e,14),this.state=1003,this.nestStatement();break;case 15:this.enterOuterAlt(e,15),this.state=1004,this.sampleStatement();break;case 16:this.enterOuterAlt(e,16),this.state=1005,this.timezoneStatement();break;case 17:this.enterOuterAlt(e,17),this.state=1006,this.queryAnnotation();break;case 18:this.enterOuterAlt(e,18),this.state=1007,this.ignoredModelAnnotations();break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}queryJoinStatement(){let e=new rM(this._ctx,this.state);this.enterRule(e,172,d.RULE_queryJoinStatement);try{this.enterOuterAlt(e,1),this.state=1010,this.joinStatement()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}groupByStatement(){let e=new iM(this._ctx,this.state);this.enterRule(e,174,d.RULE_groupByStatement);try{this.enterOuterAlt(e,1),this.state=1012,this.tags(),this.state=1013,this.match(d.GROUP_BY),this.state=1014,this.queryFieldList()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}queryFieldList(){let e=new fE(this._ctx,this.state);this.enterRule(e,176,d.RULE_queryFieldList);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=1016,this.queryFieldEntry(),this.state=1023,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,102,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=1018,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1017,this.match(d.COMMA)),this.state=1020,this.queryFieldEntry()),this.state=1025,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,102,this._ctx);this.state=1027,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1026,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}queryFieldEntry(){let e=new iR(this._ctx,this.state);this.enterRule(e,178,d.RULE_queryFieldEntry);try{switch(this.state=1031,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,104,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=1029,this.taggedRef();break;case 2:this.enterOuterAlt(e,2),this.state=1030,this.fieldDef();break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}nestStatement(){let e=new sM(this._ctx,this.state);this.enterRule(e,180,d.RULE_nestStatement);try{this.enterOuterAlt(e,1),this.state=1033,this.tags(),this.state=1034,this.match(d.NEST),this.state=1035,this.nestedQueryList()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}nestedQueryList(){let e=new oM(this._ctx,this.state);this.enterRule(e,182,d.RULE_nestedQueryList);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=1037,this.nestEntry(),this.state=1044,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,106,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=1039,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1038,this.match(d.COMMA)),this.state=1041,this.nestEntry()),this.state=1046,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,106,this._ctx);this.state=1048,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1047,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}nestEntry(){let e=new xE(this._ctx,this.state);this.enterRule(e,184,d.RULE_nestEntry);try{e=new wce(e),this.enterOuterAlt(e,1);{switch(this.state=1050,this.tags(),this.state=1054,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,108,this._ctx)){case 1:this.state=1051,this.queryName(),this.state=1052,this.isDefine();break}this.state=1056,this.vExpr()}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}aggregateStatement(){let e=new uM(this._ctx,this.state);this.enterRule(e,186,d.RULE_aggregateStatement);try{this.enterOuterAlt(e,1),this.state=1058,this.tags(),this.state=1059,this.match(d.AGGREGATE),this.state=1060,this.queryFieldList()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}calculateStatement(){let e=new aM(this._ctx,this.state);this.enterRule(e,188,d.RULE_calculateStatement);try{this.enterOuterAlt(e,1),this.state=1062,this.tags(),this.state=1063,this.match(d.CALCULATE),this.state=1064,this.queryFieldList()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}projectStatement(){let e=new lM(this._ctx,this.state);this.enterRule(e,190,d.RULE_projectStatement);try{this.enterOuterAlt(e,1),this.state=1066,this.tags(),this.state=1067,this.match(d.SELECT),this.state=1068,this.fieldCollection()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}partitionByStatement(){let e=new cM(this._ctx,this.state);this.enterRule(e,192,d.RULE_partitionByStatement);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=1070,this.match(d.PARTITION_BY),this.state=1071,this.id(),this.state=1076,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,109,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=1072,this.match(d.COMMA),this.state=1073,this.id()),this.state=1078,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,109,this._ctx);this.state=1080,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1079,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}orderByStatement(){let e=new fM(this._ctx,this.state);this.enterRule(e,194,d.RULE_orderByStatement);try{this.enterOuterAlt(e,1),this.state=1082,this.match(d.ORDER_BY),this.state=1083,this.ordering()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}ordering(){let e=new xM(this._ctx,this.state);this.enterRule(e,196,d.RULE_ordering);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=1085,this.orderBySpec(),this.state=1092,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,112,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=1087,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1086,this.match(d.COMMA)),this.state=1089,this.orderBySpec()),this.state=1094,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,112,this._ctx);this.state=1096,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1095,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}orderBySpec(){let e=new sR(this._ctx,this.state);this.enterRule(e,198,d.RULE_orderBySpec);let r;try{this.enterOuterAlt(e,1);{switch(this.state=1100,this._errHandler.sync(this),this._input.LA(1)){case d.INTEGER_LITERAL:this.state=1098,this.match(d.INTEGER_LITERAL);break;case d.BQ_STRING:case d.IDENTIFIER:this.state=1099,this.fieldName();break;default:throw new tn.NoViableAltException(this)}this.state=1103,this._errHandler.sync(this),r=this._input.LA(1),(r===d.ASC||r===d.DESC)&&(this.state=1102,r=this._input.LA(1),r===d.ASC||r===d.DESC?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}limitStatement(){let e=new oR(this._ctx,this.state);this.enterRule(e,200,d.RULE_limitStatement);try{this.enterOuterAlt(e,1),this.state=1105,this.match(d.LIMIT),this.state=1106,this.match(d.INTEGER_LITERAL)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}bySpec(){let e=new Nce(this._ctx,this.state);this.enterRule(e,202,d.RULE_bySpec);try{switch(this.state=1112,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,116,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=1108,this.match(d.BY),this.state=1109,this.fieldName();break;case 2:this.enterOuterAlt(e,2),this.state=1110,this.match(d.BY),this.state=1111,this.fieldExpr(0);break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}topStatement(){let e=new dM(this._ctx,this.state);this.enterRule(e,204,d.RULE_topStatement);try{this.enterOuterAlt(e,1),this.state=1114,this.match(d.TOP),this.state=1115,this.match(d.INTEGER_LITERAL)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}indexElement(){let e=new uR(this._ctx,this.state);this.enterRule(e,206,d.RULE_indexElement);let r;try{switch(this.state=1123,this._errHandler.sync(this),this._input.LA(1)){case d.BQ_STRING:case d.IDENTIFIER:this.enterOuterAlt(e,1),this.state=1117,this.fieldPath(),this.state=1120,this._errHandler.sync(this),r=this._input.LA(1),r===d.DOT&&(this.state=1118,this.match(d.DOT),this.state=1119,this.match(d.STAR));break;case d.STAR:this.enterOuterAlt(e,2),this.state=1122,this.match(d.STAR);break;default:throw new tn.NoViableAltException(this)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}indexFields(){let e=new hM(this._ctx,this.state);this.enterRule(e,208,d.RULE_indexFields);let r;try{let i;for(this.enterOuterAlt(e,1),this.state=1125,this.indexElement(),this.state=1132,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,120,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=1127,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1126,this.match(d.COMMA)),this.state=1129,this.indexElement()),this.state=1134,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,120,this._ctx)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}indexStatement(){let e=new pM(this._ctx,this.state);this.enterRule(e,210,d.RULE_indexStatement);let r;try{this.enterOuterAlt(e,1),this.state=1135,this.match(d.INDEX),this.state=1136,this.indexFields(),this.state=1139,this._errHandler.sync(this),r=this._input.LA(1),r===d.BY&&(this.state=1137,this.match(d.BY),this.state=1138,this.fieldName())}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}sampleStatement(){let e=new mM(this._ctx,this.state);this.enterRule(e,212,d.RULE_sampleStatement);try{this.enterOuterAlt(e,1),this.state=1141,this.match(d.SAMPLE),this.state=1142,this.sampleSpec()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}timezoneStatement(){let e=new aR(this._ctx,this.state);this.enterRule(e,214,d.RULE_timezoneStatement);try{this.enterOuterAlt(e,1),this.state=1144,this.match(d.TIMEZONE),this.state=1145,this.string()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}queryAnnotation(){let e=new gM(this._ctx,this.state);this.enterRule(e,216,d.RULE_queryAnnotation);try{this.enterOuterAlt(e,1),this.state=1147,this.match(d.ANNOTATION)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sampleSpec(){let e=new yM(this._ctx,this.state);this.enterRule(e,218,d.RULE_sampleSpec);let r;try{this.enterOuterAlt(e,1),this.state=1149,r=this._input.LA(1),r===d.FALSE||r===d.TRUE||r===d.PERCENT_LITERAL||r===d.INTEGER_LITERAL?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}aggregate(){let e=new dE(this._ctx,this.state);this.enterRule(e,220,d.RULE_aggregate);let r;try{this.enterOuterAlt(e,1),this.state=1151,r=this._input.LA(1),r===d.AVG||r===d.COUNT||!(r-73&-32)&&1<<r-73&(1<<d.MAX-73|1<<d.MIN-73|1<<d.SUM-73)?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}malloyType(){let e=new hE(this._ctx,this.state);this.enterRule(e,222,d.RULE_malloyType);let r;try{this.enterOuterAlt(e,1),this.state=1153,r=this._input.LA(1),r===d.BOOLEAN||r===d.DATE||!(r-80&-32)&&1<<r-80&(1<<d.NUMBER-80|1<<d.STRING-80|1<<d.TIMESTAMP-80)?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}compareOp(){let e=new lR(this._ctx,this.state);this.enterRule(e,224,d.RULE_compareOp);let r;try{this.enterOuterAlt(e,1),this.state=1155,r=this._input.LA(1),!(r-134&-32)&&1<<r-134&(1<<d.LT-134|1<<d.GT-134|1<<d.EQ-134|1<<d.NE-134|1<<d.LTE-134|1<<d.GTE-134|1<<d.NOT_MATCH-134|1<<d.MATCH-134)?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}string(){let e=new Fa(this._ctx,this.state);this.enterRule(e,226,d.RULE_string);try{switch(this.state=1159,this._errHandler.sync(this),this._input.LA(1)){case d.SQ_STRING:case d.DQ_STRING:this.enterOuterAlt(e,1),this.state=1157,this.shortString();break;case d.SQL_BEGIN:this.enterOuterAlt(e,2),this.state=1158,this.sqlString();break;default:throw new tn.NoViableAltException(this)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}shortString(){let e=new cR(this._ctx,this.state);this.enterRule(e,228,d.RULE_shortString);let r;try{this.enterOuterAlt(e,1),this.state=1161,r=this._input.LA(1),r===d.SQ_STRING||r===d.DQ_STRING?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}rawString(){let e=new EM(this._ctx,this.state);this.enterRule(e,230,d.RULE_rawString);let r;try{this.enterOuterAlt(e,1),this.state=1163,r=this._input.LA(1),r===d.RAW_SQ||r===d.RAW_DQ?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}numericLiteral(){let e=new AM(this._ctx,this.state);this.enterRule(e,232,d.RULE_numericLiteral);let r;try{this.enterOuterAlt(e,1),this.state=1165,r=this._input.LA(1),r===d.NUMERIC_LITERAL||r===d.INTEGER_LITERAL?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}literal(){let e=new _o(this._ctx,this.state);this.enterRule(e,234,d.RULE_literal);let r;try{switch(this.state=1176,this._errHandler.sync(this),this._input.LA(1)){case d.SQ_STRING:case d.DQ_STRING:case d.SQL_BEGIN:e=new Lce(e),this.enterOuterAlt(e,1),this.state=1167,this.string();break;case d.RAW_SQ:case d.RAW_DQ:e=new Ice(e),this.enterOuterAlt(e,2),this.state=1168,this.rawString();break;case d.NUMERIC_LITERAL:case d.INTEGER_LITERAL:e=new Bce(e),this.enterOuterAlt(e,3),this.state=1169,this.numericLiteral();break;case d.LITERAL_TIMESTAMP:case d.LITERAL_HOUR:case d.LITERAL_DAY:case d.LITERAL_QUARTER:case d.LITERAL_MONTH:case d.LITERAL_WEEK:case d.LITERAL_YEAR:e=new $ce(e),this.enterOuterAlt(e,4),this.state=1170,this.dateLiteral();break;case d.NULL:e=new kce(e),this.enterOuterAlt(e,5),this.state=1171,this.match(d.NULL);break;case d.FALSE:case d.TRUE:e=new Mce(e),this.enterOuterAlt(e,6),this.state=1172,r=this._input.LA(1),r===d.FALSE||r===d.TRUE?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this);break;case d.HACKY_REGEX:e=new Pce(e),this.enterOuterAlt(e,7),this.state=1173,this.match(d.HACKY_REGEX);break;case d.SQ3_FILTER:case d.SQ_FILTER:case d.DQ3_FILTER:case d.DQ_FILTER:case d.BQ3_FILTER:case d.BQ_FILTER:e=new Uce(e),this.enterOuterAlt(e,8),this.state=1174,this.filterString();break;case d.NOW:e=new jce(e),this.enterOuterAlt(e,9),this.state=1175,this.match(d.NOW);break;default:throw new tn.NoViableAltException(this)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}dateLiteral(){let e=new wa(this._ctx,this.state);this.enterRule(e,236,d.RULE_dateLiteral);try{switch(this.state=1185,this._errHandler.sync(this),this._input.LA(1)){case d.LITERAL_TIMESTAMP:e=new qce(e),this.enterOuterAlt(e,1),this.state=1178,this.match(d.LITERAL_TIMESTAMP);break;case d.LITERAL_HOUR:e=new Hce(e),this.enterOuterAlt(e,2),this.state=1179,this.match(d.LITERAL_HOUR);break;case d.LITERAL_DAY:e=new Qce(e),this.enterOuterAlt(e,3),this.state=1180,this.match(d.LITERAL_DAY);break;case d.LITERAL_WEEK:e=new zce(e),this.enterOuterAlt(e,4),this.state=1181,this.match(d.LITERAL_WEEK);break;case d.LITERAL_MONTH:e=new Gce(e),this.enterOuterAlt(e,5),this.state=1182,this.match(d.LITERAL_MONTH);break;case d.LITERAL_QUARTER:e=new Wce(e),this.enterOuterAlt(e,6),this.state=1183,this.match(d.LITERAL_QUARTER);break;case d.LITERAL_YEAR:e=new Vce(e),this.enterOuterAlt(e,7),this.state=1184,this.match(d.LITERAL_YEAR);break;default:throw new tn.NoViableAltException(this)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}tablePath(){let e=new _M(this._ctx,this.state);this.enterRule(e,238,d.RULE_tablePath);try{this.enterOuterAlt(e,1),this.state=1187,this.string()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}tableURI(){let e=new Yce(this._ctx,this.state);this.enterRule(e,240,d.RULE_tableURI);try{this.enterOuterAlt(e,1),this.state=1189,this.string()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}id(){let e=new Dn(this._ctx,this.state);this.enterRule(e,242,d.RULE_id);let r;try{this.enterOuterAlt(e,1),this.state=1191,r=this._input.LA(1),r===d.BQ_STRING||r===d.IDENTIFIER?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}timeframe(){let e=new ad(this._ctx,this.state);this.enterRule(e,244,d.RULE_timeframe);let r;try{this.enterOuterAlt(e,1),this.state=1193,r=this._input.LA(1),!(r-49&-32)&&1<<r-49&(1<<d.DAY-49|1<<d.HOUR-49|1<<d.MINUTE-49|1<<d.MONTH-49)||!(r-86&-32)&&1<<r-86&(1<<d.QUARTER-86|1<<d.SECOND-86|1<<d.WEEK-86|1<<d.YEAR-86)?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}ungroup(){let e=new vM(this._ctx,this.state);this.enterRule(e,246,d.RULE_ungroup);let r;try{this.enterOuterAlt(e,1),this.state=1195,r=this._input.LA(1),r===d.ALL||r===d.EXCLUDE?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}malloyOrSQLType(){let e=new fR(this._ctx,this.state);this.enterRule(e,248,d.RULE_malloyOrSQLType);try{switch(this.state=1199,this._errHandler.sync(this),this._input.LA(1)){case d.BOOLEAN:case d.DATE:case d.NUMBER:case d.STRING:case d.TIMESTAMP:this.enterOuterAlt(e,1),this.state=1197,this.malloyType();break;case d.SQ_STRING:case d.DQ_STRING:case d.SQL_BEGIN:this.enterOuterAlt(e,2),this.state=1198,this.string();break;default:throw new tn.NoViableAltException(this)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}fieldExpr(e){e===void 0&&(e=0);let r=this._ctx,i=this.state,s=new Te(this._ctx,i),o=s,u=250;this.enterRecursionRule(s,250,d.RULE_fieldExpr,e);let a;try{let l;this.enterOuterAlt(s,1);{switch(this.state=1303,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,138,this._ctx)){case 1:s=new Kce(s),this._ctx=s,o=s,this.state=1202,this.fieldPath();break;case 2:s=new Jce(s),this._ctx=s,o=s,this.state=1203,this.literal();break;case 3:{for(s=new Xce(s),this._ctx=s,o=s,this.state=1204,this.match(d.OBRACK),this.state=1205,this.fieldExpr(0),this.state=1210,this._errHandler.sync(this),l=this.interpreter.adaptivePredict(this._input,126,this._ctx);l!==2&&l!==en.ATN.INVALID_ALT_NUMBER;)l===1&&(this.state=1206,this.match(d.COMMA),this.state=1207,this.fieldExpr(0)),this.state=1212,this._errHandler.sync(this),l=this.interpreter.adaptivePredict(this._input,126,this._ctx);this.state=1214,this._errHandler.sync(this),a=this._input.LA(1),a===d.COMMA&&(this.state=1213,this.match(d.COMMA)),this.state=1216,this.match(d.CBRACK)}break;case 4:{for(s=new Zce(s),this._ctx=s,o=s,this.state=1218,this.match(d.OCURLY),this.state=1219,this.recordElement(),this.state=1224,this._errHandler.sync(this),a=this._input.LA(1);a===d.COMMA;)this.state=1220,this.match(d.COMMA),this.state=1221,this.recordElement(),this.state=1226,this._errHandler.sync(this),a=this._input.LA(1);this.state=1227,this.match(d.CCURLY)}break;case 5:s=new ife(s),this._ctx=s,o=s,this.state=1229,this.match(d.MINUS),this.state=1230,this.fieldExpr(25);break;case 6:s=new mfe(s),this._ctx=s,o=s,this.state=1231,this.match(d.NOT),this.state=1232,this.fieldExpr(13);break;case 7:s=new CM(s),this._ctx=s,o=s,this.state=1233,this.match(d.CAST),this.state=1234,this.match(d.OPAREN),this.state=1235,this.fieldExpr(0),this.state=1236,this.match(d.AS),this.state=1237,this.malloyOrSQLType(),this.state=1238,this.match(d.CPAREN);break;case 8:s=new Afe(s),this._ctx=s,o=s,this.state=1242,this._errHandler.sync(this),a=this._input.LA(1),a===d.SOURCE_KW&&(this.state=1240,this.match(d.SOURCE_KW),this.state=1241,this.match(d.DOT)),this.state=1244,this.aggregate(),this.state=1245,this.match(d.OPAREN),this.state=1247,this._errHandler.sync(this),a=this._input.LA(1),(!(a-36&-32)&&1<<a-36&(1<<d.ALL-36|1<<d.AVG-36|1<<d.CASE-36|1<<d.CAST-36|1<<d.COUNT-36|1<<d.DAY-36|1<<d.EXCLUDE-36|1<<d.FALSE-36|1<<d.HOUR-36)||!(a-73&-32)&&1<<a-73&(1<<d.MAX-73|1<<d.MIN-73|1<<d.MINUTE-73|1<<d.MONTH-73|1<<d.NOT-73|1<<d.NOW-73|1<<d.NULL-73|1<<d.PICK-73|1<<d.QUARTER-73|1<<d.SECOND-73|1<<d.SOURCE_KW-73|1<<d.SUM-73|1<<d.TRUE-73|1<<d.WEEK-73|1<<d.YEAR-73)||!(a-105&-32)&&1<<a-105&(1<<d.HACKY_REGEX-105|1<<d.RAW_SQ-105|1<<d.RAW_DQ-105|1<<d.SQ3_FILTER-105|1<<d.SQ_FILTER-105|1<<d.DQ3_FILTER-105|1<<d.DQ_FILTER-105|1<<d.BQ3_FILTER-105|1<<d.BQ_FILTER-105|1<<d.SQ_STRING-105|1<<d.DQ_STRING-105|1<<d.BQ_STRING-105|1<<d.OPAREN-105|1<<d.OBRACK-105|1<<d.OCURLY-105)||!(a-141&-32)&&1<<a-141&(1<<d.MINUS-141|1<<d.LITERAL_TIMESTAMP-141|1<<d.LITERAL_HOUR-141|1<<d.LITERAL_DAY-141|1<<d.LITERAL_QUARTER-141|1<<d.LITERAL_MONTH-141|1<<d.LITERAL_WEEK-141|1<<d.LITERAL_YEAR-141|1<<d.IDENTIFIER-141|1<<d.NUMERIC_LITERAL-141|1<<d.INTEGER_LITERAL-141|1<<d.SQL_BEGIN-141))&&(this.state=1246,this.fieldExpr(0)),this.state=1249,this.match(d.CPAREN);break;case 9:s=new _fe(s),this._ctx=s,o=s,this.state=1251,this.fieldPath(),this.state=1252,this.match(d.DOT),this.state=1253,this.aggregate(),this.state=1254,this.match(d.OPAREN),this.state=1256,this._errHandler.sync(this),a=this._input.LA(1),(!(a-36&-32)&&1<<a-36&(1<<d.ALL-36|1<<d.AVG-36|1<<d.CASE-36|1<<d.CAST-36|1<<d.COUNT-36|1<<d.DAY-36|1<<d.EXCLUDE-36|1<<d.FALSE-36|1<<d.HOUR-36)||!(a-73&-32)&&1<<a-73&(1<<d.MAX-73|1<<d.MIN-73|1<<d.MINUTE-73|1<<d.MONTH-73|1<<d.NOT-73|1<<d.NOW-73|1<<d.NULL-73|1<<d.PICK-73|1<<d.QUARTER-73|1<<d.SECOND-73|1<<d.SOURCE_KW-73|1<<d.SUM-73|1<<d.TRUE-73|1<<d.WEEK-73|1<<d.YEAR-73)||!(a-105&-32)&&1<<a-105&(1<<d.HACKY_REGEX-105|1<<d.RAW_SQ-105|1<<d.RAW_DQ-105|1<<d.SQ3_FILTER-105|1<<d.SQ_FILTER-105|1<<d.DQ3_FILTER-105|1<<d.DQ_FILTER-105|1<<d.BQ3_FILTER-105|1<<d.BQ_FILTER-105|1<<d.SQ_STRING-105|1<<d.DQ_STRING-105|1<<d.BQ_STRING-105|1<<d.OPAREN-105|1<<d.OBRACK-105|1<<d.OCURLY-105)||!(a-141&-32)&&1<<a-141&(1<<d.MINUS-141|1<<d.LITERAL_TIMESTAMP-141|1<<d.LITERAL_HOUR-141|1<<d.LITERAL_DAY-141|1<<d.LITERAL_QUARTER-141|1<<d.LITERAL_MONTH-141|1<<d.LITERAL_WEEK-141|1<<d.LITERAL_YEAR-141|1<<d.IDENTIFIER-141|1<<d.NUMERIC_LITERAL-141|1<<d.INTEGER_LITERAL-141|1<<d.SQL_BEGIN-141))&&(this.state=1255,this.fieldExpr(0)),this.state=1258,this.match(d.CPAREN);break;case 10:s=new vfe(s),this._ctx=s,o=s,this.state=1260,this.match(d.OPAREN),this.state=1261,this.fieldExpr(0),this.state=1262,this.match(d.CPAREN);break;case 11:s=new Cfe(s),this._ctx=s,o=s,this.state=1264,this.fieldPath(),this.state=1265,this.match(d.DOT),this.state=1266,this.id(),this.state=1267,this.match(d.OPAREN),this.state=1269,this._errHandler.sync(this),a=this._input.LA(1),(!(a-36&-32)&&1<<a-36&(1<<d.ALL-36|1<<d.AVG-36|1<<d.CASE-36|1<<d.CAST-36|1<<d.COUNT-36|1<<d.DAY-36|1<<d.EXCLUDE-36|1<<d.FALSE-36|1<<d.HOUR-36)||!(a-73&-32)&&1<<a-73&(1<<d.MAX-73|1<<d.MIN-73|1<<d.MINUTE-73|1<<d.MONTH-73|1<<d.NOT-73|1<<d.NOW-73|1<<d.NULL-73|1<<d.PICK-73|1<<d.QUARTER-73|1<<d.SECOND-73|1<<d.SOURCE_KW-73|1<<d.SUM-73|1<<d.TRUE-73|1<<d.WEEK-73|1<<d.YEAR-73)||!(a-105&-32)&&1<<a-105&(1<<d.HACKY_REGEX-105|1<<d.RAW_SQ-105|1<<d.RAW_DQ-105|1<<d.SQ3_FILTER-105|1<<d.SQ_FILTER-105|1<<d.DQ3_FILTER-105|1<<d.DQ_FILTER-105|1<<d.BQ3_FILTER-105|1<<d.BQ_FILTER-105|1<<d.SQ_STRING-105|1<<d.DQ_STRING-105|1<<d.BQ_STRING-105|1<<d.OPAREN-105|1<<d.OBRACK-105|1<<d.OCURLY-105)||!(a-141&-32)&&1<<a-141&(1<<d.MINUS-141|1<<d.LITERAL_TIMESTAMP-141|1<<d.LITERAL_HOUR-141|1<<d.LITERAL_DAY-141|1<<d.LITERAL_QUARTER-141|1<<d.LITERAL_MONTH-141|1<<d.LITERAL_WEEK-141|1<<d.LITERAL_YEAR-141|1<<d.IDENTIFIER-141|1<<d.NUMERIC_LITERAL-141|1<<d.INTEGER_LITERAL-141|1<<d.SQL_BEGIN-141))&&(this.state=1268,this.argumentList()),this.state=1271,this.match(d.CPAREN);break;case 12:{switch(s=new Sfe(s),this._ctx=s,o=s,this.state=1281,this._errHandler.sync(this),this._input.LA(1)){case d.BQ_STRING:case d.IDENTIFIER:this.state=1273,this.id(),this.state=1278,this._errHandler.sync(this),a=this._input.LA(1),a===d.EXCLAM&&(this.state=1274,this.match(d.EXCLAM),this.state=1276,this._errHandler.sync(this),a=this._input.LA(1),(a===d.BOOLEAN||a===d.DATE||!(a-80&-32)&&1<<a-80&(1<<d.NUMBER-80|1<<d.STRING-80|1<<d.TIMESTAMP-80))&&(this.state=1275,this.malloyType()));break;case d.DAY:case d.HOUR:case d.MINUTE:case d.MONTH:case d.QUARTER:case d.SECOND:case d.WEEK:case d.YEAR:this.state=1280,this.timeframe();break;default:throw new tn.NoViableAltException(this)}this.state=1283,this.match(d.OPAREN),this.state=1285,this._errHandler.sync(this),a=this._input.LA(1),(!(a-36&-32)&&1<<a-36&(1<<d.ALL-36|1<<d.AVG-36|1<<d.CASE-36|1<<d.CAST-36|1<<d.COUNT-36|1<<d.DAY-36|1<<d.EXCLUDE-36|1<<d.FALSE-36|1<<d.HOUR-36)||!(a-73&-32)&&1<<a-73&(1<<d.MAX-73|1<<d.MIN-73|1<<d.MINUTE-73|1<<d.MONTH-73|1<<d.NOT-73|1<<d.NOW-73|1<<d.NULL-73|1<<d.PICK-73|1<<d.QUARTER-73|1<<d.SECOND-73|1<<d.SOURCE_KW-73|1<<d.SUM-73|1<<d.TRUE-73|1<<d.WEEK-73|1<<d.YEAR-73)||!(a-105&-32)&&1<<a-105&(1<<d.HACKY_REGEX-105|1<<d.RAW_SQ-105|1<<d.RAW_DQ-105|1<<d.SQ3_FILTER-105|1<<d.SQ_FILTER-105|1<<d.DQ3_FILTER-105|1<<d.DQ_FILTER-105|1<<d.BQ3_FILTER-105|1<<d.BQ_FILTER-105|1<<d.SQ_STRING-105|1<<d.DQ_STRING-105|1<<d.BQ_STRING-105|1<<d.OPAREN-105|1<<d.OBRACK-105|1<<d.OCURLY-105)||!(a-141&-32)&&1<<a-141&(1<<d.MINUS-141|1<<d.LITERAL_TIMESTAMP-141|1<<d.LITERAL_HOUR-141|1<<d.LITERAL_DAY-141|1<<d.LITERAL_QUARTER-141|1<<d.LITERAL_MONTH-141|1<<d.LITERAL_WEEK-141|1<<d.LITERAL_YEAR-141|1<<d.IDENTIFIER-141|1<<d.NUMERIC_LITERAL-141|1<<d.INTEGER_LITERAL-141|1<<d.SQL_BEGIN-141))&&(this.state=1284,this.argumentList()),this.state=1287,this.match(d.CPAREN)}break;case 13:s=new bfe(s),this._ctx=s,o=s,this.state=1289,this.pickStatement();break;case 14:s=new Tfe(s),this._ctx=s,o=s,this.state=1290,this.caseStatement();break;case 15:{for(s=new Rfe(s),this._ctx=s,o=s,this.state=1291,this.ungroup(),this.state=1292,this.match(d.OPAREN),this.state=1293,this.fieldExpr(0),this.state=1298,this._errHandler.sync(this),a=this._input.LA(1);a===d.COMMA;)this.state=1294,this.match(d.COMMA),this.state=1295,this.fieldName(),this.state=1300,this._errHandler.sync(this),a=this._input.LA(1);this.state=1301,this.match(d.CPAREN)}break}for(this._ctx._stop=this._input.tryLT(-1),this.state=1377,this._errHandler.sync(this),l=this.interpreter.adaptivePredict(this._input,143,this._ctx);l!==2&&l!==en.ATN.INVALID_ALT_NUMBER;){if(l===1)switch(this._parseListeners!=null&&this.triggerExitRuleEvent(),o=s,this.state=1375,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,142,this._ctx)){case 1:{if(s=new sfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1305,!this.precpred(this._ctx,24))throw this.createFailedPredicateException("this.precpred(this._ctx, 24)");this.state=1306,a=this._input.LA(1),!(a-142&-32)&&1<<a-142&(1<<d.STAR-142|1<<d.SLASH-142|1<<d.PERCENT-142)?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this),this.state=1307,this.fieldExpr(25)}break;case 2:{if(s=new ofe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1308,!this.precpred(this._ctx,23))throw this.createFailedPredicateException("this.precpred(this._ctx, 23)");this.state=1309,a=this._input.LA(1),a===d.PLUS||a===d.MINUS?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this),this.state=1310,this.fieldExpr(24)}break;case 3:{if(s=new ufe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1311,!this.precpred(this._ctx,22))throw this.createFailedPredicateException("this.precpred(this._ctx, 22)");this.state=1312,this.match(d.TO),this.state=1313,this.fieldExpr(23)}break;case 4:{if(s=new ffe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1314,!this.precpred(this._ctx,18))throw this.createFailedPredicateException("this.precpred(this._ctx, 18)");this.state=1315,this.compareOp(),this.state=1316,this.fieldExpr(19)}break;case 5:{if(s=new xfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1318,!this.precpred(this._ctx,17))throw this.createFailedPredicateException("this.precpred(this._ctx, 17)");this.state=1320,this._errHandler.sync(this),a=this._input.LA(1),a===d.NOT&&(this.state=1319,this.match(d.NOT)),this.state=1322,this.match(d.LIKE),this.state=1323,this.fieldExpr(18)}break;case 6:{if(s=new gfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1324,!this.precpred(this._ctx,12))throw this.createFailedPredicateException("this.precpred(this._ctx, 12)");this.state=1325,this.match(d.AND),this.state=1326,this.fieldExpr(13)}break;case 7:{if(s=new yfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1327,!this.precpred(this._ctx,11))throw this.createFailedPredicateException("this.precpred(this._ctx, 11)");this.state=1328,this.match(d.OR),this.state=1329,this.fieldExpr(12)}break;case 8:{if(s=new Efe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1330,!this.precpred(this._ctx,10))throw this.createFailedPredicateException("this.precpred(this._ctx, 10)");this.state=1331,this.match(d.DOUBLE_QMARK),this.state=1332,this.fieldExpr(11)}break;case 9:{if(s=new efe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1333,!this.precpred(this._ctx,30))throw this.createFailedPredicateException("this.precpred(this._ctx, 30)");this.state=1334,this.fieldProperties()}break;case 10:{if(s=new tfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1335,!this.precpred(this._ctx,29))throw this.createFailedPredicateException("this.precpred(this._ctx, 29)");this.state=1336,this.timeframe()}break;case 11:{if(s=new nfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1337,!this.precpred(this._ctx,28))throw this.createFailedPredicateException("this.precpred(this._ctx, 28)");this.state=1338,this.match(d.DOT),this.state=1339,this.timeframe()}break;case 12:{if(s=new CM(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1340,!this.precpred(this._ctx,27))throw this.createFailedPredicateException("this.precpred(this._ctx, 27)");this.state=1341,this.match(d.DOUBLECOLON),this.state=1342,this.malloyOrSQLType()}break;case 13:{if(s=new rfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1343,!this.precpred(this._ctx,26))throw this.createFailedPredicateException("this.precpred(this._ctx, 26)");this.state=1344,this.match(d.TRIPLECOLON),this.state=1345,this.malloyOrSQLType()}break;case 14:{if(s=new afe(new Te(r,i)),s._startAt=o,this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1346,!this.precpred(this._ctx,21))throw this.createFailedPredicateException("this.precpred(this._ctx, 21)");this.state=1347,this.match(d.FOR),this.state=1348,s._duration=this.fieldExpr(0),this.state=1349,this.timeframe()}break;case 15:{if(s=new lfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1351,!this.precpred(this._ctx,20))throw this.createFailedPredicateException("this.precpred(this._ctx, 20)");this.state=1352,this.match(d.AMPER),this.state=1353,this.partialAllowedFieldExpr()}break;case 16:{if(s=new cfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1354,!this.precpred(this._ctx,19))throw this.createFailedPredicateException("this.precpred(this._ctx, 19)");this.state=1355,this.match(d.BAR),this.state=1356,this.partialAllowedFieldExpr()}break;case 17:{if(s=new dfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1357,!this.precpred(this._ctx,16))throw this.createFailedPredicateException("this.precpred(this._ctx, 16)");this.state=1358,this.match(d.IS),this.state=1360,this._errHandler.sync(this),a=this._input.LA(1),a===d.NOT&&(this.state=1359,this.match(d.NOT)),this.state=1362,this.match(d.NULL)}break;case 18:{if(s=new hfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1363,!this.precpred(this._ctx,15))throw this.createFailedPredicateException("this.precpred(this._ctx, 15)");this.state=1365,this._errHandler.sync(this),a=this._input.LA(1),a===d.NOT&&(this.state=1364,this.match(d.NOT)),this.state=1367,this.match(d.IN),this.state=1368,this.match(d.OPAREN),this.state=1369,this.fieldExprList(),this.state=1370,this.match(d.CPAREN)}break;case 19:{if(s=new pfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1372,!this.precpred(this._ctx,14))throw this.createFailedPredicateException("this.precpred(this._ctx, 14)");this.state=1373,this.match(d.QMARK),this.state=1374,this.partialAllowedFieldExpr()}break}this.state=1379,this._errHandler.sync(this),l=this.interpreter.adaptivePredict(this._input,143,this._ctx)}}}catch(l){if(l instanceof me.RecognitionException)s.exception=l,this._errHandler.reportError(this,l),this._errHandler.recover(this,l);else throw l}finally{this.unrollRecursionContexts(r)}return s}partialCompare(){let e=new SM(this._ctx,this.state);this.enterRule(e,252,d.RULE_partialCompare);try{this.enterOuterAlt(e,1),this.state=1380,this.compareOp(),this.state=1381,this.fieldExpr(0)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}partialTest(){let e=new bM(this._ctx,this.state);this.enterRule(e,254,d.RULE_partialTest);let r;try{switch(this.state=1389,this._errHandler.sync(this),this._input.LA(1)){case d.LT:case d.GT:case d.EQ:case d.NE:case d.LTE:case d.GTE:case d.NOT_MATCH:case d.MATCH:this.enterOuterAlt(e,1),this.state=1383,this.partialCompare();break;case d.IS:this.enterOuterAlt(e,2),this.state=1384,this.match(d.IS),this.state=1386,this._errHandler.sync(this),r=this._input.LA(1),r===d.NOT&&(this.state=1385,this.match(d.NOT)),this.state=1388,this.match(d.NULL);break;default:throw new tn.NoViableAltException(this)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}partialAllowedFieldExpr(){let e=new ld(this._ctx,this.state);this.enterRule(e,256,d.RULE_partialAllowedFieldExpr);try{switch(this.state=1397,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,146,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=1391,this.partialTest();break;case 2:this.enterOuterAlt(e,2),this.state=1392,this.match(d.OPAREN),this.state=1393,this.partialTest(),this.state=1394,this.match(d.CPAREN);break;case 3:this.enterOuterAlt(e,3),this.state=1396,this.fieldExpr(0);break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}fieldExprList(){let e=new TM(this._ctx,this.state);this.enterRule(e,258,d.RULE_fieldExprList);let r;try{for(this.enterOuterAlt(e,1),this.state=1399,this.fieldExpr(0),this.state=1404,this._errHandler.sync(this),r=this._input.LA(1);r===d.COMMA;)this.state=1400,this.match(d.COMMA),this.state=1401,this.fieldExpr(0),this.state=1406,this._errHandler.sync(this),r=this._input.LA(1)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}pickStatement(){let e=new RM(this._ctx,this.state);this.enterRule(e,260,d.RULE_pickStatement);try{let r;this.enterOuterAlt(e,1);{this.state=1408,this._errHandler.sync(this),r=1;do{switch(r){case 1:this.state=1407,this.pick();break;default:throw new tn.NoViableAltException(this)}this.state=1410,this._errHandler.sync(this),r=this.interpreter.adaptivePredict(this._input,148,this._ctx)}while(r!==2&&r!==en.ATN.INVALID_ALT_NUMBER);switch(this.state=1414,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,149,this._ctx)){case 1:this.state=1412,this.match(d.ELSE),this.state=1413,e._pickElse=this.fieldExpr(0);break}}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}pick(){let e=new xR(this._ctx,this.state);this.enterRule(e,262,d.RULE_pick);let r;try{this.enterOuterAlt(e,1),this.state=1416,this.match(d.PICK),this.state=1418,this._errHandler.sync(this),r=this._input.LA(1),(!(r-36&-32)&&1<<r-36&(1<<d.ALL-36|1<<d.AVG-36|1<<d.CASE-36|1<<d.CAST-36|1<<d.COUNT-36|1<<d.DAY-36|1<<d.EXCLUDE-36|1<<d.FALSE-36|1<<d.HOUR-36)||!(r-73&-32)&&1<<r-73&(1<<d.MAX-73|1<<d.MIN-73|1<<d.MINUTE-73|1<<d.MONTH-73|1<<d.NOT-73|1<<d.NOW-73|1<<d.NULL-73|1<<d.PICK-73|1<<d.QUARTER-73|1<<d.SECOND-73|1<<d.SOURCE_KW-73|1<<d.SUM-73|1<<d.TRUE-73|1<<d.WEEK-73|1<<d.YEAR-73)||!(r-105&-32)&&1<<r-105&(1<<d.HACKY_REGEX-105|1<<d.RAW_SQ-105|1<<d.RAW_DQ-105|1<<d.SQ3_FILTER-105|1<<d.SQ_FILTER-105|1<<d.DQ3_FILTER-105|1<<d.DQ_FILTER-105|1<<d.BQ3_FILTER-105|1<<d.BQ_FILTER-105|1<<d.SQ_STRING-105|1<<d.DQ_STRING-105|1<<d.BQ_STRING-105|1<<d.OPAREN-105|1<<d.OBRACK-105|1<<d.OCURLY-105)||!(r-141&-32)&&1<<r-141&(1<<d.MINUS-141|1<<d.LITERAL_TIMESTAMP-141|1<<d.LITERAL_HOUR-141|1<<d.LITERAL_DAY-141|1<<d.LITERAL_QUARTER-141|1<<d.LITERAL_MONTH-141|1<<d.LITERAL_WEEK-141|1<<d.LITERAL_YEAR-141|1<<d.IDENTIFIER-141|1<<d.NUMERIC_LITERAL-141|1<<d.INTEGER_LITERAL-141|1<<d.SQL_BEGIN-141))&&(this.state=1417,e._pickValue=this.fieldExpr(0)),this.state=1420,this.match(d.WHEN),this.state=1421,e._pickWhen=this.partialAllowedFieldExpr()}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}caseStatement(){let e=new DM(this._ctx,this.state);this.enterRule(e,264,d.RULE_caseStatement);let r;try{this.enterOuterAlt(e,1);{this.state=1423,this.match(d.CASE),this.state=1425,this._errHandler.sync(this),r=this._input.LA(1),(!(r-36&-32)&&1<<r-36&(1<<d.ALL-36|1<<d.AVG-36|1<<d.CASE-36|1<<d.CAST-36|1<<d.COUNT-36|1<<d.DAY-36|1<<d.EXCLUDE-36|1<<d.FALSE-36|1<<d.HOUR-36)||!(r-73&-32)&&1<<r-73&(1<<d.MAX-73|1<<d.MIN-73|1<<d.MINUTE-73|1<<d.MONTH-73|1<<d.NOT-73|1<<d.NOW-73|1<<d.NULL-73|1<<d.PICK-73|1<<d.QUARTER-73|1<<d.SECOND-73|1<<d.SOURCE_KW-73|1<<d.SUM-73|1<<d.TRUE-73|1<<d.WEEK-73|1<<d.YEAR-73)||!(r-105&-32)&&1<<r-105&(1<<d.HACKY_REGEX-105|1<<d.RAW_SQ-105|1<<d.RAW_DQ-105|1<<d.SQ3_FILTER-105|1<<d.SQ_FILTER-105|1<<d.DQ3_FILTER-105|1<<d.DQ_FILTER-105|1<<d.BQ3_FILTER-105|1<<d.BQ_FILTER-105|1<<d.SQ_STRING-105|1<<d.DQ_STRING-105|1<<d.BQ_STRING-105|1<<d.OPAREN-105|1<<d.OBRACK-105|1<<d.OCURLY-105)||!(r-141&-32)&&1<<r-141&(1<<d.MINUS-141|1<<d.LITERAL_TIMESTAMP-141|1<<d.LITERAL_HOUR-141|1<<d.LITERAL_DAY-141|1<<d.LITERAL_QUARTER-141|1<<d.LITERAL_MONTH-141|1<<d.LITERAL_WEEK-141|1<<d.LITERAL_YEAR-141|1<<d.IDENTIFIER-141|1<<d.NUMERIC_LITERAL-141|1<<d.INTEGER_LITERAL-141|1<<d.SQL_BEGIN-141))&&(this.state=1424,e._valueExpr=this.fieldExpr(0)),this.state=1428,this._errHandler.sync(this),r=this._input.LA(1);do this.state=1427,this.caseWhen(),this.state=1430,this._errHandler.sync(this),r=this._input.LA(1);while(r===d.WHEN);this.state=1434,this._errHandler.sync(this),r=this._input.LA(1),r===d.ELSE&&(this.state=1432,this.match(d.ELSE),this.state=1433,e._caseElse=this.fieldExpr(0)),this.state=1436,this.match(d.END)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}caseWhen(){let e=new dR(this._ctx,this.state);this.enterRule(e,266,d.RULE_caseWhen);try{this.enterOuterAlt(e,1),this.state=1438,this.match(d.WHEN),this.state=1439,e._condition=this.fieldExpr(0),this.state=1440,this.match(d.THEN),this.state=1441,e._result=this.fieldExpr(0)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}recordKey(){let e=new OM(this._ctx,this.state);this.enterRule(e,268,d.RULE_recordKey);try{this.enterOuterAlt(e,1),this.state=1443,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}recordElement(){let e=new S2(this._ctx,this.state);this.enterRule(e,270,d.RULE_recordElement);try{switch(this.state=1452,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,155,this._ctx)){case 1:e=new Dfe(e),this.enterOuterAlt(e,1),this.state=1445,this.fieldPath();break;case 2:e=new Ofe(e),this.enterOuterAlt(e,2);{switch(this.state=1449,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,154,this._ctx)){case 1:this.state=1446,this.recordKey(),this.state=1447,this.match(d.IS);break}this.state=1451,this.fieldExpr(0)}break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}argumentList(){let e=new hR(this._ctx,this.state);this.enterRule(e,272,d.RULE_argumentList);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=1454,this.fieldExpr(0),this.state=1459,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,156,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=1455,this.match(d.COMMA),this.state=1456,this.fieldExpr(0)),this.state=1461,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,156,this._ctx);this.state=1463,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1462,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}fieldNameList(){let e=new b2(this._ctx,this.state);this.enterRule(e,274,d.RULE_fieldNameList);let r;try{let i;for(this.enterOuterAlt(e,1),this.state=1465,this.fieldName(),this.state=1472,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,159,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=1467,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1466,this.match(d.COMMA)),this.state=1469,this.fieldName()),this.state=1474,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,159,this._ctx)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}fieldCollection(){let e=new FM(this._ctx,this.state);this.enterRule(e,276,d.RULE_fieldCollection);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=1475,this.collectionMember(),this.state=1482,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,161,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=1477,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1476,this.match(d.COMMA)),this.state=1479,this.collectionMember()),this.state=1484,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,161,this._ctx);this.state=1486,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1485,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}collectionWildCard(){let e=new pE(this._ctx,this.state);this.enterRule(e,278,d.RULE_collectionWildCard);let r;try{switch(this.enterOuterAlt(e,1),this.state=1491,this._errHandler.sync(this),r=this._input.LA(1),(r===d.BQ_STRING||r===d.IDENTIFIER)&&(this.state=1488,this.fieldPath(),this.state=1489,this.match(d.DOT)),this.state=1493,this.match(d.STAR),this.state=1495,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,164,this._ctx)){case 1:this.state=1494,this.starQualified();break}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}starQualified(){let e=new pR(this._ctx,this.state);this.enterRule(e,280,d.RULE_starQualified);let r;try{this.enterOuterAlt(e,1);{this.state=1497,this.match(d.OCURLY),this.state=1501,this._errHandler.sync(this),r=this._input.LA(1);do{switch(this.state=1501,this._errHandler.sync(this),this._input.LA(1)){case d.EXCEPT:this.state=1498,this.match(d.EXCEPT),this.state=1499,this.fieldNameList();break;case d.COMMA:this.state=1500,this.match(d.COMMA);break;default:throw new tn.NoViableAltException(this)}this.state=1503,this._errHandler.sync(this),r=this._input.LA(1)}while(r===d.EXCEPT||r===d.COMMA);this.state=1505,this.match(d.CCURLY)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}taggedRef(){let e=new mR(this._ctx,this.state);this.enterRule(e,282,d.RULE_taggedRef);let r;try{this.enterOuterAlt(e,1),this.state=1507,this.tags(),this.state=1508,this.fieldPath(),this.state=1510,this._errHandler.sync(this),r=this._input.LA(1),r===d.DOT&&(this.state=1509,this.refExpr())}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}refExpr(){let e=new wM(this._ctx,this.state);this.enterRule(e,284,d.RULE_refExpr);try{switch(this.state=1519,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,168,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=1512,this.match(d.DOT),this.state=1513,this.timeframe();break;case 2:this.enterOuterAlt(e,2),this.state=1514,this.match(d.DOT),this.state=1515,this.aggregate(),this.state=1516,this.match(d.OPAREN),this.state=1517,this.match(d.CPAREN);break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}collectionMember(){let e=new gR(this._ctx,this.state);this.enterRule(e,286,d.RULE_collectionMember);try{switch(this.state=1524,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,169,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=1521,this.taggedRef();break;case 2:this.enterOuterAlt(e,2),this.state=1522,this.collectionWildCard();break;case 3:this.enterOuterAlt(e,3),this.state=1523,this.fieldDef();break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}fieldPath(){let e=new Na(this._ctx,this.state);this.enterRule(e,288,d.RULE_fieldPath);try{let r;for(this.enterOuterAlt(e,1),this.state=1526,this.fieldName(),this.state=1531,this._errHandler.sync(this),r=this.interpreter.adaptivePredict(this._input,170,this._ctx);r!==2&&r!==en.ATN.INVALID_ALT_NUMBER;)r===1&&(this.state=1527,this.match(d.DOT),this.state=1528,this.fieldName()),this.state=1533,this._errHandler.sync(this),r=this.interpreter.adaptivePredict(this._input,170,this._ctx)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}joinName(){let e=new Ffe(this._ctx,this.state);this.enterRule(e,290,d.RULE_joinName);try{this.enterOuterAlt(e,1),this.state=1534,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}fieldName(){let e=new Ur(this._ctx,this.state);this.enterRule(e,292,d.RULE_fieldName);try{this.enterOuterAlt(e,1),this.state=1536,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sqlExploreNameRef(){let e=new wfe(this._ctx,this.state);this.enterRule(e,294,d.RULE_sqlExploreNameRef);try{this.enterOuterAlt(e,1),this.state=1538,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}nameSQLBlock(){let e=new Nfe(this._ctx,this.state);this.enterRule(e,296,d.RULE_nameSQLBlock);try{this.enterOuterAlt(e,1),this.state=1540,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}connectionName(){let e=new Lfe(this._ctx,this.state);this.enterRule(e,298,d.RULE_connectionName);try{this.enterOuterAlt(e,1),this.state=1542,this.string()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}tripFilterString(){let e=new NM(this._ctx,this.state);this.enterRule(e,300,d.RULE_tripFilterString);let r;try{this.enterOuterAlt(e,1),this.state=1544,r=this._input.LA(1),!(r-108&-32)&&1<<r-108&(1<<d.SQ3_FILTER-108|1<<d.DQ3_FILTER-108|1<<d.BQ3_FILTER-108)?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}tickFilterString(){let e=new LM(this._ctx,this.state);this.enterRule(e,302,d.RULE_tickFilterString);let r;try{this.enterOuterAlt(e,1),this.state=1546,r=this._input.LA(1),!(r-109&-32)&&1<<r-109&(1<<d.SQ_FILTER-109|1<<d.DQ_FILTER-109|1<<d.BQ_FILTER-109)?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}filterString(){let e=new IM(this._ctx,this.state);this.enterRule(e,304,d.RULE_filterString);try{switch(this.state=1550,this._errHandler.sync(this),this._input.LA(1)){case d.SQ3_FILTER:case d.DQ3_FILTER:case d.BQ3_FILTER:this.enterOuterAlt(e,1),this.state=1548,this.tripFilterString();break;case d.SQ_FILTER:case d.DQ_FILTER:case d.BQ_FILTER:this.enterOuterAlt(e,2),this.state=1549,this.tickFilterString();break;default:throw new tn.NoViableAltException(this)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}debugExpr(){let e=new Ife(this._ctx,this.state);this.enterRule(e,306,d.RULE_debugExpr);try{this.enterOuterAlt(e,1),this.state=1552,this.fieldExpr(0),this.state=1553,this.match(d.EOF)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}debugPartial(){let e=new Bfe(this._ctx,this.state);this.enterRule(e,308,d.RULE_debugPartial);try{this.enterOuterAlt(e,1),this.state=1555,this.partialAllowedFieldExpr(),this.state=1556,this.match(d.EOF)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}experimentalStatementForTesting(){let e=new BM(this._ctx,this.state);this.enterRule(e,310,d.RULE_experimentalStatementForTesting);try{this.enterOuterAlt(e,1),this.state=1558,this.match(d.SEMI),this.state=1559,this.match(d.SEMI),this.state=1560,this.match(d.OBRACK),this.state=1561,this.string(),this.state=1562,this.match(d.CBRACK)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sempred(e,r,i){switch(r){case 53:return this.sqExpr_sempred(e,i);case 62:return this.segExpr_sempred(e,i);case 125:return this.fieldExpr_sempred(e,i)}return!0}sqExpr_sempred(e,r){switch(r){case 0:return this.precpred(this._ctx,6);case 1:return this.precpred(this._ctx,5);case 2:return this.precpred(this._ctx,4);case 3:return this.precpred(this._ctx,3)}return!0}segExpr_sempred(e,r){switch(r){case 4:return this.precpred(this._ctx,1)}return!0}fieldExpr_sempred(e,r){switch(r){case 5:return this.precpred(this._ctx,24);case 6:return this.precpred(this._ctx,23);case 7:return this.precpred(this._ctx,22);case 8:return this.precpred(this._ctx,18);case 9:return this.precpred(this._ctx,17);case 10:return this.precpred(this._ctx,12);case 11:return this.precpred(this._ctx,11);case 12:return this.precpred(this._ctx,10);case 13:return this.precpred(this._ctx,30);case 14:return this.precpred(this._ctx,29);case 15:return this.precpred(this._ctx,28);case 16:return this.precpred(this._ctx,27);case 17:return this.precpred(this._ctx,26);case 18:return this.precpred(this._ctx,21);case 19:return this.precpred(this._ctx,20);case 20:return this.precpred(this._ctx,19);case 21:return this.precpred(this._ctx,16);case 22:return this.precpred(this._ctx,15);case 23:return this.precpred(this._ctx,14)}return!0}static get _ATN(){return d.__ATN||(d.__ATN=new sft.ATNDeserializer().deserialize(G0e.toCharArray(d._serializedATN))),d.__ATN}}w.MalloyParser=d,d.ACCEPT=1,d.AGGREGATE=2,d.CALCULATE=3,d.CALCULATION=4,d.CONNECTION=5,d.DECLARE=6,d.DIMENSION=7,d.EXCEPT=8,d.EXTENDQ=9,d.GROUP_BY=10,d.HAVING=11,d.INDEX=12,d.INTERNAL=13,d.JOIN_CROSS=14,d.JOIN_ONE=15,d.JOIN_MANY=16,d.LIMIT=17,d.MEASURE=18,d.NEST=19,d.ORDER_BY=20,d.PARTITION_BY=21,d.PRIMARY_KEY=22,d.PRIVATE=23,d.PROJECT=24,d.PUBLIC=25,d.QUERY=26,d.RENAME=27,d.RUN=28,d.SAMPLE=29,d.SELECT=30,d.SOURCE=31,d.TOP=32,d.WHERE=33,d.VIEW=34,d.TIMEZONE=35,d.ALL=36,d.AND=37,d.AS=38,d.ASC=39,d.AVG=40,d.BOOLEAN=41,d.BY=42,d.CASE=43,d.CAST=44,d.CONDITION=45,d.COUNT=46,d.COMPOSE=47,d.DATE=48,d.DAY=49,d.DESC=50,d.DISTINCT=51,d.ELSE=52,d.END=53,d.EXCLUDE=54,d.EXTEND=55,d.FALSE=56,d.FILTER=57,d.FULL=58,d.FOR=59,d.FROM=60,d.HAS=61,d.HOUR=62,d.IMPORT=63,d.INCLUDE=64,d.INNER=65,d.IS=66,d.IN=67,d.INTERNAL_KW=68,d.JSON=69,d.LAST=70,d.LEFT=71,d.LIKE=72,d.MAX=73,d.MIN=74,d.MINUTE=75,d.MONTH=76,d.NOT=77,d.NOW=78,d.NULL=79,d.NUMBER=80,d.ON=81,d.OR=82,d.PICK=83,d.PRIVATE_KW=84,d.PUBLIC_KW=85,d.QUARTER=86,d.RIGHT=87,d.SECOND=88,d.STRING=89,d.SOURCE_KW=90,d.SUM=91,d.SQL=92,d.TABLE=93,d.THEN=94,d.THIS=95,d.TIMESTAMP=96,d.TO=97,d.TRUE=98,d.TURTLE=99,d.WEEK=100,d.WHEN=101,d.WITH=102,d.YEAR=103,d.UNGROUPED=104,d.HACKY_REGEX=105,d.RAW_SQ=106,d.RAW_DQ=107,d.SQ3_FILTER=108,d.SQ_FILTER=109,d.DQ3_FILTER=110,d.DQ_FILTER=111,d.BQ3_FILTER=112,d.BQ_FILTER=113,d.SQ_STRING=114,d.DQ_STRING=115,d.BQ_STRING=116,d.DOC_ANNOTATION=117,d.ANNOTATION=118,d.AMPER=119,d.ARROW=120,d.FAT_ARROW=121,d.OPAREN=122,d.CPAREN=123,d.OBRACK=124,d.CBRACK=125,d.OCURLY=126,d.CCURLY=127,d.DOUBLECOLON=128,d.TRIPLECOLON=129,d.EXCLAM=130,d.COLON=131,d.COMMA=132,d.DOT=133,d.LT=134,d.GT=135,d.EQ=136,d.NE=137,d.LTE=138,d.GTE=139,d.PLUS=140,d.MINUS=141,d.STAR=142,d.STARSTAR=143,d.SLASH=144,d.BAR=145,d.SEMI=146,d.NOT_MATCH=147,d.MATCH=148,d.PERCENT=149,d.DOUBLE_QMARK=150,d.QMARK=151,d.LITERAL_TIMESTAMP=152,d.LITERAL_HOUR=153,d.LITERAL_DAY=154,d.LITERAL_QUARTER=155,d.LITERAL_MONTH=156,d.LITERAL_WEEK=157,d.LITERAL_YEAR=158,d.IDENTIFIER=159,d.PERCENT_LITERAL=160,d.NUMERIC_LITERAL=161,d.INTEGER_LITERAL=162,d.BLOCK_COMMENT=163,d.COMMENT_TO_EOL=164,d.WHITE_SPACE=165,d.SQL_BEGIN=166,d.UNWATED_CHARS_TRAILING_NUMBERS=167,d.UNEXPECTED_CHAR=168,d.OPEN_CODE=169,d.SQL_END=170,d.RULE_malloyDocument=0,d.RULE_malloyStatement=1,d.RULE_defineSourceStatement=2,d.RULE_defineQuery=3,d.RULE_topLevelAnonQueryDef=4,d.RULE_tags=5,d.RULE_isDefine=6,d.RULE_runStatement=7,d.RULE_sqlString=8,d.RULE_sqlInterpolation=9,d.RULE_importStatement=10,d.RULE_importSelect=11,d.RULE_importItem=12,d.RULE_importURL=13,d.RULE_docAnnotations=14,d.RULE_ignoredObjectAnnotations=15,d.RULE_ignoredModelAnnotations=16,d.RULE_topLevelQueryDefs=17,d.RULE_topLevelQueryDef=18,d.RULE_refineOperator=19,d.RULE_turtleName=20,d.RULE_sqlSource=21,d.RULE_exploreTable=22,d.RULE_connectionId=23,d.RULE_queryProperties=24,d.RULE_queryName=25,d.RULE_sourcePropertyList=26,d.RULE_sourceDefinition=27,d.RULE_sqExplore=28,d.RULE_sourceParameters=29,d.RULE_legalParamType=30,d.RULE_sourceParameter=31,d.RULE_parameterNameDef=32,d.RULE_sourceNameDef=33,d.RULE_exploreProperties=34,d.RULE_exploreStatement=35,d.RULE_accessLabel=36,d.RULE_accessModifierList=37,d.RULE_defMeasures=38,d.RULE_defDimensions=39,d.RULE_renameList=40,d.RULE_exploreRenameDef=41,d.RULE_defList=42,d.RULE_fieldDef=43,d.RULE_fieldNameDef=44,d.RULE_joinNameDef=45,d.RULE_declareStatement=46,d.RULE_joinStatement=47,d.RULE_queryExtend=48,d.RULE_modEither=49,d.RULE_sourceArguments=50,d.RULE_argumentId=51,d.RULE_sourceArgument=52,d.RULE_sqExpr=53,d.RULE_includeBlock=54,d.RULE_includeItem=55,d.RULE_orphanedAnnotation=56,d.RULE_accessLabelProp=57,d.RULE_includeExceptList=58,d.RULE_includeExceptListItem=59,d.RULE_includeList=60,d.RULE_includeField=61,d.RULE_segExpr=62,d.RULE_vExpr=63,d.RULE_queryExtendStatement=64,d.RULE_queryExtendStatementList=65,d.RULE_joinList=66,d.RULE_isExplore=67,d.RULE_matrixOperation=68,d.RULE_joinFrom=69,d.RULE_joinDef=70,d.RULE_joinExpression=71,d.RULE_filterStatement=72,d.RULE_fieldProperties=73,d.RULE_aggregateOrdering=74,d.RULE_aggregateOrderBySpec=75,d.RULE_aggregateOrderByStatement=76,d.RULE_fieldPropertyLimitStatement=77,d.RULE_fieldPropertyStatement=78,d.RULE_filterClauseList=79,d.RULE_whereStatement=80,d.RULE_havingStatement=81,d.RULE_subQueryDefList=82,d.RULE_exploreQueryNameDef=83,d.RULE_exploreQueryDef=84,d.RULE_queryStatement=85,d.RULE_queryJoinStatement=86,d.RULE_groupByStatement=87,d.RULE_queryFieldList=88,d.RULE_queryFieldEntry=89,d.RULE_nestStatement=90,d.RULE_nestedQueryList=91,d.RULE_nestEntry=92,d.RULE_aggregateStatement=93,d.RULE_calculateStatement=94,d.RULE_projectStatement=95,d.RULE_partitionByStatement=96,d.RULE_orderByStatement=97,d.RULE_ordering=98,d.RULE_orderBySpec=99,d.RULE_limitStatement=100,d.RULE_bySpec=101,d.RULE_topStatement=102,d.RULE_indexElement=103,d.RULE_indexFields=104,d.RULE_indexStatement=105,d.RULE_sampleStatement=106,d.RULE_timezoneStatement=107,d.RULE_queryAnnotation=108,d.RULE_sampleSpec=109,d.RULE_aggregate=110,d.RULE_malloyType=111,d.RULE_compareOp=112,d.RULE_string=113,d.RULE_shortString=114,d.RULE_rawString=115,d.RULE_numericLiteral=116,d.RULE_literal=117,d.RULE_dateLiteral=118,d.RULE_tablePath=119,d.RULE_tableURI=120,d.RULE_id=121,d.RULE_timeframe=122,d.RULE_ungroup=123,d.RULE_malloyOrSQLType=124,d.RULE_fieldExpr=125,d.RULE_partialCompare=126,d.RULE_partialTest=127,d.RULE_partialAllowedFieldExpr=128,d.RULE_fieldExprList=129,d.RULE_pickStatement=130,d.RULE_pick=131,d.RULE_caseStatement=132,d.RULE_caseWhen=133,d.RULE_recordKey=134,d.RULE_recordElement=135,d.RULE_argumentList=136,d.RULE_fieldNameList=137,d.RULE_fieldCollection=138,d.RULE_collectionWildCard=139,d.RULE_starQualified=140,d.RULE_taggedRef=141,d.RULE_refExpr=142,d.RULE_collectionMember=143,d.RULE_fieldPath=144,d.RULE_joinName=145,d.RULE_fieldName=146,d.RULE_sqlExploreNameRef=147,d.RULE_nameSQLBlock=148,d.RULE_connectionName=149,d.RULE_tripFilterString=150,d.RULE_tickFilterString=151,d.RULE_filterString=152,d.RULE_debugExpr=153,d.RULE_debugPartial=154,d.RULE_experimentalStatementForTesting=155,d.ruleNames=["malloyDocument","malloyStatement","defineSourceStatement","defineQuery","topLevelAnonQueryDef","tags","isDefine","runStatement","sqlString","sqlInterpolation","importStatement","importSelect","importItem","importURL","docAnnotations","ignoredObjectAnnotations","ignoredModelAnnotations","topLevelQueryDefs","topLevelQueryDef","refineOperator","turtleName","sqlSource","exploreTable","connectionId","queryProperties","queryName","sourcePropertyList","sourceDefinition","sqExplore","sourceParameters","legalParamType","sourceParameter","parameterNameDef","sourceNameDef","exploreProperties","exploreStatement","accessLabel","accessModifierList","defMeasures","defDimensions","renameList","exploreRenameDef","defList","fieldDef","fieldNameDef","joinNameDef","declareStatement","joinStatement","queryExtend","modEither","sourceArguments","argumentId","sourceArgument","sqExpr","includeBlock","includeItem","orphanedAnnotation","accessLabelProp","includeExceptList","includeExceptListItem","includeList","includeField","segExpr","vExpr","queryExtendStatement","queryExtendStatementList","joinList","isExplore","matrixOperation","joinFrom","joinDef","joinExpression","filterStatement","fieldProperties","aggregateOrdering","aggregateOrderBySpec","aggregateOrderByStatement","fieldPropertyLimitStatement","fieldPropertyStatement","filterClauseList","whereStatement","havingStatement","subQueryDefList","exploreQueryNameDef","exploreQueryDef","queryStatement","queryJoinStatement","groupByStatement","queryFieldList","queryFieldEntry","nestStatement","nestedQueryList","nestEntry","aggregateStatement","calculateStatement","projectStatement","partitionByStatement","orderByStatement","ordering","orderBySpec","limitStatement","bySpec","topStatement","indexElement","indexFields","indexStatement","sampleStatement","timezoneStatement","queryAnnotation","sampleSpec","aggregate","malloyType","compareOp","string","shortString","rawString","numericLiteral","literal","dateLiteral","tablePath","tableURI","id","timeframe","ungroup","malloyOrSQLType","fieldExpr","partialCompare","partialTest","partialAllowedFieldExpr","fieldExprList","pickStatement","pick","caseStatement","caseWhen","recordKey","recordElement","argumentList","fieldNameList","fieldCollection","collectionWildCard","starQualified","taggedRef","refExpr","collectionMember","fieldPath","joinName","fieldName","sqlExploreNameRef","nameSQLBlock","connectionName","tripFilterString","tickFilterString","filterString","debugExpr","debugPartial","experimentalStatementForTesting"],d._LITERAL_NAMES=[void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,"'&'","'->'","'=>'","'('","')'","'['","']'","'{'","'}'","'::'","':::'","'!'","':'","','","'.'","'<'","'>'","'='","'!='","'<='","'>='","'+'","'-'","'*'","'**'","'/'","'|'","';'","'!~'","'~'","'%'","'??'","'?'",void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,`'"""'`],d._SYMBOLIC_NAMES=[void 0,"ACCEPT","AGGREGATE","CALCULATE","CALCULATION","CONNECTION","DECLARE","DIMENSION","EXCEPT","EXTENDQ","GROUP_BY","HAVING","INDEX","INTERNAL","JOIN_CROSS","JOIN_ONE","JOIN_MANY","LIMIT","MEASURE","NEST","ORDER_BY","PARTITION_BY","PRIMARY_KEY","PRIVATE","PROJECT","PUBLIC","QUERY","RENAME","RUN","SAMPLE","SELECT","SOURCE","TOP","WHERE","VIEW","TIMEZONE","ALL","AND","AS","ASC","AVG","BOOLEAN","BY","CASE","CAST","CONDITION","COUNT","COMPOSE","DATE","DAY","DESC","DISTINCT","ELSE","END","EXCLUDE","EXTEND","FALSE","FILTER","FULL","FOR","FROM","HAS","HOUR","IMPORT","INCLUDE","INNER","IS","IN","INTERNAL_KW","JSON","LAST","LEFT","LIKE","MAX","MIN","MINUTE","MONTH","NOT","NOW","NULL","NUMBER","ON","OR","PICK","PRIVATE_KW","PUBLIC_KW","QUARTER","RIGHT","SECOND","STRING","SOURCE_KW","SUM","SQL","TABLE","THEN","THIS","TIMESTAMP","TO","TRUE","TURTLE","WEEK","WHEN","WITH","YEAR","UNGROUPED","HACKY_REGEX","RAW_SQ","RAW_DQ","SQ3_FILTER","SQ_FILTER","DQ3_FILTER","DQ_FILTER","BQ3_FILTER","BQ_FILTER","SQ_STRING","DQ_STRING","BQ_STRING","DOC_ANNOTATION","ANNOTATION","AMPER","ARROW","FAT_ARROW","OPAREN","CPAREN","OBRACK","CBRACK","OCURLY","CCURLY","DOUBLECOLON","TRIPLECOLON","EXCLAM","COLON","COMMA","DOT","LT","GT","EQ","NE","LTE","GTE","PLUS","MINUS","STAR","STARSTAR","SLASH","BAR","SEMI","NOT_MATCH","MATCH","PERCENT","DOUBLE_QMARK","QMARK","LITERAL_TIMESTAMP","LITERAL_HOUR","LITERAL_DAY","LITERAL_QUARTER","LITERAL_MONTH","LITERAL_WEEK","LITERAL_YEAR","IDENTIFIER","PERCENT_LITERAL","NUMERIC_LITERAL","INTEGER_LITERAL","BLOCK_COMMENT","COMMENT_TO_EOL","WHITE_SPACE","SQL_BEGIN","UNWATED_CHARS_TRAILING_NUMBERS","UNEXPECTED_CHAR","OPEN_CODE","SQL_END"],d.VOCABULARY=new lft.VocabularyImpl(d._LITERAL_NAMES,d._SYMBOLIC_NAMES,[]),d._serializedATNSegments=3,d._serializedATNSegment0=`줝쪺֍꾺体؇쉁¬؟     \x07 \x07\b \b 
1280
+ -ݱݦݱݨݱݩݱݫݱݯݲƷݳݵƶÛݴݳݵݸݶݷݶݴݷݹݸݶݹݺ\x07'ݺݻ\x07}ݻݼݼݽ\bÜݽƹݾހƶÛݿݾހރށނށݿނބރށބޅ\x07$ޅކ\x07$ކއ\x07$އވވމ\bÝމƻcLJǘǩǼȎȨȶɄɔɢɯɿʛʬʹˈ˔ˤ˸̷̩̋̈́͒ͫ̚͝͹·ΒΟΫλЉѕҞҦӞӭԳՄեժհշջց֋֐ֲֹ֣֭֗֜׃׈׏ימײ׷׹؁؃؋؍ؙؕ؝ڃڅښڜڞڡێې۪ۭۖۜۡۤ۲۷ܷ݃ݖݛݟݡݱݶށ\x07\x07\b\x07`,se._serializedATN=z0e.join([se._serializedATNSegment0,se._serializedATNSegment1,se._serializedATNSegment2,se._serializedATNSegment3],"");var w={},ift=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),sft=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),oft=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&ift(e,t,r);return sft(e,t),e};Object.defineProperty(w,"__esModule",{value:!0}),w.AccessLabelContext=w.DefIgnoreModel_stubContext=w.DefExploreAnnotationContext=w.DefExploreTimezoneContext=w.DefExploreQueryContext=w.DefExploreEditFieldContext=w.DefExploreRenameContext=w.DefExplorePrimaryKeyContext=w.DefExploreWhere_stubContext=w.DefJoin_stubContext=w.DefExploreMeasure_stubContext=w.DefExploreDimension_stubContext=w.ExploreStatementContext=w.ExplorePropertiesContext=w.SourceNameDefContext=w.ParameterNameDefContext=w.SourceParameterContext=w.LegalParamTypeContext=w.SourceParametersContext=w.SqExploreContext=w.SourceDefinitionContext=w.SourcePropertyListContext=w.QueryNameContext=w.QueryPropertiesContext=w.ConnectionIdContext=w.ExploreTableContext=w.SqlSourceContext=w.TurtleNameContext=w.RefineOperatorContext=w.TopLevelQueryDefContext=w.TopLevelQueryDefsContext=w.IgnoredModelAnnotationsContext=w.IgnoredObjectAnnotationsContext=w.DocAnnotationsContext=w.ImportURLContext=w.ImportItemContext=w.ImportSelectContext=w.ImportStatementContext=w.SqlInterpolationContext=w.SqlStringContext=w.RunStatementContext=w.IsDefineContext=w.TagsContext=w.TopLevelAnonQueryDefContext=w.Use_top_level_query_defsContext=w.DefineQueryContext=w.DefineSourceStatementContext=w.MalloyStatementContext=w.MalloyDocumentContext=w.MalloyParser=void 0,w.MatrixOperationContext=w.IsExploreContext=w.JoinListContext=w.QueryExtendStatementListContext=w.QueryExtendStatementContext=w.VArrowContext=w.VSegContext=w.VExprContext=w.SegRefineContext=w.SegParenContext=w.SegOpsContext=w.SegFieldContext=w.SegExprContext=w.IncludeFieldContext=w.IncludeListContext=w.IncludeExceptListItemContext=w.IncludeExceptListContext=w.AccessLabelPropContext=w.OrphanedAnnotationContext=w.IncludeItemContext=w.IncludeBlockContext=w.SQSQLContext=w.SQTableContext=w.SQIncludeContext=w.SQExtendedSourceContext=w.SQArrowContext=w.SQRefinedQueryContext=w.SQComposeContext=w.SQParensContext=w.SQIDContext=w.SqExprContext=w.SourceArgumentContext=w.ArgumentIdContext=w.SourceArgumentsContext=w.ModEitherContext=w.QueryExtendContext=w.DefJoinCrossContext=w.DefJoinManyContext=w.DefJoinOneContext=w.JoinStatementContext=w.DeclareStatementContext=w.JoinNameDefContext=w.FieldNameDefContext=w.FieldDefContext=w.DefListContext=w.ExploreRenameDefContext=w.RenameListContext=w.DefDimensionsContext=w.DefMeasuresContext=w.AccessModifierListContext=void 0,w.RawStringContext=w.ShortStringContext=w.StringContext=w.CompareOpContext=w.MalloyTypeContext=w.AggregateContext=w.SampleSpecContext=w.QueryAnnotationContext=w.TimezoneStatementContext=w.SampleStatementContext=w.IndexStatementContext=w.IndexFieldsContext=w.IndexElementContext=w.TopStatementContext=w.BySpecContext=w.LimitStatementContext=w.OrderBySpecContext=w.OrderingContext=w.OrderByStatementContext=w.PartitionByStatementContext=w.ProjectStatementContext=w.CalculateStatementContext=w.AggregateStatementContext=w.NestDefContext=w.NestEntryContext=w.NestedQueryListContext=w.NestStatementContext=w.QueryFieldEntryContext=w.QueryFieldListContext=w.GroupByStatementContext=w.QueryJoinStatementContext=w.QueryStatementContext=w.ExploreQueryDefContext=w.ExploreQueryNameDefContext=w.SubQueryDefListContext=w.HavingStatementContext=w.WhereStatementContext=w.FilterClauseListContext=w.FieldPropertyStatementContext=w.FieldPropertyLimitStatementContext=w.AggregateOrderByStatementContext=w.AggregateOrderBySpecContext=w.AggregateOrderingContext=w.FieldPropertiesContext=w.FilterStatementContext=w.JoinExpressionContext=w.JoinOnContext=w.JoinWithContext=w.JoinDefContext=w.JoinFromContext=void 0,w.ExprLogicalOrContext=w.ExprLogicalAndContext=w.ExprNotContext=w.ExprApplyContext=w.ExprWarnInContext=w.ExprNullCheckContext=w.ExprWarnLikeContext=w.ExprCompareContext=w.ExprOrTreeContext=w.ExprAndTreeContext=w.ExprForRangeContext=w.ExprRangeContext=w.ExprAddSubContext=w.ExprMulDivContext=w.ExprMinusContext=w.ExprSafeCastContext=w.ExprCastContext=w.ExprTimeTruncContext=w.ExprDurationContext=w.ExprFieldPropsContext=w.ExprLiteralRecordContext=w.ExprArrayLiteralContext=w.ExprLiteralContext=w.ExprFieldPathContext=w.FieldExprContext=w.MalloyOrSQLTypeContext=w.UngroupContext=w.TimeframeContext=w.IdContext=w.TableURIContext=w.TablePathContext=w.LiteralYearContext=w.LiteralQuarterContext=w.LiteralMonthContext=w.LiteralWeekContext=w.LiteralDayContext=w.LiteralHourContext=w.LiteralTimestampContext=w.DateLiteralContext=w.ExprNowContext=w.FilterString_stubContext=w.ExprRegexContext=w.ExprBoolContext=w.ExprNULLContext=w.ExprTimeContext=w.ExprNumberContext=w.Stub_rawStringContext=w.ExprStringContext=w.LiteralContext=w.NumericLiteralContext=void 0,w.ExperimentalStatementForTestingContext=w.DebugPartialContext=w.DebugExprContext=w.FilterStringContext=w.TickFilterStringContext=w.TripFilterStringContext=w.ConnectionNameContext=w.NameSQLBlockContext=w.SqlExploreNameRefContext=w.FieldNameContext=w.JoinNameContext=w.FieldPathContext=w.CollectionMemberContext=w.RefExprContext=w.TaggedRefContext=w.StarQualifiedContext=w.CollectionWildCardContext=w.FieldCollectionContext=w.FieldNameListContext=w.ArgumentListContext=w.RecordExprContext=w.RecordRefContext=w.RecordElementContext=w.RecordKeyContext=w.CaseWhenContext=w.CaseStatementContext=w.PickContext=w.PickStatementContext=w.FieldExprListContext=w.PartialAllowedFieldExprContext=w.PartialTestContext=w.PartialCompareContext=w.ExprUngroupContext=w.ExprCaseContext=w.ExprPickContext=w.ExprFuncContext=w.ExprAggFuncContext=w.ExprExprContext=w.ExprAggregateContext=w.ExprPathlessAggregateContext=w.ExprCoalesceContext=void 0;const en=uu(),uft=Sp(),aft=gc,tn=C3(),lft=Dp(),pe=ho(),cft=vp(),me=xo,qn=sn,fft=Fs,G0e=oft(Sn);class d extends lft.Parser{get vocabulary(){return d.VOCABULARY}get grammarFileName(){return"MalloyParser.g4"}get ruleNames(){return d.ruleNames}get serializedATN(){return d._serializedATN}createFailedPredicateException(e,r){return new aft.FailedPredicateException(this,e,r)}constructor(e){super(e),this._interp=new cft.ParserATNSimulator(d._ATN,this)}malloyDocument(){let e=new W0e(this._ctx,this.state);this.enterRule(e,0,d.RULE_malloyDocument);let r;try{this.enterOuterAlt(e,1);{for(this.state=316,this._errHandler.sync(this),r=this._input.LA(1);!(r&-32)&&1<<r&(1<<d.AGGREGATE|1<<d.CALCULATE|1<<d.DIMENSION|1<<d.EXCEPT|1<<d.GROUP_BY|1<<d.INTERNAL|1<<d.JOIN_CROSS|1<<d.JOIN_ONE|1<<d.JOIN_MANY|1<<d.MEASURE|1<<d.NEST|1<<d.PRIVATE|1<<d.PUBLIC|1<<d.QUERY|1<<d.RUN|1<<d.SELECT|1<<d.SOURCE)||!(r-34&-32)&&1<<r-34&(1<<d.VIEW-34|1<<d.ALL-34|1<<d.AVG-34|1<<d.CASE-34|1<<d.CAST-34|1<<d.COUNT-34|1<<d.COMPOSE-34|1<<d.DAY-34|1<<d.EXCLUDE-34|1<<d.FALSE-34|1<<d.HOUR-34|1<<d.IMPORT-34)||!(r-66&-32)&&1<<r-66&(1<<d.IS-66|1<<d.INTERNAL_KW-66|1<<d.MAX-66|1<<d.MIN-66|1<<d.MINUTE-66|1<<d.MONTH-66|1<<d.NOT-66|1<<d.NOW-66|1<<d.NULL-66|1<<d.PICK-66|1<<d.PRIVATE_KW-66|1<<d.PUBLIC_KW-66|1<<d.QUARTER-66|1<<d.SECOND-66|1<<d.SOURCE_KW-66|1<<d.SUM-66)||!(r-98&-32)&&1<<r-98&(1<<d.TRUE-98|1<<d.WEEK-98|1<<d.YEAR-98|1<<d.HACKY_REGEX-98|1<<d.RAW_SQ-98|1<<d.RAW_DQ-98|1<<d.SQ3_FILTER-98|1<<d.SQ_FILTER-98|1<<d.DQ3_FILTER-98|1<<d.DQ_FILTER-98|1<<d.BQ3_FILTER-98|1<<d.BQ_FILTER-98|1<<d.SQ_STRING-98|1<<d.DQ_STRING-98|1<<d.BQ_STRING-98|1<<d.DOC_ANNOTATION-98|1<<d.ANNOTATION-98|1<<d.OPAREN-98|1<<d.OBRACK-98|1<<d.OCURLY-98)||!(r-141&-32)&&1<<r-141&(1<<d.MINUS-141|1<<d.STAR-141|1<<d.SEMI-141|1<<d.LITERAL_TIMESTAMP-141|1<<d.LITERAL_HOUR-141|1<<d.LITERAL_DAY-141|1<<d.LITERAL_QUARTER-141|1<<d.LITERAL_MONTH-141|1<<d.LITERAL_WEEK-141|1<<d.LITERAL_YEAR-141|1<<d.IDENTIFIER-141|1<<d.NUMERIC_LITERAL-141|1<<d.INTEGER_LITERAL-141|1<<d.SQL_BEGIN-141);){switch(this.state=314,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,0,this._ctx)){case 1:this.state=312,this.malloyStatement();break;case 2:this.state=313,this.match(d.SEMI);break}this.state=318,this._errHandler.sync(this),r=this._input.LA(1)}this.state=319,this.match(d.EOF)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}malloyStatement(){let e=new DT(this._ctx,this.state);this.enterRule(e,2,d.RULE_malloyStatement);try{switch(this.state=328,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,2,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=321,this.defineSourceStatement();break;case 2:this.enterOuterAlt(e,2),this.state=322,this.defineQuery();break;case 3:this.enterOuterAlt(e,3),this.state=323,this.importStatement();break;case 4:this.enterOuterAlt(e,4),this.state=324,this.runStatement();break;case 5:this.enterOuterAlt(e,5),this.state=325,this.docAnnotations();break;case 6:this.enterOuterAlt(e,6),this.state=326,this.ignoredObjectAnnotations();break;case 7:this.enterOuterAlt(e,7),this.state=327,this.experimentalStatementForTesting();break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}defineSourceStatement(){let e=new Ak(this._ctx,this.state);this.enterRule(e,4,d.RULE_defineSourceStatement);try{this.enterOuterAlt(e,1),this.state=330,this.tags(),this.state=331,this.match(d.SOURCE),this.state=332,this.sourcePropertyList()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}defineQuery(){let e=new OT(this._ctx,this.state);this.enterRule(e,6,d.RULE_defineQuery);try{e=new V0e(e),this.enterOuterAlt(e,1),this.state=334,this.topLevelQueryDefs()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}topLevelAnonQueryDef(){let e=new _k(this._ctx,this.state);this.enterRule(e,8,d.RULE_topLevelAnonQueryDef);try{this.enterOuterAlt(e,1),this.state=336,this.tags(),this.state=337,this.sqExpr(0)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}tags(){let e=new Yt(this._ctx,this.state);this.enterRule(e,10,d.RULE_tags);let r;try{for(this.enterOuterAlt(e,1),this.state=342,this._errHandler.sync(this),r=this._input.LA(1);r===d.ANNOTATION;)this.state=339,this.match(d.ANNOTATION),this.state=344,this._errHandler.sync(this),r=this._input.LA(1)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}isDefine(){let e=new e0(this._ctx,this.state);this.enterRule(e,12,d.RULE_isDefine);try{this.enterOuterAlt(e,1),this.state=345,e._beforeIs=this.tags(),this.state=346,this.match(d.IS),this.state=347,e._afterIs=this.tags()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}runStatement(){let e=new vk(this._ctx,this.state);this.enterRule(e,14,d.RULE_runStatement);try{this.enterOuterAlt(e,1),this.state=349,this.tags(),this.state=350,this.match(d.RUN),this.state=351,this.topLevelAnonQueryDef()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sqlString(){let e=new FT(this._ctx,this.state);this.enterRule(e,16,d.RULE_sqlString);let r;try{this.enterOuterAlt(e,1);{for(this.state=353,this.match(d.SQL_BEGIN),this.state=357,this._errHandler.sync(this),r=this._input.LA(1);r===d.OPEN_CODE;)this.state=354,this.sqlInterpolation(),this.state=359,this._errHandler.sync(this),r=this._input.LA(1);this.state=360,this.match(d.SQL_END)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}sqlInterpolation(){let e=new wT(this._ctx,this.state);this.enterRule(e,18,d.RULE_sqlInterpolation);try{this.enterOuterAlt(e,1),this.state=362,this.match(d.OPEN_CODE),this.state=363,this.sqExpr(0),this.state=364,this.match(d.CCURLY)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}importStatement(){let e=new Ck(this._ctx,this.state);this.enterRule(e,20,d.RULE_importStatement);let r;try{this.enterOuterAlt(e,1),this.state=366,this.match(d.IMPORT),this.state=368,this._errHandler.sync(this),r=this._input.LA(1),r===d.OCURLY&&(this.state=367,this.importSelect()),this.state=370,this.importURL()}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}importSelect(){let e=new Sk(this._ctx,this.state);this.enterRule(e,22,d.RULE_importSelect);let r;try{this.enterOuterAlt(e,1);{for(this.state=372,this.match(d.OCURLY),this.state=373,this.importItem(),this.state=378,this._errHandler.sync(this),r=this._input.LA(1);r===d.COMMA;)this.state=374,this.match(d.COMMA),this.state=375,this.importItem(),this.state=380,this._errHandler.sync(this),r=this._input.LA(1);this.state=381,this.match(d.CCURLY),this.state=382,this.match(d.FROM)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}importItem(){let e=new NT(this._ctx,this.state);this.enterRule(e,24,d.RULE_importItem);let r;try{this.enterOuterAlt(e,1),this.state=384,this.id(),this.state=387,this._errHandler.sync(this),r=this._input.LA(1),r===d.IS&&(this.state=385,this.match(d.IS),this.state=386,this.id())}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}importURL(){let e=new bk(this._ctx,this.state);this.enterRule(e,26,d.RULE_importURL);try{this.enterOuterAlt(e,1),this.state=389,this.string()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}docAnnotations(){let e=new Tk(this._ctx,this.state);this.enterRule(e,28,d.RULE_docAnnotations);try{let r;this.enterOuterAlt(e,1);{this.state=392,this._errHandler.sync(this),r=1;do{switch(r){case 1:this.state=391,this.match(d.DOC_ANNOTATION);break;default:throw new tn.NoViableAltException(this)}this.state=394,this._errHandler.sync(this),r=this.interpreter.adaptivePredict(this._input,8,this._ctx)}while(r!==2&&r!==en.ATN.INVALID_ALT_NUMBER)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}ignoredObjectAnnotations(){let e=new Rk(this._ctx,this.state);this.enterRule(e,30,d.RULE_ignoredObjectAnnotations);try{let r;this.enterOuterAlt(e,1);{this.state=397,this._errHandler.sync(this),r=1;do{switch(r){case 1:this.state=396,this.match(d.ANNOTATION);break;default:throw new tn.NoViableAltException(this)}this.state=399,this._errHandler.sync(this),r=this.interpreter.adaptivePredict(this._input,9,this._ctx)}while(r!==2&&r!==en.ATN.INVALID_ALT_NUMBER)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}ignoredModelAnnotations(){let e=new LT(this._ctx,this.state);this.enterRule(e,32,d.RULE_ignoredModelAnnotations);try{let r;this.enterOuterAlt(e,1);{this.state=402,this._errHandler.sync(this),r=1;do{switch(r){case 1:this.state=401,this.match(d.DOC_ANNOTATION);break;default:throw new tn.NoViableAltException(this)}this.state=404,this._errHandler.sync(this),r=this.interpreter.adaptivePredict(this._input,10,this._ctx)}while(r!==2&&r!==en.ATN.INVALID_ALT_NUMBER)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}topLevelQueryDefs(){let e=new Dk(this._ctx,this.state);this.enterRule(e,34,d.RULE_topLevelQueryDefs);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=406,this.tags(),this.state=407,this.match(d.QUERY),this.state=408,this.topLevelQueryDef(),this.state=415,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,12,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=410,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=409,this.match(d.COMMA)),this.state=412,this.topLevelQueryDef()),this.state=417,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,12,this._ctx);this.state=419,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=418,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}topLevelQueryDef(){let e=new IT(this._ctx,this.state);this.enterRule(e,36,d.RULE_topLevelQueryDef);try{this.enterOuterAlt(e,1),this.state=421,this.tags(),this.state=422,this.queryName(),this.state=423,this.isDefine(),this.state=424,this.sqExpr(0)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}refineOperator(){let e=new Y0e(this._ctx,this.state);this.enterRule(e,38,d.RULE_refineOperator);try{this.enterOuterAlt(e,1),this.state=426,this.match(d.PLUS)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}turtleName(){let e=new K0e(this._ctx,this.state);this.enterRule(e,40,d.RULE_turtleName);try{this.enterOuterAlt(e,1),this.state=428,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sqlSource(){let e=new Ok(this._ctx,this.state);this.enterRule(e,42,d.RULE_sqlSource);try{this.enterOuterAlt(e,1);{switch(this.state=430,this.connectionId(),this.state=431,this.match(d.DOT),this.state=432,this.match(d.SQL),this.state=433,this.match(d.OPAREN),this.state=436,this._errHandler.sync(this),this._input.LA(1)){case d.SQL_BEGIN:this.state=434,this.sqlString();break;case d.SQ_STRING:case d.DQ_STRING:this.state=435,this.shortString();break;default:throw new tn.NoViableAltException(this)}this.state=438,this.match(d.CPAREN)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}exploreTable(){let e=new Fk(this._ctx,this.state);this.enterRule(e,44,d.RULE_exploreTable);try{this.enterOuterAlt(e,1),this.state=440,this.connectionId(),this.state=441,this.match(d.DOT),this.state=442,this.match(d.TABLE),this.state=443,this.match(d.OPAREN),this.state=444,this.tablePath(),this.state=445,this.match(d.CPAREN)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}connectionId(){let e=new BT(this._ctx,this.state);this.enterRule(e,46,d.RULE_connectionId);try{this.enterOuterAlt(e,1),this.state=447,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}queryProperties(){let e=new wk(this._ctx,this.state);this.enterRule(e,48,d.RULE_queryProperties);let r;try{this.enterOuterAlt(e,1);{for(this.state=449,this.match(d.OCURLY),this.state=454,this._errHandler.sync(this),r=this._input.LA(1);!(r&-32)&&1<<r&(1<<d.AGGREGATE|1<<d.CALCULATE|1<<d.DECLARE|1<<d.DIMENSION|1<<d.EXCEPT|1<<d.EXTENDQ|1<<d.GROUP_BY|1<<d.HAVING|1<<d.INDEX|1<<d.INTERNAL|1<<d.JOIN_CROSS|1<<d.JOIN_ONE|1<<d.JOIN_MANY|1<<d.LIMIT|1<<d.MEASURE|1<<d.NEST|1<<d.ORDER_BY|1<<d.PRIVATE|1<<d.PUBLIC|1<<d.QUERY|1<<d.RUN|1<<d.SAMPLE|1<<d.SELECT|1<<d.SOURCE)||!(r-32&-32)&&1<<r-32&(1<<d.TOP-32|1<<d.WHERE-32|1<<d.VIEW-32|1<<d.TIMEZONE-32|1<<d.ALL-32|1<<d.AVG-32|1<<d.CASE-32|1<<d.CAST-32|1<<d.COUNT-32|1<<d.COMPOSE-32|1<<d.DAY-32|1<<d.EXCLUDE-32|1<<d.FALSE-32|1<<d.HOUR-32)||!(r-66&-32)&&1<<r-66&(1<<d.IS-66|1<<d.INTERNAL_KW-66|1<<d.MAX-66|1<<d.MIN-66|1<<d.MINUTE-66|1<<d.MONTH-66|1<<d.NOT-66|1<<d.NOW-66|1<<d.NULL-66|1<<d.PICK-66|1<<d.PRIVATE_KW-66|1<<d.PUBLIC_KW-66|1<<d.QUARTER-66|1<<d.SECOND-66|1<<d.SOURCE_KW-66|1<<d.SUM-66)||!(r-98&-32)&&1<<r-98&(1<<d.TRUE-98|1<<d.WEEK-98|1<<d.YEAR-98|1<<d.HACKY_REGEX-98|1<<d.RAW_SQ-98|1<<d.RAW_DQ-98|1<<d.SQ3_FILTER-98|1<<d.SQ_FILTER-98|1<<d.DQ3_FILTER-98|1<<d.DQ_FILTER-98|1<<d.BQ3_FILTER-98|1<<d.BQ_FILTER-98|1<<d.SQ_STRING-98|1<<d.DQ_STRING-98|1<<d.BQ_STRING-98|1<<d.DOC_ANNOTATION-98|1<<d.ANNOTATION-98|1<<d.OPAREN-98|1<<d.OBRACK-98|1<<d.OCURLY-98)||!(r-141&-32)&&1<<r-141&(1<<d.MINUS-141|1<<d.STAR-141|1<<d.SEMI-141|1<<d.LITERAL_TIMESTAMP-141|1<<d.LITERAL_HOUR-141|1<<d.LITERAL_DAY-141|1<<d.LITERAL_QUARTER-141|1<<d.LITERAL_MONTH-141|1<<d.LITERAL_WEEK-141|1<<d.LITERAL_YEAR-141|1<<d.IDENTIFIER-141|1<<d.NUMERIC_LITERAL-141|1<<d.INTEGER_LITERAL-141|1<<d.SQL_BEGIN-141);){switch(this.state=452,this._errHandler.sync(this),this._input.LA(1)){case d.AGGREGATE:case d.CALCULATE:case d.DECLARE:case d.DIMENSION:case d.EXCEPT:case d.EXTENDQ:case d.GROUP_BY:case d.HAVING:case d.INDEX:case d.INTERNAL:case d.JOIN_CROSS:case d.JOIN_ONE:case d.JOIN_MANY:case d.LIMIT:case d.MEASURE:case d.NEST:case d.ORDER_BY:case d.PRIVATE:case d.PUBLIC:case d.QUERY:case d.RUN:case d.SAMPLE:case d.SELECT:case d.SOURCE:case d.TOP:case d.WHERE:case d.VIEW:case d.TIMEZONE:case d.ALL:case d.AVG:case d.CASE:case d.CAST:case d.COUNT:case d.COMPOSE:case d.DAY:case d.EXCLUDE:case d.FALSE:case d.HOUR:case d.IS:case d.INTERNAL_KW:case d.MAX:case d.MIN:case d.MINUTE:case d.MONTH:case d.NOT:case d.NOW:case d.NULL:case d.PICK:case d.PRIVATE_KW:case d.PUBLIC_KW:case d.QUARTER:case d.SECOND:case d.SOURCE_KW:case d.SUM:case d.TRUE:case d.WEEK:case d.YEAR:case d.HACKY_REGEX:case d.RAW_SQ:case d.RAW_DQ:case d.SQ3_FILTER:case d.SQ_FILTER:case d.DQ3_FILTER:case d.DQ_FILTER:case d.BQ3_FILTER:case d.BQ_FILTER:case d.SQ_STRING:case d.DQ_STRING:case d.BQ_STRING:case d.DOC_ANNOTATION:case d.ANNOTATION:case d.OPAREN:case d.OBRACK:case d.OCURLY:case d.MINUS:case d.STAR:case d.LITERAL_TIMESTAMP:case d.LITERAL_HOUR:case d.LITERAL_DAY:case d.LITERAL_QUARTER:case d.LITERAL_MONTH:case d.LITERAL_WEEK:case d.LITERAL_YEAR:case d.IDENTIFIER:case d.NUMERIC_LITERAL:case d.INTEGER_LITERAL:case d.SQL_BEGIN:this.state=450,this.queryStatement();break;case d.SEMI:this.state=451,this.match(d.SEMI);break;default:throw new tn.NoViableAltException(this)}this.state=456,this._errHandler.sync(this),r=this._input.LA(1)}this.state=457,this.match(d.CCURLY)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}queryName(){let e=new $T(this._ctx,this.state);this.enterRule(e,50,d.RULE_queryName);try{this.enterOuterAlt(e,1),this.state=459,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sourcePropertyList(){let e=new Nk(this._ctx,this.state);this.enterRule(e,52,d.RULE_sourcePropertyList);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=461,this.sourceDefinition(),this.state=468,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,18,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=463,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=462,this.match(d.COMMA)),this.state=465,this.sourceDefinition()),this.state=470,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,18,this._ctx);this.state=472,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=471,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}sourceDefinition(){let e=new kT(this._ctx,this.state);this.enterRule(e,54,d.RULE_sourceDefinition);try{this.enterOuterAlt(e,1);{switch(this.state=474,this.tags(),this.state=475,this.sourceNameDef(),this.state=477,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,20,this._ctx)){case 1:this.state=476,this.sourceParameters();break}this.state=479,this.isDefine(),this.state=480,this.sqExplore()}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sqExplore(){let e=new Lk(this._ctx,this.state);this.enterRule(e,56,d.RULE_sqExplore);try{this.enterOuterAlt(e,1),this.state=482,this.sqExpr(0)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sourceParameters(){let e=new Ik(this._ctx,this.state);this.enterRule(e,58,d.RULE_sourceParameters);let r;try{switch(this.state=497,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,22,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=484,this.match(d.OPAREN),this.state=485,this.match(d.CPAREN);break;case 2:this.enterOuterAlt(e,2);{for(this.state=486,this.match(d.OPAREN),this.state=487,this.sourceParameter(),this.state=492,this._errHandler.sync(this),r=this._input.LA(1);r===d.COMMA;)this.state=488,this.match(d.COMMA),this.state=489,this.sourceParameter(),this.state=494,this._errHandler.sync(this),r=this._input.LA(1);this.state=495,this.match(d.CPAREN)}break}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}legalParamType(){let e=new Bk(this._ctx,this.state);this.enterRule(e,60,d.RULE_legalParamType);try{switch(this.state=505,this._errHandler.sync(this),this._input.LA(1)){case d.BOOLEAN:case d.DATE:case d.NUMBER:case d.STRING:case d.TIMESTAMP:this.enterOuterAlt(e,1),this.state=499,this.malloyType();break;case d.FILTER:this.enterOuterAlt(e,2),this.state=500,this.match(d.FILTER),this.state=501,this.match(d.LT),this.state=502,this.malloyType(),this.state=503,this.match(d.GT);break;default:throw new tn.NoViableAltException(this)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sourceParameter(){let e=new MT(this._ctx,this.state);this.enterRule(e,62,d.RULE_sourceParameter);let r;try{this.enterOuterAlt(e,1),this.state=507,this.parameterNameDef(),this.state=510,this._errHandler.sync(this),r=this._input.LA(1),r===d.DOUBLECOLON&&(this.state=508,this.match(d.DOUBLECOLON),this.state=509,this.legalParamType()),this.state=514,this._errHandler.sync(this),r=this._input.LA(1),r===d.IS&&(this.state=512,this.match(d.IS),this.state=513,this.fieldExpr(0))}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}parameterNameDef(){let e=new $k(this._ctx,this.state);this.enterRule(e,64,d.RULE_parameterNameDef);try{this.enterOuterAlt(e,1),this.state=516,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sourceNameDef(){let e=new kk(this._ctx,this.state);this.enterRule(e,66,d.RULE_sourceNameDef);try{this.enterOuterAlt(e,1),this.state=518,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}exploreProperties(){let e=new Mk(this._ctx,this.state);this.enterRule(e,68,d.RULE_exploreProperties);let r;try{this.enterOuterAlt(e,1);{for(this.state=520,this.match(d.OCURLY),this.state=525,this._errHandler.sync(this),r=this._input.LA(1);!(r&-32)&&1<<r&(1<<d.ACCEPT|1<<d.AGGREGATE|1<<d.CALCULATE|1<<d.DIMENSION|1<<d.EXCEPT|1<<d.GROUP_BY|1<<d.INTERNAL|1<<d.JOIN_CROSS|1<<d.JOIN_ONE|1<<d.JOIN_MANY|1<<d.MEASURE|1<<d.NEST|1<<d.PRIMARY_KEY|1<<d.PRIVATE|1<<d.PUBLIC|1<<d.QUERY|1<<d.RENAME|1<<d.RUN|1<<d.SELECT|1<<d.SOURCE)||!(r-33&-32)&&1<<r-33&(1<<d.WHERE-33|1<<d.VIEW-33|1<<d.TIMEZONE-33|1<<d.ALL-33|1<<d.AVG-33|1<<d.CASE-33|1<<d.CAST-33|1<<d.COUNT-33|1<<d.COMPOSE-33|1<<d.DAY-33|1<<d.EXCLUDE-33|1<<d.FALSE-33|1<<d.HOUR-33)||!(r-66&-32)&&1<<r-66&(1<<d.IS-66|1<<d.INTERNAL_KW-66|1<<d.MAX-66|1<<d.MIN-66|1<<d.MINUTE-66|1<<d.MONTH-66|1<<d.NOT-66|1<<d.NOW-66|1<<d.NULL-66|1<<d.PICK-66|1<<d.PRIVATE_KW-66|1<<d.PUBLIC_KW-66|1<<d.QUARTER-66|1<<d.SECOND-66|1<<d.SOURCE_KW-66|1<<d.SUM-66)||!(r-98&-32)&&1<<r-98&(1<<d.TRUE-98|1<<d.WEEK-98|1<<d.YEAR-98|1<<d.HACKY_REGEX-98|1<<d.RAW_SQ-98|1<<d.RAW_DQ-98|1<<d.SQ3_FILTER-98|1<<d.SQ_FILTER-98|1<<d.DQ3_FILTER-98|1<<d.DQ_FILTER-98|1<<d.BQ3_FILTER-98|1<<d.BQ_FILTER-98|1<<d.SQ_STRING-98|1<<d.DQ_STRING-98|1<<d.BQ_STRING-98|1<<d.DOC_ANNOTATION-98|1<<d.ANNOTATION-98|1<<d.OPAREN-98|1<<d.OBRACK-98|1<<d.OCURLY-98)||!(r-141&-32)&&1<<r-141&(1<<d.MINUS-141|1<<d.STAR-141|1<<d.SEMI-141|1<<d.LITERAL_TIMESTAMP-141|1<<d.LITERAL_HOUR-141|1<<d.LITERAL_DAY-141|1<<d.LITERAL_QUARTER-141|1<<d.LITERAL_MONTH-141|1<<d.LITERAL_WEEK-141|1<<d.LITERAL_YEAR-141|1<<d.IDENTIFIER-141|1<<d.NUMERIC_LITERAL-141|1<<d.INTEGER_LITERAL-141|1<<d.SQL_BEGIN-141);){switch(this.state=523,this._errHandler.sync(this),this._input.LA(1)){case d.ACCEPT:case d.AGGREGATE:case d.CALCULATE:case d.DIMENSION:case d.EXCEPT:case d.GROUP_BY:case d.INTERNAL:case d.JOIN_CROSS:case d.JOIN_ONE:case d.JOIN_MANY:case d.MEASURE:case d.NEST:case d.PRIMARY_KEY:case d.PRIVATE:case d.PUBLIC:case d.QUERY:case d.RENAME:case d.RUN:case d.SELECT:case d.SOURCE:case d.WHERE:case d.VIEW:case d.TIMEZONE:case d.ALL:case d.AVG:case d.CASE:case d.CAST:case d.COUNT:case d.COMPOSE:case d.DAY:case d.EXCLUDE:case d.FALSE:case d.HOUR:case d.IS:case d.INTERNAL_KW:case d.MAX:case d.MIN:case d.MINUTE:case d.MONTH:case d.NOT:case d.NOW:case d.NULL:case d.PICK:case d.PRIVATE_KW:case d.PUBLIC_KW:case d.QUARTER:case d.SECOND:case d.SOURCE_KW:case d.SUM:case d.TRUE:case d.WEEK:case d.YEAR:case d.HACKY_REGEX:case d.RAW_SQ:case d.RAW_DQ:case d.SQ3_FILTER:case d.SQ_FILTER:case d.DQ3_FILTER:case d.DQ_FILTER:case d.BQ3_FILTER:case d.BQ_FILTER:case d.SQ_STRING:case d.DQ_STRING:case d.BQ_STRING:case d.DOC_ANNOTATION:case d.ANNOTATION:case d.OPAREN:case d.OBRACK:case d.OCURLY:case d.MINUS:case d.STAR:case d.LITERAL_TIMESTAMP:case d.LITERAL_HOUR:case d.LITERAL_DAY:case d.LITERAL_QUARTER:case d.LITERAL_MONTH:case d.LITERAL_WEEK:case d.LITERAL_YEAR:case d.IDENTIFIER:case d.NUMERIC_LITERAL:case d.INTEGER_LITERAL:case d.SQL_BEGIN:this.state=521,this.exploreStatement();break;case d.SEMI:this.state=522,this.match(d.SEMI);break;default:throw new tn.NoViableAltException(this)}this.state=527,this._errHandler.sync(this),r=this._input.LA(1)}this.state=528,this.match(d.CCURLY)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}exploreStatement(){let e=new qi(this._ctx,this.state);this.enterRule(e,70,d.RULE_exploreStatement);let r;try{let i;switch(this.state=557,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,31,this._ctx)){case 1:e=new J0e(e),this.enterOuterAlt(e,1),this.state=530,this.defDimensions();break;case 2:e=new X0e(e),this.enterOuterAlt(e,2),this.state=531,this.defMeasures();break;case 3:e=new Z0e(e),this.enterOuterAlt(e,3),this.state=532,this.joinStatement();break;case 4:e=new ece(e),this.enterOuterAlt(e,4),this.state=533,this.whereStatement();break;case 5:e=new tce(e),this.enterOuterAlt(e,5),this.state=534,this.match(d.PRIMARY_KEY),this.state=535,this.fieldName();break;case 6:e=new nce(e),this.enterOuterAlt(e,6),this.state=537,this._errHandler.sync(this),r=this._input.LA(1),!(r-68&-32)&&1<<r-68&(1<<d.INTERNAL_KW-68|1<<d.PRIVATE_KW-68|1<<d.PUBLIC_KW-68)&&(this.state=536,this.accessLabel()),this.state=539,this.match(d.RENAME),this.state=540,this.renameList();break;case 7:e=new rce(e),this.enterOuterAlt(e,7),this.state=541,r=this._input.LA(1),r===d.ACCEPT||r===d.EXCEPT?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this),this.state=542,this.fieldNameList();break;case 8:e=new ice(e),this.enterOuterAlt(e,8),this.state=543,this.tags(),this.state=545,this._errHandler.sync(this),r=this._input.LA(1),!(r-68&-32)&&1<<r-68&(1<<d.INTERNAL_KW-68|1<<d.PRIVATE_KW-68|1<<d.PUBLIC_KW-68)&&(this.state=544,this.accessLabel()),this.state=547,this.match(d.VIEW),this.state=548,this.subQueryDefList();break;case 9:e=new sce(e),this.enterOuterAlt(e,9),this.state=550,this.timezoneStatement();break;case 10:e=new oce(e),this.enterOuterAlt(e,10);{this.state=552,this._errHandler.sync(this),i=1;do{switch(i){case 1:this.state=551,this.match(d.ANNOTATION);break;default:throw new tn.NoViableAltException(this)}this.state=554,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,30,this._ctx)}while(i!==2&&i!==en.ATN.INVALID_ALT_NUMBER)}break;case 11:e=new uce(e),this.enterOuterAlt(e,11),this.state=556,this.ignoredModelAnnotations();break}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}accessLabel(){let e=new Oa(this._ctx,this.state);this.enterRule(e,72,d.RULE_accessLabel);let r;try{this.enterOuterAlt(e,1),this.state=559,r=this._input.LA(1),!(r-68&-32)&&1<<r-68&(1<<d.INTERNAL_KW-68|1<<d.PRIVATE_KW-68|1<<d.PUBLIC_KW-68)?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}accessModifierList(){let e=new ace(this._ctx,this.state);this.enterRule(e,74,d.RULE_accessModifierList);let r;try{switch(this.state=566,this._errHandler.sync(this),this._input.LA(1)){case d.BQ_STRING:case d.IDENTIFIER:this.enterOuterAlt(e,1),this.state=561,this.fieldNameList();break;case d.STAR:this.enterOuterAlt(e,2),this.state=562,this.match(d.STAR),this.state=564,this._errHandler.sync(this),r=this._input.LA(1),r===d.OCURLY&&(this.state=563,this.starQualified());break;default:throw new tn.NoViableAltException(this)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}defMeasures(){let e=new PT(this._ctx,this.state);this.enterRule(e,76,d.RULE_defMeasures);let r;try{this.enterOuterAlt(e,1),this.state=568,this.tags(),this.state=570,this._errHandler.sync(this),r=this._input.LA(1),!(r-68&-32)&&1<<r-68&(1<<d.INTERNAL_KW-68|1<<d.PRIVATE_KW-68|1<<d.PUBLIC_KW-68)&&(this.state=569,this.accessLabel()),this.state=572,this.match(d.MEASURE),this.state=573,this.defList()}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}defDimensions(){let e=new UT(this._ctx,this.state);this.enterRule(e,78,d.RULE_defDimensions);let r;try{this.enterOuterAlt(e,1),this.state=575,this.tags(),this.state=577,this._errHandler.sync(this),r=this._input.LA(1),!(r-68&-32)&&1<<r-68&(1<<d.INTERNAL_KW-68|1<<d.PRIVATE_KW-68|1<<d.PUBLIC_KW-68)&&(this.state=576,this.accessLabel()),this.state=579,this.match(d.DIMENSION),this.state=580,this.defList()}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}renameList(){let e=new Pk(this._ctx,this.state);this.enterRule(e,80,d.RULE_renameList);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=582,this.exploreRenameDef(),this.state=589,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,37,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=584,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=583,this.match(d.COMMA)),this.state=586,this.exploreRenameDef()),this.state=591,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,37,this._ctx);this.state=593,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=592,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}exploreRenameDef(){let e=new jT(this._ctx,this.state);this.enterRule(e,82,d.RULE_exploreRenameDef);try{this.enterOuterAlt(e,1),this.state=595,this.fieldName(),this.state=596,this.isDefine(),this.state=597,this.fieldName()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}defList(){let e=new lE(this._ctx,this.state);this.enterRule(e,84,d.RULE_defList);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=599,this.fieldDef(),this.state=606,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,40,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=601,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=600,this.match(d.COMMA)),this.state=603,this.fieldDef()),this.state=608,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,40,this._ctx);this.state=610,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=609,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}fieldDef(){let e=new v2(this._ctx,this.state);this.enterRule(e,86,d.RULE_fieldDef);try{this.enterOuterAlt(e,1),this.state=612,this.tags(),this.state=613,this.fieldNameDef(),this.state=614,this.isDefine(),this.state=615,this.fieldExpr(0)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}fieldNameDef(){let e=new Uk(this._ctx,this.state);this.enterRule(e,88,d.RULE_fieldNameDef);try{this.enterOuterAlt(e,1),this.state=617,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}joinNameDef(){let e=new jk(this._ctx,this.state);this.enterRule(e,90,d.RULE_joinNameDef);try{this.enterOuterAlt(e,1),this.state=619,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}declareStatement(){let e=new qT(this._ctx,this.state);this.enterRule(e,92,d.RULE_declareStatement);try{this.enterOuterAlt(e,1);{switch(this.state=621,this.match(d.DECLARE),this.state=623,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,42,this._ctx)){case 1:this.state=622,this.accessLabel();break}this.state=625,this.defList()}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}joinStatement(){let e=new t0(this._ctx,this.state);this.enterRule(e,94,d.RULE_joinStatement);let r;try{switch(this.state=648,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,46,this._ctx)){case 1:e=new lce(e),this.enterOuterAlt(e,1),this.state=627,this.tags(),this.state=629,this._errHandler.sync(this),r=this._input.LA(1),!(r-68&-32)&&1<<r-68&(1<<d.INTERNAL_KW-68|1<<d.PRIVATE_KW-68|1<<d.PUBLIC_KW-68)&&(this.state=628,this.accessLabel()),this.state=631,this.match(d.JOIN_ONE),this.state=632,this.joinList();break;case 2:e=new cce(e),this.enterOuterAlt(e,2),this.state=634,this.tags(),this.state=636,this._errHandler.sync(this),r=this._input.LA(1),!(r-68&-32)&&1<<r-68&(1<<d.INTERNAL_KW-68|1<<d.PRIVATE_KW-68|1<<d.PUBLIC_KW-68)&&(this.state=635,this.accessLabel()),this.state=638,this.match(d.JOIN_MANY),this.state=639,this.joinList();break;case 3:e=new fce(e),this.enterOuterAlt(e,3),this.state=641,this.tags(),this.state=643,this._errHandler.sync(this),r=this._input.LA(1),!(r-68&-32)&&1<<r-68&(1<<d.INTERNAL_KW-68|1<<d.PRIVATE_KW-68|1<<d.PUBLIC_KW-68)&&(this.state=642,this.accessLabel()),this.state=645,this.match(d.JOIN_CROSS),this.state=646,this.joinList();break}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}queryExtend(){let e=new qk(this._ctx,this.state);this.enterRule(e,96,d.RULE_queryExtend);try{this.enterOuterAlt(e,1),this.state=650,this.match(d.EXTENDQ),this.state=651,this.queryExtendStatementList()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}modEither(){let e=new xce(this._ctx,this.state);this.enterRule(e,98,d.RULE_modEither);try{switch(this.state=656,this._errHandler.sync(this),this._input.LA(1)){case d.AGGREGATE:case d.CALCULATE:case d.DIMENSION:case d.EXCEPT:case d.GROUP_BY:case d.INTERNAL:case d.JOIN_CROSS:case d.JOIN_ONE:case d.JOIN_MANY:case d.MEASURE:case d.NEST:case d.PRIVATE:case d.PUBLIC:case d.QUERY:case d.RUN:case d.SELECT:case d.SOURCE:case d.VIEW:case d.ALL:case d.AVG:case d.CASE:case d.CAST:case d.COUNT:case d.COMPOSE:case d.DAY:case d.EXCLUDE:case d.FALSE:case d.HOUR:case d.IS:case d.INTERNAL_KW:case d.MAX:case d.MIN:case d.MINUTE:case d.MONTH:case d.NOT:case d.NOW:case d.NULL:case d.PICK:case d.PRIVATE_KW:case d.PUBLIC_KW:case d.QUARTER:case d.SECOND:case d.SOURCE_KW:case d.SUM:case d.TRUE:case d.WEEK:case d.YEAR:case d.HACKY_REGEX:case d.RAW_SQ:case d.RAW_DQ:case d.SQ3_FILTER:case d.SQ_FILTER:case d.DQ3_FILTER:case d.DQ_FILTER:case d.BQ3_FILTER:case d.BQ_FILTER:case d.SQ_STRING:case d.DQ_STRING:case d.BQ_STRING:case d.ANNOTATION:case d.OPAREN:case d.OBRACK:case d.OCURLY:case d.MINUS:case d.STAR:case d.LITERAL_TIMESTAMP:case d.LITERAL_HOUR:case d.LITERAL_DAY:case d.LITERAL_QUARTER:case d.LITERAL_MONTH:case d.LITERAL_WEEK:case d.LITERAL_YEAR:case d.IDENTIFIER:case d.NUMERIC_LITERAL:case d.INTEGER_LITERAL:case d.SQL_BEGIN:this.enterOuterAlt(e,1),this.state=653,this.joinStatement();break;case d.WHERE:this.enterOuterAlt(e,2),this.state=654,this.whereStatement();break;case d.DECLARE:this.enterOuterAlt(e,3),this.state=655,this.declareStatement();break;default:throw new tn.NoViableAltException(this)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sourceArguments(){let e=new HT(this._ctx,this.state);this.enterRule(e,100,d.RULE_sourceArguments);let r;try{switch(this.state=671,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,49,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=658,this.match(d.OPAREN),this.state=659,this.match(d.CPAREN);break;case 2:this.enterOuterAlt(e,2);{for(this.state=660,this.match(d.OPAREN),this.state=661,this.sourceArgument(),this.state=666,this._errHandler.sync(this),r=this._input.LA(1);r===d.COMMA;)this.state=662,this.match(d.COMMA),this.state=663,this.sourceArgument(),this.state=668,this._errHandler.sync(this),r=this._input.LA(1);this.state=669,this.match(d.CPAREN)}break}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}argumentId(){let e=new Hk(this._ctx,this.state);this.enterRule(e,102,d.RULE_argumentId);try{this.enterOuterAlt(e,1),this.state=673,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sourceArgument(){let e=new QT(this._ctx,this.state);this.enterRule(e,104,d.RULE_sourceArgument);try{this.enterOuterAlt(e,1);{switch(this.state=678,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,50,this._ctx)){case 1:this.state=675,this.argumentId(),this.state=676,this.match(d.IS);break}this.state=680,this.fieldExpr(0)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sqExpr(e){e===void 0&&(e=0);let r=this._ctx,i=this.state,s=new un(this._ctx,i),o=s,u=106;this.enterRecursionRule(s,106,d.RULE_sqExpr,e);let a;try{let l;this.enterOuterAlt(s,1);{switch(this.state=706,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,54,this._ctx)){case 1:switch(s=new dce(s),this._ctx=s,o=s,this.state=683,this.id(),this.state=685,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,51,this._ctx)){case 1:this.state=684,this.sourceArguments();break}break;case 2:s=new hce(s),this._ctx=s,o=s,this.state=687,this.match(d.OPAREN),this.state=688,this.sqExpr(0),this.state=689,this.match(d.CPAREN);break;case 3:{if(s=new pce(s),this._ctx=s,o=s,this.state=691,this.match(d.COMPOSE),this.state=692,this.match(d.OPAREN),this.state=701,this._errHandler.sync(this),a=this._input.LA(1),a===d.COMPOSE||a===d.BQ_STRING||a===d.OPAREN||a===d.IDENTIFIER)for(this.state=693,this.sqExpr(0),this.state=698,this._errHandler.sync(this),a=this._input.LA(1);a===d.COMMA;)this.state=694,this.match(d.COMMA),this.state=695,this.sqExpr(0),this.state=700,this._errHandler.sync(this),a=this._input.LA(1);this.state=703,this.match(d.CPAREN)}break;case 4:s=new Ace(s),this._ctx=s,o=s,this.state=704,this.exploreTable();break;case 5:s=new _ce(s),this._ctx=s,o=s,this.state=705,this.sqlSource();break}for(this._ctx._stop=this._input.tryLT(-1),this.state=726,this._errHandler.sync(this),l=this.interpreter.adaptivePredict(this._input,57,this._ctx);l!==2&&l!==en.ATN.INVALID_ALT_NUMBER;){if(l===1)switch(this._parseListeners!=null&&this.triggerExitRuleEvent(),o=s,this.state=724,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,56,this._ctx)){case 1:{if(s=new mce(new un(r,i)),this.pushNewRecursionContext(s,u,d.RULE_sqExpr),this.state=708,!this.precpred(this._ctx,6))throw this.createFailedPredicateException("this.precpred(this._ctx, 6)");this.state=709,this.match(d.PLUS),this.state=710,this.segExpr(0)}break;case 2:{if(s=new gce(new un(r,i)),this.pushNewRecursionContext(s,u,d.RULE_sqExpr),this.state=711,!this.precpred(this._ctx,5))throw this.createFailedPredicateException("this.precpred(this._ctx, 5)");this.state=712,this.match(d.ARROW),this.state=713,this.segExpr(0)}break;case 3:{if(s=new yce(new un(r,i)),this.pushNewRecursionContext(s,u,d.RULE_sqExpr),this.state=714,!this.precpred(this._ctx,4))throw this.createFailedPredicateException("this.precpred(this._ctx, 4)");this.state=717,this._errHandler.sync(this),a=this._input.LA(1),a===d.INCLUDE&&(this.state=715,this.match(d.INCLUDE),this.state=716,this.includeBlock()),this.state=719,this.match(d.EXTEND),this.state=720,this.exploreProperties()}break;case 4:{if(s=new Ece(new un(r,i)),this.pushNewRecursionContext(s,u,d.RULE_sqExpr),this.state=721,!this.precpred(this._ctx,3))throw this.createFailedPredicateException("this.precpred(this._ctx, 3)");this.state=722,this.match(d.INCLUDE),this.state=723,this.includeBlock()}break}this.state=728,this._errHandler.sync(this),l=this.interpreter.adaptivePredict(this._input,57,this._ctx)}}}catch(l){if(l instanceof me.RecognitionException)s.exception=l,this._errHandler.reportError(this,l),this._errHandler.recover(this,l);else throw l}finally{this.unrollRecursionContexts(r)}return s}includeBlock(){let e=new zT(this._ctx,this.state);this.enterRule(e,108,d.RULE_includeBlock);let r;try{this.enterOuterAlt(e,1);{for(this.state=729,this.match(d.OCURLY),this.state=734,this._errHandler.sync(this),r=this._input.LA(1);!(r&-32)&&1<<r&(1<<d.AGGREGATE|1<<d.CALCULATE|1<<d.DIMENSION|1<<d.EXCEPT|1<<d.GROUP_BY|1<<d.INTERNAL|1<<d.JOIN_CROSS|1<<d.JOIN_ONE|1<<d.JOIN_MANY|1<<d.MEASURE|1<<d.NEST|1<<d.PRIVATE|1<<d.PUBLIC|1<<d.QUERY|1<<d.RUN|1<<d.SELECT|1<<d.SOURCE)||!(r-34&-32)&&1<<r-34&(1<<d.VIEW-34|1<<d.ALL-34|1<<d.AVG-34|1<<d.CASE-34|1<<d.CAST-34|1<<d.COUNT-34|1<<d.COMPOSE-34|1<<d.DAY-34|1<<d.EXCLUDE-34|1<<d.FALSE-34|1<<d.HOUR-34)||!(r-66&-32)&&1<<r-66&(1<<d.IS-66|1<<d.INTERNAL_KW-66|1<<d.MAX-66|1<<d.MIN-66|1<<d.MINUTE-66|1<<d.MONTH-66|1<<d.NOT-66|1<<d.NOW-66|1<<d.NULL-66|1<<d.PICK-66|1<<d.PRIVATE_KW-66|1<<d.PUBLIC_KW-66|1<<d.QUARTER-66|1<<d.SECOND-66|1<<d.SOURCE_KW-66|1<<d.SUM-66)||!(r-98&-32)&&1<<r-98&(1<<d.TRUE-98|1<<d.WEEK-98|1<<d.YEAR-98|1<<d.HACKY_REGEX-98|1<<d.RAW_SQ-98|1<<d.RAW_DQ-98|1<<d.SQ3_FILTER-98|1<<d.SQ_FILTER-98|1<<d.DQ3_FILTER-98|1<<d.DQ_FILTER-98|1<<d.BQ3_FILTER-98|1<<d.BQ_FILTER-98|1<<d.SQ_STRING-98|1<<d.DQ_STRING-98|1<<d.BQ_STRING-98|1<<d.ANNOTATION-98|1<<d.OPAREN-98|1<<d.OBRACK-98|1<<d.OCURLY-98)||!(r-141&-32)&&1<<r-141&(1<<d.MINUS-141|1<<d.STAR-141|1<<d.SEMI-141|1<<d.LITERAL_TIMESTAMP-141|1<<d.LITERAL_HOUR-141|1<<d.LITERAL_DAY-141|1<<d.LITERAL_QUARTER-141|1<<d.LITERAL_MONTH-141|1<<d.LITERAL_WEEK-141|1<<d.LITERAL_YEAR-141|1<<d.IDENTIFIER-141|1<<d.NUMERIC_LITERAL-141|1<<d.INTEGER_LITERAL-141|1<<d.SQL_BEGIN-141);){switch(this.state=732,this._errHandler.sync(this),this._input.LA(1)){case d.AGGREGATE:case d.CALCULATE:case d.DIMENSION:case d.EXCEPT:case d.GROUP_BY:case d.INTERNAL:case d.JOIN_CROSS:case d.JOIN_ONE:case d.JOIN_MANY:case d.MEASURE:case d.NEST:case d.PRIVATE:case d.PUBLIC:case d.QUERY:case d.RUN:case d.SELECT:case d.SOURCE:case d.VIEW:case d.ALL:case d.AVG:case d.CASE:case d.CAST:case d.COUNT:case d.COMPOSE:case d.DAY:case d.EXCLUDE:case d.FALSE:case d.HOUR:case d.IS:case d.INTERNAL_KW:case d.MAX:case d.MIN:case d.MINUTE:case d.MONTH:case d.NOT:case d.NOW:case d.NULL:case d.PICK:case d.PRIVATE_KW:case d.PUBLIC_KW:case d.QUARTER:case d.SECOND:case d.SOURCE_KW:case d.SUM:case d.TRUE:case d.WEEK:case d.YEAR:case d.HACKY_REGEX:case d.RAW_SQ:case d.RAW_DQ:case d.SQ3_FILTER:case d.SQ_FILTER:case d.DQ3_FILTER:case d.DQ_FILTER:case d.BQ3_FILTER:case d.BQ_FILTER:case d.SQ_STRING:case d.DQ_STRING:case d.BQ_STRING:case d.ANNOTATION:case d.OPAREN:case d.OBRACK:case d.OCURLY:case d.MINUS:case d.STAR:case d.LITERAL_TIMESTAMP:case d.LITERAL_HOUR:case d.LITERAL_DAY:case d.LITERAL_QUARTER:case d.LITERAL_MONTH:case d.LITERAL_WEEK:case d.LITERAL_YEAR:case d.IDENTIFIER:case d.NUMERIC_LITERAL:case d.INTEGER_LITERAL:case d.SQL_BEGIN:this.state=730,this.includeItem();break;case d.SEMI:this.state=731,this.match(d.SEMI);break;default:throw new tn.NoViableAltException(this)}this.state=736,this._errHandler.sync(this),r=this._input.LA(1)}this.state=737,this.match(d.CCURLY)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}includeItem(){let e=new GT(this._ctx,this.state);this.enterRule(e,110,d.RULE_includeItem);try{switch(this.state=749,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,60,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=739,this.tags(),this.state=740,this.accessLabelProp(),this.state=741,this.includeList();break;case 2:this.enterOuterAlt(e,2),this.state=743,this.includeList();break;case 3:this.enterOuterAlt(e,3),this.state=744,this.tags(),this.state=745,this.match(d.EXCEPT),this.state=746,this.includeExceptList();break;case 4:this.enterOuterAlt(e,4),this.state=748,this.orphanedAnnotation();break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}orphanedAnnotation(){let e=new Qk(this._ctx,this.state);this.enterRule(e,112,d.RULE_orphanedAnnotation);try{this.enterOuterAlt(e,1),this.state=751,this.match(d.ANNOTATION)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}accessLabelProp(){let e=new zk(this._ctx,this.state);this.enterRule(e,114,d.RULE_accessLabelProp);let r;try{this.enterOuterAlt(e,1),this.state=753,r=this._input.LA(1),!(r&-32)&&1<<r&(1<<d.INTERNAL|1<<d.PRIVATE|1<<d.PUBLIC)?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}includeExceptList(){let e=new Gk(this._ctx,this.state);this.enterRule(e,116,d.RULE_includeExceptList);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=755,this.includeExceptListItem(),this.state=762,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,62,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=757,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=756,this.match(d.COMMA)),this.state=759,this.includeExceptListItem()),this.state=764,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,62,this._ctx);this.state=766,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=765,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}includeExceptListItem(){let e=new WT(this._ctx,this.state);this.enterRule(e,118,d.RULE_includeExceptListItem);try{switch(this.state=774,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,64,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=768,this.tags(),this.state=769,this.fieldName();break;case 2:this.enterOuterAlt(e,2),this.state=771,this.tags(),this.state=772,this.collectionWildCard();break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}includeList(){let e=new Wk(this._ctx,this.state);this.enterRule(e,120,d.RULE_includeList);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=776,this.includeField(),this.state=783,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,66,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=778,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=777,this.match(d.COMMA)),this.state=780,this.includeField()),this.state=785,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,66,this._ctx);this.state=787,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=786,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}includeField(){let e=new VT(this._ctx,this.state);this.enterRule(e,122,d.RULE_includeField);try{switch(this.state=803,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,69,this._ctx)){case 1:this.enterOuterAlt(e,1);{switch(this.state=789,this.tags(),this.state=793,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,68,this._ctx)){case 1:this.state=790,e._as=this.fieldName(),this.state=791,this.isDefine();break}this.state=795,e._name=this.fieldName()}break;case 2:this.enterOuterAlt(e,2),this.state=797,this.tags(),this.state=798,e._name=this.fieldName();break;case 3:this.enterOuterAlt(e,3),this.state=800,this.tags(),this.state=801,this.collectionWildCard();break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}segExpr(e){e===void 0&&(e=0);let r=this._ctx,i=this.state,s=new Ms(this._ctx,i),o=s,u=124;this.enterRecursionRule(s,124,d.RULE_segExpr,e);try{let a;this.enterOuterAlt(s,1);{switch(this.state=812,this._errHandler.sync(this),this._input.LA(1)){case d.BQ_STRING:case d.IDENTIFIER:s=new vce(s),this._ctx=s,o=s,this.state=806,this.fieldPath();break;case d.OCURLY:s=new Cce(s),this._ctx=s,o=s,this.state=807,this.queryProperties();break;case d.OPAREN:s=new Sce(s),this._ctx=s,o=s,this.state=808,this.match(d.OPAREN),this.state=809,this.vExpr(),this.state=810,this.match(d.CPAREN);break;default:throw new tn.NoViableAltException(this)}for(this._ctx._stop=this._input.tryLT(-1),this.state=819,this._errHandler.sync(this),a=this.interpreter.adaptivePredict(this._input,71,this._ctx);a!==2&&a!==en.ATN.INVALID_ALT_NUMBER;){if(a===1){this._parseListeners!=null&&this.triggerExitRuleEvent(),o=s;{if(s=new bce(new Ms(r,i)),s._lhs=o,this.pushNewRecursionContext(s,u,d.RULE_segExpr),this.state=814,!this.precpred(this._ctx,1))throw this.createFailedPredicateException("this.precpred(this._ctx, 1)");this.state=815,this.match(d.PLUS),this.state=816,s._rhs=this.segExpr(2)}}this.state=821,this._errHandler.sync(this),a=this.interpreter.adaptivePredict(this._input,71,this._ctx)}}}catch(a){if(a instanceof me.RecognitionException)s.exception=a,this._errHandler.reportError(this,a),this._errHandler.recover(this,a);else throw a}finally{this.unrollRecursionContexts(r)}return s}vExpr(){let e=new zc(this._ctx,this.state);this.enterRule(e,126,d.RULE_vExpr);try{switch(this.state=827,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,72,this._ctx)){case 1:e=new Tce(e),this.enterOuterAlt(e,1),this.state=822,this.segExpr(0);break;case 2:e=new Rce(e),this.enterOuterAlt(e,2),this.state=823,e._lhs=this.segExpr(0),this.state=824,this.match(d.ARROW),this.state=825,e._rhs=this.vExpr();break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}queryExtendStatement(){let e=new YT(this._ctx,this.state);this.enterRule(e,128,d.RULE_queryExtendStatement);try{switch(this.state=832,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,73,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=829,this.defDimensions();break;case 2:this.enterOuterAlt(e,2),this.state=830,this.defMeasures();break;case 3:this.enterOuterAlt(e,3),this.state=831,this.joinStatement();break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}queryExtendStatementList(){let e=new Vk(this._ctx,this.state);this.enterRule(e,130,d.RULE_queryExtendStatementList);let r;try{this.enterOuterAlt(e,1);{for(this.state=834,this.match(d.OCURLY),this.state=839,this._errHandler.sync(this),r=this._input.LA(1);!(r&-32)&&1<<r&(1<<d.AGGREGATE|1<<d.CALCULATE|1<<d.DIMENSION|1<<d.EXCEPT|1<<d.GROUP_BY|1<<d.INTERNAL|1<<d.JOIN_CROSS|1<<d.JOIN_ONE|1<<d.JOIN_MANY|1<<d.MEASURE|1<<d.NEST|1<<d.PRIVATE|1<<d.PUBLIC|1<<d.QUERY|1<<d.RUN|1<<d.SELECT|1<<d.SOURCE)||!(r-34&-32)&&1<<r-34&(1<<d.VIEW-34|1<<d.ALL-34|1<<d.AVG-34|1<<d.CASE-34|1<<d.CAST-34|1<<d.COUNT-34|1<<d.COMPOSE-34|1<<d.DAY-34|1<<d.EXCLUDE-34|1<<d.FALSE-34|1<<d.HOUR-34)||!(r-66&-32)&&1<<r-66&(1<<d.IS-66|1<<d.INTERNAL_KW-66|1<<d.MAX-66|1<<d.MIN-66|1<<d.MINUTE-66|1<<d.MONTH-66|1<<d.NOT-66|1<<d.NOW-66|1<<d.NULL-66|1<<d.PICK-66|1<<d.PRIVATE_KW-66|1<<d.PUBLIC_KW-66|1<<d.QUARTER-66|1<<d.SECOND-66|1<<d.SOURCE_KW-66|1<<d.SUM-66)||!(r-98&-32)&&1<<r-98&(1<<d.TRUE-98|1<<d.WEEK-98|1<<d.YEAR-98|1<<d.HACKY_REGEX-98|1<<d.RAW_SQ-98|1<<d.RAW_DQ-98|1<<d.SQ3_FILTER-98|1<<d.SQ_FILTER-98|1<<d.DQ3_FILTER-98|1<<d.DQ_FILTER-98|1<<d.BQ3_FILTER-98|1<<d.BQ_FILTER-98|1<<d.SQ_STRING-98|1<<d.DQ_STRING-98|1<<d.BQ_STRING-98|1<<d.ANNOTATION-98|1<<d.OPAREN-98|1<<d.OBRACK-98|1<<d.OCURLY-98)||!(r-141&-32)&&1<<r-141&(1<<d.MINUS-141|1<<d.STAR-141|1<<d.SEMI-141|1<<d.LITERAL_TIMESTAMP-141|1<<d.LITERAL_HOUR-141|1<<d.LITERAL_DAY-141|1<<d.LITERAL_QUARTER-141|1<<d.LITERAL_MONTH-141|1<<d.LITERAL_WEEK-141|1<<d.LITERAL_YEAR-141|1<<d.IDENTIFIER-141|1<<d.NUMERIC_LITERAL-141|1<<d.INTEGER_LITERAL-141|1<<d.SQL_BEGIN-141);){switch(this.state=837,this._errHandler.sync(this),this._input.LA(1)){case d.AGGREGATE:case d.CALCULATE:case d.DIMENSION:case d.EXCEPT:case d.GROUP_BY:case d.INTERNAL:case d.JOIN_CROSS:case d.JOIN_ONE:case d.JOIN_MANY:case d.MEASURE:case d.NEST:case d.PRIVATE:case d.PUBLIC:case d.QUERY:case d.RUN:case d.SELECT:case d.SOURCE:case d.VIEW:case d.ALL:case d.AVG:case d.CASE:case d.CAST:case d.COUNT:case d.COMPOSE:case d.DAY:case d.EXCLUDE:case d.FALSE:case d.HOUR:case d.IS:case d.INTERNAL_KW:case d.MAX:case d.MIN:case d.MINUTE:case d.MONTH:case d.NOT:case d.NOW:case d.NULL:case d.PICK:case d.PRIVATE_KW:case d.PUBLIC_KW:case d.QUARTER:case d.SECOND:case d.SOURCE_KW:case d.SUM:case d.TRUE:case d.WEEK:case d.YEAR:case d.HACKY_REGEX:case d.RAW_SQ:case d.RAW_DQ:case d.SQ3_FILTER:case d.SQ_FILTER:case d.DQ3_FILTER:case d.DQ_FILTER:case d.BQ3_FILTER:case d.BQ_FILTER:case d.SQ_STRING:case d.DQ_STRING:case d.BQ_STRING:case d.ANNOTATION:case d.OPAREN:case d.OBRACK:case d.OCURLY:case d.MINUS:case d.STAR:case d.LITERAL_TIMESTAMP:case d.LITERAL_HOUR:case d.LITERAL_DAY:case d.LITERAL_QUARTER:case d.LITERAL_MONTH:case d.LITERAL_WEEK:case d.LITERAL_YEAR:case d.IDENTIFIER:case d.NUMERIC_LITERAL:case d.INTEGER_LITERAL:case d.SQL_BEGIN:this.state=835,this.queryExtendStatement();break;case d.SEMI:this.state=836,this.match(d.SEMI);break;default:throw new tn.NoViableAltException(this)}this.state=841,this._errHandler.sync(this),r=this._input.LA(1)}this.state=842,this.match(d.CCURLY)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}joinList(){let e=new cE(this._ctx,this.state);this.enterRule(e,132,d.RULE_joinList);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=844,this.joinDef(),this.state=851,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,77,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=846,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=845,this.match(d.COMMA)),this.state=848,this.joinDef()),this.state=853,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,77,this._ctx);this.state=855,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=854,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}isExplore(){let e=new Yk(this._ctx,this.state);this.enterRule(e,134,d.RULE_isExplore);try{this.enterOuterAlt(e,1),this.state=857,e._before_is=this.tags(),this.state=858,this.match(d.IS),this.state=859,e._after_is=this.tags(),this.state=860,this.sqExpr(0)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}matrixOperation(){let e=new KT(this._ctx,this.state);this.enterRule(e,136,d.RULE_matrixOperation);let r;try{this.enterOuterAlt(e,1),this.state=862,r=this._input.LA(1),!(r-58&-32)&&1<<r-58&(1<<d.FULL-58|1<<d.INNER-58|1<<d.LEFT-58|1<<d.RIGHT-58)?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}joinFrom(){let e=new JT(this._ctx,this.state);this.enterRule(e,138,d.RULE_joinFrom);try{switch(this.state=871,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,79,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=864,this.joinNameDef();break;case 2:this.enterOuterAlt(e,2),this.state=865,this.joinNameDef(),this.state=866,this.sourceArguments();break;case 3:this.enterOuterAlt(e,3),this.state=868,this.joinNameDef(),this.state=869,this.isExplore();break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}joinDef(){let e=new C2(this._ctx,this.state);this.enterRule(e,140,d.RULE_joinDef);let r;try{switch(this.state=900,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,85,this._ctx)){case 1:e=new Dce(e),this.enterOuterAlt(e,1);{for(this.state=876,this._errHandler.sync(this),r=this._input.LA(1);r===d.ANNOTATION;)this.state=873,this.match(d.ANNOTATION),this.state=878,this._errHandler.sync(this),r=this._input.LA(1);this.state=879,this.joinFrom(),this.state=881,this._errHandler.sync(this),r=this._input.LA(1),!(r-58&-32)&&1<<r-58&(1<<d.FULL-58|1<<d.INNER-58|1<<d.LEFT-58|1<<d.RIGHT-58)&&(this.state=880,this.matrixOperation()),this.state=883,this.match(d.WITH),this.state=884,this.fieldExpr(0)}break;case 2:e=new Oce(e),this.enterOuterAlt(e,2);{for(this.state=889,this._errHandler.sync(this),r=this._input.LA(1);r===d.ANNOTATION;)this.state=886,this.match(d.ANNOTATION),this.state=891,this._errHandler.sync(this),r=this._input.LA(1);this.state=892,this.joinFrom(),this.state=898,this._errHandler.sync(this),r=this._input.LA(1),!(r-58&-32)&&1<<r-58&(1<<d.FULL-58|1<<d.INNER-58|1<<d.LEFT-58|1<<d.ON-58|1<<d.RIGHT-58)&&(this.state=894,this._errHandler.sync(this),r=this._input.LA(1),!(r-58&-32)&&1<<r-58&(1<<d.FULL-58|1<<d.INNER-58|1<<d.LEFT-58|1<<d.RIGHT-58)&&(this.state=893,this.matrixOperation()),this.state=896,this.match(d.ON),this.state=897,this.joinExpression())}break}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}joinExpression(){let e=new Kk(this._ctx,this.state);this.enterRule(e,142,d.RULE_joinExpression);try{this.enterOuterAlt(e,1),this.state=902,this.fieldExpr(0)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}filterStatement(){let e=new Fce(this._ctx,this.state);this.enterRule(e,144,d.RULE_filterStatement);try{switch(this.state=906,this._errHandler.sync(this),this._input.LA(1)){case d.WHERE:this.enterOuterAlt(e,1),this.state=904,this.whereStatement();break;case d.HAVING:this.enterOuterAlt(e,2),this.state=905,this.havingStatement();break;default:throw new tn.NoViableAltException(this)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}fieldProperties(){let e=new Jk(this._ctx,this.state);this.enterRule(e,146,d.RULE_fieldProperties);let r;try{this.enterOuterAlt(e,1);{for(this.state=908,this.match(d.OCURLY),this.state=913,this._errHandler.sync(this),r=this._input.LA(1);!(r-17&-32)&&1<<r-17&(1<<d.LIMIT-17|1<<d.ORDER_BY-17|1<<d.PARTITION_BY-17|1<<d.WHERE-17)||r===d.SEMI;){switch(this.state=911,this._errHandler.sync(this),this._input.LA(1)){case d.LIMIT:case d.ORDER_BY:case d.PARTITION_BY:case d.WHERE:this.state=909,this.fieldPropertyStatement();break;case d.SEMI:this.state=910,this.match(d.SEMI);break;default:throw new tn.NoViableAltException(this)}this.state=915,this._errHandler.sync(this),r=this._input.LA(1)}this.state=916,this.match(d.CCURLY)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}aggregateOrdering(){let e=new Xk(this._ctx,this.state);this.enterRule(e,148,d.RULE_aggregateOrdering);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=918,this.aggregateOrderBySpec(),this.state=923,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,89,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=919,this.match(d.COMMA),this.state=920,this.aggregateOrderBySpec()),this.state=925,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,89,this._ctx);this.state=927,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=926,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}aggregateOrderBySpec(){let e=new XT(this._ctx,this.state);this.enterRule(e,150,d.RULE_aggregateOrderBySpec);let r;try{switch(this.state=935,this._errHandler.sync(this),this._input.LA(1)){case d.ALL:case d.AVG:case d.CASE:case d.CAST:case d.COUNT:case d.DAY:case d.EXCLUDE:case d.FALSE:case d.HOUR:case d.MAX:case d.MIN:case d.MINUTE:case d.MONTH:case d.NOT:case d.NOW:case d.NULL:case d.PICK:case d.QUARTER:case d.SECOND:case d.SOURCE_KW:case d.SUM:case d.TRUE:case d.WEEK:case d.YEAR:case d.HACKY_REGEX:case d.RAW_SQ:case d.RAW_DQ:case d.SQ3_FILTER:case d.SQ_FILTER:case d.DQ3_FILTER:case d.DQ_FILTER:case d.BQ3_FILTER:case d.BQ_FILTER:case d.SQ_STRING:case d.DQ_STRING:case d.BQ_STRING:case d.OPAREN:case d.OBRACK:case d.OCURLY:case d.MINUS:case d.LITERAL_TIMESTAMP:case d.LITERAL_HOUR:case d.LITERAL_DAY:case d.LITERAL_QUARTER:case d.LITERAL_MONTH:case d.LITERAL_WEEK:case d.LITERAL_YEAR:case d.IDENTIFIER:case d.NUMERIC_LITERAL:case d.INTEGER_LITERAL:case d.SQL_BEGIN:this.enterOuterAlt(e,1),this.state=929,this.fieldExpr(0),this.state=931,this._errHandler.sync(this),r=this._input.LA(1),(r===d.ASC||r===d.DESC)&&(this.state=930,r=this._input.LA(1),r===d.ASC||r===d.DESC?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this));break;case d.ASC:this.enterOuterAlt(e,2),this.state=933,this.match(d.ASC);break;case d.DESC:this.enterOuterAlt(e,3),this.state=934,this.match(d.DESC);break;default:throw new tn.NoViableAltException(this)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}aggregateOrderByStatement(){let e=new Zk(this._ctx,this.state);this.enterRule(e,152,d.RULE_aggregateOrderByStatement);try{this.enterOuterAlt(e,1),this.state=937,this.match(d.ORDER_BY),this.state=938,this.aggregateOrdering()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}fieldPropertyLimitStatement(){let e=new eM(this._ctx,this.state);this.enterRule(e,154,d.RULE_fieldPropertyLimitStatement);try{this.enterOuterAlt(e,1),this.state=940,this.limitStatement()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}fieldPropertyStatement(){let e=new ZT(this._ctx,this.state);this.enterRule(e,156,d.RULE_fieldPropertyStatement);try{switch(this.state=946,this._errHandler.sync(this),this._input.LA(1)){case d.WHERE:this.enterOuterAlt(e,1),this.state=942,this.whereStatement();break;case d.PARTITION_BY:this.enterOuterAlt(e,2),this.state=943,this.partitionByStatement();break;case d.ORDER_BY:this.enterOuterAlt(e,3),this.state=944,this.aggregateOrderByStatement();break;case d.LIMIT:this.enterOuterAlt(e,4),this.state=945,this.fieldPropertyLimitStatement();break;default:throw new tn.NoViableAltException(this)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}filterClauseList(){let e=new eR(this._ctx,this.state);this.enterRule(e,158,d.RULE_filterClauseList);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=948,this.fieldExpr(0),this.state=953,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,94,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=949,this.match(d.COMMA),this.state=950,this.fieldExpr(0)),this.state=955,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,94,this._ctx);this.state=957,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=956,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}whereStatement(){let e=new ud(this._ctx,this.state);this.enterRule(e,160,d.RULE_whereStatement);try{this.enterOuterAlt(e,1),this.state=959,this.match(d.WHERE),this.state=960,this.filterClauseList()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}havingStatement(){let e=new tR(this._ctx,this.state);this.enterRule(e,162,d.RULE_havingStatement);try{this.enterOuterAlt(e,1),this.state=962,this.match(d.HAVING),this.state=963,this.filterClauseList()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}subQueryDefList(){let e=new tM(this._ctx,this.state);this.enterRule(e,164,d.RULE_subQueryDefList);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=965,this.exploreQueryDef(),this.state=972,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,97,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=967,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=966,this.match(d.COMMA)),this.state=969,this.exploreQueryDef()),this.state=974,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,97,this._ctx);this.state=976,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=975,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}exploreQueryNameDef(){let e=new nM(this._ctx,this.state);this.enterRule(e,166,d.RULE_exploreQueryNameDef);try{this.enterOuterAlt(e,1),this.state=978,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}exploreQueryDef(){let e=new nR(this._ctx,this.state);this.enterRule(e,168,d.RULE_exploreQueryDef);let r;try{this.enterOuterAlt(e,1);{for(this.state=983,this._errHandler.sync(this),r=this._input.LA(1);r===d.ANNOTATION;)this.state=980,this.match(d.ANNOTATION),this.state=985,this._errHandler.sync(this),r=this._input.LA(1);this.state=986,this.exploreQueryNameDef(),this.state=987,this.isDefine(),this.state=988,this.vExpr()}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}queryStatement(){let e=new rR(this._ctx,this.state);this.enterRule(e,170,d.RULE_queryStatement);try{switch(this.state=1008,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,100,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=990,this.groupByStatement();break;case 2:this.enterOuterAlt(e,2),this.state=991,this.declareStatement();break;case 3:this.enterOuterAlt(e,3),this.state=992,this.queryJoinStatement();break;case 4:this.enterOuterAlt(e,4),this.state=993,this.queryExtend();break;case 5:this.enterOuterAlt(e,5),this.state=994,this.projectStatement();break;case 6:this.enterOuterAlt(e,6),this.state=995,this.indexStatement();break;case 7:this.enterOuterAlt(e,7),this.state=996,this.aggregateStatement();break;case 8:this.enterOuterAlt(e,8),this.state=997,this.calculateStatement();break;case 9:this.enterOuterAlt(e,9),this.state=998,this.topStatement();break;case 10:this.enterOuterAlt(e,10),this.state=999,this.limitStatement();break;case 11:this.enterOuterAlt(e,11),this.state=1e3,this.orderByStatement();break;case 12:this.enterOuterAlt(e,12),this.state=1001,this.whereStatement();break;case 13:this.enterOuterAlt(e,13),this.state=1002,this.havingStatement();break;case 14:this.enterOuterAlt(e,14),this.state=1003,this.nestStatement();break;case 15:this.enterOuterAlt(e,15),this.state=1004,this.sampleStatement();break;case 16:this.enterOuterAlt(e,16),this.state=1005,this.timezoneStatement();break;case 17:this.enterOuterAlt(e,17),this.state=1006,this.queryAnnotation();break;case 18:this.enterOuterAlt(e,18),this.state=1007,this.ignoredModelAnnotations();break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}queryJoinStatement(){let e=new rM(this._ctx,this.state);this.enterRule(e,172,d.RULE_queryJoinStatement);try{this.enterOuterAlt(e,1),this.state=1010,this.joinStatement()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}groupByStatement(){let e=new iM(this._ctx,this.state);this.enterRule(e,174,d.RULE_groupByStatement);try{this.enterOuterAlt(e,1),this.state=1012,this.tags(),this.state=1013,this.match(d.GROUP_BY),this.state=1014,this.queryFieldList()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}queryFieldList(){let e=new fE(this._ctx,this.state);this.enterRule(e,176,d.RULE_queryFieldList);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=1016,this.queryFieldEntry(),this.state=1023,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,102,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=1018,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1017,this.match(d.COMMA)),this.state=1020,this.queryFieldEntry()),this.state=1025,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,102,this._ctx);this.state=1027,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1026,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}queryFieldEntry(){let e=new iR(this._ctx,this.state);this.enterRule(e,178,d.RULE_queryFieldEntry);try{switch(this.state=1031,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,104,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=1029,this.taggedRef();break;case 2:this.enterOuterAlt(e,2),this.state=1030,this.fieldDef();break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}nestStatement(){let e=new sM(this._ctx,this.state);this.enterRule(e,180,d.RULE_nestStatement);try{this.enterOuterAlt(e,1),this.state=1033,this.tags(),this.state=1034,this.match(d.NEST),this.state=1035,this.nestedQueryList()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}nestedQueryList(){let e=new oM(this._ctx,this.state);this.enterRule(e,182,d.RULE_nestedQueryList);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=1037,this.nestEntry(),this.state=1044,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,106,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=1039,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1038,this.match(d.COMMA)),this.state=1041,this.nestEntry()),this.state=1046,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,106,this._ctx);this.state=1048,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1047,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}nestEntry(){let e=new xE(this._ctx,this.state);this.enterRule(e,184,d.RULE_nestEntry);try{e=new wce(e),this.enterOuterAlt(e,1);{switch(this.state=1050,this.tags(),this.state=1054,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,108,this._ctx)){case 1:this.state=1051,this.queryName(),this.state=1052,this.isDefine();break}this.state=1056,this.vExpr()}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}aggregateStatement(){let e=new uM(this._ctx,this.state);this.enterRule(e,186,d.RULE_aggregateStatement);try{this.enterOuterAlt(e,1),this.state=1058,this.tags(),this.state=1059,this.match(d.AGGREGATE),this.state=1060,this.queryFieldList()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}calculateStatement(){let e=new aM(this._ctx,this.state);this.enterRule(e,188,d.RULE_calculateStatement);try{this.enterOuterAlt(e,1),this.state=1062,this.tags(),this.state=1063,this.match(d.CALCULATE),this.state=1064,this.queryFieldList()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}projectStatement(){let e=new lM(this._ctx,this.state);this.enterRule(e,190,d.RULE_projectStatement);try{this.enterOuterAlt(e,1),this.state=1066,this.tags(),this.state=1067,this.match(d.SELECT),this.state=1068,this.fieldCollection()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}partitionByStatement(){let e=new cM(this._ctx,this.state);this.enterRule(e,192,d.RULE_partitionByStatement);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=1070,this.match(d.PARTITION_BY),this.state=1071,this.id(),this.state=1076,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,109,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=1072,this.match(d.COMMA),this.state=1073,this.id()),this.state=1078,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,109,this._ctx);this.state=1080,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1079,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}orderByStatement(){let e=new fM(this._ctx,this.state);this.enterRule(e,194,d.RULE_orderByStatement);try{this.enterOuterAlt(e,1),this.state=1082,this.match(d.ORDER_BY),this.state=1083,this.ordering()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}ordering(){let e=new xM(this._ctx,this.state);this.enterRule(e,196,d.RULE_ordering);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=1085,this.orderBySpec(),this.state=1092,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,112,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=1087,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1086,this.match(d.COMMA)),this.state=1089,this.orderBySpec()),this.state=1094,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,112,this._ctx);this.state=1096,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1095,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}orderBySpec(){let e=new sR(this._ctx,this.state);this.enterRule(e,198,d.RULE_orderBySpec);let r;try{this.enterOuterAlt(e,1);{switch(this.state=1100,this._errHandler.sync(this),this._input.LA(1)){case d.INTEGER_LITERAL:this.state=1098,this.match(d.INTEGER_LITERAL);break;case d.BQ_STRING:case d.IDENTIFIER:this.state=1099,this.fieldName();break;default:throw new tn.NoViableAltException(this)}this.state=1103,this._errHandler.sync(this),r=this._input.LA(1),(r===d.ASC||r===d.DESC)&&(this.state=1102,r=this._input.LA(1),r===d.ASC||r===d.DESC?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}limitStatement(){let e=new oR(this._ctx,this.state);this.enterRule(e,200,d.RULE_limitStatement);try{this.enterOuterAlt(e,1),this.state=1105,this.match(d.LIMIT),this.state=1106,this.match(d.INTEGER_LITERAL)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}bySpec(){let e=new Nce(this._ctx,this.state);this.enterRule(e,202,d.RULE_bySpec);try{switch(this.state=1112,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,116,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=1108,this.match(d.BY),this.state=1109,this.fieldName();break;case 2:this.enterOuterAlt(e,2),this.state=1110,this.match(d.BY),this.state=1111,this.fieldExpr(0);break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}topStatement(){let e=new dM(this._ctx,this.state);this.enterRule(e,204,d.RULE_topStatement);try{this.enterOuterAlt(e,1),this.state=1114,this.match(d.TOP),this.state=1115,this.match(d.INTEGER_LITERAL)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}indexElement(){let e=new uR(this._ctx,this.state);this.enterRule(e,206,d.RULE_indexElement);let r;try{switch(this.state=1123,this._errHandler.sync(this),this._input.LA(1)){case d.BQ_STRING:case d.IDENTIFIER:this.enterOuterAlt(e,1),this.state=1117,this.fieldPath(),this.state=1120,this._errHandler.sync(this),r=this._input.LA(1),r===d.DOT&&(this.state=1118,this.match(d.DOT),this.state=1119,this.match(d.STAR));break;case d.STAR:this.enterOuterAlt(e,2),this.state=1122,this.match(d.STAR);break;default:throw new tn.NoViableAltException(this)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}indexFields(){let e=new hM(this._ctx,this.state);this.enterRule(e,208,d.RULE_indexFields);let r;try{let i;for(this.enterOuterAlt(e,1),this.state=1125,this.indexElement(),this.state=1132,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,120,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=1127,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1126,this.match(d.COMMA)),this.state=1129,this.indexElement()),this.state=1134,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,120,this._ctx)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}indexStatement(){let e=new pM(this._ctx,this.state);this.enterRule(e,210,d.RULE_indexStatement);let r;try{this.enterOuterAlt(e,1),this.state=1135,this.match(d.INDEX),this.state=1136,this.indexFields(),this.state=1139,this._errHandler.sync(this),r=this._input.LA(1),r===d.BY&&(this.state=1137,this.match(d.BY),this.state=1138,this.fieldName())}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}sampleStatement(){let e=new mM(this._ctx,this.state);this.enterRule(e,212,d.RULE_sampleStatement);try{this.enterOuterAlt(e,1),this.state=1141,this.match(d.SAMPLE),this.state=1142,this.sampleSpec()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}timezoneStatement(){let e=new aR(this._ctx,this.state);this.enterRule(e,214,d.RULE_timezoneStatement);try{this.enterOuterAlt(e,1),this.state=1144,this.match(d.TIMEZONE),this.state=1145,this.string()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}queryAnnotation(){let e=new gM(this._ctx,this.state);this.enterRule(e,216,d.RULE_queryAnnotation);try{this.enterOuterAlt(e,1),this.state=1147,this.match(d.ANNOTATION)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sampleSpec(){let e=new yM(this._ctx,this.state);this.enterRule(e,218,d.RULE_sampleSpec);let r;try{this.enterOuterAlt(e,1),this.state=1149,r=this._input.LA(1),r===d.FALSE||r===d.TRUE||r===d.PERCENT_LITERAL||r===d.INTEGER_LITERAL?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}aggregate(){let e=new dE(this._ctx,this.state);this.enterRule(e,220,d.RULE_aggregate);let r;try{this.enterOuterAlt(e,1),this.state=1151,r=this._input.LA(1),r===d.AVG||r===d.COUNT||!(r-73&-32)&&1<<r-73&(1<<d.MAX-73|1<<d.MIN-73|1<<d.SUM-73)?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}malloyType(){let e=new hE(this._ctx,this.state);this.enterRule(e,222,d.RULE_malloyType);let r;try{this.enterOuterAlt(e,1),this.state=1153,r=this._input.LA(1),r===d.BOOLEAN||r===d.DATE||!(r-80&-32)&&1<<r-80&(1<<d.NUMBER-80|1<<d.STRING-80|1<<d.TIMESTAMP-80)?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}compareOp(){let e=new lR(this._ctx,this.state);this.enterRule(e,224,d.RULE_compareOp);let r;try{this.enterOuterAlt(e,1),this.state=1155,r=this._input.LA(1),!(r-134&-32)&&1<<r-134&(1<<d.LT-134|1<<d.GT-134|1<<d.EQ-134|1<<d.NE-134|1<<d.LTE-134|1<<d.GTE-134|1<<d.NOT_MATCH-134|1<<d.MATCH-134)?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}string(){let e=new Fa(this._ctx,this.state);this.enterRule(e,226,d.RULE_string);try{switch(this.state=1159,this._errHandler.sync(this),this._input.LA(1)){case d.SQ_STRING:case d.DQ_STRING:this.enterOuterAlt(e,1),this.state=1157,this.shortString();break;case d.SQL_BEGIN:this.enterOuterAlt(e,2),this.state=1158,this.sqlString();break;default:throw new tn.NoViableAltException(this)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}shortString(){let e=new cR(this._ctx,this.state);this.enterRule(e,228,d.RULE_shortString);let r;try{this.enterOuterAlt(e,1),this.state=1161,r=this._input.LA(1),r===d.SQ_STRING||r===d.DQ_STRING?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}rawString(){let e=new EM(this._ctx,this.state);this.enterRule(e,230,d.RULE_rawString);let r;try{this.enterOuterAlt(e,1),this.state=1163,r=this._input.LA(1),r===d.RAW_SQ||r===d.RAW_DQ?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}numericLiteral(){let e=new AM(this._ctx,this.state);this.enterRule(e,232,d.RULE_numericLiteral);let r;try{this.enterOuterAlt(e,1),this.state=1165,r=this._input.LA(1),r===d.NUMERIC_LITERAL||r===d.INTEGER_LITERAL?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}literal(){let e=new _o(this._ctx,this.state);this.enterRule(e,234,d.RULE_literal);let r;try{switch(this.state=1176,this._errHandler.sync(this),this._input.LA(1)){case d.SQ_STRING:case d.DQ_STRING:case d.SQL_BEGIN:e=new Lce(e),this.enterOuterAlt(e,1),this.state=1167,this.string();break;case d.RAW_SQ:case d.RAW_DQ:e=new Ice(e),this.enterOuterAlt(e,2),this.state=1168,this.rawString();break;case d.NUMERIC_LITERAL:case d.INTEGER_LITERAL:e=new Bce(e),this.enterOuterAlt(e,3),this.state=1169,this.numericLiteral();break;case d.LITERAL_TIMESTAMP:case d.LITERAL_HOUR:case d.LITERAL_DAY:case d.LITERAL_QUARTER:case d.LITERAL_MONTH:case d.LITERAL_WEEK:case d.LITERAL_YEAR:e=new $ce(e),this.enterOuterAlt(e,4),this.state=1170,this.dateLiteral();break;case d.NULL:e=new kce(e),this.enterOuterAlt(e,5),this.state=1171,this.match(d.NULL);break;case d.FALSE:case d.TRUE:e=new Mce(e),this.enterOuterAlt(e,6),this.state=1172,r=this._input.LA(1),r===d.FALSE||r===d.TRUE?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this);break;case d.HACKY_REGEX:e=new Pce(e),this.enterOuterAlt(e,7),this.state=1173,this.match(d.HACKY_REGEX);break;case d.SQ3_FILTER:case d.SQ_FILTER:case d.DQ3_FILTER:case d.DQ_FILTER:case d.BQ3_FILTER:case d.BQ_FILTER:e=new Uce(e),this.enterOuterAlt(e,8),this.state=1174,this.filterString();break;case d.NOW:e=new jce(e),this.enterOuterAlt(e,9),this.state=1175,this.match(d.NOW);break;default:throw new tn.NoViableAltException(this)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}dateLiteral(){let e=new wa(this._ctx,this.state);this.enterRule(e,236,d.RULE_dateLiteral);try{switch(this.state=1185,this._errHandler.sync(this),this._input.LA(1)){case d.LITERAL_TIMESTAMP:e=new qce(e),this.enterOuterAlt(e,1),this.state=1178,this.match(d.LITERAL_TIMESTAMP);break;case d.LITERAL_HOUR:e=new Hce(e),this.enterOuterAlt(e,2),this.state=1179,this.match(d.LITERAL_HOUR);break;case d.LITERAL_DAY:e=new Qce(e),this.enterOuterAlt(e,3),this.state=1180,this.match(d.LITERAL_DAY);break;case d.LITERAL_WEEK:e=new zce(e),this.enterOuterAlt(e,4),this.state=1181,this.match(d.LITERAL_WEEK);break;case d.LITERAL_MONTH:e=new Gce(e),this.enterOuterAlt(e,5),this.state=1182,this.match(d.LITERAL_MONTH);break;case d.LITERAL_QUARTER:e=new Wce(e),this.enterOuterAlt(e,6),this.state=1183,this.match(d.LITERAL_QUARTER);break;case d.LITERAL_YEAR:e=new Vce(e),this.enterOuterAlt(e,7),this.state=1184,this.match(d.LITERAL_YEAR);break;default:throw new tn.NoViableAltException(this)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}tablePath(){let e=new _M(this._ctx,this.state);this.enterRule(e,238,d.RULE_tablePath);try{this.enterOuterAlt(e,1),this.state=1187,this.string()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}tableURI(){let e=new Yce(this._ctx,this.state);this.enterRule(e,240,d.RULE_tableURI);try{this.enterOuterAlt(e,1),this.state=1189,this.string()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}id(){let e=new Dn(this._ctx,this.state);this.enterRule(e,242,d.RULE_id);let r;try{this.enterOuterAlt(e,1),this.state=1191,r=this._input.LA(1),r===d.BQ_STRING||r===d.IDENTIFIER?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}timeframe(){let e=new ad(this._ctx,this.state);this.enterRule(e,244,d.RULE_timeframe);let r;try{this.enterOuterAlt(e,1),this.state=1193,r=this._input.LA(1),!(r-49&-32)&&1<<r-49&(1<<d.DAY-49|1<<d.HOUR-49|1<<d.MINUTE-49|1<<d.MONTH-49)||!(r-86&-32)&&1<<r-86&(1<<d.QUARTER-86|1<<d.SECOND-86|1<<d.WEEK-86|1<<d.YEAR-86)?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}ungroup(){let e=new vM(this._ctx,this.state);this.enterRule(e,246,d.RULE_ungroup);let r;try{this.enterOuterAlt(e,1),this.state=1195,r=this._input.LA(1),r===d.ALL||r===d.EXCLUDE?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}malloyOrSQLType(){let e=new fR(this._ctx,this.state);this.enterRule(e,248,d.RULE_malloyOrSQLType);try{switch(this.state=1199,this._errHandler.sync(this),this._input.LA(1)){case d.BOOLEAN:case d.DATE:case d.NUMBER:case d.STRING:case d.TIMESTAMP:this.enterOuterAlt(e,1),this.state=1197,this.malloyType();break;case d.SQ_STRING:case d.DQ_STRING:case d.SQL_BEGIN:this.enterOuterAlt(e,2),this.state=1198,this.string();break;default:throw new tn.NoViableAltException(this)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}fieldExpr(e){e===void 0&&(e=0);let r=this._ctx,i=this.state,s=new Te(this._ctx,i),o=s,u=250;this.enterRecursionRule(s,250,d.RULE_fieldExpr,e);let a;try{let l;this.enterOuterAlt(s,1);{switch(this.state=1303,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,138,this._ctx)){case 1:s=new Kce(s),this._ctx=s,o=s,this.state=1202,this.fieldPath();break;case 2:s=new Jce(s),this._ctx=s,o=s,this.state=1203,this.literal();break;case 3:{for(s=new Xce(s),this._ctx=s,o=s,this.state=1204,this.match(d.OBRACK),this.state=1205,this.fieldExpr(0),this.state=1210,this._errHandler.sync(this),l=this.interpreter.adaptivePredict(this._input,126,this._ctx);l!==2&&l!==en.ATN.INVALID_ALT_NUMBER;)l===1&&(this.state=1206,this.match(d.COMMA),this.state=1207,this.fieldExpr(0)),this.state=1212,this._errHandler.sync(this),l=this.interpreter.adaptivePredict(this._input,126,this._ctx);this.state=1214,this._errHandler.sync(this),a=this._input.LA(1),a===d.COMMA&&(this.state=1213,this.match(d.COMMA)),this.state=1216,this.match(d.CBRACK)}break;case 4:{for(s=new Zce(s),this._ctx=s,o=s,this.state=1218,this.match(d.OCURLY),this.state=1219,this.recordElement(),this.state=1224,this._errHandler.sync(this),a=this._input.LA(1);a===d.COMMA;)this.state=1220,this.match(d.COMMA),this.state=1221,this.recordElement(),this.state=1226,this._errHandler.sync(this),a=this._input.LA(1);this.state=1227,this.match(d.CCURLY)}break;case 5:s=new ife(s),this._ctx=s,o=s,this.state=1229,this.match(d.MINUS),this.state=1230,this.fieldExpr(25);break;case 6:s=new mfe(s),this._ctx=s,o=s,this.state=1231,this.match(d.NOT),this.state=1232,this.fieldExpr(13);break;case 7:s=new CM(s),this._ctx=s,o=s,this.state=1233,this.match(d.CAST),this.state=1234,this.match(d.OPAREN),this.state=1235,this.fieldExpr(0),this.state=1236,this.match(d.AS),this.state=1237,this.malloyOrSQLType(),this.state=1238,this.match(d.CPAREN);break;case 8:s=new Afe(s),this._ctx=s,o=s,this.state=1242,this._errHandler.sync(this),a=this._input.LA(1),a===d.SOURCE_KW&&(this.state=1240,this.match(d.SOURCE_KW),this.state=1241,this.match(d.DOT)),this.state=1244,this.aggregate(),this.state=1245,this.match(d.OPAREN),this.state=1247,this._errHandler.sync(this),a=this._input.LA(1),(!(a-36&-32)&&1<<a-36&(1<<d.ALL-36|1<<d.AVG-36|1<<d.CASE-36|1<<d.CAST-36|1<<d.COUNT-36|1<<d.DAY-36|1<<d.EXCLUDE-36|1<<d.FALSE-36|1<<d.HOUR-36)||!(a-73&-32)&&1<<a-73&(1<<d.MAX-73|1<<d.MIN-73|1<<d.MINUTE-73|1<<d.MONTH-73|1<<d.NOT-73|1<<d.NOW-73|1<<d.NULL-73|1<<d.PICK-73|1<<d.QUARTER-73|1<<d.SECOND-73|1<<d.SOURCE_KW-73|1<<d.SUM-73|1<<d.TRUE-73|1<<d.WEEK-73|1<<d.YEAR-73)||!(a-105&-32)&&1<<a-105&(1<<d.HACKY_REGEX-105|1<<d.RAW_SQ-105|1<<d.RAW_DQ-105|1<<d.SQ3_FILTER-105|1<<d.SQ_FILTER-105|1<<d.DQ3_FILTER-105|1<<d.DQ_FILTER-105|1<<d.BQ3_FILTER-105|1<<d.BQ_FILTER-105|1<<d.SQ_STRING-105|1<<d.DQ_STRING-105|1<<d.BQ_STRING-105|1<<d.OPAREN-105|1<<d.OBRACK-105|1<<d.OCURLY-105)||!(a-141&-32)&&1<<a-141&(1<<d.MINUS-141|1<<d.LITERAL_TIMESTAMP-141|1<<d.LITERAL_HOUR-141|1<<d.LITERAL_DAY-141|1<<d.LITERAL_QUARTER-141|1<<d.LITERAL_MONTH-141|1<<d.LITERAL_WEEK-141|1<<d.LITERAL_YEAR-141|1<<d.IDENTIFIER-141|1<<d.NUMERIC_LITERAL-141|1<<d.INTEGER_LITERAL-141|1<<d.SQL_BEGIN-141))&&(this.state=1246,this.fieldExpr(0)),this.state=1249,this.match(d.CPAREN);break;case 9:s=new _fe(s),this._ctx=s,o=s,this.state=1251,this.fieldPath(),this.state=1252,this.match(d.DOT),this.state=1253,this.aggregate(),this.state=1254,this.match(d.OPAREN),this.state=1256,this._errHandler.sync(this),a=this._input.LA(1),(!(a-36&-32)&&1<<a-36&(1<<d.ALL-36|1<<d.AVG-36|1<<d.CASE-36|1<<d.CAST-36|1<<d.COUNT-36|1<<d.DAY-36|1<<d.EXCLUDE-36|1<<d.FALSE-36|1<<d.HOUR-36)||!(a-73&-32)&&1<<a-73&(1<<d.MAX-73|1<<d.MIN-73|1<<d.MINUTE-73|1<<d.MONTH-73|1<<d.NOT-73|1<<d.NOW-73|1<<d.NULL-73|1<<d.PICK-73|1<<d.QUARTER-73|1<<d.SECOND-73|1<<d.SOURCE_KW-73|1<<d.SUM-73|1<<d.TRUE-73|1<<d.WEEK-73|1<<d.YEAR-73)||!(a-105&-32)&&1<<a-105&(1<<d.HACKY_REGEX-105|1<<d.RAW_SQ-105|1<<d.RAW_DQ-105|1<<d.SQ3_FILTER-105|1<<d.SQ_FILTER-105|1<<d.DQ3_FILTER-105|1<<d.DQ_FILTER-105|1<<d.BQ3_FILTER-105|1<<d.BQ_FILTER-105|1<<d.SQ_STRING-105|1<<d.DQ_STRING-105|1<<d.BQ_STRING-105|1<<d.OPAREN-105|1<<d.OBRACK-105|1<<d.OCURLY-105)||!(a-141&-32)&&1<<a-141&(1<<d.MINUS-141|1<<d.LITERAL_TIMESTAMP-141|1<<d.LITERAL_HOUR-141|1<<d.LITERAL_DAY-141|1<<d.LITERAL_QUARTER-141|1<<d.LITERAL_MONTH-141|1<<d.LITERAL_WEEK-141|1<<d.LITERAL_YEAR-141|1<<d.IDENTIFIER-141|1<<d.NUMERIC_LITERAL-141|1<<d.INTEGER_LITERAL-141|1<<d.SQL_BEGIN-141))&&(this.state=1255,this.fieldExpr(0)),this.state=1258,this.match(d.CPAREN);break;case 10:s=new vfe(s),this._ctx=s,o=s,this.state=1260,this.match(d.OPAREN),this.state=1261,this.fieldExpr(0),this.state=1262,this.match(d.CPAREN);break;case 11:s=new Cfe(s),this._ctx=s,o=s,this.state=1264,this.fieldPath(),this.state=1265,this.match(d.DOT),this.state=1266,this.id(),this.state=1267,this.match(d.OPAREN),this.state=1269,this._errHandler.sync(this),a=this._input.LA(1),(!(a-36&-32)&&1<<a-36&(1<<d.ALL-36|1<<d.AVG-36|1<<d.CASE-36|1<<d.CAST-36|1<<d.COUNT-36|1<<d.DAY-36|1<<d.EXCLUDE-36|1<<d.FALSE-36|1<<d.HOUR-36)||!(a-73&-32)&&1<<a-73&(1<<d.MAX-73|1<<d.MIN-73|1<<d.MINUTE-73|1<<d.MONTH-73|1<<d.NOT-73|1<<d.NOW-73|1<<d.NULL-73|1<<d.PICK-73|1<<d.QUARTER-73|1<<d.SECOND-73|1<<d.SOURCE_KW-73|1<<d.SUM-73|1<<d.TRUE-73|1<<d.WEEK-73|1<<d.YEAR-73)||!(a-105&-32)&&1<<a-105&(1<<d.HACKY_REGEX-105|1<<d.RAW_SQ-105|1<<d.RAW_DQ-105|1<<d.SQ3_FILTER-105|1<<d.SQ_FILTER-105|1<<d.DQ3_FILTER-105|1<<d.DQ_FILTER-105|1<<d.BQ3_FILTER-105|1<<d.BQ_FILTER-105|1<<d.SQ_STRING-105|1<<d.DQ_STRING-105|1<<d.BQ_STRING-105|1<<d.OPAREN-105|1<<d.OBRACK-105|1<<d.OCURLY-105)||!(a-141&-32)&&1<<a-141&(1<<d.MINUS-141|1<<d.LITERAL_TIMESTAMP-141|1<<d.LITERAL_HOUR-141|1<<d.LITERAL_DAY-141|1<<d.LITERAL_QUARTER-141|1<<d.LITERAL_MONTH-141|1<<d.LITERAL_WEEK-141|1<<d.LITERAL_YEAR-141|1<<d.IDENTIFIER-141|1<<d.NUMERIC_LITERAL-141|1<<d.INTEGER_LITERAL-141|1<<d.SQL_BEGIN-141))&&(this.state=1268,this.argumentList()),this.state=1271,this.match(d.CPAREN);break;case 12:{switch(s=new Sfe(s),this._ctx=s,o=s,this.state=1281,this._errHandler.sync(this),this._input.LA(1)){case d.BQ_STRING:case d.IDENTIFIER:this.state=1273,this.id(),this.state=1278,this._errHandler.sync(this),a=this._input.LA(1),a===d.EXCLAM&&(this.state=1274,this.match(d.EXCLAM),this.state=1276,this._errHandler.sync(this),a=this._input.LA(1),(a===d.BOOLEAN||a===d.DATE||!(a-80&-32)&&1<<a-80&(1<<d.NUMBER-80|1<<d.STRING-80|1<<d.TIMESTAMP-80))&&(this.state=1275,this.malloyType()));break;case d.DAY:case d.HOUR:case d.MINUTE:case d.MONTH:case d.QUARTER:case d.SECOND:case d.WEEK:case d.YEAR:this.state=1280,this.timeframe();break;default:throw new tn.NoViableAltException(this)}this.state=1283,this.match(d.OPAREN),this.state=1285,this._errHandler.sync(this),a=this._input.LA(1),(!(a-36&-32)&&1<<a-36&(1<<d.ALL-36|1<<d.AVG-36|1<<d.CASE-36|1<<d.CAST-36|1<<d.COUNT-36|1<<d.DAY-36|1<<d.EXCLUDE-36|1<<d.FALSE-36|1<<d.HOUR-36)||!(a-73&-32)&&1<<a-73&(1<<d.MAX-73|1<<d.MIN-73|1<<d.MINUTE-73|1<<d.MONTH-73|1<<d.NOT-73|1<<d.NOW-73|1<<d.NULL-73|1<<d.PICK-73|1<<d.QUARTER-73|1<<d.SECOND-73|1<<d.SOURCE_KW-73|1<<d.SUM-73|1<<d.TRUE-73|1<<d.WEEK-73|1<<d.YEAR-73)||!(a-105&-32)&&1<<a-105&(1<<d.HACKY_REGEX-105|1<<d.RAW_SQ-105|1<<d.RAW_DQ-105|1<<d.SQ3_FILTER-105|1<<d.SQ_FILTER-105|1<<d.DQ3_FILTER-105|1<<d.DQ_FILTER-105|1<<d.BQ3_FILTER-105|1<<d.BQ_FILTER-105|1<<d.SQ_STRING-105|1<<d.DQ_STRING-105|1<<d.BQ_STRING-105|1<<d.OPAREN-105|1<<d.OBRACK-105|1<<d.OCURLY-105)||!(a-141&-32)&&1<<a-141&(1<<d.MINUS-141|1<<d.LITERAL_TIMESTAMP-141|1<<d.LITERAL_HOUR-141|1<<d.LITERAL_DAY-141|1<<d.LITERAL_QUARTER-141|1<<d.LITERAL_MONTH-141|1<<d.LITERAL_WEEK-141|1<<d.LITERAL_YEAR-141|1<<d.IDENTIFIER-141|1<<d.NUMERIC_LITERAL-141|1<<d.INTEGER_LITERAL-141|1<<d.SQL_BEGIN-141))&&(this.state=1284,this.argumentList()),this.state=1287,this.match(d.CPAREN)}break;case 13:s=new bfe(s),this._ctx=s,o=s,this.state=1289,this.pickStatement();break;case 14:s=new Tfe(s),this._ctx=s,o=s,this.state=1290,this.caseStatement();break;case 15:{for(s=new Rfe(s),this._ctx=s,o=s,this.state=1291,this.ungroup(),this.state=1292,this.match(d.OPAREN),this.state=1293,this.fieldExpr(0),this.state=1298,this._errHandler.sync(this),a=this._input.LA(1);a===d.COMMA;)this.state=1294,this.match(d.COMMA),this.state=1295,this.fieldName(),this.state=1300,this._errHandler.sync(this),a=this._input.LA(1);this.state=1301,this.match(d.CPAREN)}break}for(this._ctx._stop=this._input.tryLT(-1),this.state=1377,this._errHandler.sync(this),l=this.interpreter.adaptivePredict(this._input,143,this._ctx);l!==2&&l!==en.ATN.INVALID_ALT_NUMBER;){if(l===1)switch(this._parseListeners!=null&&this.triggerExitRuleEvent(),o=s,this.state=1375,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,142,this._ctx)){case 1:{if(s=new sfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1305,!this.precpred(this._ctx,24))throw this.createFailedPredicateException("this.precpred(this._ctx, 24)");this.state=1306,a=this._input.LA(1),!(a-142&-32)&&1<<a-142&(1<<d.STAR-142|1<<d.SLASH-142|1<<d.PERCENT-142)?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this),this.state=1307,this.fieldExpr(25)}break;case 2:{if(s=new ofe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1308,!this.precpred(this._ctx,23))throw this.createFailedPredicateException("this.precpred(this._ctx, 23)");this.state=1309,a=this._input.LA(1),a===d.PLUS||a===d.MINUS?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this),this.state=1310,this.fieldExpr(24)}break;case 3:{if(s=new ufe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1311,!this.precpred(this._ctx,22))throw this.createFailedPredicateException("this.precpred(this._ctx, 22)");this.state=1312,this.match(d.TO),this.state=1313,this.fieldExpr(23)}break;case 4:{if(s=new ffe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1314,!this.precpred(this._ctx,18))throw this.createFailedPredicateException("this.precpred(this._ctx, 18)");this.state=1315,this.compareOp(),this.state=1316,this.fieldExpr(19)}break;case 5:{if(s=new xfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1318,!this.precpred(this._ctx,17))throw this.createFailedPredicateException("this.precpred(this._ctx, 17)");this.state=1320,this._errHandler.sync(this),a=this._input.LA(1),a===d.NOT&&(this.state=1319,this.match(d.NOT)),this.state=1322,this.match(d.LIKE),this.state=1323,this.fieldExpr(18)}break;case 6:{if(s=new gfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1324,!this.precpred(this._ctx,12))throw this.createFailedPredicateException("this.precpred(this._ctx, 12)");this.state=1325,this.match(d.AND),this.state=1326,this.fieldExpr(13)}break;case 7:{if(s=new yfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1327,!this.precpred(this._ctx,11))throw this.createFailedPredicateException("this.precpred(this._ctx, 11)");this.state=1328,this.match(d.OR),this.state=1329,this.fieldExpr(12)}break;case 8:{if(s=new Efe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1330,!this.precpred(this._ctx,10))throw this.createFailedPredicateException("this.precpred(this._ctx, 10)");this.state=1331,this.match(d.DOUBLE_QMARK),this.state=1332,this.fieldExpr(11)}break;case 9:{if(s=new efe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1333,!this.precpred(this._ctx,30))throw this.createFailedPredicateException("this.precpred(this._ctx, 30)");this.state=1334,this.fieldProperties()}break;case 10:{if(s=new tfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1335,!this.precpred(this._ctx,29))throw this.createFailedPredicateException("this.precpred(this._ctx, 29)");this.state=1336,this.timeframe()}break;case 11:{if(s=new nfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1337,!this.precpred(this._ctx,28))throw this.createFailedPredicateException("this.precpred(this._ctx, 28)");this.state=1338,this.match(d.DOT),this.state=1339,this.timeframe()}break;case 12:{if(s=new CM(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1340,!this.precpred(this._ctx,27))throw this.createFailedPredicateException("this.precpred(this._ctx, 27)");this.state=1341,this.match(d.DOUBLECOLON),this.state=1342,this.malloyOrSQLType()}break;case 13:{if(s=new rfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1343,!this.precpred(this._ctx,26))throw this.createFailedPredicateException("this.precpred(this._ctx, 26)");this.state=1344,this.match(d.TRIPLECOLON),this.state=1345,this.malloyOrSQLType()}break;case 14:{if(s=new afe(new Te(r,i)),s._startAt=o,this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1346,!this.precpred(this._ctx,21))throw this.createFailedPredicateException("this.precpred(this._ctx, 21)");this.state=1347,this.match(d.FOR),this.state=1348,s._duration=this.fieldExpr(0),this.state=1349,this.timeframe()}break;case 15:{if(s=new lfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1351,!this.precpred(this._ctx,20))throw this.createFailedPredicateException("this.precpred(this._ctx, 20)");this.state=1352,this.match(d.AMPER),this.state=1353,this.partialAllowedFieldExpr()}break;case 16:{if(s=new cfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1354,!this.precpred(this._ctx,19))throw this.createFailedPredicateException("this.precpred(this._ctx, 19)");this.state=1355,this.match(d.BAR),this.state=1356,this.partialAllowedFieldExpr()}break;case 17:{if(s=new dfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1357,!this.precpred(this._ctx,16))throw this.createFailedPredicateException("this.precpred(this._ctx, 16)");this.state=1358,this.match(d.IS),this.state=1360,this._errHandler.sync(this),a=this._input.LA(1),a===d.NOT&&(this.state=1359,this.match(d.NOT)),this.state=1362,this.match(d.NULL)}break;case 18:{if(s=new hfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1363,!this.precpred(this._ctx,15))throw this.createFailedPredicateException("this.precpred(this._ctx, 15)");this.state=1365,this._errHandler.sync(this),a=this._input.LA(1),a===d.NOT&&(this.state=1364,this.match(d.NOT)),this.state=1367,this.match(d.IN),this.state=1368,this.match(d.OPAREN),this.state=1369,this.fieldExprList(),this.state=1370,this.match(d.CPAREN)}break;case 19:{if(s=new pfe(new Te(r,i)),this.pushNewRecursionContext(s,u,d.RULE_fieldExpr),this.state=1372,!this.precpred(this._ctx,14))throw this.createFailedPredicateException("this.precpred(this._ctx, 14)");this.state=1373,this.match(d.QMARK),this.state=1374,this.partialAllowedFieldExpr()}break}this.state=1379,this._errHandler.sync(this),l=this.interpreter.adaptivePredict(this._input,143,this._ctx)}}}catch(l){if(l instanceof me.RecognitionException)s.exception=l,this._errHandler.reportError(this,l),this._errHandler.recover(this,l);else throw l}finally{this.unrollRecursionContexts(r)}return s}partialCompare(){let e=new SM(this._ctx,this.state);this.enterRule(e,252,d.RULE_partialCompare);try{this.enterOuterAlt(e,1),this.state=1380,this.compareOp(),this.state=1381,this.fieldExpr(0)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}partialTest(){let e=new bM(this._ctx,this.state);this.enterRule(e,254,d.RULE_partialTest);let r;try{switch(this.state=1389,this._errHandler.sync(this),this._input.LA(1)){case d.LT:case d.GT:case d.EQ:case d.NE:case d.LTE:case d.GTE:case d.NOT_MATCH:case d.MATCH:this.enterOuterAlt(e,1),this.state=1383,this.partialCompare();break;case d.IS:this.enterOuterAlt(e,2),this.state=1384,this.match(d.IS),this.state=1386,this._errHandler.sync(this),r=this._input.LA(1),r===d.NOT&&(this.state=1385,this.match(d.NOT)),this.state=1388,this.match(d.NULL);break;default:throw new tn.NoViableAltException(this)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}partialAllowedFieldExpr(){let e=new ld(this._ctx,this.state);this.enterRule(e,256,d.RULE_partialAllowedFieldExpr);try{switch(this.state=1397,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,146,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=1391,this.partialTest();break;case 2:this.enterOuterAlt(e,2),this.state=1392,this.match(d.OPAREN),this.state=1393,this.partialTest(),this.state=1394,this.match(d.CPAREN);break;case 3:this.enterOuterAlt(e,3),this.state=1396,this.fieldExpr(0);break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}fieldExprList(){let e=new TM(this._ctx,this.state);this.enterRule(e,258,d.RULE_fieldExprList);let r;try{for(this.enterOuterAlt(e,1),this.state=1399,this.fieldExpr(0),this.state=1404,this._errHandler.sync(this),r=this._input.LA(1);r===d.COMMA;)this.state=1400,this.match(d.COMMA),this.state=1401,this.fieldExpr(0),this.state=1406,this._errHandler.sync(this),r=this._input.LA(1)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}pickStatement(){let e=new RM(this._ctx,this.state);this.enterRule(e,260,d.RULE_pickStatement);try{let r;this.enterOuterAlt(e,1);{this.state=1408,this._errHandler.sync(this),r=1;do{switch(r){case 1:this.state=1407,this.pick();break;default:throw new tn.NoViableAltException(this)}this.state=1410,this._errHandler.sync(this),r=this.interpreter.adaptivePredict(this._input,148,this._ctx)}while(r!==2&&r!==en.ATN.INVALID_ALT_NUMBER);switch(this.state=1414,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,149,this._ctx)){case 1:this.state=1412,this.match(d.ELSE),this.state=1413,e._pickElse=this.fieldExpr(0);break}}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}pick(){let e=new xR(this._ctx,this.state);this.enterRule(e,262,d.RULE_pick);let r;try{this.enterOuterAlt(e,1),this.state=1416,this.match(d.PICK),this.state=1418,this._errHandler.sync(this),r=this._input.LA(1),(!(r-36&-32)&&1<<r-36&(1<<d.ALL-36|1<<d.AVG-36|1<<d.CASE-36|1<<d.CAST-36|1<<d.COUNT-36|1<<d.DAY-36|1<<d.EXCLUDE-36|1<<d.FALSE-36|1<<d.HOUR-36)||!(r-73&-32)&&1<<r-73&(1<<d.MAX-73|1<<d.MIN-73|1<<d.MINUTE-73|1<<d.MONTH-73|1<<d.NOT-73|1<<d.NOW-73|1<<d.NULL-73|1<<d.PICK-73|1<<d.QUARTER-73|1<<d.SECOND-73|1<<d.SOURCE_KW-73|1<<d.SUM-73|1<<d.TRUE-73|1<<d.WEEK-73|1<<d.YEAR-73)||!(r-105&-32)&&1<<r-105&(1<<d.HACKY_REGEX-105|1<<d.RAW_SQ-105|1<<d.RAW_DQ-105|1<<d.SQ3_FILTER-105|1<<d.SQ_FILTER-105|1<<d.DQ3_FILTER-105|1<<d.DQ_FILTER-105|1<<d.BQ3_FILTER-105|1<<d.BQ_FILTER-105|1<<d.SQ_STRING-105|1<<d.DQ_STRING-105|1<<d.BQ_STRING-105|1<<d.OPAREN-105|1<<d.OBRACK-105|1<<d.OCURLY-105)||!(r-141&-32)&&1<<r-141&(1<<d.MINUS-141|1<<d.LITERAL_TIMESTAMP-141|1<<d.LITERAL_HOUR-141|1<<d.LITERAL_DAY-141|1<<d.LITERAL_QUARTER-141|1<<d.LITERAL_MONTH-141|1<<d.LITERAL_WEEK-141|1<<d.LITERAL_YEAR-141|1<<d.IDENTIFIER-141|1<<d.NUMERIC_LITERAL-141|1<<d.INTEGER_LITERAL-141|1<<d.SQL_BEGIN-141))&&(this.state=1417,e._pickValue=this.fieldExpr(0)),this.state=1420,this.match(d.WHEN),this.state=1421,e._pickWhen=this.partialAllowedFieldExpr()}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}caseStatement(){let e=new DM(this._ctx,this.state);this.enterRule(e,264,d.RULE_caseStatement);let r;try{this.enterOuterAlt(e,1);{this.state=1423,this.match(d.CASE),this.state=1425,this._errHandler.sync(this),r=this._input.LA(1),(!(r-36&-32)&&1<<r-36&(1<<d.ALL-36|1<<d.AVG-36|1<<d.CASE-36|1<<d.CAST-36|1<<d.COUNT-36|1<<d.DAY-36|1<<d.EXCLUDE-36|1<<d.FALSE-36|1<<d.HOUR-36)||!(r-73&-32)&&1<<r-73&(1<<d.MAX-73|1<<d.MIN-73|1<<d.MINUTE-73|1<<d.MONTH-73|1<<d.NOT-73|1<<d.NOW-73|1<<d.NULL-73|1<<d.PICK-73|1<<d.QUARTER-73|1<<d.SECOND-73|1<<d.SOURCE_KW-73|1<<d.SUM-73|1<<d.TRUE-73|1<<d.WEEK-73|1<<d.YEAR-73)||!(r-105&-32)&&1<<r-105&(1<<d.HACKY_REGEX-105|1<<d.RAW_SQ-105|1<<d.RAW_DQ-105|1<<d.SQ3_FILTER-105|1<<d.SQ_FILTER-105|1<<d.DQ3_FILTER-105|1<<d.DQ_FILTER-105|1<<d.BQ3_FILTER-105|1<<d.BQ_FILTER-105|1<<d.SQ_STRING-105|1<<d.DQ_STRING-105|1<<d.BQ_STRING-105|1<<d.OPAREN-105|1<<d.OBRACK-105|1<<d.OCURLY-105)||!(r-141&-32)&&1<<r-141&(1<<d.MINUS-141|1<<d.LITERAL_TIMESTAMP-141|1<<d.LITERAL_HOUR-141|1<<d.LITERAL_DAY-141|1<<d.LITERAL_QUARTER-141|1<<d.LITERAL_MONTH-141|1<<d.LITERAL_WEEK-141|1<<d.LITERAL_YEAR-141|1<<d.IDENTIFIER-141|1<<d.NUMERIC_LITERAL-141|1<<d.INTEGER_LITERAL-141|1<<d.SQL_BEGIN-141))&&(this.state=1424,e._valueExpr=this.fieldExpr(0)),this.state=1428,this._errHandler.sync(this),r=this._input.LA(1);do this.state=1427,this.caseWhen(),this.state=1430,this._errHandler.sync(this),r=this._input.LA(1);while(r===d.WHEN);this.state=1434,this._errHandler.sync(this),r=this._input.LA(1),r===d.ELSE&&(this.state=1432,this.match(d.ELSE),this.state=1433,e._caseElse=this.fieldExpr(0)),this.state=1436,this.match(d.END)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}caseWhen(){let e=new dR(this._ctx,this.state);this.enterRule(e,266,d.RULE_caseWhen);try{this.enterOuterAlt(e,1),this.state=1438,this.match(d.WHEN),this.state=1439,e._condition=this.fieldExpr(0),this.state=1440,this.match(d.THEN),this.state=1441,e._result=this.fieldExpr(0)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}recordKey(){let e=new OM(this._ctx,this.state);this.enterRule(e,268,d.RULE_recordKey);try{this.enterOuterAlt(e,1),this.state=1443,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}recordElement(){let e=new S2(this._ctx,this.state);this.enterRule(e,270,d.RULE_recordElement);try{switch(this.state=1452,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,155,this._ctx)){case 1:e=new Dfe(e),this.enterOuterAlt(e,1),this.state=1445,this.fieldPath();break;case 2:e=new Ofe(e),this.enterOuterAlt(e,2);{switch(this.state=1449,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,154,this._ctx)){case 1:this.state=1446,this.recordKey(),this.state=1447,this.match(d.IS);break}this.state=1451,this.fieldExpr(0)}break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}argumentList(){let e=new hR(this._ctx,this.state);this.enterRule(e,272,d.RULE_argumentList);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=1454,this.fieldExpr(0),this.state=1459,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,156,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=1455,this.match(d.COMMA),this.state=1456,this.fieldExpr(0)),this.state=1461,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,156,this._ctx);this.state=1463,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1462,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}fieldNameList(){let e=new b2(this._ctx,this.state);this.enterRule(e,274,d.RULE_fieldNameList);let r;try{let i;for(this.enterOuterAlt(e,1),this.state=1465,this.fieldName(),this.state=1472,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,159,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=1467,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1466,this.match(d.COMMA)),this.state=1469,this.fieldName()),this.state=1474,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,159,this._ctx)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}fieldCollection(){let e=new FM(this._ctx,this.state);this.enterRule(e,276,d.RULE_fieldCollection);let r;try{let i;this.enterOuterAlt(e,1);{for(this.state=1475,this.collectionMember(),this.state=1482,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,161,this._ctx);i!==2&&i!==en.ATN.INVALID_ALT_NUMBER;)i===1&&(this.state=1477,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1476,this.match(d.COMMA)),this.state=1479,this.collectionMember()),this.state=1484,this._errHandler.sync(this),i=this.interpreter.adaptivePredict(this._input,161,this._ctx);this.state=1486,this._errHandler.sync(this),r=this._input.LA(1),r===d.COMMA&&(this.state=1485,this.match(d.COMMA))}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}collectionWildCard(){let e=new pE(this._ctx,this.state);this.enterRule(e,278,d.RULE_collectionWildCard);let r;try{switch(this.enterOuterAlt(e,1),this.state=1491,this._errHandler.sync(this),r=this._input.LA(1),(r===d.BQ_STRING||r===d.IDENTIFIER)&&(this.state=1488,this.fieldPath(),this.state=1489,this.match(d.DOT)),this.state=1493,this.match(d.STAR),this.state=1495,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,164,this._ctx)){case 1:this.state=1494,this.starQualified();break}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}starQualified(){let e=new pR(this._ctx,this.state);this.enterRule(e,280,d.RULE_starQualified);let r;try{this.enterOuterAlt(e,1);{this.state=1497,this.match(d.OCURLY),this.state=1501,this._errHandler.sync(this),r=this._input.LA(1);do{switch(this.state=1501,this._errHandler.sync(this),this._input.LA(1)){case d.EXCEPT:this.state=1498,this.match(d.EXCEPT),this.state=1499,this.fieldNameList();break;case d.COMMA:this.state=1500,this.match(d.COMMA);break;default:throw new tn.NoViableAltException(this)}this.state=1503,this._errHandler.sync(this),r=this._input.LA(1)}while(r===d.EXCEPT||r===d.COMMA);this.state=1505,this.match(d.CCURLY)}}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}taggedRef(){let e=new mR(this._ctx,this.state);this.enterRule(e,282,d.RULE_taggedRef);let r;try{this.enterOuterAlt(e,1),this.state=1507,this.tags(),this.state=1508,this.fieldPath(),this.state=1510,this._errHandler.sync(this),r=this._input.LA(1),r===d.DOT&&(this.state=1509,this.refExpr())}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}refExpr(){let e=new wM(this._ctx,this.state);this.enterRule(e,284,d.RULE_refExpr);try{switch(this.state=1519,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,168,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=1512,this.match(d.DOT),this.state=1513,this.timeframe();break;case 2:this.enterOuterAlt(e,2),this.state=1514,this.match(d.DOT),this.state=1515,this.aggregate(),this.state=1516,this.match(d.OPAREN),this.state=1517,this.match(d.CPAREN);break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}collectionMember(){let e=new gR(this._ctx,this.state);this.enterRule(e,286,d.RULE_collectionMember);try{switch(this.state=1524,this._errHandler.sync(this),this.interpreter.adaptivePredict(this._input,169,this._ctx)){case 1:this.enterOuterAlt(e,1),this.state=1521,this.taggedRef();break;case 2:this.enterOuterAlt(e,2),this.state=1522,this.collectionWildCard();break;case 3:this.enterOuterAlt(e,3),this.state=1523,this.fieldDef();break}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}fieldPath(){let e=new Na(this._ctx,this.state);this.enterRule(e,288,d.RULE_fieldPath);try{let r;for(this.enterOuterAlt(e,1),this.state=1526,this.fieldName(),this.state=1531,this._errHandler.sync(this),r=this.interpreter.adaptivePredict(this._input,170,this._ctx);r!==2&&r!==en.ATN.INVALID_ALT_NUMBER;)r===1&&(this.state=1527,this.match(d.DOT),this.state=1528,this.fieldName()),this.state=1533,this._errHandler.sync(this),r=this.interpreter.adaptivePredict(this._input,170,this._ctx)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}joinName(){let e=new Ffe(this._ctx,this.state);this.enterRule(e,290,d.RULE_joinName);try{this.enterOuterAlt(e,1),this.state=1534,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}fieldName(){let e=new Ur(this._ctx,this.state);this.enterRule(e,292,d.RULE_fieldName);try{this.enterOuterAlt(e,1),this.state=1536,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sqlExploreNameRef(){let e=new wfe(this._ctx,this.state);this.enterRule(e,294,d.RULE_sqlExploreNameRef);try{this.enterOuterAlt(e,1),this.state=1538,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}nameSQLBlock(){let e=new Nfe(this._ctx,this.state);this.enterRule(e,296,d.RULE_nameSQLBlock);try{this.enterOuterAlt(e,1),this.state=1540,this.id()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}connectionName(){let e=new Lfe(this._ctx,this.state);this.enterRule(e,298,d.RULE_connectionName);try{this.enterOuterAlt(e,1),this.state=1542,this.string()}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}tripFilterString(){let e=new NM(this._ctx,this.state);this.enterRule(e,300,d.RULE_tripFilterString);let r;try{this.enterOuterAlt(e,1),this.state=1544,r=this._input.LA(1),!(r-108&-32)&&1<<r-108&(1<<d.SQ3_FILTER-108|1<<d.DQ3_FILTER-108|1<<d.BQ3_FILTER-108)?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}tickFilterString(){let e=new LM(this._ctx,this.state);this.enterRule(e,302,d.RULE_tickFilterString);let r;try{this.enterOuterAlt(e,1),this.state=1546,r=this._input.LA(1),!(r-109&-32)&&1<<r-109&(1<<d.SQ_FILTER-109|1<<d.DQ_FILTER-109|1<<d.BQ_FILTER-109)?(this._input.LA(1)===qn.Token.EOF&&(this.matchedEOF=!0),this._errHandler.reportMatch(this),this.consume()):this._errHandler.recoverInline(this)}catch(i){if(i instanceof me.RecognitionException)e.exception=i,this._errHandler.reportError(this,i),this._errHandler.recover(this,i);else throw i}finally{this.exitRule()}return e}filterString(){let e=new IM(this._ctx,this.state);this.enterRule(e,304,d.RULE_filterString);try{switch(this.state=1550,this._errHandler.sync(this),this._input.LA(1)){case d.SQ3_FILTER:case d.DQ3_FILTER:case d.BQ3_FILTER:this.enterOuterAlt(e,1),this.state=1548,this.tripFilterString();break;case d.SQ_FILTER:case d.DQ_FILTER:case d.BQ_FILTER:this.enterOuterAlt(e,2),this.state=1549,this.tickFilterString();break;default:throw new tn.NoViableAltException(this)}}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}debugExpr(){let e=new Ife(this._ctx,this.state);this.enterRule(e,306,d.RULE_debugExpr);try{this.enterOuterAlt(e,1),this.state=1552,this.fieldExpr(0),this.state=1553,this.match(d.EOF)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}debugPartial(){let e=new Bfe(this._ctx,this.state);this.enterRule(e,308,d.RULE_debugPartial);try{this.enterOuterAlt(e,1),this.state=1555,this.partialAllowedFieldExpr(),this.state=1556,this.match(d.EOF)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}experimentalStatementForTesting(){let e=new BM(this._ctx,this.state);this.enterRule(e,310,d.RULE_experimentalStatementForTesting);try{this.enterOuterAlt(e,1),this.state=1558,this.match(d.SEMI),this.state=1559,this.match(d.SEMI),this.state=1560,this.match(d.OBRACK),this.state=1561,this.string(),this.state=1562,this.match(d.CBRACK)}catch(r){if(r instanceof me.RecognitionException)e.exception=r,this._errHandler.reportError(this,r),this._errHandler.recover(this,r);else throw r}finally{this.exitRule()}return e}sempred(e,r,i){switch(r){case 53:return this.sqExpr_sempred(e,i);case 62:return this.segExpr_sempred(e,i);case 125:return this.fieldExpr_sempred(e,i)}return!0}sqExpr_sempred(e,r){switch(r){case 0:return this.precpred(this._ctx,6);case 1:return this.precpred(this._ctx,5);case 2:return this.precpred(this._ctx,4);case 3:return this.precpred(this._ctx,3)}return!0}segExpr_sempred(e,r){switch(r){case 4:return this.precpred(this._ctx,1)}return!0}fieldExpr_sempred(e,r){switch(r){case 5:return this.precpred(this._ctx,24);case 6:return this.precpred(this._ctx,23);case 7:return this.precpred(this._ctx,22);case 8:return this.precpred(this._ctx,18);case 9:return this.precpred(this._ctx,17);case 10:return this.precpred(this._ctx,12);case 11:return this.precpred(this._ctx,11);case 12:return this.precpred(this._ctx,10);case 13:return this.precpred(this._ctx,30);case 14:return this.precpred(this._ctx,29);case 15:return this.precpred(this._ctx,28);case 16:return this.precpred(this._ctx,27);case 17:return this.precpred(this._ctx,26);case 18:return this.precpred(this._ctx,21);case 19:return this.precpred(this._ctx,20);case 20:return this.precpred(this._ctx,19);case 21:return this.precpred(this._ctx,16);case 22:return this.precpred(this._ctx,15);case 23:return this.precpred(this._ctx,14)}return!0}static get _ATN(){return d.__ATN||(d.__ATN=new uft.ATNDeserializer().deserialize(G0e.toCharArray(d._serializedATN))),d.__ATN}}w.MalloyParser=d,d.ACCEPT=1,d.AGGREGATE=2,d.CALCULATE=3,d.CALCULATION=4,d.CONNECTION=5,d.DECLARE=6,d.DIMENSION=7,d.EXCEPT=8,d.EXTENDQ=9,d.GROUP_BY=10,d.HAVING=11,d.INDEX=12,d.INTERNAL=13,d.JOIN_CROSS=14,d.JOIN_ONE=15,d.JOIN_MANY=16,d.LIMIT=17,d.MEASURE=18,d.NEST=19,d.ORDER_BY=20,d.PARTITION_BY=21,d.PRIMARY_KEY=22,d.PRIVATE=23,d.PROJECT=24,d.PUBLIC=25,d.QUERY=26,d.RENAME=27,d.RUN=28,d.SAMPLE=29,d.SELECT=30,d.SOURCE=31,d.TOP=32,d.WHERE=33,d.VIEW=34,d.TIMEZONE=35,d.ALL=36,d.AND=37,d.AS=38,d.ASC=39,d.AVG=40,d.BOOLEAN=41,d.BY=42,d.CASE=43,d.CAST=44,d.CONDITION=45,d.COUNT=46,d.COMPOSE=47,d.DATE=48,d.DAY=49,d.DESC=50,d.DISTINCT=51,d.ELSE=52,d.END=53,d.EXCLUDE=54,d.EXTEND=55,d.FALSE=56,d.FILTER=57,d.FULL=58,d.FOR=59,d.FROM=60,d.HAS=61,d.HOUR=62,d.IMPORT=63,d.INCLUDE=64,d.INNER=65,d.IS=66,d.IN=67,d.INTERNAL_KW=68,d.JSON=69,d.LAST=70,d.LEFT=71,d.LIKE=72,d.MAX=73,d.MIN=74,d.MINUTE=75,d.MONTH=76,d.NOT=77,d.NOW=78,d.NULL=79,d.NUMBER=80,d.ON=81,d.OR=82,d.PICK=83,d.PRIVATE_KW=84,d.PUBLIC_KW=85,d.QUARTER=86,d.RIGHT=87,d.SECOND=88,d.STRING=89,d.SOURCE_KW=90,d.SUM=91,d.SQL=92,d.TABLE=93,d.THEN=94,d.THIS=95,d.TIMESTAMP=96,d.TO=97,d.TRUE=98,d.TURTLE=99,d.WEEK=100,d.WHEN=101,d.WITH=102,d.YEAR=103,d.UNGROUPED=104,d.HACKY_REGEX=105,d.RAW_SQ=106,d.RAW_DQ=107,d.SQ3_FILTER=108,d.SQ_FILTER=109,d.DQ3_FILTER=110,d.DQ_FILTER=111,d.BQ3_FILTER=112,d.BQ_FILTER=113,d.SQ_STRING=114,d.DQ_STRING=115,d.BQ_STRING=116,d.DOC_ANNOTATION=117,d.ANNOTATION=118,d.AMPER=119,d.ARROW=120,d.FAT_ARROW=121,d.OPAREN=122,d.CPAREN=123,d.OBRACK=124,d.CBRACK=125,d.OCURLY=126,d.CCURLY=127,d.DOUBLECOLON=128,d.TRIPLECOLON=129,d.EXCLAM=130,d.COLON=131,d.COMMA=132,d.DOT=133,d.LT=134,d.GT=135,d.EQ=136,d.NE=137,d.LTE=138,d.GTE=139,d.PLUS=140,d.MINUS=141,d.STAR=142,d.STARSTAR=143,d.SLASH=144,d.BAR=145,d.SEMI=146,d.NOT_MATCH=147,d.MATCH=148,d.PERCENT=149,d.DOUBLE_QMARK=150,d.QMARK=151,d.LITERAL_TIMESTAMP=152,d.LITERAL_HOUR=153,d.LITERAL_DAY=154,d.LITERAL_QUARTER=155,d.LITERAL_MONTH=156,d.LITERAL_WEEK=157,d.LITERAL_YEAR=158,d.IDENTIFIER=159,d.PERCENT_LITERAL=160,d.NUMERIC_LITERAL=161,d.INTEGER_LITERAL=162,d.BLOCK_COMMENT=163,d.COMMENT_TO_EOL=164,d.WHITE_SPACE=165,d.SQL_BEGIN=166,d.UNWATED_CHARS_TRAILING_NUMBERS=167,d.UNEXPECTED_CHAR=168,d.OPEN_CODE=169,d.SQL_END=170,d.RULE_malloyDocument=0,d.RULE_malloyStatement=1,d.RULE_defineSourceStatement=2,d.RULE_defineQuery=3,d.RULE_topLevelAnonQueryDef=4,d.RULE_tags=5,d.RULE_isDefine=6,d.RULE_runStatement=7,d.RULE_sqlString=8,d.RULE_sqlInterpolation=9,d.RULE_importStatement=10,d.RULE_importSelect=11,d.RULE_importItem=12,d.RULE_importURL=13,d.RULE_docAnnotations=14,d.RULE_ignoredObjectAnnotations=15,d.RULE_ignoredModelAnnotations=16,d.RULE_topLevelQueryDefs=17,d.RULE_topLevelQueryDef=18,d.RULE_refineOperator=19,d.RULE_turtleName=20,d.RULE_sqlSource=21,d.RULE_exploreTable=22,d.RULE_connectionId=23,d.RULE_queryProperties=24,d.RULE_queryName=25,d.RULE_sourcePropertyList=26,d.RULE_sourceDefinition=27,d.RULE_sqExplore=28,d.RULE_sourceParameters=29,d.RULE_legalParamType=30,d.RULE_sourceParameter=31,d.RULE_parameterNameDef=32,d.RULE_sourceNameDef=33,d.RULE_exploreProperties=34,d.RULE_exploreStatement=35,d.RULE_accessLabel=36,d.RULE_accessModifierList=37,d.RULE_defMeasures=38,d.RULE_defDimensions=39,d.RULE_renameList=40,d.RULE_exploreRenameDef=41,d.RULE_defList=42,d.RULE_fieldDef=43,d.RULE_fieldNameDef=44,d.RULE_joinNameDef=45,d.RULE_declareStatement=46,d.RULE_joinStatement=47,d.RULE_queryExtend=48,d.RULE_modEither=49,d.RULE_sourceArguments=50,d.RULE_argumentId=51,d.RULE_sourceArgument=52,d.RULE_sqExpr=53,d.RULE_includeBlock=54,d.RULE_includeItem=55,d.RULE_orphanedAnnotation=56,d.RULE_accessLabelProp=57,d.RULE_includeExceptList=58,d.RULE_includeExceptListItem=59,d.RULE_includeList=60,d.RULE_includeField=61,d.RULE_segExpr=62,d.RULE_vExpr=63,d.RULE_queryExtendStatement=64,d.RULE_queryExtendStatementList=65,d.RULE_joinList=66,d.RULE_isExplore=67,d.RULE_matrixOperation=68,d.RULE_joinFrom=69,d.RULE_joinDef=70,d.RULE_joinExpression=71,d.RULE_filterStatement=72,d.RULE_fieldProperties=73,d.RULE_aggregateOrdering=74,d.RULE_aggregateOrderBySpec=75,d.RULE_aggregateOrderByStatement=76,d.RULE_fieldPropertyLimitStatement=77,d.RULE_fieldPropertyStatement=78,d.RULE_filterClauseList=79,d.RULE_whereStatement=80,d.RULE_havingStatement=81,d.RULE_subQueryDefList=82,d.RULE_exploreQueryNameDef=83,d.RULE_exploreQueryDef=84,d.RULE_queryStatement=85,d.RULE_queryJoinStatement=86,d.RULE_groupByStatement=87,d.RULE_queryFieldList=88,d.RULE_queryFieldEntry=89,d.RULE_nestStatement=90,d.RULE_nestedQueryList=91,d.RULE_nestEntry=92,d.RULE_aggregateStatement=93,d.RULE_calculateStatement=94,d.RULE_projectStatement=95,d.RULE_partitionByStatement=96,d.RULE_orderByStatement=97,d.RULE_ordering=98,d.RULE_orderBySpec=99,d.RULE_limitStatement=100,d.RULE_bySpec=101,d.RULE_topStatement=102,d.RULE_indexElement=103,d.RULE_indexFields=104,d.RULE_indexStatement=105,d.RULE_sampleStatement=106,d.RULE_timezoneStatement=107,d.RULE_queryAnnotation=108,d.RULE_sampleSpec=109,d.RULE_aggregate=110,d.RULE_malloyType=111,d.RULE_compareOp=112,d.RULE_string=113,d.RULE_shortString=114,d.RULE_rawString=115,d.RULE_numericLiteral=116,d.RULE_literal=117,d.RULE_dateLiteral=118,d.RULE_tablePath=119,d.RULE_tableURI=120,d.RULE_id=121,d.RULE_timeframe=122,d.RULE_ungroup=123,d.RULE_malloyOrSQLType=124,d.RULE_fieldExpr=125,d.RULE_partialCompare=126,d.RULE_partialTest=127,d.RULE_partialAllowedFieldExpr=128,d.RULE_fieldExprList=129,d.RULE_pickStatement=130,d.RULE_pick=131,d.RULE_caseStatement=132,d.RULE_caseWhen=133,d.RULE_recordKey=134,d.RULE_recordElement=135,d.RULE_argumentList=136,d.RULE_fieldNameList=137,d.RULE_fieldCollection=138,d.RULE_collectionWildCard=139,d.RULE_starQualified=140,d.RULE_taggedRef=141,d.RULE_refExpr=142,d.RULE_collectionMember=143,d.RULE_fieldPath=144,d.RULE_joinName=145,d.RULE_fieldName=146,d.RULE_sqlExploreNameRef=147,d.RULE_nameSQLBlock=148,d.RULE_connectionName=149,d.RULE_tripFilterString=150,d.RULE_tickFilterString=151,d.RULE_filterString=152,d.RULE_debugExpr=153,d.RULE_debugPartial=154,d.RULE_experimentalStatementForTesting=155,d.ruleNames=["malloyDocument","malloyStatement","defineSourceStatement","defineQuery","topLevelAnonQueryDef","tags","isDefine","runStatement","sqlString","sqlInterpolation","importStatement","importSelect","importItem","importURL","docAnnotations","ignoredObjectAnnotations","ignoredModelAnnotations","topLevelQueryDefs","topLevelQueryDef","refineOperator","turtleName","sqlSource","exploreTable","connectionId","queryProperties","queryName","sourcePropertyList","sourceDefinition","sqExplore","sourceParameters","legalParamType","sourceParameter","parameterNameDef","sourceNameDef","exploreProperties","exploreStatement","accessLabel","accessModifierList","defMeasures","defDimensions","renameList","exploreRenameDef","defList","fieldDef","fieldNameDef","joinNameDef","declareStatement","joinStatement","queryExtend","modEither","sourceArguments","argumentId","sourceArgument","sqExpr","includeBlock","includeItem","orphanedAnnotation","accessLabelProp","includeExceptList","includeExceptListItem","includeList","includeField","segExpr","vExpr","queryExtendStatement","queryExtendStatementList","joinList","isExplore","matrixOperation","joinFrom","joinDef","joinExpression","filterStatement","fieldProperties","aggregateOrdering","aggregateOrderBySpec","aggregateOrderByStatement","fieldPropertyLimitStatement","fieldPropertyStatement","filterClauseList","whereStatement","havingStatement","subQueryDefList","exploreQueryNameDef","exploreQueryDef","queryStatement","queryJoinStatement","groupByStatement","queryFieldList","queryFieldEntry","nestStatement","nestedQueryList","nestEntry","aggregateStatement","calculateStatement","projectStatement","partitionByStatement","orderByStatement","ordering","orderBySpec","limitStatement","bySpec","topStatement","indexElement","indexFields","indexStatement","sampleStatement","timezoneStatement","queryAnnotation","sampleSpec","aggregate","malloyType","compareOp","string","shortString","rawString","numericLiteral","literal","dateLiteral","tablePath","tableURI","id","timeframe","ungroup","malloyOrSQLType","fieldExpr","partialCompare","partialTest","partialAllowedFieldExpr","fieldExprList","pickStatement","pick","caseStatement","caseWhen","recordKey","recordElement","argumentList","fieldNameList","fieldCollection","collectionWildCard","starQualified","taggedRef","refExpr","collectionMember","fieldPath","joinName","fieldName","sqlExploreNameRef","nameSQLBlock","connectionName","tripFilterString","tickFilterString","filterString","debugExpr","debugPartial","experimentalStatementForTesting"],d._LITERAL_NAMES=[void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,"'&'","'->'","'=>'","'('","')'","'['","']'","'{'","'}'","'::'","':::'","'!'","':'","','","'.'","'<'","'>'","'='","'!='","'<='","'>='","'+'","'-'","'*'","'**'","'/'","'|'","';'","'!~'","'~'","'%'","'??'","'?'",void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,`'"""'`],d._SYMBOLIC_NAMES=[void 0,"ACCEPT","AGGREGATE","CALCULATE","CALCULATION","CONNECTION","DECLARE","DIMENSION","EXCEPT","EXTENDQ","GROUP_BY","HAVING","INDEX","INTERNAL","JOIN_CROSS","JOIN_ONE","JOIN_MANY","LIMIT","MEASURE","NEST","ORDER_BY","PARTITION_BY","PRIMARY_KEY","PRIVATE","PROJECT","PUBLIC","QUERY","RENAME","RUN","SAMPLE","SELECT","SOURCE","TOP","WHERE","VIEW","TIMEZONE","ALL","AND","AS","ASC","AVG","BOOLEAN","BY","CASE","CAST","CONDITION","COUNT","COMPOSE","DATE","DAY","DESC","DISTINCT","ELSE","END","EXCLUDE","EXTEND","FALSE","FILTER","FULL","FOR","FROM","HAS","HOUR","IMPORT","INCLUDE","INNER","IS","IN","INTERNAL_KW","JSON","LAST","LEFT","LIKE","MAX","MIN","MINUTE","MONTH","NOT","NOW","NULL","NUMBER","ON","OR","PICK","PRIVATE_KW","PUBLIC_KW","QUARTER","RIGHT","SECOND","STRING","SOURCE_KW","SUM","SQL","TABLE","THEN","THIS","TIMESTAMP","TO","TRUE","TURTLE","WEEK","WHEN","WITH","YEAR","UNGROUPED","HACKY_REGEX","RAW_SQ","RAW_DQ","SQ3_FILTER","SQ_FILTER","DQ3_FILTER","DQ_FILTER","BQ3_FILTER","BQ_FILTER","SQ_STRING","DQ_STRING","BQ_STRING","DOC_ANNOTATION","ANNOTATION","AMPER","ARROW","FAT_ARROW","OPAREN","CPAREN","OBRACK","CBRACK","OCURLY","CCURLY","DOUBLECOLON","TRIPLECOLON","EXCLAM","COLON","COMMA","DOT","LT","GT","EQ","NE","LTE","GTE","PLUS","MINUS","STAR","STARSTAR","SLASH","BAR","SEMI","NOT_MATCH","MATCH","PERCENT","DOUBLE_QMARK","QMARK","LITERAL_TIMESTAMP","LITERAL_HOUR","LITERAL_DAY","LITERAL_QUARTER","LITERAL_MONTH","LITERAL_WEEK","LITERAL_YEAR","IDENTIFIER","PERCENT_LITERAL","NUMERIC_LITERAL","INTEGER_LITERAL","BLOCK_COMMENT","COMMENT_TO_EOL","WHITE_SPACE","SQL_BEGIN","UNWATED_CHARS_TRAILING_NUMBERS","UNEXPECTED_CHAR","OPEN_CODE","SQL_END"],d.VOCABULARY=new fft.VocabularyImpl(d._LITERAL_NAMES,d._SYMBOLIC_NAMES,[]),d._serializedATNSegments=3,d._serializedATNSegment0=`줝쪺֍꾺体؇쉁¬؟     \x07 \x07\b \b 
1281
1281
 
1282
1282
  \v \v\f \f\r \r             \x1B \x1B     ! !" "# #$ $% %& &' '( () )* *+ +, ,- -. ./ /0 01 12 23 34 45 56 67 78 89 9: :; ;< <= => >? ?@ @A AB BC CD DE EF FG GH HI IJ JK KL LM MN NO OP PQ QR RS ST TU UV VW WX XY YZ Z[ [\\ \\] ]^ ^_ _\` \`a ab bc cd de ef fg gh hi ij jk kl lm mn no op pq qr rs st tu uv vw wx xy yz z{ {| |} }~ ~ € € ‚ ‚ƒ ƒ„ „… …† †‡ ‡ˆ ˆ‰ ‰Š Š‹ ‹Œ Œ Ž Ž  ‘ ‘’ ’“ “” ”• •– –— —˜ ˜™ ™š š› ›œ œ \x07Ľ
1283
1283
  \fŀ\vŋ
@@ -1458,13 +1458,13 @@ xyyzz{{||}}~~~Ҳ
1458
1458
  Œ\fŘśşţŬŰŶƂƇƊ Ə"Ɣ$Ƙ&Ƨ(Ƭ*Ʈ,ư.ƺ0ǁ2ǃ4Ǎ6Ǐ8ǜ:Ǥ<dz>ǻ@ǽBȆDȈFȊHȯJȱLȸNȺPɁRɈTɕVəXɦZɫ\\ɭ^ɯ\`ʊbʌdʒfʡhʣjʨl˄n˛p˯r˱t˳v˵ẍz̊|̥~̮€̽‚͂„̈́†͎ˆ͛Š͠ŒͩŽΆΈ’Ό”Ύ–Θ˜ΩšΫœήžδ ζ¢ρ¤τ¦χ¨ϔªϙ¬ϲ®ϴ°϶²Ϻ´Љ¶Ћ¸ЏºМ¼Ф¾ШÀЬÂаÄмÆпÈюÊѓÌњÎќÐѥÒѧÔѱÖѷØѺÚѽÜѿÞҁà҃â҅ä҉æҋèҍêҏìҚîңðҥòҧôҩöҫøҭúұüԙþզĀկĂշĄչĆւĈ֊Ċ֑Č֠Ď֥Đ֮ĒְĔֻĖׅĘוĚכĜץĞױĠ׶Ģ׸Ĥ؀Ħ؂Ĩ؄Ī؆Ĭ؈Į؊İ،IJؐĴؒĶؕĸؘĺĽĻĽ\x07”ļĺļĻĽŀľļľĿĿŁŀľŁł\x07łŃŋńŋ\bŅŋ\fņŋ Ňŋňŋ ʼnŋĸŊŃŊńŊŅŊņŊŇŊňŊʼnŋŌō\f\x07ōŎ\x07!Ŏŏ6ŏ\x07Őő$ő Œœ\f\x07œŔl7Ŕ\vŕŗ\x07xŖŕŗŚŘŖŘř`,d._serializedATNSegment1='ř\rŚŘśŜ\f\x07Ŝŝ\x07DŝŞ\f\x07ŞşŠ\f\x07Šš\x07šŢ\nŢţŧ\x07¨ŤŦ\vťŤŦũŧťŧŨŨŪũŧŪū\x07¬ūŬŭ\x07«ŭŮl7Ůů\x07ůŰŲ\x07Aűų\rŲűŲųųŴŴŵŵŶŷ\x07€ŷżŸŹ\x07†ŹŻźŸŻžżźżŽŽſžżſƀ\x07ƀƁ\x07>ƁƂƅô{ƃƄ\x07DƄƆô{ƅƃƅƆƆ\x1BƇƈäsƈƉƋ\x07wƊƉƋƌƌƊƌƍƍƎƐ\x07xƏƎƐƑƑƏƑƒƒ!Ɠƕ\x07wƔƓƕƖƖƔƖƗƗ#Ƙƙ\f\x07ƙƚ\x07ƚơ&ƛƝ\x07†ƜƛƜƝƝƞƞƠ&ƟƜƠƣơƟơƢƢƥƣơƤƦ\x07†ƥƤƥƦƦ%Ƨƨ\f\x07ƨƩ4\x1BƩƪ\bƪƫl7ƫ\'Ƭƭ\x07Žƭ)ƮƯô{Ư+ưƱ0ƱƲ\x07‡ƲƳ\x07^Ƴƶ\x07|ƴƷ\nƵƷætƶƴƶƵƷƸƸƹ\x07}ƹ-ƺƻ0ƻƼ\x07‡Ƽƽ\x07_ƽƾ\x07|ƾƿðyƿǀ\x07}ǀ/ǁǂô{ǂ1ǃLj\x07€DŽLJ¬WDžLJ\x07”džDŽdžDžLJNJLjdžLjljljNjNJLjNjnj\x07nj3Ǎǎô{ǎ5Ǐǖ8ǐǒ\x07†ǑǐǑǒǒǓǓǕ8ǔǑǕǘǖǔǖǗǗǚǘǖǙǛ\x07†ǚǙǚǛǛ7ǜǝ\f\x07ǝǟD#ǞǠ<ǟǞǟǠǠǡǡǢ\bǢǣ:ǣ9Ǥǥl7ǥ;Ǧǧ\x07|ǧǴ\x07}Ǩǩ\x07|ǩǮ@!Ǫǫ\x07†ǫǭ@!ǬǪǭǰǮǬǮǯǯDZǰǮDZDz\x07}DzǴdzǦdzǨǴ=ǵǼàqǶǷ\x07;ǷǸ\x07ˆǸǹàqǹǺ\x07‰ǺǼǻǵǻǶǼ?ǽȀB"Ǿǿ\x07‚ǿȁ> ȀǾȀȁȁȄȂȃ\x07DȃȅüȄȂȄȅȅAȆȇô{ȇCȈȉô{ȉEȊȏ\x07€ȋȎH%ȌȎ\x07”ȍȋȍȌȎȑȏȍȏȐȐȒȑȏȒȓ\x07ȓGȔȰP)ȕȰN(ȖȰ`1ȗȰ¢RȘș\x07șȰĦ”ȚȜJ&țȚțȜȜȝȝȞ\x07ȞȰR*ȟȠ ȠȰĔ‹ȡȣ\f\x07ȢȤJ&ȣȢȣȤȤȥȥȦ\x07$Ȧȧ¦TȧȰȨȰØmȩȫ\x07xȪȩȫȬȬȪȬȭȭȰȮȰ"ȯȔȯȕȯȖȯȗȯȘȯțȯȟȯȡȯȨȯȪȯȮȰIȱȲ ȲKȳȹĔ‹ȴȶ\x07ȵȷ̎ȶȵȶȷȷȹȸȳȸȴȹMȺȼ\f\x07ȻȽJ&ȼȻȼȽȽȾȾȿ\x07ȿɀV,ɀOɁɃ\f\x07ɂɄJ&ɃɂɃɄɄɅɅɆ\x07 ɆɇV,ɇQɈɏT+ɉɋ\x07†ɊɉɊɋɋɌɌɎT+ɍɊɎɑɏɍɏɐɐɓɑɏɒɔ\x07†ɓɒɓɔɔSɕɖĦ”ɖɗ\bɗɘĦ”ɘUəɠX-ɚɜ\x07†ɛɚɛɜɜɝɝɟX-ɞɛɟɢɠɞɠɡɡɤɢɠɣɥ\x07†ɤɣɤɥɥWɦɧ\f\x07ɧɨZ.ɨɩ\bɩɪüɪYɫɬô{ɬ[ɭɮô{ɮ]ɯɱ\x07\bɰɲJ&ɱɰɱɲɲɳɳɴV,ɴ_ɵɷ\f\x07ɶɸJ&ɷɶɷɸɸɹɹɺ\x07ɺɻ†Dɻʋɼɾ\f\x07ɽɿJ&ɾɽɾɿɿʀʀʁ\x07ʁʂ†Dʂʋʃʅ\f\x07ʄʆJ&ʅʄʅʆʆʇʇʈ\x07ʈʉ†Dʉʋʊɵʊɼʊʃʋaʌʍ\x07\vʍʎ„Cʎcʏʓ`1ʐʓ¢Rʑʓ^0ʒʏʒʐʒʑʓeʔʕ\x07|ʕʢ\x07}ʖʗ\x07|ʗʜj6ʘʙ\x07†ʙʛj6ʚʘʛʞʜʚʜʝʝʟʞʜʟʠ\x07}ʠʢʡʔʡʖʢgʣʤô{ʤiʥʦh5ʦʧ\x07Dʧʩʨʥʨʩʩʪʪʫüʫkʬʭ\b7ʭʯô{ʮʰf4ʯʮʯʰʰ˅ʱʲ\x07|ʲʳl7ʳʴ\x07}ʴ˅ʵʶ\x071ʶʿ\x07|ʷʼl7ʸʹ\x07†ʹʻl7ʺʸʻʾʼʺʼʽʽˀʾʼʿʷʿˀˀˁˁ˅\x07}˂˅.˃˅,˄ʬ˄ʱ˄ʵ˄˂˄˃˅˘ˆˇ\f\bˇˈ\x07Žˈ˗~@ˉˊ\f\x07ˊˋ\x07zˋ˗~@ˌˏ\fˍˎ\x07Bˎːn8ˏˍˏːːˑˑ˒\x079˒˗F$˓˔\f˔˕\x07B˕˗n8˖ˆ˖ˉ˖ˌ˖˓˗˚˘˖˘˙˙m˚˘˛ˠ\x07€˜˟p9˝˟\x07”˞˜˞˝˟ˢˠ˞ˠˡˡˣˢˠˣˤ\x07ˤo˥˦\f\x07˦˧t;˧˨z>˨˰˩˰z>˪˫\f\x07˫ˬ\x07\nˬ˭v<˭˰ˮ˰r:˯˥˯˩˯˪˯ˮ˰q˱˲\x07x˲s˳˴ ˴u˵˼x=˶˸\x07†˷˶˷˸˸˹˹˻x=˺˷˻˾˼˺˼˽˽̀˾˼˿́\x07†̀˿̀́́ŵ̃\f\x07̃̄Ħ”̄̉̅̆\f\x07̆̇ʍ̇̉̈̂̈̅̉ẙ̑|?̋̍\x07†̌̋̌̍̍̎̎̐|?̖̏̌̐̓̑̏̑̒̒̓̑̔̕\x07†̖̖̔̕̕{̛̗\f\x07̘̙Ħ”̙̚\b̛̛̜̘̜̜̝̝̞̚Ħ”̞̦̟̠\f\x07̡̠Ħ”̡̢̦̣\f\x07̣̤ʍ̢̤̦̥̗̥̟̥̦}̧̨\b@̨̯Ģ’̩̯2̪̫\x07|̫̬€A̬̭\x07}̵̧̭̯̮̮̩̮̪̯̰̱\f̱̲\x07Ž̴̲~@̴̷̵̵̶̶̷̵̸̳̰̳̾~@̹̺~@̺̻\x07z̻̼€A̸̼̹̾̽̽̾̿̓P)̀̓N(́̓`1͂̿͂̀͂́̓ƒ͉̈́\x07€͈ͅ‚B͈͆\x07”͇͇͈͉͇͉͉͍͆͋͊͊͌͋͌ͅ\x07͍…͎͕ŽH͏͑\x07†͐͏͔͐͑͑͒͒ŽH͓͔͕͓͕͖͖͙͕͚͐͗͗͘\x07†͙͙͚͚͘‡͛͜\f\x07͜͝\x07D͝͞\f\x07͟͞l7͟‰͠͡ ͡‹ͪ͢\\/ͣͤ\\/ͤͥf4ͥͪͦͧ\\/ͧͨˆEͨͪͩͩͣͩͦͪ͢ͫͭ\x07xͬͫͭͰͮͬͮͯͯͱͰͮͱͳŒGͲʹŠFͳͲͳʹʹ͵͵Ͷ\x07hͶͷüͷ·͸ͺ\x07x͹͸ͺͽͻ͹ͻͼͼ;ͽͻ;΄ŒGͿ΁ŠF΀Ϳ΀΁΁΂΂΃\x07S΃΅I΄΀΄΅΅·ΆͮΆͻ·ΈΉüΉ‘Ί΍¢R΋΍¤SΌΊΌ΋΍“ΎΓ\x07€ΏΒžPΐΒ\x07”ΑΏΑΐΒΕΓΑΓΔΔΖΕΓΖΗ\x07Η•ΘΝ˜MΙΚ\x07†ΚΜ˜MΛΙΜΟΝΛΝΞΞΡΟΝΠ΢\x07†ΡΠΡ΢΢—ΣΥüΤΦ ΥΤΥΦΦΪΧΪ\x07)ΨΪ\x074ΩΣΩΧΩΨΪ™Ϋά\x07άέ–Lέ›ήίÊfߝΰε¢RαεÂbβεšNγεœOδΰδαδβδγεŸζλüηθ\x07†θκüιηκνλιλμμονλξπ\x07†οξοππ¡ρς\x07#ςσ Qσ£τυ\x07\rυφ Qφ¥χώªVψϊ\x07†ωψωϊϊϋϋύªVόωύϐώόώϏϏϒϐώϑϓ\x07†ϒϑϒϓϓ§ϔϕô{ϕ©ϖϘ\x07xϗϖϘϛϙϗϙϚϚϜϛϙϜϝ¨UϝϞ\bϞϟ€Aϟ«Ϡϳ°Yϡϳ^0Ϣϳ®Xϣϳb2ϤϳÀaϥϳÔkϦϳ¼_ϧϳ¾`ϨϳÎhϩϳÊfϪϳÄcϫϳ¢RϬϳ¤Sϭϳ¶\\ϮϳÖlϯϳØmϰϳÚnϱϳ"ϲϠϲϡϲϢϲϣϲϤϲϥϲϦϲϧϲϨϲϩϲϪϲϫϲϬϲϭϲϮϲϯϲϰϲϱϳ­ϴϵ`1ϵ¯϶Ϸ\f\x07Ϸϸ\x07\fϸϹ²ZϹ±ϺЁ´[ϻϽ\x07†ϼϻϼϽϽϾϾЀ´[ϿϼЀЃЁϿЁЂЂЅЃЁЄІ\x07†ЅЄЅІІ³ЇЊĜЈЊX-ЉЇЉЈЊµЋЌ\f\x07ЌЍ',d._serializedATNSegment2=`\x07ЍЎ¸]Ў·ЏЖº^АВ\x07†БАБВВГГЕº^ДБЕИЖДЖЗЗКИЖЙЛ\x07†КЙКЛЛ¹МР\f\x07НО4\x1BОП\bПСРНРССТТУ€AУ»ФХ\f\x07ХЦ\x07ЦЧ²ZЧ½ШЩ\f\x07ЩЪ\x07ЪЫ²ZЫ¿ЬЭ\f\x07ЭЮ\x07 ЮЯˌЯÁаб\x07бжô{вг\x07†геô{двеижджззкижйл\x07†кйкллÃмн\x07ноÆdоÅпцÈeрт\x07†срсттуухÈeфсхшцфцччъшцщы\x07†ъщъыыÇья\x07¤эяĦ”юьюэяёѐђ ёѐёђђÉѓє\x07єѕ\x07¤ѕËії\x07,їћĦ”јљ\x07,љћüњіњјћÍќѝ\x07"ѝў\x07¤ўÏџѢĢ’Ѡѡ\x07‡ѡѣ\x07ѢѠѢѣѣѦѤѦ\x07ѥџѥѤѦÑѧѮÐiѨѪ\x07†ѩѨѩѪѪѫѫѭÐiѬѩѭѰѮѬѮѯѯÓѰѮѱѲ\x07ѲѵÒjѳѴ\x07,ѴѶĦ”ѵѳѵѶѶÕѷѸ\x07ѸѹÜoѹ×Ѻѻ\x07%ѻѼäsѼÙѽѾ\x07xѾÛѿҀ \x07ҀÝҁ҂ \b҂ß҃҄ ҄á҅҆
1459
1459
  ҆ã҇Ҋæt҈Ҋ
1460
1460
  ҉҇҉҈ҊåҋҌ \vҌçҍҎ \fҎéҏҐ \rҐëґқäsҒқèuғқêvҔқîxҕқ\x07QҖқ җқ\x07kҘқIJšҙқ\x07PҚґҚҒҚғҚҔҚҕҚҖҚҗҚҘҚҙқíҜҤ\x07šҝҤ\x07›ҞҤ\x07œҟҤ\x07ŸҠҤ\x07žҡҤ\x07ҢҤ\x07 ңҜңҝңҞңҟңҠңҡңҢҤïҥҦäsҦñҧҨäsҨóҩҪ ҪõҫҬ Ҭ÷ҭҮ ҮùүҲàqҰҲäsұүұҰҲûҳҴ\bҴԚĢ’ҵԚìwҶҷ\x07~ҷҼüҸҹ\x07†ҹһüҺҸһҾҼҺҼҽҽӀҾҼҿӁ\x07†ӀҿӀӁӁӂӂӃ\x07ӃԚӄӅ\x07€ӅӊЉӆӇ\x07†ӇӉЉӈӆӉӌӊӈӊӋӋӍӌӊӍӎ\x07ӎԚӏӐ\x07ӐԚü\x1BӑӒ\x07OӒԚüӓӔ\x07.Ӕӕ\x07|ӕӖüӖӗ\x07(ӗӘú~Әә\x07}әԚӚӛ\x07\\ӛӝ\x07‡ӜӚӜӝӝӞӞӟÞpӟӡ\x07|ӠӢüӡӠӡӢӢӣӣӤ\x07}ӤԚӥӦĢ’Ӧӧ\x07‡ӧӨÞpӨӪ\x07|өӫüӪөӪӫӫӬӬӭ\x07}ӭԚӮӯ\x07|ӯӰüӰӱ\x07}ӱԚӲӳĢ’ӳӴ\x07‡Ӵӵô{ӵӷ\x07|ӶӸNJӷӶӷӸӸӹӹӺ\x07}ӺԚӻԀô{ӼӾ\x07„ӽӿàqӾӽӾӿӿԁԀӼԀԁԁԄԂԄö|ԃӻԃԂԄԅԅԇ\x07|ԆԈNJԇԆԇԈԈԉԉԊ\x07}ԊԚԋԚƄԌԚĊ†ԍԎø}Ԏԏ\x07|ԏԔüԐԑ\x07†ԑԓĦ”ԒԐԓԖԔԒԔԕԕԗԖԔԗԘ\x07}ԘԚԙҳԙҵԙҶԙӄԙӏԙӑԙӓԙӜԙӥԙӮԙӲԙԃԙԋԙԌԙԍԚգԛԜ\fԜԝ ԝբü\x1BԞԟ\fԟԠ ԠբüԡԢ\fԢԣ\x07cԣբüԤԥ\fԥԦârԦԧüԧբԨԪ\fԩԫ\x07OԪԩԪԫԫԬԬԭ\x07JԭբüԮԯ\fԯ԰\x07'԰բüԱԲ\f\rԲԳ\x07TԳբüԴԵ\f\fԵԶ\x07˜Զբü\rԷԸ\f Ըբ”KԹԺ\fԺբö|ԻԼ\fԼԽ\x07‡Խբö|ԾԿ\fԿՀ\x07‚Հբú~ՁՂ\fՂՃ\x07ƒՃբú~ՄՅ\fՅՆ\x07=ՆՇüՇՈö|ՈբՉՊ\fՊՋ\x07yՋբÂՌՍ\fՍՎ\x07“ՎբÂՏՐ\fՐՒ\x07DՑՓ\x07OՒՑՒՓՓՔՔբ\x07QՕ՗\fՖ՘\x07O՗Ֆ՗՘՘ՙՙ՚\x07E՚՛\x07|՛՜Ąƒ՜՝\x07}՝բ՞՟\f՟ՠ\x07™ՠբÂաԛաԞաԡաԤաԨաԮաԱաԴաԷաԹաԻաԾաՁաՄաՉաՌաՏաՕա՞բեգագդդýեգզէârէըüըÿթհþ€ժլ\x07Dիխ\x07Oլիլխխծծհ\x07Qկթկժհāձողճ\x07|ճմմյ\x07}յոնոüշձշղշնոăչվüպջ\x07†ջսüռպսրվռվտտąրվցփĈ…ւցփքքւքօօֈֆև\x076և։üֈֆֈ։։ć֊֌\x07U֋֍ü֌֋֌֍֍֎֎֏\x07g֏֐Â֐ĉ֑֓\x07-֒֔ü֖֓֒֓֔֔֕֗ȇ֖֖֛֚֕֗֘֘֘֙֙֜\x076֛֝ü֚֜֜֝֝֞֞֟\x077֟ċ֠֡\x07g֢֡ü֢֣\x07\`֣֤ü֤č֥֦ô{֦ď֧֯Ģ’֨֩ψ֪֩\x07D֪֭֭֬֫֨֫֬֬֯ü֧֮֮֫֯đְֵüֱֲ\x07†ֲִüֱֳֳִֵֵֵֶֶַַָֹֺ\x07†ָֹֹֺֺēֻׂĦ”ּ־\x07†ּֽֽ־־ֿֿׁĦ”׀ֽׁׂׄ׀ׂ׃׃ĕׂׅׄ׌Ġ‘׆׈\x07†ׇ׆ׇ׈׈׉׉׋Ġ‘׊ׇ׋׎׌׊׌׍׍א׎׌׏ב\x07†א׏אבבėגדĢ’דה\x07‡הזוגוזזחחי\x07טך̎יטיךךęכן\x07€לם\x07
1461
- םנĔ‹מנ\x07†ןלןמנססןסעעףףפ\x07פěץצ\f\x07צרĢ’קשАרקרששĝת׫\x07‡׫ײö|׬׭\x07‡׭׮Þp׮ׯ\x07|ׯװ\x07}װײױתױ׬ײğ׳׷Ĝ״׷ʍ׵׷X-׶׳׶״׶׵׷ġ׸׽Ħ”׹׺\x07‡׺׼Ħ”׻׹׼׿׽׻׽׾׾ģ׿׽؀؁ô{؁ĥ؂؃ô{؃ħ؄؅ô{؅ĩ؆؇ô{؇ī؈؉äs؉ĭ؊؋ ؋į،؍ ؍ı؎ؑĮ˜؏ؑİ™ؐ؎ؐ؏ؑijؒؓüؓؔ\x07ؔĵؕؖÂؖؗ\x07ؗķؘؙ\x07”ؙؚ\x07”ؚ؛\x07~؛؜äs؜؝\x07؝Ĺ®ļľŊŘŧŲżƅƌƑƖƜơƥƶdžLjǑǖǚǟǮdzǻȀȄȍȏțȣȬȯȶȸȼɃɊɏɓɛɠɤɱɷɾʅʊʒʜʡʨʯʼʿ˄ˏ˖˘˞ˠ˯˷˼̵̛̥̮͇͉͕͙̀̈̌̑̽͂͐ͩͮ̕ͳͻ΀΄ΆΌΑΓΝΡΥΩδλοωώϒϙϲϼЁЅЉБЖКРжксцъюёњѢѥѩѮѵ҉ҚңұҼӀӊӜӡӪӷӾԀԃԇԔԙԪՒ՗ագլկշվքֈ֌ֵׇֹֽׂ֮֓֘֜֫׌אויןסרױ׶׽ؐ`,d._serializedATN=G0e.join([d._serializedATNSegment0,d._serializedATNSegment1,d._serializedATNSegment2],"");class W0e extends pe.ParserRuleContext{EOF(){return this.getToken(d.EOF,0)}malloyStatement(e){return e===void 0?this.getRuleContexts(DT):this.getRuleContext(e,DT)}SEMI(e){return e===void 0?this.getTokens(d.SEMI):this.getToken(d.SEMI,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_malloyDocument}enterRule(e){e.enterMalloyDocument&&e.enterMalloyDocument(this)}exitRule(e){e.exitMalloyDocument&&e.exitMalloyDocument(this)}accept(e){return e.visitMalloyDocument?e.visitMalloyDocument(this):e.visitChildren(this)}}w.MalloyDocumentContext=W0e;class DT extends pe.ParserRuleContext{defineSourceStatement(){return this.tryGetRuleContext(0,Ak)}defineQuery(){return this.tryGetRuleContext(0,OT)}importStatement(){return this.tryGetRuleContext(0,Ck)}runStatement(){return this.tryGetRuleContext(0,vk)}docAnnotations(){return this.tryGetRuleContext(0,Tk)}ignoredObjectAnnotations(){return this.tryGetRuleContext(0,Rk)}experimentalStatementForTesting(){return this.tryGetRuleContext(0,BM)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_malloyStatement}enterRule(e){e.enterMalloyStatement&&e.enterMalloyStatement(this)}exitRule(e){e.exitMalloyStatement&&e.exitMalloyStatement(this)}accept(e){return e.visitMalloyStatement?e.visitMalloyStatement(this):e.visitChildren(this)}}w.MalloyStatementContext=DT;class Ak extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}SOURCE(){return this.getToken(d.SOURCE,0)}sourcePropertyList(){return this.getRuleContext(0,Nk)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_defineSourceStatement}enterRule(e){e.enterDefineSourceStatement&&e.enterDefineSourceStatement(this)}exitRule(e){e.exitDefineSourceStatement&&e.exitDefineSourceStatement(this)}accept(e){return e.visitDefineSourceStatement?e.visitDefineSourceStatement(this):e.visitChildren(this)}}w.DefineSourceStatementContext=Ak;class OT extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_defineQuery}copyFrom(e){super.copyFrom(e)}}w.DefineQueryContext=OT;class V0e extends OT{topLevelQueryDefs(){return this.getRuleContext(0,Dk)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterUse_top_level_query_defs&&e.enterUse_top_level_query_defs(this)}exitRule(e){e.exitUse_top_level_query_defs&&e.exitUse_top_level_query_defs(this)}accept(e){return e.visitUse_top_level_query_defs?e.visitUse_top_level_query_defs(this):e.visitChildren(this)}}w.Use_top_level_query_defsContext=V0e;class _k extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}sqExpr(){return this.getRuleContext(0,un)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_topLevelAnonQueryDef}enterRule(e){e.enterTopLevelAnonQueryDef&&e.enterTopLevelAnonQueryDef(this)}exitRule(e){e.exitTopLevelAnonQueryDef&&e.exitTopLevelAnonQueryDef(this)}accept(e){return e.visitTopLevelAnonQueryDef?e.visitTopLevelAnonQueryDef(this):e.visitChildren(this)}}w.TopLevelAnonQueryDefContext=_k;class Yt extends pe.ParserRuleContext{ANNOTATION(e){return e===void 0?this.getTokens(d.ANNOTATION):this.getToken(d.ANNOTATION,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_tags}enterRule(e){e.enterTags&&e.enterTags(this)}exitRule(e){e.exitTags&&e.exitTags(this)}accept(e){return e.visitTags?e.visitTags(this):e.visitChildren(this)}}w.TagsContext=Yt;class e0 extends pe.ParserRuleContext{IS(){return this.getToken(d.IS,0)}tags(e){return e===void 0?this.getRuleContexts(Yt):this.getRuleContext(e,Yt)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_isDefine}enterRule(e){e.enterIsDefine&&e.enterIsDefine(this)}exitRule(e){e.exitIsDefine&&e.exitIsDefine(this)}accept(e){return e.visitIsDefine?e.visitIsDefine(this):e.visitChildren(this)}}w.IsDefineContext=e0;class vk extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}RUN(){return this.getToken(d.RUN,0)}topLevelAnonQueryDef(){return this.getRuleContext(0,_k)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_runStatement}enterRule(e){e.enterRunStatement&&e.enterRunStatement(this)}exitRule(e){e.exitRunStatement&&e.exitRunStatement(this)}accept(e){return e.visitRunStatement?e.visitRunStatement(this):e.visitChildren(this)}}w.RunStatementContext=vk;class FT extends pe.ParserRuleContext{SQL_BEGIN(){return this.getToken(d.SQL_BEGIN,0)}SQL_END(){return this.getToken(d.SQL_END,0)}sqlInterpolation(e){return e===void 0?this.getRuleContexts(wT):this.getRuleContext(e,wT)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sqlString}enterRule(e){e.enterSqlString&&e.enterSqlString(this)}exitRule(e){e.exitSqlString&&e.exitSqlString(this)}accept(e){return e.visitSqlString?e.visitSqlString(this):e.visitChildren(this)}}w.SqlStringContext=FT;class wT extends pe.ParserRuleContext{OPEN_CODE(){return this.getToken(d.OPEN_CODE,0)}sqExpr(){return this.getRuleContext(0,un)}CCURLY(){return this.getToken(d.CCURLY,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sqlInterpolation}enterRule(e){e.enterSqlInterpolation&&e.enterSqlInterpolation(this)}exitRule(e){e.exitSqlInterpolation&&e.exitSqlInterpolation(this)}accept(e){return e.visitSqlInterpolation?e.visitSqlInterpolation(this):e.visitChildren(this)}}w.SqlInterpolationContext=wT;class Ck extends pe.ParserRuleContext{IMPORT(){return this.getToken(d.IMPORT,0)}importURL(){return this.getRuleContext(0,bk)}importSelect(){return this.tryGetRuleContext(0,Sk)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_importStatement}enterRule(e){e.enterImportStatement&&e.enterImportStatement(this)}exitRule(e){e.exitImportStatement&&e.exitImportStatement(this)}accept(e){return e.visitImportStatement?e.visitImportStatement(this):e.visitChildren(this)}}w.ImportStatementContext=Ck;class Sk extends pe.ParserRuleContext{OCURLY(){return this.getToken(d.OCURLY,0)}importItem(e){return e===void 0?this.getRuleContexts(NT):this.getRuleContext(e,NT)}CCURLY(){return this.getToken(d.CCURLY,0)}FROM(){return this.getToken(d.FROM,0)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_importSelect}enterRule(e){e.enterImportSelect&&e.enterImportSelect(this)}exitRule(e){e.exitImportSelect&&e.exitImportSelect(this)}accept(e){return e.visitImportSelect?e.visitImportSelect(this):e.visitChildren(this)}}w.ImportSelectContext=Sk;class NT extends pe.ParserRuleContext{id(e){return e===void 0?this.getRuleContexts(Dn):this.getRuleContext(e,Dn)}IS(){return this.tryGetToken(d.IS,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_importItem}enterRule(e){e.enterImportItem&&e.enterImportItem(this)}exitRule(e){e.exitImportItem&&e.exitImportItem(this)}accept(e){return e.visitImportItem?e.visitImportItem(this):e.visitChildren(this)}}w.ImportItemContext=NT;class bk extends pe.ParserRuleContext{string(){return this.getRuleContext(0,Fa)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_importURL}enterRule(e){e.enterImportURL&&e.enterImportURL(this)}exitRule(e){e.exitImportURL&&e.exitImportURL(this)}accept(e){return e.visitImportURL?e.visitImportURL(this):e.visitChildren(this)}}w.ImportURLContext=bk;class Tk extends pe.ParserRuleContext{DOC_ANNOTATION(e){return e===void 0?this.getTokens(d.DOC_ANNOTATION):this.getToken(d.DOC_ANNOTATION,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_docAnnotations}enterRule(e){e.enterDocAnnotations&&e.enterDocAnnotations(this)}exitRule(e){e.exitDocAnnotations&&e.exitDocAnnotations(this)}accept(e){return e.visitDocAnnotations?e.visitDocAnnotations(this):e.visitChildren(this)}}w.DocAnnotationsContext=Tk;class Rk extends pe.ParserRuleContext{ANNOTATION(e){return e===void 0?this.getTokens(d.ANNOTATION):this.getToken(d.ANNOTATION,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_ignoredObjectAnnotations}enterRule(e){e.enterIgnoredObjectAnnotations&&e.enterIgnoredObjectAnnotations(this)}exitRule(e){e.exitIgnoredObjectAnnotations&&e.exitIgnoredObjectAnnotations(this)}accept(e){return e.visitIgnoredObjectAnnotations?e.visitIgnoredObjectAnnotations(this):e.visitChildren(this)}}w.IgnoredObjectAnnotationsContext=Rk;class LT extends pe.ParserRuleContext{DOC_ANNOTATION(e){return e===void 0?this.getTokens(d.DOC_ANNOTATION):this.getToken(d.DOC_ANNOTATION,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_ignoredModelAnnotations}enterRule(e){e.enterIgnoredModelAnnotations&&e.enterIgnoredModelAnnotations(this)}exitRule(e){e.exitIgnoredModelAnnotations&&e.exitIgnoredModelAnnotations(this)}accept(e){return e.visitIgnoredModelAnnotations?e.visitIgnoredModelAnnotations(this):e.visitChildren(this)}}w.IgnoredModelAnnotationsContext=LT;class Dk extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}QUERY(){return this.getToken(d.QUERY,0)}topLevelQueryDef(e){return e===void 0?this.getRuleContexts(IT):this.getRuleContext(e,IT)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_topLevelQueryDefs}enterRule(e){e.enterTopLevelQueryDefs&&e.enterTopLevelQueryDefs(this)}exitRule(e){e.exitTopLevelQueryDefs&&e.exitTopLevelQueryDefs(this)}accept(e){return e.visitTopLevelQueryDefs?e.visitTopLevelQueryDefs(this):e.visitChildren(this)}}w.TopLevelQueryDefsContext=Dk;class IT extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}queryName(){return this.getRuleContext(0,$T)}isDefine(){return this.getRuleContext(0,e0)}sqExpr(){return this.getRuleContext(0,un)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_topLevelQueryDef}enterRule(e){e.enterTopLevelQueryDef&&e.enterTopLevelQueryDef(this)}exitRule(e){e.exitTopLevelQueryDef&&e.exitTopLevelQueryDef(this)}accept(e){return e.visitTopLevelQueryDef?e.visitTopLevelQueryDef(this):e.visitChildren(this)}}w.TopLevelQueryDefContext=IT;class Y0e extends pe.ParserRuleContext{PLUS(){return this.getToken(d.PLUS,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_refineOperator}enterRule(e){e.enterRefineOperator&&e.enterRefineOperator(this)}exitRule(e){e.exitRefineOperator&&e.exitRefineOperator(this)}accept(e){return e.visitRefineOperator?e.visitRefineOperator(this):e.visitChildren(this)}}w.RefineOperatorContext=Y0e;class K0e extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_turtleName}enterRule(e){e.enterTurtleName&&e.enterTurtleName(this)}exitRule(e){e.exitTurtleName&&e.exitTurtleName(this)}accept(e){return e.visitTurtleName?e.visitTurtleName(this):e.visitChildren(this)}}w.TurtleNameContext=K0e;class Ok extends pe.ParserRuleContext{connectionId(){return this.getRuleContext(0,BT)}DOT(){return this.getToken(d.DOT,0)}SQL(){return this.getToken(d.SQL,0)}OPAREN(){return this.getToken(d.OPAREN,0)}CPAREN(){return this.getToken(d.CPAREN,0)}sqlString(){return this.tryGetRuleContext(0,FT)}shortString(){return this.tryGetRuleContext(0,cR)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sqlSource}enterRule(e){e.enterSqlSource&&e.enterSqlSource(this)}exitRule(e){e.exitSqlSource&&e.exitSqlSource(this)}accept(e){return e.visitSqlSource?e.visitSqlSource(this):e.visitChildren(this)}}w.SqlSourceContext=Ok;class Fk extends pe.ParserRuleContext{connectionId(){return this.getRuleContext(0,BT)}DOT(){return this.getToken(d.DOT,0)}TABLE(){return this.getToken(d.TABLE,0)}OPAREN(){return this.getToken(d.OPAREN,0)}tablePath(){return this.getRuleContext(0,_M)}CPAREN(){return this.getToken(d.CPAREN,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_exploreTable}enterRule(e){e.enterExploreTable&&e.enterExploreTable(this)}exitRule(e){e.exitExploreTable&&e.exitExploreTable(this)}accept(e){return e.visitExploreTable?e.visitExploreTable(this):e.visitChildren(this)}}w.ExploreTableContext=Fk;class BT extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_connectionId}enterRule(e){e.enterConnectionId&&e.enterConnectionId(this)}exitRule(e){e.exitConnectionId&&e.exitConnectionId(this)}accept(e){return e.visitConnectionId?e.visitConnectionId(this):e.visitChildren(this)}}w.ConnectionIdContext=BT;class wk extends pe.ParserRuleContext{OCURLY(){return this.getToken(d.OCURLY,0)}CCURLY(){return this.getToken(d.CCURLY,0)}queryStatement(e){return e===void 0?this.getRuleContexts(rR):this.getRuleContext(e,rR)}SEMI(e){return e===void 0?this.getTokens(d.SEMI):this.getToken(d.SEMI,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_queryProperties}enterRule(e){e.enterQueryProperties&&e.enterQueryProperties(this)}exitRule(e){e.exitQueryProperties&&e.exitQueryProperties(this)}accept(e){return e.visitQueryProperties?e.visitQueryProperties(this):e.visitChildren(this)}}w.QueryPropertiesContext=wk;class $T extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_queryName}enterRule(e){e.enterQueryName&&e.enterQueryName(this)}exitRule(e){e.exitQueryName&&e.exitQueryName(this)}accept(e){return e.visitQueryName?e.visitQueryName(this):e.visitChildren(this)}}w.QueryNameContext=$T;class Nk extends pe.ParserRuleContext{sourceDefinition(e){return e===void 0?this.getRuleContexts(kT):this.getRuleContext(e,kT)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sourcePropertyList}enterRule(e){e.enterSourcePropertyList&&e.enterSourcePropertyList(this)}exitRule(e){e.exitSourcePropertyList&&e.exitSourcePropertyList(this)}accept(e){return e.visitSourcePropertyList?e.visitSourcePropertyList(this):e.visitChildren(this)}}w.SourcePropertyListContext=Nk;class kT extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}sourceNameDef(){return this.getRuleContext(0,kk)}isDefine(){return this.getRuleContext(0,e0)}sqExplore(){return this.getRuleContext(0,Lk)}sourceParameters(){return this.tryGetRuleContext(0,Ik)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sourceDefinition}enterRule(e){e.enterSourceDefinition&&e.enterSourceDefinition(this)}exitRule(e){e.exitSourceDefinition&&e.exitSourceDefinition(this)}accept(e){return e.visitSourceDefinition?e.visitSourceDefinition(this):e.visitChildren(this)}}w.SourceDefinitionContext=kT;class Lk extends pe.ParserRuleContext{sqExpr(){return this.getRuleContext(0,un)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sqExplore}enterRule(e){e.enterSqExplore&&e.enterSqExplore(this)}exitRule(e){e.exitSqExplore&&e.exitSqExplore(this)}accept(e){return e.visitSqExplore?e.visitSqExplore(this):e.visitChildren(this)}}w.SqExploreContext=Lk;class Ik extends pe.ParserRuleContext{OPAREN(){return this.getToken(d.OPAREN,0)}CPAREN(){return this.getToken(d.CPAREN,0)}sourceParameter(e){return e===void 0?this.getRuleContexts(MT):this.getRuleContext(e,MT)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sourceParameters}enterRule(e){e.enterSourceParameters&&e.enterSourceParameters(this)}exitRule(e){e.exitSourceParameters&&e.exitSourceParameters(this)}accept(e){return e.visitSourceParameters?e.visitSourceParameters(this):e.visitChildren(this)}}w.SourceParametersContext=Ik;class Bk extends pe.ParserRuleContext{malloyType(){return this.getRuleContext(0,hE)}FILTER(){return this.tryGetToken(d.FILTER,0)}LT(){return this.tryGetToken(d.LT,0)}GT(){return this.tryGetToken(d.GT,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_legalParamType}enterRule(e){e.enterLegalParamType&&e.enterLegalParamType(this)}exitRule(e){e.exitLegalParamType&&e.exitLegalParamType(this)}accept(e){return e.visitLegalParamType?e.visitLegalParamType(this):e.visitChildren(this)}}w.LegalParamTypeContext=Bk;class MT extends pe.ParserRuleContext{parameterNameDef(){return this.getRuleContext(0,$k)}DOUBLECOLON(){return this.tryGetToken(d.DOUBLECOLON,0)}legalParamType(){return this.tryGetRuleContext(0,Bk)}IS(){return this.tryGetToken(d.IS,0)}fieldExpr(){return this.tryGetRuleContext(0,Te)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sourceParameter}enterRule(e){e.enterSourceParameter&&e.enterSourceParameter(this)}exitRule(e){e.exitSourceParameter&&e.exitSourceParameter(this)}accept(e){return e.visitSourceParameter?e.visitSourceParameter(this):e.visitChildren(this)}}w.SourceParameterContext=MT;class $k extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_parameterNameDef}enterRule(e){e.enterParameterNameDef&&e.enterParameterNameDef(this)}exitRule(e){e.exitParameterNameDef&&e.exitParameterNameDef(this)}accept(e){return e.visitParameterNameDef?e.visitParameterNameDef(this):e.visitChildren(this)}}w.ParameterNameDefContext=$k;class kk extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sourceNameDef}enterRule(e){e.enterSourceNameDef&&e.enterSourceNameDef(this)}exitRule(e){e.exitSourceNameDef&&e.exitSourceNameDef(this)}accept(e){return e.visitSourceNameDef?e.visitSourceNameDef(this):e.visitChildren(this)}}w.SourceNameDefContext=kk;class Mk extends pe.ParserRuleContext{OCURLY(){return this.getToken(d.OCURLY,0)}CCURLY(){return this.getToken(d.CCURLY,0)}exploreStatement(e){return e===void 0?this.getRuleContexts(qi):this.getRuleContext(e,qi)}SEMI(e){return e===void 0?this.getTokens(d.SEMI):this.getToken(d.SEMI,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_exploreProperties}enterRule(e){e.enterExploreProperties&&e.enterExploreProperties(this)}exitRule(e){e.exitExploreProperties&&e.exitExploreProperties(this)}accept(e){return e.visitExploreProperties?e.visitExploreProperties(this):e.visitChildren(this)}}w.ExplorePropertiesContext=Mk;class qi extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_exploreStatement}copyFrom(e){super.copyFrom(e)}}w.ExploreStatementContext=qi;class J0e extends qi{defDimensions(){return this.getRuleContext(0,UT)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefExploreDimension_stub&&e.enterDefExploreDimension_stub(this)}exitRule(e){e.exitDefExploreDimension_stub&&e.exitDefExploreDimension_stub(this)}accept(e){return e.visitDefExploreDimension_stub?e.visitDefExploreDimension_stub(this):e.visitChildren(this)}}w.DefExploreDimension_stubContext=J0e;class X0e extends qi{defMeasures(){return this.getRuleContext(0,PT)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefExploreMeasure_stub&&e.enterDefExploreMeasure_stub(this)}exitRule(e){e.exitDefExploreMeasure_stub&&e.exitDefExploreMeasure_stub(this)}accept(e){return e.visitDefExploreMeasure_stub?e.visitDefExploreMeasure_stub(this):e.visitChildren(this)}}w.DefExploreMeasure_stubContext=X0e;class Z0e extends qi{joinStatement(){return this.getRuleContext(0,t0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefJoin_stub&&e.enterDefJoin_stub(this)}exitRule(e){e.exitDefJoin_stub&&e.exitDefJoin_stub(this)}accept(e){return e.visitDefJoin_stub?e.visitDefJoin_stub(this):e.visitChildren(this)}}w.DefJoin_stubContext=Z0e;class ece extends qi{whereStatement(){return this.getRuleContext(0,ud)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefExploreWhere_stub&&e.enterDefExploreWhere_stub(this)}exitRule(e){e.exitDefExploreWhere_stub&&e.exitDefExploreWhere_stub(this)}accept(e){return e.visitDefExploreWhere_stub?e.visitDefExploreWhere_stub(this):e.visitChildren(this)}}w.DefExploreWhere_stubContext=ece;class tce extends qi{PRIMARY_KEY(){return this.getToken(d.PRIMARY_KEY,0)}fieldName(){return this.getRuleContext(0,Ur)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefExplorePrimaryKey&&e.enterDefExplorePrimaryKey(this)}exitRule(e){e.exitDefExplorePrimaryKey&&e.exitDefExplorePrimaryKey(this)}accept(e){return e.visitDefExplorePrimaryKey?e.visitDefExplorePrimaryKey(this):e.visitChildren(this)}}w.DefExplorePrimaryKeyContext=tce;class nce extends qi{RENAME(){return this.getToken(d.RENAME,0)}renameList(){return this.getRuleContext(0,Pk)}accessLabel(){return this.tryGetRuleContext(0,Oa)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefExploreRename&&e.enterDefExploreRename(this)}exitRule(e){e.exitDefExploreRename&&e.exitDefExploreRename(this)}accept(e){return e.visitDefExploreRename?e.visitDefExploreRename(this):e.visitChildren(this)}}w.DefExploreRenameContext=nce;class rce extends qi{fieldNameList(){return this.getRuleContext(0,b2)}ACCEPT(){return this.tryGetToken(d.ACCEPT,0)}EXCEPT(){return this.tryGetToken(d.EXCEPT,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefExploreEditField&&e.enterDefExploreEditField(this)}exitRule(e){e.exitDefExploreEditField&&e.exitDefExploreEditField(this)}accept(e){return e.visitDefExploreEditField?e.visitDefExploreEditField(this):e.visitChildren(this)}}w.DefExploreEditFieldContext=rce;class ice extends qi{tags(){return this.getRuleContext(0,Yt)}VIEW(){return this.getToken(d.VIEW,0)}subQueryDefList(){return this.getRuleContext(0,tM)}accessLabel(){return this.tryGetRuleContext(0,Oa)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefExploreQuery&&e.enterDefExploreQuery(this)}exitRule(e){e.exitDefExploreQuery&&e.exitDefExploreQuery(this)}accept(e){return e.visitDefExploreQuery?e.visitDefExploreQuery(this):e.visitChildren(this)}}w.DefExploreQueryContext=ice;class sce extends qi{timezoneStatement(){return this.getRuleContext(0,aR)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefExploreTimezone&&e.enterDefExploreTimezone(this)}exitRule(e){e.exitDefExploreTimezone&&e.exitDefExploreTimezone(this)}accept(e){return e.visitDefExploreTimezone?e.visitDefExploreTimezone(this):e.visitChildren(this)}}w.DefExploreTimezoneContext=sce;class oce extends qi{ANNOTATION(e){return e===void 0?this.getTokens(d.ANNOTATION):this.getToken(d.ANNOTATION,e)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefExploreAnnotation&&e.enterDefExploreAnnotation(this)}exitRule(e){e.exitDefExploreAnnotation&&e.exitDefExploreAnnotation(this)}accept(e){return e.visitDefExploreAnnotation?e.visitDefExploreAnnotation(this):e.visitChildren(this)}}w.DefExploreAnnotationContext=oce;class uce extends qi{ignoredModelAnnotations(){return this.getRuleContext(0,LT)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefIgnoreModel_stub&&e.enterDefIgnoreModel_stub(this)}exitRule(e){e.exitDefIgnoreModel_stub&&e.exitDefIgnoreModel_stub(this)}accept(e){return e.visitDefIgnoreModel_stub?e.visitDefIgnoreModel_stub(this):e.visitChildren(this)}}w.DefIgnoreModel_stubContext=uce;class Oa extends pe.ParserRuleContext{PUBLIC_KW(){return this.tryGetToken(d.PUBLIC_KW,0)}PRIVATE_KW(){return this.tryGetToken(d.PRIVATE_KW,0)}INTERNAL_KW(){return this.tryGetToken(d.INTERNAL_KW,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_accessLabel}enterRule(e){e.enterAccessLabel&&e.enterAccessLabel(this)}exitRule(e){e.exitAccessLabel&&e.exitAccessLabel(this)}accept(e){return e.visitAccessLabel?e.visitAccessLabel(this):e.visitChildren(this)}}w.AccessLabelContext=Oa;class ace extends pe.ParserRuleContext{fieldNameList(){return this.tryGetRuleContext(0,b2)}STAR(){return this.tryGetToken(d.STAR,0)}starQualified(){return this.tryGetRuleContext(0,pR)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_accessModifierList}enterRule(e){e.enterAccessModifierList&&e.enterAccessModifierList(this)}exitRule(e){e.exitAccessModifierList&&e.exitAccessModifierList(this)}accept(e){return e.visitAccessModifierList?e.visitAccessModifierList(this):e.visitChildren(this)}}w.AccessModifierListContext=ace;class PT extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}MEASURE(){return this.getToken(d.MEASURE,0)}defList(){return this.getRuleContext(0,lE)}accessLabel(){return this.tryGetRuleContext(0,Oa)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_defMeasures}enterRule(e){e.enterDefMeasures&&e.enterDefMeasures(this)}exitRule(e){e.exitDefMeasures&&e.exitDefMeasures(this)}accept(e){return e.visitDefMeasures?e.visitDefMeasures(this):e.visitChildren(this)}}w.DefMeasuresContext=PT;class UT extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}DIMENSION(){return this.getToken(d.DIMENSION,0)}defList(){return this.getRuleContext(0,lE)}accessLabel(){return this.tryGetRuleContext(0,Oa)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_defDimensions}enterRule(e){e.enterDefDimensions&&e.enterDefDimensions(this)}exitRule(e){e.exitDefDimensions&&e.exitDefDimensions(this)}accept(e){return e.visitDefDimensions?e.visitDefDimensions(this):e.visitChildren(this)}}w.DefDimensionsContext=UT;class Pk extends pe.ParserRuleContext{exploreRenameDef(e){return e===void 0?this.getRuleContexts(jT):this.getRuleContext(e,jT)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_renameList}enterRule(e){e.enterRenameList&&e.enterRenameList(this)}exitRule(e){e.exitRenameList&&e.exitRenameList(this)}accept(e){return e.visitRenameList?e.visitRenameList(this):e.visitChildren(this)}}w.RenameListContext=Pk;class jT extends pe.ParserRuleContext{fieldName(e){return e===void 0?this.getRuleContexts(Ur):this.getRuleContext(e,Ur)}isDefine(){return this.getRuleContext(0,e0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_exploreRenameDef}enterRule(e){e.enterExploreRenameDef&&e.enterExploreRenameDef(this)}exitRule(e){e.exitExploreRenameDef&&e.exitExploreRenameDef(this)}accept(e){return e.visitExploreRenameDef?e.visitExploreRenameDef(this):e.visitChildren(this)}}w.ExploreRenameDefContext=jT;class lE extends pe.ParserRuleContext{fieldDef(e){return e===void 0?this.getRuleContexts(v2):this.getRuleContext(e,v2)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_defList}enterRule(e){e.enterDefList&&e.enterDefList(this)}exitRule(e){e.exitDefList&&e.exitDefList(this)}accept(e){return e.visitDefList?e.visitDefList(this):e.visitChildren(this)}}w.DefListContext=lE;class v2 extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}fieldNameDef(){return this.getRuleContext(0,Uk)}isDefine(){return this.getRuleContext(0,e0)}fieldExpr(){return this.getRuleContext(0,Te)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_fieldDef}enterRule(e){e.enterFieldDef&&e.enterFieldDef(this)}exitRule(e){e.exitFieldDef&&e.exitFieldDef(this)}accept(e){return e.visitFieldDef?e.visitFieldDef(this):e.visitChildren(this)}}w.FieldDefContext=v2;class Uk extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_fieldNameDef}enterRule(e){e.enterFieldNameDef&&e.enterFieldNameDef(this)}exitRule(e){e.exitFieldNameDef&&e.exitFieldNameDef(this)}accept(e){return e.visitFieldNameDef?e.visitFieldNameDef(this):e.visitChildren(this)}}w.FieldNameDefContext=Uk;class jk extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_joinNameDef}enterRule(e){e.enterJoinNameDef&&e.enterJoinNameDef(this)}exitRule(e){e.exitJoinNameDef&&e.exitJoinNameDef(this)}accept(e){return e.visitJoinNameDef?e.visitJoinNameDef(this):e.visitChildren(this)}}w.JoinNameDefContext=jk;class qT extends pe.ParserRuleContext{DECLARE(){return this.getToken(d.DECLARE,0)}defList(){return this.getRuleContext(0,lE)}accessLabel(){return this.tryGetRuleContext(0,Oa)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_declareStatement}enterRule(e){e.enterDeclareStatement&&e.enterDeclareStatement(this)}exitRule(e){e.exitDeclareStatement&&e.exitDeclareStatement(this)}accept(e){return e.visitDeclareStatement?e.visitDeclareStatement(this):e.visitChildren(this)}}w.DeclareStatementContext=qT;class t0 extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_joinStatement}copyFrom(e){super.copyFrom(e)}}w.JoinStatementContext=t0;class lce extends t0{tags(){return this.getRuleContext(0,Yt)}JOIN_ONE(){return this.getToken(d.JOIN_ONE,0)}joinList(){return this.getRuleContext(0,cE)}accessLabel(){return this.tryGetRuleContext(0,Oa)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefJoinOne&&e.enterDefJoinOne(this)}exitRule(e){e.exitDefJoinOne&&e.exitDefJoinOne(this)}accept(e){return e.visitDefJoinOne?e.visitDefJoinOne(this):e.visitChildren(this)}}w.DefJoinOneContext=lce;class cce extends t0{tags(){return this.getRuleContext(0,Yt)}JOIN_MANY(){return this.getToken(d.JOIN_MANY,0)}joinList(){return this.getRuleContext(0,cE)}accessLabel(){return this.tryGetRuleContext(0,Oa)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefJoinMany&&e.enterDefJoinMany(this)}exitRule(e){e.exitDefJoinMany&&e.exitDefJoinMany(this)}accept(e){return e.visitDefJoinMany?e.visitDefJoinMany(this):e.visitChildren(this)}}w.DefJoinManyContext=cce;class fce extends t0{tags(){return this.getRuleContext(0,Yt)}JOIN_CROSS(){return this.getToken(d.JOIN_CROSS,0)}joinList(){return this.getRuleContext(0,cE)}accessLabel(){return this.tryGetRuleContext(0,Oa)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefJoinCross&&e.enterDefJoinCross(this)}exitRule(e){e.exitDefJoinCross&&e.exitDefJoinCross(this)}accept(e){return e.visitDefJoinCross?e.visitDefJoinCross(this):e.visitChildren(this)}}w.DefJoinCrossContext=fce;class qk extends pe.ParserRuleContext{EXTENDQ(){return this.getToken(d.EXTENDQ,0)}queryExtendStatementList(){return this.getRuleContext(0,Vk)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_queryExtend}enterRule(e){e.enterQueryExtend&&e.enterQueryExtend(this)}exitRule(e){e.exitQueryExtend&&e.exitQueryExtend(this)}accept(e){return e.visitQueryExtend?e.visitQueryExtend(this):e.visitChildren(this)}}w.QueryExtendContext=qk;class xce extends pe.ParserRuleContext{joinStatement(){return this.tryGetRuleContext(0,t0)}whereStatement(){return this.tryGetRuleContext(0,ud)}declareStatement(){return this.tryGetRuleContext(0,qT)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_modEither}enterRule(e){e.enterModEither&&e.enterModEither(this)}exitRule(e){e.exitModEither&&e.exitModEither(this)}accept(e){return e.visitModEither?e.visitModEither(this):e.visitChildren(this)}}w.ModEitherContext=xce;class HT extends pe.ParserRuleContext{OPAREN(){return this.getToken(d.OPAREN,0)}CPAREN(){return this.getToken(d.CPAREN,0)}sourceArgument(e){return e===void 0?this.getRuleContexts(QT):this.getRuleContext(e,QT)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sourceArguments}enterRule(e){e.enterSourceArguments&&e.enterSourceArguments(this)}exitRule(e){e.exitSourceArguments&&e.exitSourceArguments(this)}accept(e){return e.visitSourceArguments?e.visitSourceArguments(this):e.visitChildren(this)}}w.SourceArgumentsContext=HT;class Hk extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_argumentId}enterRule(e){e.enterArgumentId&&e.enterArgumentId(this)}exitRule(e){e.exitArgumentId&&e.exitArgumentId(this)}accept(e){return e.visitArgumentId?e.visitArgumentId(this):e.visitChildren(this)}}w.ArgumentIdContext=Hk;class QT extends pe.ParserRuleContext{fieldExpr(){return this.getRuleContext(0,Te)}argumentId(){return this.tryGetRuleContext(0,Hk)}IS(){return this.tryGetToken(d.IS,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sourceArgument}enterRule(e){e.enterSourceArgument&&e.enterSourceArgument(this)}exitRule(e){e.exitSourceArgument&&e.exitSourceArgument(this)}accept(e){return e.visitSourceArgument?e.visitSourceArgument(this):e.visitChildren(this)}}w.SourceArgumentContext=QT;class un extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sqExpr}copyFrom(e){super.copyFrom(e)}}w.SqExprContext=un;class dce extends un{id(){return this.getRuleContext(0,Dn)}sourceArguments(){return this.tryGetRuleContext(0,HT)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSQID&&e.enterSQID(this)}exitRule(e){e.exitSQID&&e.exitSQID(this)}accept(e){return e.visitSQID?e.visitSQID(this):e.visitChildren(this)}}w.SQIDContext=dce;class hce extends un{OPAREN(){return this.getToken(d.OPAREN,0)}sqExpr(){return this.getRuleContext(0,un)}CPAREN(){return this.getToken(d.CPAREN,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSQParens&&e.enterSQParens(this)}exitRule(e){e.exitSQParens&&e.exitSQParens(this)}accept(e){return e.visitSQParens?e.visitSQParens(this):e.visitChildren(this)}}w.SQParensContext=hce;class pce extends un{COMPOSE(){return this.getToken(d.COMPOSE,0)}OPAREN(){return this.getToken(d.OPAREN,0)}CPAREN(){return this.getToken(d.CPAREN,0)}sqExpr(e){return e===void 0?this.getRuleContexts(un):this.getRuleContext(e,un)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSQCompose&&e.enterSQCompose(this)}exitRule(e){e.exitSQCompose&&e.exitSQCompose(this)}accept(e){return e.visitSQCompose?e.visitSQCompose(this):e.visitChildren(this)}}w.SQComposeContext=pce;class mce extends un{sqExpr(){return this.getRuleContext(0,un)}PLUS(){return this.getToken(d.PLUS,0)}segExpr(){return this.getRuleContext(0,Ms)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSQRefinedQuery&&e.enterSQRefinedQuery(this)}exitRule(e){e.exitSQRefinedQuery&&e.exitSQRefinedQuery(this)}accept(e){return e.visitSQRefinedQuery?e.visitSQRefinedQuery(this):e.visitChildren(this)}}w.SQRefinedQueryContext=mce;class gce extends un{sqExpr(){return this.getRuleContext(0,un)}ARROW(){return this.getToken(d.ARROW,0)}segExpr(){return this.getRuleContext(0,Ms)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSQArrow&&e.enterSQArrow(this)}exitRule(e){e.exitSQArrow&&e.exitSQArrow(this)}accept(e){return e.visitSQArrow?e.visitSQArrow(this):e.visitChildren(this)}}w.SQArrowContext=gce;class yce extends un{sqExpr(){return this.getRuleContext(0,un)}EXTEND(){return this.getToken(d.EXTEND,0)}exploreProperties(){return this.getRuleContext(0,Mk)}INCLUDE(){return this.tryGetToken(d.INCLUDE,0)}includeBlock(){return this.tryGetRuleContext(0,zT)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSQExtendedSource&&e.enterSQExtendedSource(this)}exitRule(e){e.exitSQExtendedSource&&e.exitSQExtendedSource(this)}accept(e){return e.visitSQExtendedSource?e.visitSQExtendedSource(this):e.visitChildren(this)}}w.SQExtendedSourceContext=yce;class Ece extends un{sqExpr(){return this.getRuleContext(0,un)}INCLUDE(){return this.getToken(d.INCLUDE,0)}includeBlock(){return this.getRuleContext(0,zT)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSQInclude&&e.enterSQInclude(this)}exitRule(e){e.exitSQInclude&&e.exitSQInclude(this)}accept(e){return e.visitSQInclude?e.visitSQInclude(this):e.visitChildren(this)}}w.SQIncludeContext=Ece;class Ace extends un{exploreTable(){return this.getRuleContext(0,Fk)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSQTable&&e.enterSQTable(this)}exitRule(e){e.exitSQTable&&e.exitSQTable(this)}accept(e){return e.visitSQTable?e.visitSQTable(this):e.visitChildren(this)}}w.SQTableContext=Ace;class _ce extends un{sqlSource(){return this.getRuleContext(0,Ok)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSQSQL&&e.enterSQSQL(this)}exitRule(e){e.exitSQSQL&&e.exitSQSQL(this)}accept(e){return e.visitSQSQL?e.visitSQSQL(this):e.visitChildren(this)}}w.SQSQLContext=_ce;class zT extends pe.ParserRuleContext{OCURLY(){return this.getToken(d.OCURLY,0)}CCURLY(){return this.getToken(d.CCURLY,0)}includeItem(e){return e===void 0?this.getRuleContexts(GT):this.getRuleContext(e,GT)}SEMI(e){return e===void 0?this.getTokens(d.SEMI):this.getToken(d.SEMI,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_includeBlock}enterRule(e){e.enterIncludeBlock&&e.enterIncludeBlock(this)}exitRule(e){e.exitIncludeBlock&&e.exitIncludeBlock(this)}accept(e){return e.visitIncludeBlock?e.visitIncludeBlock(this):e.visitChildren(this)}}w.IncludeBlockContext=zT;class GT extends pe.ParserRuleContext{tags(){return this.tryGetRuleContext(0,Yt)}accessLabelProp(){return this.tryGetRuleContext(0,zk)}includeList(){return this.tryGetRuleContext(0,Wk)}EXCEPT(){return this.tryGetToken(d.EXCEPT,0)}includeExceptList(){return this.tryGetRuleContext(0,Gk)}orphanedAnnotation(){return this.tryGetRuleContext(0,Qk)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_includeItem}enterRule(e){e.enterIncludeItem&&e.enterIncludeItem(this)}exitRule(e){e.exitIncludeItem&&e.exitIncludeItem(this)}accept(e){return e.visitIncludeItem?e.visitIncludeItem(this):e.visitChildren(this)}}w.IncludeItemContext=GT;class Qk extends pe.ParserRuleContext{ANNOTATION(){return this.getToken(d.ANNOTATION,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_orphanedAnnotation}enterRule(e){e.enterOrphanedAnnotation&&e.enterOrphanedAnnotation(this)}exitRule(e){e.exitOrphanedAnnotation&&e.exitOrphanedAnnotation(this)}accept(e){return e.visitOrphanedAnnotation?e.visitOrphanedAnnotation(this):e.visitChildren(this)}}w.OrphanedAnnotationContext=Qk;class zk extends pe.ParserRuleContext{PUBLIC(){return this.tryGetToken(d.PUBLIC,0)}PRIVATE(){return this.tryGetToken(d.PRIVATE,0)}INTERNAL(){return this.tryGetToken(d.INTERNAL,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_accessLabelProp}enterRule(e){e.enterAccessLabelProp&&e.enterAccessLabelProp(this)}exitRule(e){e.exitAccessLabelProp&&e.exitAccessLabelProp(this)}accept(e){return e.visitAccessLabelProp?e.visitAccessLabelProp(this):e.visitChildren(this)}}w.AccessLabelPropContext=zk;class Gk extends pe.ParserRuleContext{includeExceptListItem(e){return e===void 0?this.getRuleContexts(WT):this.getRuleContext(e,WT)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_includeExceptList}enterRule(e){e.enterIncludeExceptList&&e.enterIncludeExceptList(this)}exitRule(e){e.exitIncludeExceptList&&e.exitIncludeExceptList(this)}accept(e){return e.visitIncludeExceptList?e.visitIncludeExceptList(this):e.visitChildren(this)}}w.IncludeExceptListContext=Gk;class WT extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}fieldName(){return this.tryGetRuleContext(0,Ur)}collectionWildCard(){return this.tryGetRuleContext(0,pE)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_includeExceptListItem}enterRule(e){e.enterIncludeExceptListItem&&e.enterIncludeExceptListItem(this)}exitRule(e){e.exitIncludeExceptListItem&&e.exitIncludeExceptListItem(this)}accept(e){return e.visitIncludeExceptListItem?e.visitIncludeExceptListItem(this):e.visitChildren(this)}}w.IncludeExceptListItemContext=WT;class Wk extends pe.ParserRuleContext{includeField(e){return e===void 0?this.getRuleContexts(VT):this.getRuleContext(e,VT)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_includeList}enterRule(e){e.enterIncludeList&&e.enterIncludeList(this)}exitRule(e){e.exitIncludeList&&e.exitIncludeList(this)}accept(e){return e.visitIncludeList?e.visitIncludeList(this):e.visitChildren(this)}}w.IncludeListContext=Wk;class VT extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}fieldName(e){return e===void 0?this.getRuleContexts(Ur):this.getRuleContext(e,Ur)}isDefine(){return this.tryGetRuleContext(0,e0)}collectionWildCard(){return this.tryGetRuleContext(0,pE)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_includeField}enterRule(e){e.enterIncludeField&&e.enterIncludeField(this)}exitRule(e){e.exitIncludeField&&e.exitIncludeField(this)}accept(e){return e.visitIncludeField?e.visitIncludeField(this):e.visitChildren(this)}}w.IncludeFieldContext=VT;class Ms extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_segExpr}copyFrom(e){super.copyFrom(e)}}w.SegExprContext=Ms;class vce extends Ms{fieldPath(){return this.getRuleContext(0,Na)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSegField&&e.enterSegField(this)}exitRule(e){e.exitSegField&&e.exitSegField(this)}accept(e){return e.visitSegField?e.visitSegField(this):e.visitChildren(this)}}w.SegFieldContext=vce;class Cce extends Ms{queryProperties(){return this.getRuleContext(0,wk)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSegOps&&e.enterSegOps(this)}exitRule(e){e.exitSegOps&&e.exitSegOps(this)}accept(e){return e.visitSegOps?e.visitSegOps(this):e.visitChildren(this)}}w.SegOpsContext=Cce;class Sce extends Ms{OPAREN(){return this.getToken(d.OPAREN,0)}vExpr(){return this.getRuleContext(0,zc)}CPAREN(){return this.getToken(d.CPAREN,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSegParen&&e.enterSegParen(this)}exitRule(e){e.exitSegParen&&e.exitSegParen(this)}accept(e){return e.visitSegParen?e.visitSegParen(this):e.visitChildren(this)}}w.SegParenContext=Sce;class bce extends Ms{PLUS(){return this.getToken(d.PLUS,0)}segExpr(e){return e===void 0?this.getRuleContexts(Ms):this.getRuleContext(e,Ms)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSegRefine&&e.enterSegRefine(this)}exitRule(e){e.exitSegRefine&&e.exitSegRefine(this)}accept(e){return e.visitSegRefine?e.visitSegRefine(this):e.visitChildren(this)}}w.SegRefineContext=bce;class zc extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_vExpr}copyFrom(e){super.copyFrom(e)}}w.VExprContext=zc;class Tce extends zc{segExpr(){return this.getRuleContext(0,Ms)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterVSeg&&e.enterVSeg(this)}exitRule(e){e.exitVSeg&&e.exitVSeg(this)}accept(e){return e.visitVSeg?e.visitVSeg(this):e.visitChildren(this)}}w.VSegContext=Tce;class Rce extends zc{ARROW(){return this.getToken(d.ARROW,0)}segExpr(){return this.getRuleContext(0,Ms)}vExpr(){return this.getRuleContext(0,zc)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterVArrow&&e.enterVArrow(this)}exitRule(e){e.exitVArrow&&e.exitVArrow(this)}accept(e){return e.visitVArrow?e.visitVArrow(this):e.visitChildren(this)}}w.VArrowContext=Rce;class YT extends pe.ParserRuleContext{defDimensions(){return this.tryGetRuleContext(0,UT)}defMeasures(){return this.tryGetRuleContext(0,PT)}joinStatement(){return this.tryGetRuleContext(0,t0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_queryExtendStatement}enterRule(e){e.enterQueryExtendStatement&&e.enterQueryExtendStatement(this)}exitRule(e){e.exitQueryExtendStatement&&e.exitQueryExtendStatement(this)}accept(e){return e.visitQueryExtendStatement?e.visitQueryExtendStatement(this):e.visitChildren(this)}}w.QueryExtendStatementContext=YT;class Vk extends pe.ParserRuleContext{OCURLY(){return this.getToken(d.OCURLY,0)}CCURLY(){return this.getToken(d.CCURLY,0)}queryExtendStatement(e){return e===void 0?this.getRuleContexts(YT):this.getRuleContext(e,YT)}SEMI(e){return e===void 0?this.getTokens(d.SEMI):this.getToken(d.SEMI,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_queryExtendStatementList}enterRule(e){e.enterQueryExtendStatementList&&e.enterQueryExtendStatementList(this)}exitRule(e){e.exitQueryExtendStatementList&&e.exitQueryExtendStatementList(this)}accept(e){return e.visitQueryExtendStatementList?e.visitQueryExtendStatementList(this):e.visitChildren(this)}}w.QueryExtendStatementListContext=Vk;class cE extends pe.ParserRuleContext{joinDef(e){return e===void 0?this.getRuleContexts(C2):this.getRuleContext(e,C2)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_joinList}enterRule(e){e.enterJoinList&&e.enterJoinList(this)}exitRule(e){e.exitJoinList&&e.exitJoinList(this)}accept(e){return e.visitJoinList?e.visitJoinList(this):e.visitChildren(this)}}w.JoinListContext=cE;class Yk extends pe.ParserRuleContext{IS(){return this.getToken(d.IS,0)}sqExpr(){return this.getRuleContext(0,un)}tags(e){return e===void 0?this.getRuleContexts(Yt):this.getRuleContext(e,Yt)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_isExplore}enterRule(e){e.enterIsExplore&&e.enterIsExplore(this)}exitRule(e){e.exitIsExplore&&e.exitIsExplore(this)}accept(e){return e.visitIsExplore?e.visitIsExplore(this):e.visitChildren(this)}}w.IsExploreContext=Yk;class KT extends pe.ParserRuleContext{LEFT(){return this.tryGetToken(d.LEFT,0)}RIGHT(){return this.tryGetToken(d.RIGHT,0)}FULL(){return this.tryGetToken(d.FULL,0)}INNER(){return this.tryGetToken(d.INNER,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_matrixOperation}enterRule(e){e.enterMatrixOperation&&e.enterMatrixOperation(this)}exitRule(e){e.exitMatrixOperation&&e.exitMatrixOperation(this)}accept(e){return e.visitMatrixOperation?e.visitMatrixOperation(this):e.visitChildren(this)}}w.MatrixOperationContext=KT;class JT extends pe.ParserRuleContext{joinNameDef(){return this.getRuleContext(0,jk)}sourceArguments(){return this.tryGetRuleContext(0,HT)}isExplore(){return this.tryGetRuleContext(0,Yk)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_joinFrom}enterRule(e){e.enterJoinFrom&&e.enterJoinFrom(this)}exitRule(e){e.exitJoinFrom&&e.exitJoinFrom(this)}accept(e){return e.visitJoinFrom?e.visitJoinFrom(this):e.visitChildren(this)}}w.JoinFromContext=JT;class C2 extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_joinDef}copyFrom(e){super.copyFrom(e)}}w.JoinDefContext=C2;class Dce extends C2{joinFrom(){return this.getRuleContext(0,JT)}WITH(){return this.getToken(d.WITH,0)}fieldExpr(){return this.getRuleContext(0,Te)}ANNOTATION(e){return e===void 0?this.getTokens(d.ANNOTATION):this.getToken(d.ANNOTATION,e)}matrixOperation(){return this.tryGetRuleContext(0,KT)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterJoinWith&&e.enterJoinWith(this)}exitRule(e){e.exitJoinWith&&e.exitJoinWith(this)}accept(e){return e.visitJoinWith?e.visitJoinWith(this):e.visitChildren(this)}}w.JoinWithContext=Dce;class Oce extends C2{joinFrom(){return this.getRuleContext(0,JT)}ANNOTATION(e){return e===void 0?this.getTokens(d.ANNOTATION):this.getToken(d.ANNOTATION,e)}ON(){return this.tryGetToken(d.ON,0)}joinExpression(){return this.tryGetRuleContext(0,Kk)}matrixOperation(){return this.tryGetRuleContext(0,KT)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterJoinOn&&e.enterJoinOn(this)}exitRule(e){e.exitJoinOn&&e.exitJoinOn(this)}accept(e){return e.visitJoinOn?e.visitJoinOn(this):e.visitChildren(this)}}w.JoinOnContext=Oce;class Kk extends pe.ParserRuleContext{fieldExpr(){return this.getRuleContext(0,Te)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_joinExpression}enterRule(e){e.enterJoinExpression&&e.enterJoinExpression(this)}exitRule(e){e.exitJoinExpression&&e.exitJoinExpression(this)}accept(e){return e.visitJoinExpression?e.visitJoinExpression(this):e.visitChildren(this)}}w.JoinExpressionContext=Kk;class Fce extends pe.ParserRuleContext{whereStatement(){return this.tryGetRuleContext(0,ud)}havingStatement(){return this.tryGetRuleContext(0,tR)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_filterStatement}enterRule(e){e.enterFilterStatement&&e.enterFilterStatement(this)}exitRule(e){e.exitFilterStatement&&e.exitFilterStatement(this)}accept(e){return e.visitFilterStatement?e.visitFilterStatement(this):e.visitChildren(this)}}w.FilterStatementContext=Fce;class Jk extends pe.ParserRuleContext{OCURLY(){return this.getToken(d.OCURLY,0)}CCURLY(){return this.getToken(d.CCURLY,0)}fieldPropertyStatement(e){return e===void 0?this.getRuleContexts(ZT):this.getRuleContext(e,ZT)}SEMI(e){return e===void 0?this.getTokens(d.SEMI):this.getToken(d.SEMI,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_fieldProperties}enterRule(e){e.enterFieldProperties&&e.enterFieldProperties(this)}exitRule(e){e.exitFieldProperties&&e.exitFieldProperties(this)}accept(e){return e.visitFieldProperties?e.visitFieldProperties(this):e.visitChildren(this)}}w.FieldPropertiesContext=Jk;class Xk extends pe.ParserRuleContext{aggregateOrderBySpec(e){return e===void 0?this.getRuleContexts(XT):this.getRuleContext(e,XT)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_aggregateOrdering}enterRule(e){e.enterAggregateOrdering&&e.enterAggregateOrdering(this)}exitRule(e){e.exitAggregateOrdering&&e.exitAggregateOrdering(this)}accept(e){return e.visitAggregateOrdering?e.visitAggregateOrdering(this):e.visitChildren(this)}}w.AggregateOrderingContext=Xk;class XT extends pe.ParserRuleContext{fieldExpr(){return this.tryGetRuleContext(0,Te)}ASC(){return this.tryGetToken(d.ASC,0)}DESC(){return this.tryGetToken(d.DESC,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_aggregateOrderBySpec}enterRule(e){e.enterAggregateOrderBySpec&&e.enterAggregateOrderBySpec(this)}exitRule(e){e.exitAggregateOrderBySpec&&e.exitAggregateOrderBySpec(this)}accept(e){return e.visitAggregateOrderBySpec?e.visitAggregateOrderBySpec(this):e.visitChildren(this)}}w.AggregateOrderBySpecContext=XT;class Zk extends pe.ParserRuleContext{ORDER_BY(){return this.getToken(d.ORDER_BY,0)}aggregateOrdering(){return this.getRuleContext(0,Xk)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_aggregateOrderByStatement}enterRule(e){e.enterAggregateOrderByStatement&&e.enterAggregateOrderByStatement(this)}exitRule(e){e.exitAggregateOrderByStatement&&e.exitAggregateOrderByStatement(this)}accept(e){return e.visitAggregateOrderByStatement?e.visitAggregateOrderByStatement(this):e.visitChildren(this)}}w.AggregateOrderByStatementContext=Zk;class eM extends pe.ParserRuleContext{limitStatement(){return this.getRuleContext(0,oR)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_fieldPropertyLimitStatement}enterRule(e){e.enterFieldPropertyLimitStatement&&e.enterFieldPropertyLimitStatement(this)}exitRule(e){e.exitFieldPropertyLimitStatement&&e.exitFieldPropertyLimitStatement(this)}accept(e){return e.visitFieldPropertyLimitStatement?e.visitFieldPropertyLimitStatement(this):e.visitChildren(this)}}w.FieldPropertyLimitStatementContext=eM;class ZT extends pe.ParserRuleContext{whereStatement(){return this.tryGetRuleContext(0,ud)}partitionByStatement(){return this.tryGetRuleContext(0,cM)}aggregateOrderByStatement(){return this.tryGetRuleContext(0,Zk)}fieldPropertyLimitStatement(){return this.tryGetRuleContext(0,eM)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_fieldPropertyStatement}enterRule(e){e.enterFieldPropertyStatement&&e.enterFieldPropertyStatement(this)}exitRule(e){e.exitFieldPropertyStatement&&e.exitFieldPropertyStatement(this)}accept(e){return e.visitFieldPropertyStatement?e.visitFieldPropertyStatement(this):e.visitChildren(this)}}w.FieldPropertyStatementContext=ZT;class eR extends pe.ParserRuleContext{fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_filterClauseList}enterRule(e){e.enterFilterClauseList&&e.enterFilterClauseList(this)}exitRule(e){e.exitFilterClauseList&&e.exitFilterClauseList(this)}accept(e){return e.visitFilterClauseList?e.visitFilterClauseList(this):e.visitChildren(this)}}w.FilterClauseListContext=eR;class ud extends pe.ParserRuleContext{WHERE(){return this.getToken(d.WHERE,0)}filterClauseList(){return this.getRuleContext(0,eR)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_whereStatement}enterRule(e){e.enterWhereStatement&&e.enterWhereStatement(this)}exitRule(e){e.exitWhereStatement&&e.exitWhereStatement(this)}accept(e){return e.visitWhereStatement?e.visitWhereStatement(this):e.visitChildren(this)}}w.WhereStatementContext=ud;class tR extends pe.ParserRuleContext{HAVING(){return this.getToken(d.HAVING,0)}filterClauseList(){return this.getRuleContext(0,eR)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_havingStatement}enterRule(e){e.enterHavingStatement&&e.enterHavingStatement(this)}exitRule(e){e.exitHavingStatement&&e.exitHavingStatement(this)}accept(e){return e.visitHavingStatement?e.visitHavingStatement(this):e.visitChildren(this)}}w.HavingStatementContext=tR;class tM extends pe.ParserRuleContext{exploreQueryDef(e){return e===void 0?this.getRuleContexts(nR):this.getRuleContext(e,nR)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_subQueryDefList}enterRule(e){e.enterSubQueryDefList&&e.enterSubQueryDefList(this)}exitRule(e){e.exitSubQueryDefList&&e.exitSubQueryDefList(this)}accept(e){return e.visitSubQueryDefList?e.visitSubQueryDefList(this):e.visitChildren(this)}}w.SubQueryDefListContext=tM;class nM extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_exploreQueryNameDef}enterRule(e){e.enterExploreQueryNameDef&&e.enterExploreQueryNameDef(this)}exitRule(e){e.exitExploreQueryNameDef&&e.exitExploreQueryNameDef(this)}accept(e){return e.visitExploreQueryNameDef?e.visitExploreQueryNameDef(this):e.visitChildren(this)}}w.ExploreQueryNameDefContext=nM;class nR extends pe.ParserRuleContext{exploreQueryNameDef(){return this.getRuleContext(0,nM)}isDefine(){return this.getRuleContext(0,e0)}vExpr(){return this.getRuleContext(0,zc)}ANNOTATION(e){return e===void 0?this.getTokens(d.ANNOTATION):this.getToken(d.ANNOTATION,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_exploreQueryDef}enterRule(e){e.enterExploreQueryDef&&e.enterExploreQueryDef(this)}exitRule(e){e.exitExploreQueryDef&&e.exitExploreQueryDef(this)}accept(e){return e.visitExploreQueryDef?e.visitExploreQueryDef(this):e.visitChildren(this)}}w.ExploreQueryDefContext=nR;class rR extends pe.ParserRuleContext{groupByStatement(){return this.tryGetRuleContext(0,iM)}declareStatement(){return this.tryGetRuleContext(0,qT)}queryJoinStatement(){return this.tryGetRuleContext(0,rM)}queryExtend(){return this.tryGetRuleContext(0,qk)}projectStatement(){return this.tryGetRuleContext(0,lM)}indexStatement(){return this.tryGetRuleContext(0,pM)}aggregateStatement(){return this.tryGetRuleContext(0,uM)}calculateStatement(){return this.tryGetRuleContext(0,aM)}topStatement(){return this.tryGetRuleContext(0,dM)}limitStatement(){return this.tryGetRuleContext(0,oR)}orderByStatement(){return this.tryGetRuleContext(0,fM)}whereStatement(){return this.tryGetRuleContext(0,ud)}havingStatement(){return this.tryGetRuleContext(0,tR)}nestStatement(){return this.tryGetRuleContext(0,sM)}sampleStatement(){return this.tryGetRuleContext(0,mM)}timezoneStatement(){return this.tryGetRuleContext(0,aR)}queryAnnotation(){return this.tryGetRuleContext(0,gM)}ignoredModelAnnotations(){return this.tryGetRuleContext(0,LT)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_queryStatement}enterRule(e){e.enterQueryStatement&&e.enterQueryStatement(this)}exitRule(e){e.exitQueryStatement&&e.exitQueryStatement(this)}accept(e){return e.visitQueryStatement?e.visitQueryStatement(this):e.visitChildren(this)}}w.QueryStatementContext=rR;class rM extends pe.ParserRuleContext{joinStatement(){return this.getRuleContext(0,t0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_queryJoinStatement}enterRule(e){e.enterQueryJoinStatement&&e.enterQueryJoinStatement(this)}exitRule(e){e.exitQueryJoinStatement&&e.exitQueryJoinStatement(this)}accept(e){return e.visitQueryJoinStatement?e.visitQueryJoinStatement(this):e.visitChildren(this)}}w.QueryJoinStatementContext=rM;class iM extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}GROUP_BY(){return this.getToken(d.GROUP_BY,0)}queryFieldList(){return this.getRuleContext(0,fE)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_groupByStatement}enterRule(e){e.enterGroupByStatement&&e.enterGroupByStatement(this)}exitRule(e){e.exitGroupByStatement&&e.exitGroupByStatement(this)}accept(e){return e.visitGroupByStatement?e.visitGroupByStatement(this):e.visitChildren(this)}}w.GroupByStatementContext=iM;class fE extends pe.ParserRuleContext{queryFieldEntry(e){return e===void 0?this.getRuleContexts(iR):this.getRuleContext(e,iR)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_queryFieldList}enterRule(e){e.enterQueryFieldList&&e.enterQueryFieldList(this)}exitRule(e){e.exitQueryFieldList&&e.exitQueryFieldList(this)}accept(e){return e.visitQueryFieldList?e.visitQueryFieldList(this):e.visitChildren(this)}}w.QueryFieldListContext=fE;class iR extends pe.ParserRuleContext{taggedRef(){return this.tryGetRuleContext(0,mR)}fieldDef(){return this.tryGetRuleContext(0,v2)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_queryFieldEntry}enterRule(e){e.enterQueryFieldEntry&&e.enterQueryFieldEntry(this)}exitRule(e){e.exitQueryFieldEntry&&e.exitQueryFieldEntry(this)}accept(e){return e.visitQueryFieldEntry?e.visitQueryFieldEntry(this):e.visitChildren(this)}}w.QueryFieldEntryContext=iR;class sM extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}NEST(){return this.getToken(d.NEST,0)}nestedQueryList(){return this.getRuleContext(0,oM)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_nestStatement}enterRule(e){e.enterNestStatement&&e.enterNestStatement(this)}exitRule(e){e.exitNestStatement&&e.exitNestStatement(this)}accept(e){return e.visitNestStatement?e.visitNestStatement(this):e.visitChildren(this)}}w.NestStatementContext=sM;class oM extends pe.ParserRuleContext{nestEntry(e){return e===void 0?this.getRuleContexts(xE):this.getRuleContext(e,xE)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_nestedQueryList}enterRule(e){e.enterNestedQueryList&&e.enterNestedQueryList(this)}exitRule(e){e.exitNestedQueryList&&e.exitNestedQueryList(this)}accept(e){return e.visitNestedQueryList?e.visitNestedQueryList(this):e.visitChildren(this)}}w.NestedQueryListContext=oM;class xE extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_nestEntry}copyFrom(e){super.copyFrom(e)}}w.NestEntryContext=xE;class wce extends xE{tags(){return this.getRuleContext(0,Yt)}vExpr(){return this.getRuleContext(0,zc)}queryName(){return this.tryGetRuleContext(0,$T)}isDefine(){return this.tryGetRuleContext(0,e0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterNestDef&&e.enterNestDef(this)}exitRule(e){e.exitNestDef&&e.exitNestDef(this)}accept(e){return e.visitNestDef?e.visitNestDef(this):e.visitChildren(this)}}w.NestDefContext=wce;class uM extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}AGGREGATE(){return this.getToken(d.AGGREGATE,0)}queryFieldList(){return this.getRuleContext(0,fE)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_aggregateStatement}enterRule(e){e.enterAggregateStatement&&e.enterAggregateStatement(this)}exitRule(e){e.exitAggregateStatement&&e.exitAggregateStatement(this)}accept(e){return e.visitAggregateStatement?e.visitAggregateStatement(this):e.visitChildren(this)}}w.AggregateStatementContext=uM;class aM extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}CALCULATE(){return this.getToken(d.CALCULATE,0)}queryFieldList(){return this.getRuleContext(0,fE)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_calculateStatement}enterRule(e){e.enterCalculateStatement&&e.enterCalculateStatement(this)}exitRule(e){e.exitCalculateStatement&&e.exitCalculateStatement(this)}accept(e){return e.visitCalculateStatement?e.visitCalculateStatement(this):e.visitChildren(this)}}w.CalculateStatementContext=aM;class lM extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}SELECT(){return this.getToken(d.SELECT,0)}fieldCollection(){return this.getRuleContext(0,FM)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_projectStatement}enterRule(e){e.enterProjectStatement&&e.enterProjectStatement(this)}exitRule(e){e.exitProjectStatement&&e.exitProjectStatement(this)}accept(e){return e.visitProjectStatement?e.visitProjectStatement(this):e.visitChildren(this)}}w.ProjectStatementContext=lM;class cM extends pe.ParserRuleContext{PARTITION_BY(){return this.getToken(d.PARTITION_BY,0)}id(e){return e===void 0?this.getRuleContexts(Dn):this.getRuleContext(e,Dn)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_partitionByStatement}enterRule(e){e.enterPartitionByStatement&&e.enterPartitionByStatement(this)}exitRule(e){e.exitPartitionByStatement&&e.exitPartitionByStatement(this)}accept(e){return e.visitPartitionByStatement?e.visitPartitionByStatement(this):e.visitChildren(this)}}w.PartitionByStatementContext=cM;class fM extends pe.ParserRuleContext{ORDER_BY(){return this.getToken(d.ORDER_BY,0)}ordering(){return this.getRuleContext(0,xM)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_orderByStatement}enterRule(e){e.enterOrderByStatement&&e.enterOrderByStatement(this)}exitRule(e){e.exitOrderByStatement&&e.exitOrderByStatement(this)}accept(e){return e.visitOrderByStatement?e.visitOrderByStatement(this):e.visitChildren(this)}}w.OrderByStatementContext=fM;class xM extends pe.ParserRuleContext{orderBySpec(e){return e===void 0?this.getRuleContexts(sR):this.getRuleContext(e,sR)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_ordering}enterRule(e){e.enterOrdering&&e.enterOrdering(this)}exitRule(e){e.exitOrdering&&e.exitOrdering(this)}accept(e){return e.visitOrdering?e.visitOrdering(this):e.visitChildren(this)}}w.OrderingContext=xM;class sR extends pe.ParserRuleContext{INTEGER_LITERAL(){return this.tryGetToken(d.INTEGER_LITERAL,0)}fieldName(){return this.tryGetRuleContext(0,Ur)}ASC(){return this.tryGetToken(d.ASC,0)}DESC(){return this.tryGetToken(d.DESC,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_orderBySpec}enterRule(e){e.enterOrderBySpec&&e.enterOrderBySpec(this)}exitRule(e){e.exitOrderBySpec&&e.exitOrderBySpec(this)}accept(e){return e.visitOrderBySpec?e.visitOrderBySpec(this):e.visitChildren(this)}}w.OrderBySpecContext=sR;class oR extends pe.ParserRuleContext{LIMIT(){return this.getToken(d.LIMIT,0)}INTEGER_LITERAL(){return this.getToken(d.INTEGER_LITERAL,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_limitStatement}enterRule(e){e.enterLimitStatement&&e.enterLimitStatement(this)}exitRule(e){e.exitLimitStatement&&e.exitLimitStatement(this)}accept(e){return e.visitLimitStatement?e.visitLimitStatement(this):e.visitChildren(this)}}w.LimitStatementContext=oR;class Nce extends pe.ParserRuleContext{BY(){return this.getToken(d.BY,0)}fieldName(){return this.tryGetRuleContext(0,Ur)}fieldExpr(){return this.tryGetRuleContext(0,Te)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_bySpec}enterRule(e){e.enterBySpec&&e.enterBySpec(this)}exitRule(e){e.exitBySpec&&e.exitBySpec(this)}accept(e){return e.visitBySpec?e.visitBySpec(this):e.visitChildren(this)}}w.BySpecContext=Nce;class dM extends pe.ParserRuleContext{TOP(){return this.getToken(d.TOP,0)}INTEGER_LITERAL(){return this.getToken(d.INTEGER_LITERAL,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_topStatement}enterRule(e){e.enterTopStatement&&e.enterTopStatement(this)}exitRule(e){e.exitTopStatement&&e.exitTopStatement(this)}accept(e){return e.visitTopStatement?e.visitTopStatement(this):e.visitChildren(this)}}w.TopStatementContext=dM;class uR extends pe.ParserRuleContext{fieldPath(){return this.tryGetRuleContext(0,Na)}DOT(){return this.tryGetToken(d.DOT,0)}STAR(){return this.tryGetToken(d.STAR,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_indexElement}enterRule(e){e.enterIndexElement&&e.enterIndexElement(this)}exitRule(e){e.exitIndexElement&&e.exitIndexElement(this)}accept(e){return e.visitIndexElement?e.visitIndexElement(this):e.visitChildren(this)}}w.IndexElementContext=uR;class hM extends pe.ParserRuleContext{indexElement(e){return e===void 0?this.getRuleContexts(uR):this.getRuleContext(e,uR)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_indexFields}enterRule(e){e.enterIndexFields&&e.enterIndexFields(this)}exitRule(e){e.exitIndexFields&&e.exitIndexFields(this)}accept(e){return e.visitIndexFields?e.visitIndexFields(this):e.visitChildren(this)}}w.IndexFieldsContext=hM;class pM extends pe.ParserRuleContext{INDEX(){return this.getToken(d.INDEX,0)}indexFields(){return this.getRuleContext(0,hM)}BY(){return this.tryGetToken(d.BY,0)}fieldName(){return this.tryGetRuleContext(0,Ur)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_indexStatement}enterRule(e){e.enterIndexStatement&&e.enterIndexStatement(this)}exitRule(e){e.exitIndexStatement&&e.exitIndexStatement(this)}accept(e){return e.visitIndexStatement?e.visitIndexStatement(this):e.visitChildren(this)}}w.IndexStatementContext=pM;class mM extends pe.ParserRuleContext{SAMPLE(){return this.getToken(d.SAMPLE,0)}sampleSpec(){return this.getRuleContext(0,yM)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sampleStatement}enterRule(e){e.enterSampleStatement&&e.enterSampleStatement(this)}exitRule(e){e.exitSampleStatement&&e.exitSampleStatement(this)}accept(e){return e.visitSampleStatement?e.visitSampleStatement(this):e.visitChildren(this)}}w.SampleStatementContext=mM;class aR extends pe.ParserRuleContext{TIMEZONE(){return this.getToken(d.TIMEZONE,0)}string(){return this.getRuleContext(0,Fa)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_timezoneStatement}enterRule(e){e.enterTimezoneStatement&&e.enterTimezoneStatement(this)}exitRule(e){e.exitTimezoneStatement&&e.exitTimezoneStatement(this)}accept(e){return e.visitTimezoneStatement?e.visitTimezoneStatement(this):e.visitChildren(this)}}w.TimezoneStatementContext=aR;class gM extends pe.ParserRuleContext{ANNOTATION(){return this.getToken(d.ANNOTATION,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_queryAnnotation}enterRule(e){e.enterQueryAnnotation&&e.enterQueryAnnotation(this)}exitRule(e){e.exitQueryAnnotation&&e.exitQueryAnnotation(this)}accept(e){return e.visitQueryAnnotation?e.visitQueryAnnotation(this):e.visitChildren(this)}}w.QueryAnnotationContext=gM;class yM extends pe.ParserRuleContext{PERCENT_LITERAL(){return this.tryGetToken(d.PERCENT_LITERAL,0)}INTEGER_LITERAL(){return this.tryGetToken(d.INTEGER_LITERAL,0)}TRUE(){return this.tryGetToken(d.TRUE,0)}FALSE(){return this.tryGetToken(d.FALSE,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sampleSpec}enterRule(e){e.enterSampleSpec&&e.enterSampleSpec(this)}exitRule(e){e.exitSampleSpec&&e.exitSampleSpec(this)}accept(e){return e.visitSampleSpec?e.visitSampleSpec(this):e.visitChildren(this)}}w.SampleSpecContext=yM;class dE extends pe.ParserRuleContext{SUM(){return this.tryGetToken(d.SUM,0)}COUNT(){return this.tryGetToken(d.COUNT,0)}AVG(){return this.tryGetToken(d.AVG,0)}MIN(){return this.tryGetToken(d.MIN,0)}MAX(){return this.tryGetToken(d.MAX,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_aggregate}enterRule(e){e.enterAggregate&&e.enterAggregate(this)}exitRule(e){e.exitAggregate&&e.exitAggregate(this)}accept(e){return e.visitAggregate?e.visitAggregate(this):e.visitChildren(this)}}w.AggregateContext=dE;class hE extends pe.ParserRuleContext{STRING(){return this.tryGetToken(d.STRING,0)}NUMBER(){return this.tryGetToken(d.NUMBER,0)}BOOLEAN(){return this.tryGetToken(d.BOOLEAN,0)}DATE(){return this.tryGetToken(d.DATE,0)}TIMESTAMP(){return this.tryGetToken(d.TIMESTAMP,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_malloyType}enterRule(e){e.enterMalloyType&&e.enterMalloyType(this)}exitRule(e){e.exitMalloyType&&e.exitMalloyType(this)}accept(e){return e.visitMalloyType?e.visitMalloyType(this):e.visitChildren(this)}}w.MalloyTypeContext=hE;class lR extends pe.ParserRuleContext{MATCH(){return this.tryGetToken(d.MATCH,0)}NOT_MATCH(){return this.tryGetToken(d.NOT_MATCH,0)}GT(){return this.tryGetToken(d.GT,0)}LT(){return this.tryGetToken(d.LT,0)}GTE(){return this.tryGetToken(d.GTE,0)}LTE(){return this.tryGetToken(d.LTE,0)}EQ(){return this.tryGetToken(d.EQ,0)}NE(){return this.tryGetToken(d.NE,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_compareOp}enterRule(e){e.enterCompareOp&&e.enterCompareOp(this)}exitRule(e){e.exitCompareOp&&e.exitCompareOp(this)}accept(e){return e.visitCompareOp?e.visitCompareOp(this):e.visitChildren(this)}}w.CompareOpContext=lR;class Fa extends pe.ParserRuleContext{shortString(){return this.tryGetRuleContext(0,cR)}sqlString(){return this.tryGetRuleContext(0,FT)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_string}enterRule(e){e.enterString&&e.enterString(this)}exitRule(e){e.exitString&&e.exitString(this)}accept(e){return e.visitString?e.visitString(this):e.visitChildren(this)}}w.StringContext=Fa;class cR extends pe.ParserRuleContext{SQ_STRING(){return this.tryGetToken(d.SQ_STRING,0)}DQ_STRING(){return this.tryGetToken(d.DQ_STRING,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_shortString}enterRule(e){e.enterShortString&&e.enterShortString(this)}exitRule(e){e.exitShortString&&e.exitShortString(this)}accept(e){return e.visitShortString?e.visitShortString(this):e.visitChildren(this)}}w.ShortStringContext=cR;class EM extends pe.ParserRuleContext{RAW_SQ(){return this.tryGetToken(d.RAW_SQ,0)}RAW_DQ(){return this.tryGetToken(d.RAW_DQ,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_rawString}enterRule(e){e.enterRawString&&e.enterRawString(this)}exitRule(e){e.exitRawString&&e.exitRawString(this)}accept(e){return e.visitRawString?e.visitRawString(this):e.visitChildren(this)}}w.RawStringContext=EM;class AM extends pe.ParserRuleContext{NUMERIC_LITERAL(){return this.tryGetToken(d.NUMERIC_LITERAL,0)}INTEGER_LITERAL(){return this.tryGetToken(d.INTEGER_LITERAL,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_numericLiteral}enterRule(e){e.enterNumericLiteral&&e.enterNumericLiteral(this)}exitRule(e){e.exitNumericLiteral&&e.exitNumericLiteral(this)}accept(e){return e.visitNumericLiteral?e.visitNumericLiteral(this):e.visitChildren(this)}}w.NumericLiteralContext=AM;class _o extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_literal}copyFrom(e){super.copyFrom(e)}}w.LiteralContext=_o;class Lce extends _o{string(){return this.getRuleContext(0,Fa)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprString&&e.enterExprString(this)}exitRule(e){e.exitExprString&&e.exitExprString(this)}accept(e){return e.visitExprString?e.visitExprString(this):e.visitChildren(this)}}w.ExprStringContext=Lce;class Ice extends _o{rawString(){return this.getRuleContext(0,EM)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterStub_rawString&&e.enterStub_rawString(this)}exitRule(e){e.exitStub_rawString&&e.exitStub_rawString(this)}accept(e){return e.visitStub_rawString?e.visitStub_rawString(this):e.visitChildren(this)}}w.Stub_rawStringContext=Ice;class Bce extends _o{numericLiteral(){return this.getRuleContext(0,AM)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprNumber&&e.enterExprNumber(this)}exitRule(e){e.exitExprNumber&&e.exitExprNumber(this)}accept(e){return e.visitExprNumber?e.visitExprNumber(this):e.visitChildren(this)}}w.ExprNumberContext=Bce;class $ce extends _o{dateLiteral(){return this.getRuleContext(0,wa)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprTime&&e.enterExprTime(this)}exitRule(e){e.exitExprTime&&e.exitExprTime(this)}accept(e){return e.visitExprTime?e.visitExprTime(this):e.visitChildren(this)}}w.ExprTimeContext=$ce;class kce extends _o{NULL(){return this.getToken(d.NULL,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprNULL&&e.enterExprNULL(this)}exitRule(e){e.exitExprNULL&&e.exitExprNULL(this)}accept(e){return e.visitExprNULL?e.visitExprNULL(this):e.visitChildren(this)}}w.ExprNULLContext=kce;class Mce extends _o{TRUE(){return this.tryGetToken(d.TRUE,0)}FALSE(){return this.tryGetToken(d.FALSE,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprBool&&e.enterExprBool(this)}exitRule(e){e.exitExprBool&&e.exitExprBool(this)}accept(e){return e.visitExprBool?e.visitExprBool(this):e.visitChildren(this)}}w.ExprBoolContext=Mce;class Pce extends _o{HACKY_REGEX(){return this.getToken(d.HACKY_REGEX,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprRegex&&e.enterExprRegex(this)}exitRule(e){e.exitExprRegex&&e.exitExprRegex(this)}accept(e){return e.visitExprRegex?e.visitExprRegex(this):e.visitChildren(this)}}w.ExprRegexContext=Pce;class Uce extends _o{filterString(){return this.getRuleContext(0,IM)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterFilterString_stub&&e.enterFilterString_stub(this)}exitRule(e){e.exitFilterString_stub&&e.exitFilterString_stub(this)}accept(e){return e.visitFilterString_stub?e.visitFilterString_stub(this):e.visitChildren(this)}}w.FilterString_stubContext=Uce;class jce extends _o{NOW(){return this.getToken(d.NOW,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprNow&&e.enterExprNow(this)}exitRule(e){e.exitExprNow&&e.exitExprNow(this)}accept(e){return e.visitExprNow?e.visitExprNow(this):e.visitChildren(this)}}w.ExprNowContext=jce;class wa extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_dateLiteral}copyFrom(e){super.copyFrom(e)}}w.DateLiteralContext=wa;class qce extends wa{LITERAL_TIMESTAMP(){return this.getToken(d.LITERAL_TIMESTAMP,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterLiteralTimestamp&&e.enterLiteralTimestamp(this)}exitRule(e){e.exitLiteralTimestamp&&e.exitLiteralTimestamp(this)}accept(e){return e.visitLiteralTimestamp?e.visitLiteralTimestamp(this):e.visitChildren(this)}}w.LiteralTimestampContext=qce;class Hce extends wa{LITERAL_HOUR(){return this.getToken(d.LITERAL_HOUR,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterLiteralHour&&e.enterLiteralHour(this)}exitRule(e){e.exitLiteralHour&&e.exitLiteralHour(this)}accept(e){return e.visitLiteralHour?e.visitLiteralHour(this):e.visitChildren(this)}}w.LiteralHourContext=Hce;class Qce extends wa{LITERAL_DAY(){return this.getToken(d.LITERAL_DAY,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterLiteralDay&&e.enterLiteralDay(this)}exitRule(e){e.exitLiteralDay&&e.exitLiteralDay(this)}accept(e){return e.visitLiteralDay?e.visitLiteralDay(this):e.visitChildren(this)}}w.LiteralDayContext=Qce;class zce extends wa{LITERAL_WEEK(){return this.getToken(d.LITERAL_WEEK,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterLiteralWeek&&e.enterLiteralWeek(this)}exitRule(e){e.exitLiteralWeek&&e.exitLiteralWeek(this)}accept(e){return e.visitLiteralWeek?e.visitLiteralWeek(this):e.visitChildren(this)}}w.LiteralWeekContext=zce;class Gce extends wa{LITERAL_MONTH(){return this.getToken(d.LITERAL_MONTH,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterLiteralMonth&&e.enterLiteralMonth(this)}exitRule(e){e.exitLiteralMonth&&e.exitLiteralMonth(this)}accept(e){return e.visitLiteralMonth?e.visitLiteralMonth(this):e.visitChildren(this)}}w.LiteralMonthContext=Gce;class Wce extends wa{LITERAL_QUARTER(){return this.getToken(d.LITERAL_QUARTER,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterLiteralQuarter&&e.enterLiteralQuarter(this)}exitRule(e){e.exitLiteralQuarter&&e.exitLiteralQuarter(this)}accept(e){return e.visitLiteralQuarter?e.visitLiteralQuarter(this):e.visitChildren(this)}}w.LiteralQuarterContext=Wce;class Vce extends wa{LITERAL_YEAR(){return this.getToken(d.LITERAL_YEAR,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterLiteralYear&&e.enterLiteralYear(this)}exitRule(e){e.exitLiteralYear&&e.exitLiteralYear(this)}accept(e){return e.visitLiteralYear?e.visitLiteralYear(this):e.visitChildren(this)}}w.LiteralYearContext=Vce;class _M extends pe.ParserRuleContext{string(){return this.getRuleContext(0,Fa)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_tablePath}enterRule(e){e.enterTablePath&&e.enterTablePath(this)}exitRule(e){e.exitTablePath&&e.exitTablePath(this)}accept(e){return e.visitTablePath?e.visitTablePath(this):e.visitChildren(this)}}w.TablePathContext=_M;class Yce extends pe.ParserRuleContext{string(){return this.getRuleContext(0,Fa)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_tableURI}enterRule(e){e.enterTableURI&&e.enterTableURI(this)}exitRule(e){e.exitTableURI&&e.exitTableURI(this)}accept(e){return e.visitTableURI?e.visitTableURI(this):e.visitChildren(this)}}w.TableURIContext=Yce;class Dn extends pe.ParserRuleContext{IDENTIFIER(){return this.tryGetToken(d.IDENTIFIER,0)}BQ_STRING(){return this.tryGetToken(d.BQ_STRING,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_id}enterRule(e){e.enterId&&e.enterId(this)}exitRule(e){e.exitId&&e.exitId(this)}accept(e){return e.visitId?e.visitId(this):e.visitChildren(this)}}w.IdContext=Dn;class ad extends pe.ParserRuleContext{SECOND(){return this.tryGetToken(d.SECOND,0)}MINUTE(){return this.tryGetToken(d.MINUTE,0)}HOUR(){return this.tryGetToken(d.HOUR,0)}DAY(){return this.tryGetToken(d.DAY,0)}WEEK(){return this.tryGetToken(d.WEEK,0)}MONTH(){return this.tryGetToken(d.MONTH,0)}QUARTER(){return this.tryGetToken(d.QUARTER,0)}YEAR(){return this.tryGetToken(d.YEAR,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_timeframe}enterRule(e){e.enterTimeframe&&e.enterTimeframe(this)}exitRule(e){e.exitTimeframe&&e.exitTimeframe(this)}accept(e){return e.visitTimeframe?e.visitTimeframe(this):e.visitChildren(this)}}w.TimeframeContext=ad;class vM extends pe.ParserRuleContext{ALL(){return this.tryGetToken(d.ALL,0)}EXCLUDE(){return this.tryGetToken(d.EXCLUDE,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_ungroup}enterRule(e){e.enterUngroup&&e.enterUngroup(this)}exitRule(e){e.exitUngroup&&e.exitUngroup(this)}accept(e){return e.visitUngroup?e.visitUngroup(this):e.visitChildren(this)}}w.UngroupContext=vM;class fR extends pe.ParserRuleContext{malloyType(){return this.tryGetRuleContext(0,hE)}string(){return this.tryGetRuleContext(0,Fa)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_malloyOrSQLType}enterRule(e){e.enterMalloyOrSQLType&&e.enterMalloyOrSQLType(this)}exitRule(e){e.exitMalloyOrSQLType&&e.exitMalloyOrSQLType(this)}accept(e){return e.visitMalloyOrSQLType?e.visitMalloyOrSQLType(this):e.visitChildren(this)}}w.MalloyOrSQLTypeContext=fR;class Te extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_fieldExpr}copyFrom(e){super.copyFrom(e)}}w.FieldExprContext=Te;class Kce extends Te{fieldPath(){return this.getRuleContext(0,Na)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprFieldPath&&e.enterExprFieldPath(this)}exitRule(e){e.exitExprFieldPath&&e.exitExprFieldPath(this)}accept(e){return e.visitExprFieldPath?e.visitExprFieldPath(this):e.visitChildren(this)}}w.ExprFieldPathContext=Kce;class Jce extends Te{literal(){return this.getRuleContext(0,_o)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprLiteral&&e.enterExprLiteral(this)}exitRule(e){e.exitExprLiteral&&e.exitExprLiteral(this)}accept(e){return e.visitExprLiteral?e.visitExprLiteral(this):e.visitChildren(this)}}w.ExprLiteralContext=Jce;class Xce extends Te{OBRACK(){return this.getToken(d.OBRACK,0)}fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}CBRACK(){return this.getToken(d.CBRACK,0)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprArrayLiteral&&e.enterExprArrayLiteral(this)}exitRule(e){e.exitExprArrayLiteral&&e.exitExprArrayLiteral(this)}accept(e){return e.visitExprArrayLiteral?e.visitExprArrayLiteral(this):e.visitChildren(this)}}w.ExprArrayLiteralContext=Xce;class Zce extends Te{OCURLY(){return this.getToken(d.OCURLY,0)}recordElement(e){return e===void 0?this.getRuleContexts(S2):this.getRuleContext(e,S2)}CCURLY(){return this.getToken(d.CCURLY,0)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprLiteralRecord&&e.enterExprLiteralRecord(this)}exitRule(e){e.exitExprLiteralRecord&&e.exitExprLiteralRecord(this)}accept(e){return e.visitExprLiteralRecord?e.visitExprLiteralRecord(this):e.visitChildren(this)}}w.ExprLiteralRecordContext=Zce;class efe extends Te{fieldExpr(){return this.getRuleContext(0,Te)}fieldProperties(){return this.getRuleContext(0,Jk)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprFieldProps&&e.enterExprFieldProps(this)}exitRule(e){e.exitExprFieldProps&&e.exitExprFieldProps(this)}accept(e){return e.visitExprFieldProps?e.visitExprFieldProps(this):e.visitChildren(this)}}w.ExprFieldPropsContext=efe;class tfe extends Te{fieldExpr(){return this.getRuleContext(0,Te)}timeframe(){return this.getRuleContext(0,ad)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprDuration&&e.enterExprDuration(this)}exitRule(e){e.exitExprDuration&&e.exitExprDuration(this)}accept(e){return e.visitExprDuration?e.visitExprDuration(this):e.visitChildren(this)}}w.ExprDurationContext=tfe;class nfe extends Te{fieldExpr(){return this.getRuleContext(0,Te)}DOT(){return this.getToken(d.DOT,0)}timeframe(){return this.getRuleContext(0,ad)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprTimeTrunc&&e.enterExprTimeTrunc(this)}exitRule(e){e.exitExprTimeTrunc&&e.exitExprTimeTrunc(this)}accept(e){return e.visitExprTimeTrunc?e.visitExprTimeTrunc(this):e.visitChildren(this)}}w.ExprTimeTruncContext=nfe;class CM extends Te{fieldExpr(){return this.getRuleContext(0,Te)}DOUBLECOLON(){return this.tryGetToken(d.DOUBLECOLON,0)}malloyOrSQLType(){return this.getRuleContext(0,fR)}CAST(){return this.tryGetToken(d.CAST,0)}OPAREN(){return this.tryGetToken(d.OPAREN,0)}AS(){return this.tryGetToken(d.AS,0)}CPAREN(){return this.tryGetToken(d.CPAREN,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprCast&&e.enterExprCast(this)}exitRule(e){e.exitExprCast&&e.exitExprCast(this)}accept(e){return e.visitExprCast?e.visitExprCast(this):e.visitChildren(this)}}w.ExprCastContext=CM;class rfe extends Te{fieldExpr(){return this.getRuleContext(0,Te)}TRIPLECOLON(){return this.getToken(d.TRIPLECOLON,0)}malloyOrSQLType(){return this.getRuleContext(0,fR)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprSafeCast&&e.enterExprSafeCast(this)}exitRule(e){e.exitExprSafeCast&&e.exitExprSafeCast(this)}accept(e){return e.visitExprSafeCast?e.visitExprSafeCast(this):e.visitChildren(this)}}w.ExprSafeCastContext=rfe;class ife extends Te{MINUS(){return this.getToken(d.MINUS,0)}fieldExpr(){return this.getRuleContext(0,Te)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprMinus&&e.enterExprMinus(this)}exitRule(e){e.exitExprMinus&&e.exitExprMinus(this)}accept(e){return e.visitExprMinus?e.visitExprMinus(this):e.visitChildren(this)}}w.ExprMinusContext=ife;class sfe extends Te{fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}STAR(){return this.tryGetToken(d.STAR,0)}SLASH(){return this.tryGetToken(d.SLASH,0)}PERCENT(){return this.tryGetToken(d.PERCENT,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprMulDiv&&e.enterExprMulDiv(this)}exitRule(e){e.exitExprMulDiv&&e.exitExprMulDiv(this)}accept(e){return e.visitExprMulDiv?e.visitExprMulDiv(this):e.visitChildren(this)}}w.ExprMulDivContext=sfe;class ofe extends Te{fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}PLUS(){return this.tryGetToken(d.PLUS,0)}MINUS(){return this.tryGetToken(d.MINUS,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprAddSub&&e.enterExprAddSub(this)}exitRule(e){e.exitExprAddSub&&e.exitExprAddSub(this)}accept(e){return e.visitExprAddSub?e.visitExprAddSub(this):e.visitChildren(this)}}w.ExprAddSubContext=ofe;class ufe extends Te{fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}TO(){return this.getToken(d.TO,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprRange&&e.enterExprRange(this)}exitRule(e){e.exitExprRange&&e.exitExprRange(this)}accept(e){return e.visitExprRange?e.visitExprRange(this):e.visitChildren(this)}}w.ExprRangeContext=ufe;class afe extends Te{FOR(){return this.getToken(d.FOR,0)}timeframe(){return this.getRuleContext(0,ad)}fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprForRange&&e.enterExprForRange(this)}exitRule(e){e.exitExprForRange&&e.exitExprForRange(this)}accept(e){return e.visitExprForRange?e.visitExprForRange(this):e.visitChildren(this)}}w.ExprForRangeContext=afe;class lfe extends Te{fieldExpr(){return this.getRuleContext(0,Te)}AMPER(){return this.getToken(d.AMPER,0)}partialAllowedFieldExpr(){return this.getRuleContext(0,ld)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprAndTree&&e.enterExprAndTree(this)}exitRule(e){e.exitExprAndTree&&e.exitExprAndTree(this)}accept(e){return e.visitExprAndTree?e.visitExprAndTree(this):e.visitChildren(this)}}w.ExprAndTreeContext=lfe;class cfe extends Te{fieldExpr(){return this.getRuleContext(0,Te)}BAR(){return this.getToken(d.BAR,0)}partialAllowedFieldExpr(){return this.getRuleContext(0,ld)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprOrTree&&e.enterExprOrTree(this)}exitRule(e){e.exitExprOrTree&&e.exitExprOrTree(this)}accept(e){return e.visitExprOrTree?e.visitExprOrTree(this):e.visitChildren(this)}}w.ExprOrTreeContext=cfe;class ffe extends Te{fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}compareOp(){return this.getRuleContext(0,lR)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprCompare&&e.enterExprCompare(this)}exitRule(e){e.exitExprCompare&&e.exitExprCompare(this)}accept(e){return e.visitExprCompare?e.visitExprCompare(this):e.visitChildren(this)}}w.ExprCompareContext=ffe;class xfe extends Te{fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}LIKE(){return this.getToken(d.LIKE,0)}NOT(){return this.tryGetToken(d.NOT,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprWarnLike&&e.enterExprWarnLike(this)}exitRule(e){e.exitExprWarnLike&&e.exitExprWarnLike(this)}accept(e){return e.visitExprWarnLike?e.visitExprWarnLike(this):e.visitChildren(this)}}w.ExprWarnLikeContext=xfe;class dfe extends Te{fieldExpr(){return this.getRuleContext(0,Te)}IS(){return this.getToken(d.IS,0)}NULL(){return this.getToken(d.NULL,0)}NOT(){return this.tryGetToken(d.NOT,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprNullCheck&&e.enterExprNullCheck(this)}exitRule(e){e.exitExprNullCheck&&e.exitExprNullCheck(this)}accept(e){return e.visitExprNullCheck?e.visitExprNullCheck(this):e.visitChildren(this)}}w.ExprNullCheckContext=dfe;class hfe extends Te{fieldExpr(){return this.getRuleContext(0,Te)}IN(){return this.getToken(d.IN,0)}OPAREN(){return this.getToken(d.OPAREN,0)}fieldExprList(){return this.getRuleContext(0,TM)}CPAREN(){return this.getToken(d.CPAREN,0)}NOT(){return this.tryGetToken(d.NOT,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprWarnIn&&e.enterExprWarnIn(this)}exitRule(e){e.exitExprWarnIn&&e.exitExprWarnIn(this)}accept(e){return e.visitExprWarnIn?e.visitExprWarnIn(this):e.visitChildren(this)}}w.ExprWarnInContext=hfe;class pfe extends Te{fieldExpr(){return this.getRuleContext(0,Te)}QMARK(){return this.getToken(d.QMARK,0)}partialAllowedFieldExpr(){return this.getRuleContext(0,ld)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprApply&&e.enterExprApply(this)}exitRule(e){e.exitExprApply&&e.exitExprApply(this)}accept(e){return e.visitExprApply?e.visitExprApply(this):e.visitChildren(this)}}w.ExprApplyContext=pfe;class mfe extends Te{NOT(){return this.getToken(d.NOT,0)}fieldExpr(){return this.getRuleContext(0,Te)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprNot&&e.enterExprNot(this)}exitRule(e){e.exitExprNot&&e.exitExprNot(this)}accept(e){return e.visitExprNot?e.visitExprNot(this):e.visitChildren(this)}}w.ExprNotContext=mfe;class gfe extends Te{fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}AND(){return this.getToken(d.AND,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprLogicalAnd&&e.enterExprLogicalAnd(this)}exitRule(e){e.exitExprLogicalAnd&&e.exitExprLogicalAnd(this)}accept(e){return e.visitExprLogicalAnd?e.visitExprLogicalAnd(this):e.visitChildren(this)}}w.ExprLogicalAndContext=gfe;class yfe extends Te{fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}OR(){return this.getToken(d.OR,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprLogicalOr&&e.enterExprLogicalOr(this)}exitRule(e){e.exitExprLogicalOr&&e.exitExprLogicalOr(this)}accept(e){return e.visitExprLogicalOr?e.visitExprLogicalOr(this):e.visitChildren(this)}}w.ExprLogicalOrContext=yfe;class Efe extends Te{fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}DOUBLE_QMARK(){return this.getToken(d.DOUBLE_QMARK,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprCoalesce&&e.enterExprCoalesce(this)}exitRule(e){e.exitExprCoalesce&&e.exitExprCoalesce(this)}accept(e){return e.visitExprCoalesce?e.visitExprCoalesce(this):e.visitChildren(this)}}w.ExprCoalesceContext=Efe;class Afe extends Te{aggregate(){return this.getRuleContext(0,dE)}OPAREN(){return this.getToken(d.OPAREN,0)}CPAREN(){return this.getToken(d.CPAREN,0)}SOURCE_KW(){return this.tryGetToken(d.SOURCE_KW,0)}DOT(){return this.tryGetToken(d.DOT,0)}fieldExpr(){return this.tryGetRuleContext(0,Te)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprPathlessAggregate&&e.enterExprPathlessAggregate(this)}exitRule(e){e.exitExprPathlessAggregate&&e.exitExprPathlessAggregate(this)}accept(e){return e.visitExprPathlessAggregate?e.visitExprPathlessAggregate(this):e.visitChildren(this)}}w.ExprPathlessAggregateContext=Afe;class _fe extends Te{fieldPath(){return this.getRuleContext(0,Na)}DOT(){return this.getToken(d.DOT,0)}aggregate(){return this.getRuleContext(0,dE)}OPAREN(){return this.getToken(d.OPAREN,0)}CPAREN(){return this.getToken(d.CPAREN,0)}fieldExpr(){return this.tryGetRuleContext(0,Te)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprAggregate&&e.enterExprAggregate(this)}exitRule(e){e.exitExprAggregate&&e.exitExprAggregate(this)}accept(e){return e.visitExprAggregate?e.visitExprAggregate(this):e.visitChildren(this)}}w.ExprAggregateContext=_fe;class vfe extends Te{OPAREN(){return this.getToken(d.OPAREN,0)}fieldExpr(){return this.getRuleContext(0,Te)}CPAREN(){return this.getToken(d.CPAREN,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprExpr&&e.enterExprExpr(this)}exitRule(e){e.exitExprExpr&&e.exitExprExpr(this)}accept(e){return e.visitExprExpr?e.visitExprExpr(this):e.visitChildren(this)}}w.ExprExprContext=vfe;class Cfe extends Te{fieldPath(){return this.getRuleContext(0,Na)}DOT(){return this.getToken(d.DOT,0)}id(){return this.getRuleContext(0,Dn)}OPAREN(){return this.getToken(d.OPAREN,0)}CPAREN(){return this.getToken(d.CPAREN,0)}argumentList(){return this.tryGetRuleContext(0,hR)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprAggFunc&&e.enterExprAggFunc(this)}exitRule(e){e.exitExprAggFunc&&e.exitExprAggFunc(this)}accept(e){return e.visitExprAggFunc?e.visitExprAggFunc(this):e.visitChildren(this)}}w.ExprAggFuncContext=Cfe;class Sfe extends Te{OPAREN(){return this.getToken(d.OPAREN,0)}CPAREN(){return this.getToken(d.CPAREN,0)}timeframe(){return this.tryGetRuleContext(0,ad)}id(){return this.tryGetRuleContext(0,Dn)}argumentList(){return this.tryGetRuleContext(0,hR)}EXCLAM(){return this.tryGetToken(d.EXCLAM,0)}malloyType(){return this.tryGetRuleContext(0,hE)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprFunc&&e.enterExprFunc(this)}exitRule(e){e.exitExprFunc&&e.exitExprFunc(this)}accept(e){return e.visitExprFunc?e.visitExprFunc(this):e.visitChildren(this)}}w.ExprFuncContext=Sfe;class bfe extends Te{pickStatement(){return this.getRuleContext(0,RM)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprPick&&e.enterExprPick(this)}exitRule(e){e.exitExprPick&&e.exitExprPick(this)}accept(e){return e.visitExprPick?e.visitExprPick(this):e.visitChildren(this)}}w.ExprPickContext=bfe;class Tfe extends Te{caseStatement(){return this.getRuleContext(0,DM)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprCase&&e.enterExprCase(this)}exitRule(e){e.exitExprCase&&e.exitExprCase(this)}accept(e){return e.visitExprCase?e.visitExprCase(this):e.visitChildren(this)}}w.ExprCaseContext=Tfe;class Rfe extends Te{ungroup(){return this.getRuleContext(0,vM)}OPAREN(){return this.getToken(d.OPAREN,0)}fieldExpr(){return this.getRuleContext(0,Te)}CPAREN(){return this.getToken(d.CPAREN,0)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}fieldName(e){return e===void 0?this.getRuleContexts(Ur):this.getRuleContext(e,Ur)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprUngroup&&e.enterExprUngroup(this)}exitRule(e){e.exitExprUngroup&&e.exitExprUngroup(this)}accept(e){return e.visitExprUngroup?e.visitExprUngroup(this):e.visitChildren(this)}}w.ExprUngroupContext=Rfe;class SM extends pe.ParserRuleContext{compareOp(){return this.getRuleContext(0,lR)}fieldExpr(){return this.getRuleContext(0,Te)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_partialCompare}enterRule(e){e.enterPartialCompare&&e.enterPartialCompare(this)}exitRule(e){e.exitPartialCompare&&e.exitPartialCompare(this)}accept(e){return e.visitPartialCompare?e.visitPartialCompare(this):e.visitChildren(this)}}w.PartialCompareContext=SM;class bM extends pe.ParserRuleContext{partialCompare(){return this.tryGetRuleContext(0,SM)}IS(){return this.tryGetToken(d.IS,0)}NULL(){return this.tryGetToken(d.NULL,0)}NOT(){return this.tryGetToken(d.NOT,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_partialTest}enterRule(e){e.enterPartialTest&&e.enterPartialTest(this)}exitRule(e){e.exitPartialTest&&e.exitPartialTest(this)}accept(e){return e.visitPartialTest?e.visitPartialTest(this):e.visitChildren(this)}}w.PartialTestContext=bM;class ld extends pe.ParserRuleContext{partialTest(){return this.tryGetRuleContext(0,bM)}OPAREN(){return this.tryGetToken(d.OPAREN,0)}CPAREN(){return this.tryGetToken(d.CPAREN,0)}fieldExpr(){return this.tryGetRuleContext(0,Te)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_partialAllowedFieldExpr}enterRule(e){e.enterPartialAllowedFieldExpr&&e.enterPartialAllowedFieldExpr(this)}exitRule(e){e.exitPartialAllowedFieldExpr&&e.exitPartialAllowedFieldExpr(this)}accept(e){return e.visitPartialAllowedFieldExpr?e.visitPartialAllowedFieldExpr(this):e.visitChildren(this)}}w.PartialAllowedFieldExprContext=ld;class TM extends pe.ParserRuleContext{fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_fieldExprList}enterRule(e){e.enterFieldExprList&&e.enterFieldExprList(this)}exitRule(e){e.exitFieldExprList&&e.exitFieldExprList(this)}accept(e){return e.visitFieldExprList?e.visitFieldExprList(this):e.visitChildren(this)}}w.FieldExprListContext=TM;class RM extends pe.ParserRuleContext{pick(e){return e===void 0?this.getRuleContexts(xR):this.getRuleContext(e,xR)}ELSE(){return this.tryGetToken(d.ELSE,0)}fieldExpr(){return this.tryGetRuleContext(0,Te)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_pickStatement}enterRule(e){e.enterPickStatement&&e.enterPickStatement(this)}exitRule(e){e.exitPickStatement&&e.exitPickStatement(this)}accept(e){return e.visitPickStatement?e.visitPickStatement(this):e.visitChildren(this)}}w.PickStatementContext=RM;class xR extends pe.ParserRuleContext{PICK(){return this.getToken(d.PICK,0)}WHEN(){return this.getToken(d.WHEN,0)}partialAllowedFieldExpr(){return this.getRuleContext(0,ld)}fieldExpr(){return this.tryGetRuleContext(0,Te)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_pick}enterRule(e){e.enterPick&&e.enterPick(this)}exitRule(e){e.exitPick&&e.exitPick(this)}accept(e){return e.visitPick?e.visitPick(this):e.visitChildren(this)}}w.PickContext=xR;class DM extends pe.ParserRuleContext{CASE(){return this.getToken(d.CASE,0)}END(){return this.getToken(d.END,0)}caseWhen(e){return e===void 0?this.getRuleContexts(dR):this.getRuleContext(e,dR)}ELSE(){return this.tryGetToken(d.ELSE,0)}fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_caseStatement}enterRule(e){e.enterCaseStatement&&e.enterCaseStatement(this)}exitRule(e){e.exitCaseStatement&&e.exitCaseStatement(this)}accept(e){return e.visitCaseStatement?e.visitCaseStatement(this):e.visitChildren(this)}}w.CaseStatementContext=DM;class dR extends pe.ParserRuleContext{WHEN(){return this.getToken(d.WHEN,0)}THEN(){return this.getToken(d.THEN,0)}fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_caseWhen}enterRule(e){e.enterCaseWhen&&e.enterCaseWhen(this)}exitRule(e){e.exitCaseWhen&&e.exitCaseWhen(this)}accept(e){return e.visitCaseWhen?e.visitCaseWhen(this):e.visitChildren(this)}}w.CaseWhenContext=dR;class OM extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_recordKey}enterRule(e){e.enterRecordKey&&e.enterRecordKey(this)}exitRule(e){e.exitRecordKey&&e.exitRecordKey(this)}accept(e){return e.visitRecordKey?e.visitRecordKey(this):e.visitChildren(this)}}w.RecordKeyContext=OM;class S2 extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_recordElement}copyFrom(e){super.copyFrom(e)}}w.RecordElementContext=S2;class Dfe extends S2{fieldPath(){return this.getRuleContext(0,Na)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterRecordRef&&e.enterRecordRef(this)}exitRule(e){e.exitRecordRef&&e.exitRecordRef(this)}accept(e){return e.visitRecordRef?e.visitRecordRef(this):e.visitChildren(this)}}w.RecordRefContext=Dfe;class Ofe extends S2{fieldExpr(){return this.getRuleContext(0,Te)}recordKey(){return this.tryGetRuleContext(0,OM)}IS(){return this.tryGetToken(d.IS,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterRecordExpr&&e.enterRecordExpr(this)}exitRule(e){e.exitRecordExpr&&e.exitRecordExpr(this)}accept(e){return e.visitRecordExpr?e.visitRecordExpr(this):e.visitChildren(this)}}w.RecordExprContext=Ofe;class hR extends pe.ParserRuleContext{fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_argumentList}enterRule(e){e.enterArgumentList&&e.enterArgumentList(this)}exitRule(e){e.exitArgumentList&&e.exitArgumentList(this)}accept(e){return e.visitArgumentList?e.visitArgumentList(this):e.visitChildren(this)}}w.ArgumentListContext=hR;class b2 extends pe.ParserRuleContext{fieldName(e){return e===void 0?this.getRuleContexts(Ur):this.getRuleContext(e,Ur)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_fieldNameList}enterRule(e){e.enterFieldNameList&&e.enterFieldNameList(this)}exitRule(e){e.exitFieldNameList&&e.exitFieldNameList(this)}accept(e){return e.visitFieldNameList?e.visitFieldNameList(this):e.visitChildren(this)}}w.FieldNameListContext=b2;class FM extends pe.ParserRuleContext{collectionMember(e){return e===void 0?this.getRuleContexts(gR):this.getRuleContext(e,gR)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_fieldCollection}enterRule(e){e.enterFieldCollection&&e.enterFieldCollection(this)}exitRule(e){e.exitFieldCollection&&e.exitFieldCollection(this)}accept(e){return e.visitFieldCollection?e.visitFieldCollection(this):e.visitChildren(this)}}w.FieldCollectionContext=FM;class pE extends pe.ParserRuleContext{STAR(){return this.getToken(d.STAR,0)}fieldPath(){return this.tryGetRuleContext(0,Na)}DOT(){return this.tryGetToken(d.DOT,0)}starQualified(){return this.tryGetRuleContext(0,pR)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_collectionWildCard}enterRule(e){e.enterCollectionWildCard&&e.enterCollectionWildCard(this)}exitRule(e){e.exitCollectionWildCard&&e.exitCollectionWildCard(this)}accept(e){return e.visitCollectionWildCard?e.visitCollectionWildCard(this):e.visitChildren(this)}}w.CollectionWildCardContext=pE;class pR extends pe.ParserRuleContext{OCURLY(){return this.getToken(d.OCURLY,0)}CCURLY(){return this.getToken(d.CCURLY,0)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}EXCEPT(e){return e===void 0?this.getTokens(d.EXCEPT):this.getToken(d.EXCEPT,e)}fieldNameList(e){return e===void 0?this.getRuleContexts(b2):this.getRuleContext(e,b2)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_starQualified}enterRule(e){e.enterStarQualified&&e.enterStarQualified(this)}exitRule(e){e.exitStarQualified&&e.exitStarQualified(this)}accept(e){return e.visitStarQualified?e.visitStarQualified(this):e.visitChildren(this)}}w.StarQualifiedContext=pR;class mR extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}fieldPath(){return this.getRuleContext(0,Na)}refExpr(){return this.tryGetRuleContext(0,wM)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_taggedRef}enterRule(e){e.enterTaggedRef&&e.enterTaggedRef(this)}exitRule(e){e.exitTaggedRef&&e.exitTaggedRef(this)}accept(e){return e.visitTaggedRef?e.visitTaggedRef(this):e.visitChildren(this)}}w.TaggedRefContext=mR;class wM extends pe.ParserRuleContext{DOT(){return this.getToken(d.DOT,0)}timeframe(){return this.tryGetRuleContext(0,ad)}aggregate(){return this.tryGetRuleContext(0,dE)}OPAREN(){return this.tryGetToken(d.OPAREN,0)}CPAREN(){return this.tryGetToken(d.CPAREN,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_refExpr}enterRule(e){e.enterRefExpr&&e.enterRefExpr(this)}exitRule(e){e.exitRefExpr&&e.exitRefExpr(this)}accept(e){return e.visitRefExpr?e.visitRefExpr(this):e.visitChildren(this)}}w.RefExprContext=wM;class gR extends pe.ParserRuleContext{taggedRef(){return this.tryGetRuleContext(0,mR)}collectionWildCard(){return this.tryGetRuleContext(0,pE)}fieldDef(){return this.tryGetRuleContext(0,v2)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_collectionMember}enterRule(e){e.enterCollectionMember&&e.enterCollectionMember(this)}exitRule(e){e.exitCollectionMember&&e.exitCollectionMember(this)}accept(e){return e.visitCollectionMember?e.visitCollectionMember(this):e.visitChildren(this)}}w.CollectionMemberContext=gR;class Na extends pe.ParserRuleContext{fieldName(e){return e===void 0?this.getRuleContexts(Ur):this.getRuleContext(e,Ur)}DOT(e){return e===void 0?this.getTokens(d.DOT):this.getToken(d.DOT,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_fieldPath}enterRule(e){e.enterFieldPath&&e.enterFieldPath(this)}exitRule(e){e.exitFieldPath&&e.exitFieldPath(this)}accept(e){return e.visitFieldPath?e.visitFieldPath(this):e.visitChildren(this)}}w.FieldPathContext=Na;class Ffe extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_joinName}enterRule(e){e.enterJoinName&&e.enterJoinName(this)}exitRule(e){e.exitJoinName&&e.exitJoinName(this)}accept(e){return e.visitJoinName?e.visitJoinName(this):e.visitChildren(this)}}w.JoinNameContext=Ffe;class Ur extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_fieldName}enterRule(e){e.enterFieldName&&e.enterFieldName(this)}exitRule(e){e.exitFieldName&&e.exitFieldName(this)}accept(e){return e.visitFieldName?e.visitFieldName(this):e.visitChildren(this)}}w.FieldNameContext=Ur;class wfe extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sqlExploreNameRef}enterRule(e){e.enterSqlExploreNameRef&&e.enterSqlExploreNameRef(this)}exitRule(e){e.exitSqlExploreNameRef&&e.exitSqlExploreNameRef(this)}accept(e){return e.visitSqlExploreNameRef?e.visitSqlExploreNameRef(this):e.visitChildren(this)}}w.SqlExploreNameRefContext=wfe;class Nfe extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_nameSQLBlock}enterRule(e){e.enterNameSQLBlock&&e.enterNameSQLBlock(this)}exitRule(e){e.exitNameSQLBlock&&e.exitNameSQLBlock(this)}accept(e){return e.visitNameSQLBlock?e.visitNameSQLBlock(this):e.visitChildren(this)}}w.NameSQLBlockContext=Nfe;class Lfe extends pe.ParserRuleContext{string(){return this.getRuleContext(0,Fa)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_connectionName}enterRule(e){e.enterConnectionName&&e.enterConnectionName(this)}exitRule(e){e.exitConnectionName&&e.exitConnectionName(this)}accept(e){return e.visitConnectionName?e.visitConnectionName(this):e.visitChildren(this)}}w.ConnectionNameContext=Lfe;class NM extends pe.ParserRuleContext{SQ3_FILTER(){return this.tryGetToken(d.SQ3_FILTER,0)}BQ3_FILTER(){return this.tryGetToken(d.BQ3_FILTER,0)}DQ3_FILTER(){return this.tryGetToken(d.DQ3_FILTER,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_tripFilterString}enterRule(e){e.enterTripFilterString&&e.enterTripFilterString(this)}exitRule(e){e.exitTripFilterString&&e.exitTripFilterString(this)}accept(e){return e.visitTripFilterString?e.visitTripFilterString(this):e.visitChildren(this)}}w.TripFilterStringContext=NM;class LM extends pe.ParserRuleContext{SQ_FILTER(){return this.tryGetToken(d.SQ_FILTER,0)}BQ_FILTER(){return this.tryGetToken(d.BQ_FILTER,0)}DQ_FILTER(){return this.tryGetToken(d.DQ_FILTER,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_tickFilterString}enterRule(e){e.enterTickFilterString&&e.enterTickFilterString(this)}exitRule(e){e.exitTickFilterString&&e.exitTickFilterString(this)}accept(e){return e.visitTickFilterString?e.visitTickFilterString(this):e.visitChildren(this)}}w.TickFilterStringContext=LM;class IM extends pe.ParserRuleContext{tripFilterString(){return this.tryGetRuleContext(0,NM)}tickFilterString(){return this.tryGetRuleContext(0,LM)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_filterString}enterRule(e){e.enterFilterString&&e.enterFilterString(this)}exitRule(e){e.exitFilterString&&e.exitFilterString(this)}accept(e){return e.visitFilterString?e.visitFilterString(this):e.visitChildren(this)}}w.FilterStringContext=IM;class Ife extends pe.ParserRuleContext{fieldExpr(){return this.getRuleContext(0,Te)}EOF(){return this.getToken(d.EOF,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_debugExpr}enterRule(e){e.enterDebugExpr&&e.enterDebugExpr(this)}exitRule(e){e.exitDebugExpr&&e.exitDebugExpr(this)}accept(e){return e.visitDebugExpr?e.visitDebugExpr(this):e.visitChildren(this)}}w.DebugExprContext=Ife;class Bfe extends pe.ParserRuleContext{partialAllowedFieldExpr(){return this.getRuleContext(0,ld)}EOF(){return this.getToken(d.EOF,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_debugPartial}enterRule(e){e.enterDebugPartial&&e.enterDebugPartial(this)}exitRule(e){e.exitDebugPartial&&e.exitDebugPartial(this)}accept(e){return e.visitDebugPartial?e.visitDebugPartial(this):e.visitChildren(this)}}w.DebugPartialContext=Bfe;class BM extends pe.ParserRuleContext{SEMI(e){return e===void 0?this.getTokens(d.SEMI):this.getToken(d.SEMI,e)}OBRACK(){return this.getToken(d.OBRACK,0)}string(){return this.getRuleContext(0,Fa)}CBRACK(){return this.getToken(d.CBRACK,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_experimentalStatementForTesting}enterRule(e){e.enterExperimentalStatementForTesting&&e.enterExperimentalStatementForTesting(this)}exitRule(e){e.exitExperimentalStatementForTesting&&e.exitExperimentalStatementForTesting(this)}accept(e){return e.visitExperimentalStatementForTesting?e.visitExperimentalStatementForTesting(this):e.visitChildren(this)}}w.ExperimentalStatementForTestingContext=BM;var yR={};Object.defineProperty(yR,"__esModule",{value:!0}),yR.MalloyErrorStrategy=void 0;const cft=py;class fft extends cft.DefaultErrorStrategy{}yR.MalloyErrorStrategy=fft;var $fe={},ER={},kfe={exports:{}};(function(t,e){(function(r){function i(o,u){for(var a in u)u.hasOwnProperty(a)&&(o[a]=u[a]);return o}function s(o,u,a){var l=0,c={caseSensitive:!0},f=i(c,a),x,h;if(o.length===0||u.length===0)return 0;if(f.caseSensitive||(o=o.toUpperCase(),u=u.toUpperCase()),o===u)return 1;var p=Math.floor(Math.max(o.length,u.length)/2)-1,m=new Array(o.length),g=new Array(u.length);for(x=0;x<o.length;x++){var y=x>=p?x-p:0,E=x+p<=u.length-1?x+p:u.length-1;for(h=y;h<=E;h++)if(m[x]!==!0&&g[h]!==!0&&o[x]===u[h]){++l,m[x]=g[h]=!0;break}}if(l===0)return 0;var A=0,_=0;for(x=0;x<o.length;x++)if(m[x]===!0){for(h=A;h<u.length;h++)if(g[h]===!0){A=h+1;break}o[x]!==u[h]&&++_}var v=(l/o.length+l/u.length+(l-_/2)/l)/3,C=0,b=.1;if(v>.7){for(;o[C]===u[C]&&C<4;)++C;v=v+C*b*(1-v)}return v}t.exports=s})()})(kfe);var xft=kfe.exports,dft=T&&T.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ER,"__esModule",{value:!0}),ER.checkCustomErrorMessage=void 0;const Mfe=dft(xft),hft=(t,e,r)=>{var i,s;const o=t.getRuleInvocationStack()[0],u=t.currentToken;for(const a of r){const l=!a.currentToken||u.type===a.currentToken,c=!a.offendingSymbol||(e==null?void 0:e.type)===a.offendingSymbol,f=!a.ruleContextOptions||a.ruleContextOptions.includes(o),x=!a.offendingSymbolTextOptions||a.offendingSymbolTextOptions.includes(((i=e==null?void 0:e.text)===null||i===void 0?void 0:i.toLowerCase())||"");if(l&&c&&f&&x){if(a.lookbackSiblingRuleOptions){const m=t.ruleContext.children;if(!m)continue;const g=m[m.length-1];if(!a.lookbackSiblingRuleOptions.includes(g.ruleIndex))continue}if(a.precedingTokenOptions&&!a.precedingTokenOptions.some(g=>Ufe(t,g,"lookback",e==null?void 0:e.tokenIndex))||a.lookAheadOptions&&!a.lookAheadOptions.some(g=>Ufe(t,g,"lookahead",e==null?void 0:e.tokenIndex)))continue;if(a.predecessorHasAncestorRule){const m=(s=t.ruleContext.children)===null||s===void 0?void 0:s[0];if(!m||!Pfe(m,a.predecessorHasAncestorRule))continue}const h=m=>{const g=m.replace("${currentToken}",u.text||"").replace("${offendingSymbol}",(e==null?void 0:e.text)||"");try{const y=t.inputStream.LT(-1);return g.replace("${previousToken}",y.text||"")}catch{}return g};let p=h(a.errorMessage);if(a.alternatives){const m=h(a.alternatives.replace);let g=a.alternatives.with[0],y=(0,Mfe.default)(g,m);for(const E of a.alternatives.with.slice(1)){const A=(0,Mfe.default)(E,m);A>y&&(y=A,g=E)}p+=` Did you mean '${g}'?`}return p}}return""};ER.checkCustomErrorMessage=hft;const Pfe=(t,e,r=20)=>{var i;if(t.ruleIndex===e)return!0;if(r<=0)return!1;const s=((i=t.children)===null||i===void 0?void 0:i.length)||0;if(t.children&&s>0){const o=t.children[t.children.length-1];return Pfe(o,e,r-1)}return!1},Ufe=(t,e,r,i)=>{var s;try{for(let o=0;o<e.length;o++){let u;if(typeof i=="number"){const a=r==="lookahead"?o+1:-1*(o+1);u=t.inputStream.get(i+a)}else{const a=r==="lookahead"?o+2:-1*(o+1);u=t.inputStream.LT(a)}if(typeof e[o]=="number"){const a=e[o];if(a>=-1&&u.type!==a||a<-1&&u.type===-1*a)return!1}else if(typeof e[o]=="string"&&e[o]!==((s=u.text)===null||s===void 0?void 0:s.toLowerCase()))return!1}return!0}catch{return!1}};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.MalloyParserErrorListener=t.malloyCustomErrorCases=void 0;const e=w,r=ER,i=Yp,s=Vn;t.malloyCustomErrorCases=[{errorMessage:"'view:' must be followed by '<identifier> is {'",ruleContextOptions:["exploreQueryDef"],offendingSymbol:e.MalloyParser.OCURLY,precedingTokenOptions:[[e.MalloyParser.VIEW],[e.MalloyParser.COLON]]},{errorMessage:"Missing '}' at '${offendingSymbol}'",ruleContextOptions:["vExpr"],offendingSymbol:e.MalloyParser.VIEW,currentToken:e.MalloyParser.OCURLY},{errorMessage:"Missing '}' at '${currentToken}'",ruleContextOptions:["exploreProperties","queryProperties","exploreStatement"],offendingSymbolTextOptions:["<eof>","run:","source:"]},{errorMessage:"'aggregate:' entries must include a name (ex: `some_name is count()`)",precedingTokenOptions:[[e.MalloyParser.AGGREGATE]],lookAheadOptions:[[-e.MalloyParser.IS]]},{errorMessage:"Expected ':' following 'source'",offendingSymbol:e.MalloyParser.SOURCE_KW,ruleContextOptions:["malloyDocument"]},{errorMessage:"Expected ':' following '${offendingSymbol}'",offendingSymbolTextOptions:["dimension","measure","where","declare","join_one","join_many","join_cross","primary_key"],ruleContextOptions:["exploreStatement"]},{errorMessage:"Expected 'is' or '(' following identifier '${previousToken}'",ruleContextOptions:["sourceDefinition"],lookbackSiblingRuleOptions:[e.MalloyParser.RULE_sourceNameDef,e.MalloyParser.RULE_sourceParameters]},{errorMessage:"Unexpected '{' following source expression. Expected: 'extend', 'include', '+' or '->'",offendingSymbol:e.MalloyParser.OCURLY,ruleContextOptions:["malloyDocument"],predecessorHasAncestorRule:e.MalloyParser.RULE_sqExplore},{errorMessage:"Unexpected 'join:'. Did you mean 'join_one:', 'join_many:' or 'join_cross:'?",ruleContextOptions:["exploreStatement"],offendingSymbolTextOptions:["join"],lookAheadOptions:[[e.MalloyParser.COLON]]},{errorMessage:"Unexpected '${offendingSymbol}'. Did you mean 'primary_key:'?",ruleContextOptions:["exploreStatement"],offendingSymbolTextOptions:["primarykey","primary"],lookAheadOptions:[[e.MalloyParser.COLON],["key",e.MalloyParser.COLON],["key",e.MalloyParser.IDENTIFIER]]},{errorMessage:"Unexpected '${offendingSymbol}'. Did you mean 'group_by:'?",ruleContextOptions:["queryStatement"],offendingSymbolTextOptions:["groupby","group"],lookAheadOptions:[[e.MalloyParser.COLON],["by",e.MalloyParser.COLON],["by",e.MalloyParser.IDENTIFIER]]},{errorMessage:"Unexpected '${offendingSymbol}'. Did you mean 'order_by:'?",ruleContextOptions:["queryStatement"],offendingSymbolTextOptions:["orderby","order"],lookAheadOptions:[[e.MalloyParser.COLON],["by",e.MalloyParser.COLON],["by",e.MalloyParser.IDENTIFIER]]},{errorMessage:"Expected ':' following '${offendingSymbol}'",offendingSymbolTextOptions:["group_by","declare","join_one","join_many","join_cross","extend","select","project","index","aggregate","calculate","top","limit","order_by","where","having","nest","sample","timezone"],ruleContextOptions:["queryStatement"]},{errorMessage:"Expected a query statement, '${offendingSymbol}:' is not a keyword.",ruleContextOptions:["queryStatement"],offendingSymbol:e.MalloyParser.IDENTIFIER,lookAheadOptions:[[e.MalloyParser.COLON,e.MalloyParser.IDENTIFIER]],alternatives:{replace:"${offendingSymbol}:",with:["group_by:","select:","aggregate:","calculate:","nest:"]}},{errorMessage:"Expected a source statement, '${offendingSymbol}:' is not a keyword.",ruleContextOptions:["exploreStatement"],offendingSymbol:e.MalloyParser.IDENTIFIER,lookAheadOptions:[[e.MalloyParser.COLON,e.MalloyParser.IDENTIFIER]],alternatives:{replace:"${offendingSymbol}:",with:["dimension:","measure:","primary_key:","view:","join:"]}},{errorMessage:"Expected a statement, '${offendingSymbol}:' is not a keyword.",ruleContextOptions:["malloyDocument"],offendingSymbol:e.MalloyParser.IDENTIFIER,lookAheadOptions:[[e.MalloyParser.COLON,e.MalloyParser.IDENTIFIER]],alternatives:{replace:"${offendingSymbol}:",with:["run:","query:","source:"]}}];class o{constructor(a,l,c){this.messages=a,this.sourceURL=l,this.sourceInfo=c}logError(a,l,c){return this.messages.log((0,i.makeLogMessage)(a,l,{severity:"error",...c})),a}syntaxError(a,l,c,f,x,h){const p={line:c-1,character:f},m=l?(0,s.rangeFromToken)(this.sourceInfo,l):{start:p,end:p},g=(0,r.checkCustomErrorMessage)(a,l,t.malloyCustomErrorCases);g&&(x=g),this.logError("syntax-error",{message:x},{at:{url:this.sourceURL,range:m}})}}t.MalloyParserErrorListener=o})($fe),Object.defineProperty(aE,"__esModule",{value:!0}),aE.runMalloyParser=void 0;const jfe=py,pft=RT,mft=w,gft=yR,yft=$fe;class Eft extends pft.MalloyLexer{popMode(){return this._modeStack.isEmpty?this._mode:super.popMode()}}function Aft(t,e,r,i,s="malloyDocument"){const o=jfe.CharStreams.fromString(t),u=new Eft(o),a=new jfe.CommonTokenStream(u),l=new mft.MalloyParser(a);l.removeErrorListeners(),l.addErrorListener(new yft.MalloyParserErrorListener(i,e,r)),l.errorHandler=new gft.MalloyErrorStrategy;const c=l[s];if(!c)throw new Error(`No such parse rule as ${s}`);return{root:c.call(l),tokenStream:a,sourceStream:o,sourceInfo:r,sourceURL:e,malloyVersion:"4.0.0"}}aE.runMalloyParser=Aft;var _ft=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),vft=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Cft=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&_ft(e,t,r);return vft(e,t),e};Object.defineProperty(Tc,"__esModule",{value:!0}),Tc.MalloyTranslator=Tc.MalloyChildTranslator=Tc.MalloyTranslation=void 0;const Sft=Xe,qfe=Cft(Q4),bft=gT,Hfe=Yp,Tft=Zl,$M=ET,Rft=AT,Dft=_T,Oft=vT,Fft=CT,AR=ST,kM=Vn,wft=Zo,Nft=bT,Lft=TT,Ift=ui,Bft=aE;class $ft{step(e){if(this.response)return this.response;if(!e.urlIsFullPath)return e.fatalResponse();const r=e.root.importZone.getEntry(e.sourceURL);if(r.status!=="present"){if(r.status==="error"){const o=r.firstReference||e.defaultLocation();return e.root.logError("import-error",{message:r.message,url:e.sourceURL},{at:o}),this.response=e.fatalResponse(),this.response}return{urls:[e.sourceURL]}}const i=r.value===""?`
1462
- `:r.value;this.sourceInfo=(0,kM.getSourceInfo)(i);let s;try{s=this.runParser(i,this.sourceInfo,e)}catch(o){e.root.logError("parse-exception",{message:o.message}),s=void 0}return e.root.logger.hasErrors()?this.response={parse:s,...e.fatalResponse()}:this.response={parse:s},this.response}runParser(e,r,i){return{...(0,Bft.runMalloyParser)(e,i.sourceURL,r,i.root.logger,i.grammarRule),importBaseURL:i.importBaseURL||i.sourceURL}}}class kft{constructor(e){this.parseStep=e,this.parseReferences=void 0}step(e){var r;const i=this.parseStep.step(e);if(i.parse===void 0)return i;if(!this.parseReferences){this.parseReferences=(0,Tft.findReferences)(e,i.parse.tokenStream,i.parse.root);for(const a in this.parseReferences.tables)e.root.schemaZone.reference(a,{url:e.sourceURL,range:this.parseReferences.tables[a].firstReference});for(const a in this.parseReferences.urls){const l=this.parseReferences.urls[a];try{const c=decodeURI(new URL(a,e.importBaseURL||e.sourceURL).toString());e.addChild(c),e.imports.push({importURL:c,location:{url:e.sourceURL,range:l}}),e.root.importZone.reference(c,{url:e.sourceURL,range:l})}catch{e.root.logError("invalid-import-url",`Malformed URL '${a}'"`,{at:{url:e.sourceURL,range:l}})}}}if(e.root.logger.hasErrors())return null;let s={};const o=e.root.schemaZone.getUndefined();if(o){const a={};for(const l of o){const c=this.parseReferences.tables[l];a[l]={connectionName:c.connectionName,tablePath:c.tablePath}}s={tables:a}}const u=((r=e.root.importZone.getUndefined())!==null&&r!==void 0?r:[]).filter(a=>e.root.pretranslatedModels.get(a)===void 0);if(u.length>0&&(s={...s,urls:u}),(0,AR.isNeedResponse)(s))return s;for(const a of e.childTranslators.values()){if(e.root.pretranslatedModels.get(a.sourceURL))continue;const l=a.importsAndTablesStep.step(a);if((0,AR.isNeedResponse)(l))return l}return null}}class Mft{constructor(e){this.importStep=e,this.walked=!1}step(e){if(this.response)return this.response;const r=this.importStep.step(e);if(r)return r;const i=e.parseStep.response;if(e.root.logger.hasErrors())return this.response=e.fatalResponse(),this.response;const s=i==null?void 0:i.parse;if(!s)throw new Error("TRANSLATOR INTERNAL ERROR: Translator parse response had no errors, but also no parser");const o=new bft.MalloyToAST(s,e.root.logger,e.compilerFlags),u=o.visit(s.root);if(e.compilerFlags=o.compilerFlags,u.elementType==="unimplemented"&&u.logError("untranslated-parse-node","INTERNAL COMPILER ERROR: Untranslated parse node"),!this.walked){for(const a of u.walk())a instanceof qfe.Unimplemented&&a.logError("untranslated-parse-node","INTERNAL COMPILER ERROR: Untranslated parse node");this.walked=!0}if(e.root.logger.hasErrors())return this.response=e.fatalResponse(),this.response;for(const a of e.childTranslators.values()){if(e.root.pretranslatedModels.get(a.sourceURL))continue;const l=a.astStep.step(a);if((0,AR.isNeedResponse)(l))return l}return u.setTranslator(e),this.response={...e.problemResponse(),ast:u,final:!0},this.response}}class Pft{constructor(e){this.parseStep=e}step(e){if(!this.response){const r=this.parseStep.step(e);if(r.parse){let i;try{i=(0,Rft.walkForDocumentSymbols)(e,r.parse.tokenStream,r.parse.root)}catch{}this.response={symbols:i,final:!0}}else return r}return this.response}}class Uft{constructor(e){this.parseStep=e}step(e,r){const i=this.parseStep.step(e);if(i.parse){let s=[];if(r!==void 0)try{s=(0,Dft.walkForDocumentCompletions)(i.parse.tokenStream,i.parse.root,r)}catch{}return{...i,completions:s}}else return i}}class jft{constructor(e){this.parseStep=e}step(e,r){const i=this.parseStep.step(e);if(i.parse){let s;if(r!==void 0)try{s=(0,Oft.walkForDocumentHelpContext)(i.parse.root,r)}catch{}return{...i,helpContext:s}}else return i}}class qft{constructor(e){this.parseStep=e}step(e,r){if(!this.response){const i=this.parseStep.step(e);if(!i.parse||i.final)return i;{const s=(0,Nft.walkForModelAnnotation)(e,i.parse.tokenStream,i.parse);this.response={modelAnnotation:{...s,inherits:r==null?void 0:r.annotation}}}}return this.response}}class Hft{constructor(e){this.parseStep=e}step(e){if(!this.response){const r=this.parseStep.step(e);if(r.parse){const i=(0,Lft.walkForTablePath)(e,r.parse.tokenStream,r.parse);this.response={pathInfo:i}}else return r}return this.response}}class Qft{constructor(e){this.astStep=e,this.importedAnnotations=!1}step(e,r){if(this.response)return this.response;const i=e.root.pretranslatedModels.get(e.sourceURL);if(i!==void 0)return e.modelDef=i,{modelDef:i,final:!0,fromSources:e.getDependencies()};if(r&&!this.importedAnnotations){const o=(0,Ift.annotationToTag)(r.annotation,{prefix:/^##! /});e.compilerFlags=o.tag,this.importedAnnotations=!0}const s=this.astStep.step(e);if((0,AR.isNeedResponse)(s))return s;if(!s.ast)return this.response=s,this.response;if(e.grammarRule==="malloyDocument")if(s.ast instanceof qfe.Document){const o=s.ast;for(o.initModelDef(r);;){const u=o.compile();if(u.needs)return u.needs;e.modelDef=u.modelDef;break}}else e.root.logError("parsed-non-malloy-document",{url:e.sourceURL},{at:e.defaultLocation()});return e.root.logger.hasErrors()?this.response={fromSources:e.getDependencies(),...e.fatalResponse()}:this.response={modelDef:{...e.modelDef,dependencies:e.getDependencyTree()},fromSources:e.getDependencies(),...e.problemResponse(),final:!0},this.response}}class MM{constructor(e,r=null,i="malloyDocument"){this.sourceURL=e,this.importBaseURL=r,this.grammarRule=i,this.sqlSources=[],this.imports=[],this.compilerFlags=new wft.Tag,this._urlIsFullPath=void 0,this.dialectAlreadyChecked={},this.allDialectsEnabled=!1,this.childTranslators=new Map,this.modelDef={name:e,exports:[],contents:{},queryList:[],dependencies:{}},this.parseStep=new $ft,this.modelAnnotationStep=new qft(this.parseStep),this.metadataStep=new Pft(this.parseStep),this.completionsStep=new Uft(this.parseStep),this.helpContextStep=new jft(this.parseStep),this.importsAndTablesStep=new kft(this.parseStep),this.astStep=new Mft(this.importsAndTablesStep),this.tablePathInfoStep=new Hft(this.parseStep),this.translateStep=new Qft(this.astStep),this.references=new Fft.ReferenceList(e)}get urlIsFullPath(){if(this._urlIsFullPath===void 0)try{const e=new URL(this.sourceURL);this._urlIsFullPath=!0}catch(e){const r=e instanceof Error?e.message:"";this._urlIsFullPath=!1,this.root.logError("failed-to-compute-absolute-import-url",`Could not compute full path URL: ${r}`)}return this._urlIsFullPath}addChild(e){this.childTranslators.get(e)||this.childTranslators.set(e,new Qfe(e,this.root))}getDependencies(){const e=this.getDependencyTree();return[this.sourceURL,...zfe(e)]}getDependencyTree(){const e=this.root.pretranslatedModels.get(this.sourceURL);if(e!==void 0)return e.dependencies;const r={};for(const[i,s]of this.childTranslators)r[i]=s.getDependencyTree();return r}newlyTranslatedDependencies(){if(this.root.pretranslatedModels.get(this.sourceURL)!==void 0)return[];const r=[];for(const[i,s]of this.childTranslators){if(this.root.pretranslatedModels.get(i)!==void 0)continue;const u=s.translate();u.modelDef&&(r.push({url:i,modelDef:u.modelDef}),r.push(...s.newlyTranslatedDependencies()))}return r}addReference(e){this.references.add(e)}referenceAt(e){return this.references.find(e)}fatalResponse(){return{final:!0,...this.problemResponse()}}problemResponse(){return{problems:this.problems()}}problems(){return[...this.root.logger.getLog()]}getLineMap(e){var r,i;if(e===this.sourceURL)return(r=this.parseStep.sourceInfo)===null||r===void 0?void 0:r.lines;const s=this.childTranslators.get(e);if(s)return(i=s.parseStep.sourceInfo)===null||i===void 0?void 0:i.lines}codeAtLocation(e){const r=this.getLineMap(e.url)||[];if(e.range.start.line===e.range.end.line)return r[e.range.start.line].slice(e.range.start.character,e.range.end.character);let i="";i+=r[e.range.start.line].slice(e.range.start.character);for(let s=e.range.start.line+1;s<e.range.end.line;s++)i+=r[s];return i+=r[e.range.end.line].slice(0,e.range.end.character),i}prettyErrors(){let e="",r="";for(const i of this.root.logger.getLog()){let s=i.message,o=this.sourceURL;if(i.at){o=i.at.url;const u=i.at.range.start.line,a=i.at.range.start.character,l=this.getLineMap(i.at.url);if(l){const c=l[u];s=`line ${u+1}: ${i.message}
1461
+ םנĔ‹מנ\x07†ןלןמנססןסעעףףפ\x07פěץצ\f\x07צרĢ’קשАרקרששĝת׫\x07‡׫ײö|׬׭\x07‡׭׮Þp׮ׯ\x07|ׯװ\x07}װײױתױ׬ײğ׳׷Ĝ״׷ʍ׵׷X-׶׳׶״׶׵׷ġ׸׽Ħ”׹׺\x07‡׺׼Ħ”׻׹׼׿׽׻׽׾׾ģ׿׽؀؁ô{؁ĥ؂؃ô{؃ħ؄؅ô{؅ĩ؆؇ô{؇ī؈؉äs؉ĭ؊؋ ؋į،؍ ؍ı؎ؑĮ˜؏ؑİ™ؐ؎ؐ؏ؑijؒؓüؓؔ\x07ؔĵؕؖÂؖؗ\x07ؗķؘؙ\x07”ؙؚ\x07”ؚ؛\x07~؛؜äs؜؝\x07؝Ĺ®ļľŊŘŧŲżƅƌƑƖƜơƥƶdžLjǑǖǚǟǮdzǻȀȄȍȏțȣȬȯȶȸȼɃɊɏɓɛɠɤɱɷɾʅʊʒʜʡʨʯʼʿ˄ˏ˖˘˞ˠ˯˷˼̵̛̥̮͇͉͕͙̀̈̌̑̽͂͐ͩͮ̕ͳͻ΀΄ΆΌΑΓΝΡΥΩδλοωώϒϙϲϼЁЅЉБЖКРжксцъюёњѢѥѩѮѵ҉ҚңұҼӀӊӜӡӪӷӾԀԃԇԔԙԪՒ՗ագլկշվքֈ֌ֵׇֹֽׂ֮֓֘֜֫׌אויןסרױ׶׽ؐ`,d._serializedATN=G0e.join([d._serializedATNSegment0,d._serializedATNSegment1,d._serializedATNSegment2],"");class W0e extends pe.ParserRuleContext{EOF(){return this.getToken(d.EOF,0)}malloyStatement(e){return e===void 0?this.getRuleContexts(DT):this.getRuleContext(e,DT)}SEMI(e){return e===void 0?this.getTokens(d.SEMI):this.getToken(d.SEMI,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_malloyDocument}enterRule(e){e.enterMalloyDocument&&e.enterMalloyDocument(this)}exitRule(e){e.exitMalloyDocument&&e.exitMalloyDocument(this)}accept(e){return e.visitMalloyDocument?e.visitMalloyDocument(this):e.visitChildren(this)}}w.MalloyDocumentContext=W0e;class DT extends pe.ParserRuleContext{defineSourceStatement(){return this.tryGetRuleContext(0,Ak)}defineQuery(){return this.tryGetRuleContext(0,OT)}importStatement(){return this.tryGetRuleContext(0,Ck)}runStatement(){return this.tryGetRuleContext(0,vk)}docAnnotations(){return this.tryGetRuleContext(0,Tk)}ignoredObjectAnnotations(){return this.tryGetRuleContext(0,Rk)}experimentalStatementForTesting(){return this.tryGetRuleContext(0,BM)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_malloyStatement}enterRule(e){e.enterMalloyStatement&&e.enterMalloyStatement(this)}exitRule(e){e.exitMalloyStatement&&e.exitMalloyStatement(this)}accept(e){return e.visitMalloyStatement?e.visitMalloyStatement(this):e.visitChildren(this)}}w.MalloyStatementContext=DT;class Ak extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}SOURCE(){return this.getToken(d.SOURCE,0)}sourcePropertyList(){return this.getRuleContext(0,Nk)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_defineSourceStatement}enterRule(e){e.enterDefineSourceStatement&&e.enterDefineSourceStatement(this)}exitRule(e){e.exitDefineSourceStatement&&e.exitDefineSourceStatement(this)}accept(e){return e.visitDefineSourceStatement?e.visitDefineSourceStatement(this):e.visitChildren(this)}}w.DefineSourceStatementContext=Ak;class OT extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_defineQuery}copyFrom(e){super.copyFrom(e)}}w.DefineQueryContext=OT;class V0e extends OT{topLevelQueryDefs(){return this.getRuleContext(0,Dk)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterUse_top_level_query_defs&&e.enterUse_top_level_query_defs(this)}exitRule(e){e.exitUse_top_level_query_defs&&e.exitUse_top_level_query_defs(this)}accept(e){return e.visitUse_top_level_query_defs?e.visitUse_top_level_query_defs(this):e.visitChildren(this)}}w.Use_top_level_query_defsContext=V0e;class _k extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}sqExpr(){return this.getRuleContext(0,un)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_topLevelAnonQueryDef}enterRule(e){e.enterTopLevelAnonQueryDef&&e.enterTopLevelAnonQueryDef(this)}exitRule(e){e.exitTopLevelAnonQueryDef&&e.exitTopLevelAnonQueryDef(this)}accept(e){return e.visitTopLevelAnonQueryDef?e.visitTopLevelAnonQueryDef(this):e.visitChildren(this)}}w.TopLevelAnonQueryDefContext=_k;class Yt extends pe.ParserRuleContext{ANNOTATION(e){return e===void 0?this.getTokens(d.ANNOTATION):this.getToken(d.ANNOTATION,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_tags}enterRule(e){e.enterTags&&e.enterTags(this)}exitRule(e){e.exitTags&&e.exitTags(this)}accept(e){return e.visitTags?e.visitTags(this):e.visitChildren(this)}}w.TagsContext=Yt;class e0 extends pe.ParserRuleContext{IS(){return this.getToken(d.IS,0)}tags(e){return e===void 0?this.getRuleContexts(Yt):this.getRuleContext(e,Yt)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_isDefine}enterRule(e){e.enterIsDefine&&e.enterIsDefine(this)}exitRule(e){e.exitIsDefine&&e.exitIsDefine(this)}accept(e){return e.visitIsDefine?e.visitIsDefine(this):e.visitChildren(this)}}w.IsDefineContext=e0;class vk extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}RUN(){return this.getToken(d.RUN,0)}topLevelAnonQueryDef(){return this.getRuleContext(0,_k)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_runStatement}enterRule(e){e.enterRunStatement&&e.enterRunStatement(this)}exitRule(e){e.exitRunStatement&&e.exitRunStatement(this)}accept(e){return e.visitRunStatement?e.visitRunStatement(this):e.visitChildren(this)}}w.RunStatementContext=vk;class FT extends pe.ParserRuleContext{SQL_BEGIN(){return this.getToken(d.SQL_BEGIN,0)}SQL_END(){return this.getToken(d.SQL_END,0)}sqlInterpolation(e){return e===void 0?this.getRuleContexts(wT):this.getRuleContext(e,wT)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sqlString}enterRule(e){e.enterSqlString&&e.enterSqlString(this)}exitRule(e){e.exitSqlString&&e.exitSqlString(this)}accept(e){return e.visitSqlString?e.visitSqlString(this):e.visitChildren(this)}}w.SqlStringContext=FT;class wT extends pe.ParserRuleContext{OPEN_CODE(){return this.getToken(d.OPEN_CODE,0)}sqExpr(){return this.getRuleContext(0,un)}CCURLY(){return this.getToken(d.CCURLY,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sqlInterpolation}enterRule(e){e.enterSqlInterpolation&&e.enterSqlInterpolation(this)}exitRule(e){e.exitSqlInterpolation&&e.exitSqlInterpolation(this)}accept(e){return e.visitSqlInterpolation?e.visitSqlInterpolation(this):e.visitChildren(this)}}w.SqlInterpolationContext=wT;class Ck extends pe.ParserRuleContext{IMPORT(){return this.getToken(d.IMPORT,0)}importURL(){return this.getRuleContext(0,bk)}importSelect(){return this.tryGetRuleContext(0,Sk)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_importStatement}enterRule(e){e.enterImportStatement&&e.enterImportStatement(this)}exitRule(e){e.exitImportStatement&&e.exitImportStatement(this)}accept(e){return e.visitImportStatement?e.visitImportStatement(this):e.visitChildren(this)}}w.ImportStatementContext=Ck;class Sk extends pe.ParserRuleContext{OCURLY(){return this.getToken(d.OCURLY,0)}importItem(e){return e===void 0?this.getRuleContexts(NT):this.getRuleContext(e,NT)}CCURLY(){return this.getToken(d.CCURLY,0)}FROM(){return this.getToken(d.FROM,0)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_importSelect}enterRule(e){e.enterImportSelect&&e.enterImportSelect(this)}exitRule(e){e.exitImportSelect&&e.exitImportSelect(this)}accept(e){return e.visitImportSelect?e.visitImportSelect(this):e.visitChildren(this)}}w.ImportSelectContext=Sk;class NT extends pe.ParserRuleContext{id(e){return e===void 0?this.getRuleContexts(Dn):this.getRuleContext(e,Dn)}IS(){return this.tryGetToken(d.IS,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_importItem}enterRule(e){e.enterImportItem&&e.enterImportItem(this)}exitRule(e){e.exitImportItem&&e.exitImportItem(this)}accept(e){return e.visitImportItem?e.visitImportItem(this):e.visitChildren(this)}}w.ImportItemContext=NT;class bk extends pe.ParserRuleContext{string(){return this.getRuleContext(0,Fa)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_importURL}enterRule(e){e.enterImportURL&&e.enterImportURL(this)}exitRule(e){e.exitImportURL&&e.exitImportURL(this)}accept(e){return e.visitImportURL?e.visitImportURL(this):e.visitChildren(this)}}w.ImportURLContext=bk;class Tk extends pe.ParserRuleContext{DOC_ANNOTATION(e){return e===void 0?this.getTokens(d.DOC_ANNOTATION):this.getToken(d.DOC_ANNOTATION,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_docAnnotations}enterRule(e){e.enterDocAnnotations&&e.enterDocAnnotations(this)}exitRule(e){e.exitDocAnnotations&&e.exitDocAnnotations(this)}accept(e){return e.visitDocAnnotations?e.visitDocAnnotations(this):e.visitChildren(this)}}w.DocAnnotationsContext=Tk;class Rk extends pe.ParserRuleContext{ANNOTATION(e){return e===void 0?this.getTokens(d.ANNOTATION):this.getToken(d.ANNOTATION,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_ignoredObjectAnnotations}enterRule(e){e.enterIgnoredObjectAnnotations&&e.enterIgnoredObjectAnnotations(this)}exitRule(e){e.exitIgnoredObjectAnnotations&&e.exitIgnoredObjectAnnotations(this)}accept(e){return e.visitIgnoredObjectAnnotations?e.visitIgnoredObjectAnnotations(this):e.visitChildren(this)}}w.IgnoredObjectAnnotationsContext=Rk;class LT extends pe.ParserRuleContext{DOC_ANNOTATION(e){return e===void 0?this.getTokens(d.DOC_ANNOTATION):this.getToken(d.DOC_ANNOTATION,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_ignoredModelAnnotations}enterRule(e){e.enterIgnoredModelAnnotations&&e.enterIgnoredModelAnnotations(this)}exitRule(e){e.exitIgnoredModelAnnotations&&e.exitIgnoredModelAnnotations(this)}accept(e){return e.visitIgnoredModelAnnotations?e.visitIgnoredModelAnnotations(this):e.visitChildren(this)}}w.IgnoredModelAnnotationsContext=LT;class Dk extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}QUERY(){return this.getToken(d.QUERY,0)}topLevelQueryDef(e){return e===void 0?this.getRuleContexts(IT):this.getRuleContext(e,IT)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_topLevelQueryDefs}enterRule(e){e.enterTopLevelQueryDefs&&e.enterTopLevelQueryDefs(this)}exitRule(e){e.exitTopLevelQueryDefs&&e.exitTopLevelQueryDefs(this)}accept(e){return e.visitTopLevelQueryDefs?e.visitTopLevelQueryDefs(this):e.visitChildren(this)}}w.TopLevelQueryDefsContext=Dk;class IT extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}queryName(){return this.getRuleContext(0,$T)}isDefine(){return this.getRuleContext(0,e0)}sqExpr(){return this.getRuleContext(0,un)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_topLevelQueryDef}enterRule(e){e.enterTopLevelQueryDef&&e.enterTopLevelQueryDef(this)}exitRule(e){e.exitTopLevelQueryDef&&e.exitTopLevelQueryDef(this)}accept(e){return e.visitTopLevelQueryDef?e.visitTopLevelQueryDef(this):e.visitChildren(this)}}w.TopLevelQueryDefContext=IT;class Y0e extends pe.ParserRuleContext{PLUS(){return this.getToken(d.PLUS,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_refineOperator}enterRule(e){e.enterRefineOperator&&e.enterRefineOperator(this)}exitRule(e){e.exitRefineOperator&&e.exitRefineOperator(this)}accept(e){return e.visitRefineOperator?e.visitRefineOperator(this):e.visitChildren(this)}}w.RefineOperatorContext=Y0e;class K0e extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_turtleName}enterRule(e){e.enterTurtleName&&e.enterTurtleName(this)}exitRule(e){e.exitTurtleName&&e.exitTurtleName(this)}accept(e){return e.visitTurtleName?e.visitTurtleName(this):e.visitChildren(this)}}w.TurtleNameContext=K0e;class Ok extends pe.ParserRuleContext{connectionId(){return this.getRuleContext(0,BT)}DOT(){return this.getToken(d.DOT,0)}SQL(){return this.getToken(d.SQL,0)}OPAREN(){return this.getToken(d.OPAREN,0)}CPAREN(){return this.getToken(d.CPAREN,0)}sqlString(){return this.tryGetRuleContext(0,FT)}shortString(){return this.tryGetRuleContext(0,cR)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sqlSource}enterRule(e){e.enterSqlSource&&e.enterSqlSource(this)}exitRule(e){e.exitSqlSource&&e.exitSqlSource(this)}accept(e){return e.visitSqlSource?e.visitSqlSource(this):e.visitChildren(this)}}w.SqlSourceContext=Ok;class Fk extends pe.ParserRuleContext{connectionId(){return this.getRuleContext(0,BT)}DOT(){return this.getToken(d.DOT,0)}TABLE(){return this.getToken(d.TABLE,0)}OPAREN(){return this.getToken(d.OPAREN,0)}tablePath(){return this.getRuleContext(0,_M)}CPAREN(){return this.getToken(d.CPAREN,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_exploreTable}enterRule(e){e.enterExploreTable&&e.enterExploreTable(this)}exitRule(e){e.exitExploreTable&&e.exitExploreTable(this)}accept(e){return e.visitExploreTable?e.visitExploreTable(this):e.visitChildren(this)}}w.ExploreTableContext=Fk;class BT extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_connectionId}enterRule(e){e.enterConnectionId&&e.enterConnectionId(this)}exitRule(e){e.exitConnectionId&&e.exitConnectionId(this)}accept(e){return e.visitConnectionId?e.visitConnectionId(this):e.visitChildren(this)}}w.ConnectionIdContext=BT;class wk extends pe.ParserRuleContext{OCURLY(){return this.getToken(d.OCURLY,0)}CCURLY(){return this.getToken(d.CCURLY,0)}queryStatement(e){return e===void 0?this.getRuleContexts(rR):this.getRuleContext(e,rR)}SEMI(e){return e===void 0?this.getTokens(d.SEMI):this.getToken(d.SEMI,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_queryProperties}enterRule(e){e.enterQueryProperties&&e.enterQueryProperties(this)}exitRule(e){e.exitQueryProperties&&e.exitQueryProperties(this)}accept(e){return e.visitQueryProperties?e.visitQueryProperties(this):e.visitChildren(this)}}w.QueryPropertiesContext=wk;class $T extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_queryName}enterRule(e){e.enterQueryName&&e.enterQueryName(this)}exitRule(e){e.exitQueryName&&e.exitQueryName(this)}accept(e){return e.visitQueryName?e.visitQueryName(this):e.visitChildren(this)}}w.QueryNameContext=$T;class Nk extends pe.ParserRuleContext{sourceDefinition(e){return e===void 0?this.getRuleContexts(kT):this.getRuleContext(e,kT)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sourcePropertyList}enterRule(e){e.enterSourcePropertyList&&e.enterSourcePropertyList(this)}exitRule(e){e.exitSourcePropertyList&&e.exitSourcePropertyList(this)}accept(e){return e.visitSourcePropertyList?e.visitSourcePropertyList(this):e.visitChildren(this)}}w.SourcePropertyListContext=Nk;class kT extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}sourceNameDef(){return this.getRuleContext(0,kk)}isDefine(){return this.getRuleContext(0,e0)}sqExplore(){return this.getRuleContext(0,Lk)}sourceParameters(){return this.tryGetRuleContext(0,Ik)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sourceDefinition}enterRule(e){e.enterSourceDefinition&&e.enterSourceDefinition(this)}exitRule(e){e.exitSourceDefinition&&e.exitSourceDefinition(this)}accept(e){return e.visitSourceDefinition?e.visitSourceDefinition(this):e.visitChildren(this)}}w.SourceDefinitionContext=kT;class Lk extends pe.ParserRuleContext{sqExpr(){return this.getRuleContext(0,un)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sqExplore}enterRule(e){e.enterSqExplore&&e.enterSqExplore(this)}exitRule(e){e.exitSqExplore&&e.exitSqExplore(this)}accept(e){return e.visitSqExplore?e.visitSqExplore(this):e.visitChildren(this)}}w.SqExploreContext=Lk;class Ik extends pe.ParserRuleContext{OPAREN(){return this.getToken(d.OPAREN,0)}CPAREN(){return this.getToken(d.CPAREN,0)}sourceParameter(e){return e===void 0?this.getRuleContexts(MT):this.getRuleContext(e,MT)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sourceParameters}enterRule(e){e.enterSourceParameters&&e.enterSourceParameters(this)}exitRule(e){e.exitSourceParameters&&e.exitSourceParameters(this)}accept(e){return e.visitSourceParameters?e.visitSourceParameters(this):e.visitChildren(this)}}w.SourceParametersContext=Ik;class Bk extends pe.ParserRuleContext{malloyType(){return this.getRuleContext(0,hE)}FILTER(){return this.tryGetToken(d.FILTER,0)}LT(){return this.tryGetToken(d.LT,0)}GT(){return this.tryGetToken(d.GT,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_legalParamType}enterRule(e){e.enterLegalParamType&&e.enterLegalParamType(this)}exitRule(e){e.exitLegalParamType&&e.exitLegalParamType(this)}accept(e){return e.visitLegalParamType?e.visitLegalParamType(this):e.visitChildren(this)}}w.LegalParamTypeContext=Bk;class MT extends pe.ParserRuleContext{parameterNameDef(){return this.getRuleContext(0,$k)}DOUBLECOLON(){return this.tryGetToken(d.DOUBLECOLON,0)}legalParamType(){return this.tryGetRuleContext(0,Bk)}IS(){return this.tryGetToken(d.IS,0)}fieldExpr(){return this.tryGetRuleContext(0,Te)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sourceParameter}enterRule(e){e.enterSourceParameter&&e.enterSourceParameter(this)}exitRule(e){e.exitSourceParameter&&e.exitSourceParameter(this)}accept(e){return e.visitSourceParameter?e.visitSourceParameter(this):e.visitChildren(this)}}w.SourceParameterContext=MT;class $k extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_parameterNameDef}enterRule(e){e.enterParameterNameDef&&e.enterParameterNameDef(this)}exitRule(e){e.exitParameterNameDef&&e.exitParameterNameDef(this)}accept(e){return e.visitParameterNameDef?e.visitParameterNameDef(this):e.visitChildren(this)}}w.ParameterNameDefContext=$k;class kk extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sourceNameDef}enterRule(e){e.enterSourceNameDef&&e.enterSourceNameDef(this)}exitRule(e){e.exitSourceNameDef&&e.exitSourceNameDef(this)}accept(e){return e.visitSourceNameDef?e.visitSourceNameDef(this):e.visitChildren(this)}}w.SourceNameDefContext=kk;class Mk extends pe.ParserRuleContext{OCURLY(){return this.getToken(d.OCURLY,0)}CCURLY(){return this.getToken(d.CCURLY,0)}exploreStatement(e){return e===void 0?this.getRuleContexts(qi):this.getRuleContext(e,qi)}SEMI(e){return e===void 0?this.getTokens(d.SEMI):this.getToken(d.SEMI,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_exploreProperties}enterRule(e){e.enterExploreProperties&&e.enterExploreProperties(this)}exitRule(e){e.exitExploreProperties&&e.exitExploreProperties(this)}accept(e){return e.visitExploreProperties?e.visitExploreProperties(this):e.visitChildren(this)}}w.ExplorePropertiesContext=Mk;class qi extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_exploreStatement}copyFrom(e){super.copyFrom(e)}}w.ExploreStatementContext=qi;class J0e extends qi{defDimensions(){return this.getRuleContext(0,UT)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefExploreDimension_stub&&e.enterDefExploreDimension_stub(this)}exitRule(e){e.exitDefExploreDimension_stub&&e.exitDefExploreDimension_stub(this)}accept(e){return e.visitDefExploreDimension_stub?e.visitDefExploreDimension_stub(this):e.visitChildren(this)}}w.DefExploreDimension_stubContext=J0e;class X0e extends qi{defMeasures(){return this.getRuleContext(0,PT)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefExploreMeasure_stub&&e.enterDefExploreMeasure_stub(this)}exitRule(e){e.exitDefExploreMeasure_stub&&e.exitDefExploreMeasure_stub(this)}accept(e){return e.visitDefExploreMeasure_stub?e.visitDefExploreMeasure_stub(this):e.visitChildren(this)}}w.DefExploreMeasure_stubContext=X0e;class Z0e extends qi{joinStatement(){return this.getRuleContext(0,t0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefJoin_stub&&e.enterDefJoin_stub(this)}exitRule(e){e.exitDefJoin_stub&&e.exitDefJoin_stub(this)}accept(e){return e.visitDefJoin_stub?e.visitDefJoin_stub(this):e.visitChildren(this)}}w.DefJoin_stubContext=Z0e;class ece extends qi{whereStatement(){return this.getRuleContext(0,ud)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefExploreWhere_stub&&e.enterDefExploreWhere_stub(this)}exitRule(e){e.exitDefExploreWhere_stub&&e.exitDefExploreWhere_stub(this)}accept(e){return e.visitDefExploreWhere_stub?e.visitDefExploreWhere_stub(this):e.visitChildren(this)}}w.DefExploreWhere_stubContext=ece;class tce extends qi{PRIMARY_KEY(){return this.getToken(d.PRIMARY_KEY,0)}fieldName(){return this.getRuleContext(0,Ur)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefExplorePrimaryKey&&e.enterDefExplorePrimaryKey(this)}exitRule(e){e.exitDefExplorePrimaryKey&&e.exitDefExplorePrimaryKey(this)}accept(e){return e.visitDefExplorePrimaryKey?e.visitDefExplorePrimaryKey(this):e.visitChildren(this)}}w.DefExplorePrimaryKeyContext=tce;class nce extends qi{RENAME(){return this.getToken(d.RENAME,0)}renameList(){return this.getRuleContext(0,Pk)}accessLabel(){return this.tryGetRuleContext(0,Oa)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefExploreRename&&e.enterDefExploreRename(this)}exitRule(e){e.exitDefExploreRename&&e.exitDefExploreRename(this)}accept(e){return e.visitDefExploreRename?e.visitDefExploreRename(this):e.visitChildren(this)}}w.DefExploreRenameContext=nce;class rce extends qi{fieldNameList(){return this.getRuleContext(0,b2)}ACCEPT(){return this.tryGetToken(d.ACCEPT,0)}EXCEPT(){return this.tryGetToken(d.EXCEPT,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefExploreEditField&&e.enterDefExploreEditField(this)}exitRule(e){e.exitDefExploreEditField&&e.exitDefExploreEditField(this)}accept(e){return e.visitDefExploreEditField?e.visitDefExploreEditField(this):e.visitChildren(this)}}w.DefExploreEditFieldContext=rce;class ice extends qi{tags(){return this.getRuleContext(0,Yt)}VIEW(){return this.getToken(d.VIEW,0)}subQueryDefList(){return this.getRuleContext(0,tM)}accessLabel(){return this.tryGetRuleContext(0,Oa)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefExploreQuery&&e.enterDefExploreQuery(this)}exitRule(e){e.exitDefExploreQuery&&e.exitDefExploreQuery(this)}accept(e){return e.visitDefExploreQuery?e.visitDefExploreQuery(this):e.visitChildren(this)}}w.DefExploreQueryContext=ice;class sce extends qi{timezoneStatement(){return this.getRuleContext(0,aR)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefExploreTimezone&&e.enterDefExploreTimezone(this)}exitRule(e){e.exitDefExploreTimezone&&e.exitDefExploreTimezone(this)}accept(e){return e.visitDefExploreTimezone?e.visitDefExploreTimezone(this):e.visitChildren(this)}}w.DefExploreTimezoneContext=sce;class oce extends qi{ANNOTATION(e){return e===void 0?this.getTokens(d.ANNOTATION):this.getToken(d.ANNOTATION,e)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefExploreAnnotation&&e.enterDefExploreAnnotation(this)}exitRule(e){e.exitDefExploreAnnotation&&e.exitDefExploreAnnotation(this)}accept(e){return e.visitDefExploreAnnotation?e.visitDefExploreAnnotation(this):e.visitChildren(this)}}w.DefExploreAnnotationContext=oce;class uce extends qi{ignoredModelAnnotations(){return this.getRuleContext(0,LT)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefIgnoreModel_stub&&e.enterDefIgnoreModel_stub(this)}exitRule(e){e.exitDefIgnoreModel_stub&&e.exitDefIgnoreModel_stub(this)}accept(e){return e.visitDefIgnoreModel_stub?e.visitDefIgnoreModel_stub(this):e.visitChildren(this)}}w.DefIgnoreModel_stubContext=uce;class Oa extends pe.ParserRuleContext{PUBLIC_KW(){return this.tryGetToken(d.PUBLIC_KW,0)}PRIVATE_KW(){return this.tryGetToken(d.PRIVATE_KW,0)}INTERNAL_KW(){return this.tryGetToken(d.INTERNAL_KW,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_accessLabel}enterRule(e){e.enterAccessLabel&&e.enterAccessLabel(this)}exitRule(e){e.exitAccessLabel&&e.exitAccessLabel(this)}accept(e){return e.visitAccessLabel?e.visitAccessLabel(this):e.visitChildren(this)}}w.AccessLabelContext=Oa;class ace extends pe.ParserRuleContext{fieldNameList(){return this.tryGetRuleContext(0,b2)}STAR(){return this.tryGetToken(d.STAR,0)}starQualified(){return this.tryGetRuleContext(0,pR)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_accessModifierList}enterRule(e){e.enterAccessModifierList&&e.enterAccessModifierList(this)}exitRule(e){e.exitAccessModifierList&&e.exitAccessModifierList(this)}accept(e){return e.visitAccessModifierList?e.visitAccessModifierList(this):e.visitChildren(this)}}w.AccessModifierListContext=ace;class PT extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}MEASURE(){return this.getToken(d.MEASURE,0)}defList(){return this.getRuleContext(0,lE)}accessLabel(){return this.tryGetRuleContext(0,Oa)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_defMeasures}enterRule(e){e.enterDefMeasures&&e.enterDefMeasures(this)}exitRule(e){e.exitDefMeasures&&e.exitDefMeasures(this)}accept(e){return e.visitDefMeasures?e.visitDefMeasures(this):e.visitChildren(this)}}w.DefMeasuresContext=PT;class UT extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}DIMENSION(){return this.getToken(d.DIMENSION,0)}defList(){return this.getRuleContext(0,lE)}accessLabel(){return this.tryGetRuleContext(0,Oa)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_defDimensions}enterRule(e){e.enterDefDimensions&&e.enterDefDimensions(this)}exitRule(e){e.exitDefDimensions&&e.exitDefDimensions(this)}accept(e){return e.visitDefDimensions?e.visitDefDimensions(this):e.visitChildren(this)}}w.DefDimensionsContext=UT;class Pk extends pe.ParserRuleContext{exploreRenameDef(e){return e===void 0?this.getRuleContexts(jT):this.getRuleContext(e,jT)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_renameList}enterRule(e){e.enterRenameList&&e.enterRenameList(this)}exitRule(e){e.exitRenameList&&e.exitRenameList(this)}accept(e){return e.visitRenameList?e.visitRenameList(this):e.visitChildren(this)}}w.RenameListContext=Pk;class jT extends pe.ParserRuleContext{fieldName(e){return e===void 0?this.getRuleContexts(Ur):this.getRuleContext(e,Ur)}isDefine(){return this.getRuleContext(0,e0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_exploreRenameDef}enterRule(e){e.enterExploreRenameDef&&e.enterExploreRenameDef(this)}exitRule(e){e.exitExploreRenameDef&&e.exitExploreRenameDef(this)}accept(e){return e.visitExploreRenameDef?e.visitExploreRenameDef(this):e.visitChildren(this)}}w.ExploreRenameDefContext=jT;class lE extends pe.ParserRuleContext{fieldDef(e){return e===void 0?this.getRuleContexts(v2):this.getRuleContext(e,v2)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_defList}enterRule(e){e.enterDefList&&e.enterDefList(this)}exitRule(e){e.exitDefList&&e.exitDefList(this)}accept(e){return e.visitDefList?e.visitDefList(this):e.visitChildren(this)}}w.DefListContext=lE;class v2 extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}fieldNameDef(){return this.getRuleContext(0,Uk)}isDefine(){return this.getRuleContext(0,e0)}fieldExpr(){return this.getRuleContext(0,Te)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_fieldDef}enterRule(e){e.enterFieldDef&&e.enterFieldDef(this)}exitRule(e){e.exitFieldDef&&e.exitFieldDef(this)}accept(e){return e.visitFieldDef?e.visitFieldDef(this):e.visitChildren(this)}}w.FieldDefContext=v2;class Uk extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_fieldNameDef}enterRule(e){e.enterFieldNameDef&&e.enterFieldNameDef(this)}exitRule(e){e.exitFieldNameDef&&e.exitFieldNameDef(this)}accept(e){return e.visitFieldNameDef?e.visitFieldNameDef(this):e.visitChildren(this)}}w.FieldNameDefContext=Uk;class jk extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_joinNameDef}enterRule(e){e.enterJoinNameDef&&e.enterJoinNameDef(this)}exitRule(e){e.exitJoinNameDef&&e.exitJoinNameDef(this)}accept(e){return e.visitJoinNameDef?e.visitJoinNameDef(this):e.visitChildren(this)}}w.JoinNameDefContext=jk;class qT extends pe.ParserRuleContext{DECLARE(){return this.getToken(d.DECLARE,0)}defList(){return this.getRuleContext(0,lE)}accessLabel(){return this.tryGetRuleContext(0,Oa)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_declareStatement}enterRule(e){e.enterDeclareStatement&&e.enterDeclareStatement(this)}exitRule(e){e.exitDeclareStatement&&e.exitDeclareStatement(this)}accept(e){return e.visitDeclareStatement?e.visitDeclareStatement(this):e.visitChildren(this)}}w.DeclareStatementContext=qT;class t0 extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_joinStatement}copyFrom(e){super.copyFrom(e)}}w.JoinStatementContext=t0;class lce extends t0{tags(){return this.getRuleContext(0,Yt)}JOIN_ONE(){return this.getToken(d.JOIN_ONE,0)}joinList(){return this.getRuleContext(0,cE)}accessLabel(){return this.tryGetRuleContext(0,Oa)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefJoinOne&&e.enterDefJoinOne(this)}exitRule(e){e.exitDefJoinOne&&e.exitDefJoinOne(this)}accept(e){return e.visitDefJoinOne?e.visitDefJoinOne(this):e.visitChildren(this)}}w.DefJoinOneContext=lce;class cce extends t0{tags(){return this.getRuleContext(0,Yt)}JOIN_MANY(){return this.getToken(d.JOIN_MANY,0)}joinList(){return this.getRuleContext(0,cE)}accessLabel(){return this.tryGetRuleContext(0,Oa)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefJoinMany&&e.enterDefJoinMany(this)}exitRule(e){e.exitDefJoinMany&&e.exitDefJoinMany(this)}accept(e){return e.visitDefJoinMany?e.visitDefJoinMany(this):e.visitChildren(this)}}w.DefJoinManyContext=cce;class fce extends t0{tags(){return this.getRuleContext(0,Yt)}JOIN_CROSS(){return this.getToken(d.JOIN_CROSS,0)}joinList(){return this.getRuleContext(0,cE)}accessLabel(){return this.tryGetRuleContext(0,Oa)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterDefJoinCross&&e.enterDefJoinCross(this)}exitRule(e){e.exitDefJoinCross&&e.exitDefJoinCross(this)}accept(e){return e.visitDefJoinCross?e.visitDefJoinCross(this):e.visitChildren(this)}}w.DefJoinCrossContext=fce;class qk extends pe.ParserRuleContext{EXTENDQ(){return this.getToken(d.EXTENDQ,0)}queryExtendStatementList(){return this.getRuleContext(0,Vk)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_queryExtend}enterRule(e){e.enterQueryExtend&&e.enterQueryExtend(this)}exitRule(e){e.exitQueryExtend&&e.exitQueryExtend(this)}accept(e){return e.visitQueryExtend?e.visitQueryExtend(this):e.visitChildren(this)}}w.QueryExtendContext=qk;class xce extends pe.ParserRuleContext{joinStatement(){return this.tryGetRuleContext(0,t0)}whereStatement(){return this.tryGetRuleContext(0,ud)}declareStatement(){return this.tryGetRuleContext(0,qT)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_modEither}enterRule(e){e.enterModEither&&e.enterModEither(this)}exitRule(e){e.exitModEither&&e.exitModEither(this)}accept(e){return e.visitModEither?e.visitModEither(this):e.visitChildren(this)}}w.ModEitherContext=xce;class HT extends pe.ParserRuleContext{OPAREN(){return this.getToken(d.OPAREN,0)}CPAREN(){return this.getToken(d.CPAREN,0)}sourceArgument(e){return e===void 0?this.getRuleContexts(QT):this.getRuleContext(e,QT)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sourceArguments}enterRule(e){e.enterSourceArguments&&e.enterSourceArguments(this)}exitRule(e){e.exitSourceArguments&&e.exitSourceArguments(this)}accept(e){return e.visitSourceArguments?e.visitSourceArguments(this):e.visitChildren(this)}}w.SourceArgumentsContext=HT;class Hk extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_argumentId}enterRule(e){e.enterArgumentId&&e.enterArgumentId(this)}exitRule(e){e.exitArgumentId&&e.exitArgumentId(this)}accept(e){return e.visitArgumentId?e.visitArgumentId(this):e.visitChildren(this)}}w.ArgumentIdContext=Hk;class QT extends pe.ParserRuleContext{fieldExpr(){return this.getRuleContext(0,Te)}argumentId(){return this.tryGetRuleContext(0,Hk)}IS(){return this.tryGetToken(d.IS,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sourceArgument}enterRule(e){e.enterSourceArgument&&e.enterSourceArgument(this)}exitRule(e){e.exitSourceArgument&&e.exitSourceArgument(this)}accept(e){return e.visitSourceArgument?e.visitSourceArgument(this):e.visitChildren(this)}}w.SourceArgumentContext=QT;class un extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sqExpr}copyFrom(e){super.copyFrom(e)}}w.SqExprContext=un;class dce extends un{id(){return this.getRuleContext(0,Dn)}sourceArguments(){return this.tryGetRuleContext(0,HT)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSQID&&e.enterSQID(this)}exitRule(e){e.exitSQID&&e.exitSQID(this)}accept(e){return e.visitSQID?e.visitSQID(this):e.visitChildren(this)}}w.SQIDContext=dce;class hce extends un{OPAREN(){return this.getToken(d.OPAREN,0)}sqExpr(){return this.getRuleContext(0,un)}CPAREN(){return this.getToken(d.CPAREN,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSQParens&&e.enterSQParens(this)}exitRule(e){e.exitSQParens&&e.exitSQParens(this)}accept(e){return e.visitSQParens?e.visitSQParens(this):e.visitChildren(this)}}w.SQParensContext=hce;class pce extends un{COMPOSE(){return this.getToken(d.COMPOSE,0)}OPAREN(){return this.getToken(d.OPAREN,0)}CPAREN(){return this.getToken(d.CPAREN,0)}sqExpr(e){return e===void 0?this.getRuleContexts(un):this.getRuleContext(e,un)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSQCompose&&e.enterSQCompose(this)}exitRule(e){e.exitSQCompose&&e.exitSQCompose(this)}accept(e){return e.visitSQCompose?e.visitSQCompose(this):e.visitChildren(this)}}w.SQComposeContext=pce;class mce extends un{sqExpr(){return this.getRuleContext(0,un)}PLUS(){return this.getToken(d.PLUS,0)}segExpr(){return this.getRuleContext(0,Ms)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSQRefinedQuery&&e.enterSQRefinedQuery(this)}exitRule(e){e.exitSQRefinedQuery&&e.exitSQRefinedQuery(this)}accept(e){return e.visitSQRefinedQuery?e.visitSQRefinedQuery(this):e.visitChildren(this)}}w.SQRefinedQueryContext=mce;class gce extends un{sqExpr(){return this.getRuleContext(0,un)}ARROW(){return this.getToken(d.ARROW,0)}segExpr(){return this.getRuleContext(0,Ms)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSQArrow&&e.enterSQArrow(this)}exitRule(e){e.exitSQArrow&&e.exitSQArrow(this)}accept(e){return e.visitSQArrow?e.visitSQArrow(this):e.visitChildren(this)}}w.SQArrowContext=gce;class yce extends un{sqExpr(){return this.getRuleContext(0,un)}EXTEND(){return this.getToken(d.EXTEND,0)}exploreProperties(){return this.getRuleContext(0,Mk)}INCLUDE(){return this.tryGetToken(d.INCLUDE,0)}includeBlock(){return this.tryGetRuleContext(0,zT)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSQExtendedSource&&e.enterSQExtendedSource(this)}exitRule(e){e.exitSQExtendedSource&&e.exitSQExtendedSource(this)}accept(e){return e.visitSQExtendedSource?e.visitSQExtendedSource(this):e.visitChildren(this)}}w.SQExtendedSourceContext=yce;class Ece extends un{sqExpr(){return this.getRuleContext(0,un)}INCLUDE(){return this.getToken(d.INCLUDE,0)}includeBlock(){return this.getRuleContext(0,zT)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSQInclude&&e.enterSQInclude(this)}exitRule(e){e.exitSQInclude&&e.exitSQInclude(this)}accept(e){return e.visitSQInclude?e.visitSQInclude(this):e.visitChildren(this)}}w.SQIncludeContext=Ece;class Ace extends un{exploreTable(){return this.getRuleContext(0,Fk)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSQTable&&e.enterSQTable(this)}exitRule(e){e.exitSQTable&&e.exitSQTable(this)}accept(e){return e.visitSQTable?e.visitSQTable(this):e.visitChildren(this)}}w.SQTableContext=Ace;class _ce extends un{sqlSource(){return this.getRuleContext(0,Ok)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSQSQL&&e.enterSQSQL(this)}exitRule(e){e.exitSQSQL&&e.exitSQSQL(this)}accept(e){return e.visitSQSQL?e.visitSQSQL(this):e.visitChildren(this)}}w.SQSQLContext=_ce;class zT extends pe.ParserRuleContext{OCURLY(){return this.getToken(d.OCURLY,0)}CCURLY(){return this.getToken(d.CCURLY,0)}includeItem(e){return e===void 0?this.getRuleContexts(GT):this.getRuleContext(e,GT)}SEMI(e){return e===void 0?this.getTokens(d.SEMI):this.getToken(d.SEMI,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_includeBlock}enterRule(e){e.enterIncludeBlock&&e.enterIncludeBlock(this)}exitRule(e){e.exitIncludeBlock&&e.exitIncludeBlock(this)}accept(e){return e.visitIncludeBlock?e.visitIncludeBlock(this):e.visitChildren(this)}}w.IncludeBlockContext=zT;class GT extends pe.ParserRuleContext{tags(){return this.tryGetRuleContext(0,Yt)}accessLabelProp(){return this.tryGetRuleContext(0,zk)}includeList(){return this.tryGetRuleContext(0,Wk)}EXCEPT(){return this.tryGetToken(d.EXCEPT,0)}includeExceptList(){return this.tryGetRuleContext(0,Gk)}orphanedAnnotation(){return this.tryGetRuleContext(0,Qk)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_includeItem}enterRule(e){e.enterIncludeItem&&e.enterIncludeItem(this)}exitRule(e){e.exitIncludeItem&&e.exitIncludeItem(this)}accept(e){return e.visitIncludeItem?e.visitIncludeItem(this):e.visitChildren(this)}}w.IncludeItemContext=GT;class Qk extends pe.ParserRuleContext{ANNOTATION(){return this.getToken(d.ANNOTATION,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_orphanedAnnotation}enterRule(e){e.enterOrphanedAnnotation&&e.enterOrphanedAnnotation(this)}exitRule(e){e.exitOrphanedAnnotation&&e.exitOrphanedAnnotation(this)}accept(e){return e.visitOrphanedAnnotation?e.visitOrphanedAnnotation(this):e.visitChildren(this)}}w.OrphanedAnnotationContext=Qk;class zk extends pe.ParserRuleContext{PUBLIC(){return this.tryGetToken(d.PUBLIC,0)}PRIVATE(){return this.tryGetToken(d.PRIVATE,0)}INTERNAL(){return this.tryGetToken(d.INTERNAL,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_accessLabelProp}enterRule(e){e.enterAccessLabelProp&&e.enterAccessLabelProp(this)}exitRule(e){e.exitAccessLabelProp&&e.exitAccessLabelProp(this)}accept(e){return e.visitAccessLabelProp?e.visitAccessLabelProp(this):e.visitChildren(this)}}w.AccessLabelPropContext=zk;class Gk extends pe.ParserRuleContext{includeExceptListItem(e){return e===void 0?this.getRuleContexts(WT):this.getRuleContext(e,WT)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_includeExceptList}enterRule(e){e.enterIncludeExceptList&&e.enterIncludeExceptList(this)}exitRule(e){e.exitIncludeExceptList&&e.exitIncludeExceptList(this)}accept(e){return e.visitIncludeExceptList?e.visitIncludeExceptList(this):e.visitChildren(this)}}w.IncludeExceptListContext=Gk;class WT extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}fieldName(){return this.tryGetRuleContext(0,Ur)}collectionWildCard(){return this.tryGetRuleContext(0,pE)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_includeExceptListItem}enterRule(e){e.enterIncludeExceptListItem&&e.enterIncludeExceptListItem(this)}exitRule(e){e.exitIncludeExceptListItem&&e.exitIncludeExceptListItem(this)}accept(e){return e.visitIncludeExceptListItem?e.visitIncludeExceptListItem(this):e.visitChildren(this)}}w.IncludeExceptListItemContext=WT;class Wk extends pe.ParserRuleContext{includeField(e){return e===void 0?this.getRuleContexts(VT):this.getRuleContext(e,VT)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_includeList}enterRule(e){e.enterIncludeList&&e.enterIncludeList(this)}exitRule(e){e.exitIncludeList&&e.exitIncludeList(this)}accept(e){return e.visitIncludeList?e.visitIncludeList(this):e.visitChildren(this)}}w.IncludeListContext=Wk;class VT extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}fieldName(e){return e===void 0?this.getRuleContexts(Ur):this.getRuleContext(e,Ur)}isDefine(){return this.tryGetRuleContext(0,e0)}collectionWildCard(){return this.tryGetRuleContext(0,pE)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_includeField}enterRule(e){e.enterIncludeField&&e.enterIncludeField(this)}exitRule(e){e.exitIncludeField&&e.exitIncludeField(this)}accept(e){return e.visitIncludeField?e.visitIncludeField(this):e.visitChildren(this)}}w.IncludeFieldContext=VT;class Ms extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_segExpr}copyFrom(e){super.copyFrom(e)}}w.SegExprContext=Ms;class vce extends Ms{fieldPath(){return this.getRuleContext(0,Na)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSegField&&e.enterSegField(this)}exitRule(e){e.exitSegField&&e.exitSegField(this)}accept(e){return e.visitSegField?e.visitSegField(this):e.visitChildren(this)}}w.SegFieldContext=vce;class Cce extends Ms{queryProperties(){return this.getRuleContext(0,wk)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSegOps&&e.enterSegOps(this)}exitRule(e){e.exitSegOps&&e.exitSegOps(this)}accept(e){return e.visitSegOps?e.visitSegOps(this):e.visitChildren(this)}}w.SegOpsContext=Cce;class Sce extends Ms{OPAREN(){return this.getToken(d.OPAREN,0)}vExpr(){return this.getRuleContext(0,zc)}CPAREN(){return this.getToken(d.CPAREN,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSegParen&&e.enterSegParen(this)}exitRule(e){e.exitSegParen&&e.exitSegParen(this)}accept(e){return e.visitSegParen?e.visitSegParen(this):e.visitChildren(this)}}w.SegParenContext=Sce;class bce extends Ms{PLUS(){return this.getToken(d.PLUS,0)}segExpr(e){return e===void 0?this.getRuleContexts(Ms):this.getRuleContext(e,Ms)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterSegRefine&&e.enterSegRefine(this)}exitRule(e){e.exitSegRefine&&e.exitSegRefine(this)}accept(e){return e.visitSegRefine?e.visitSegRefine(this):e.visitChildren(this)}}w.SegRefineContext=bce;class zc extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_vExpr}copyFrom(e){super.copyFrom(e)}}w.VExprContext=zc;class Tce extends zc{segExpr(){return this.getRuleContext(0,Ms)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterVSeg&&e.enterVSeg(this)}exitRule(e){e.exitVSeg&&e.exitVSeg(this)}accept(e){return e.visitVSeg?e.visitVSeg(this):e.visitChildren(this)}}w.VSegContext=Tce;class Rce extends zc{ARROW(){return this.getToken(d.ARROW,0)}segExpr(){return this.getRuleContext(0,Ms)}vExpr(){return this.getRuleContext(0,zc)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterVArrow&&e.enterVArrow(this)}exitRule(e){e.exitVArrow&&e.exitVArrow(this)}accept(e){return e.visitVArrow?e.visitVArrow(this):e.visitChildren(this)}}w.VArrowContext=Rce;class YT extends pe.ParserRuleContext{defDimensions(){return this.tryGetRuleContext(0,UT)}defMeasures(){return this.tryGetRuleContext(0,PT)}joinStatement(){return this.tryGetRuleContext(0,t0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_queryExtendStatement}enterRule(e){e.enterQueryExtendStatement&&e.enterQueryExtendStatement(this)}exitRule(e){e.exitQueryExtendStatement&&e.exitQueryExtendStatement(this)}accept(e){return e.visitQueryExtendStatement?e.visitQueryExtendStatement(this):e.visitChildren(this)}}w.QueryExtendStatementContext=YT;class Vk extends pe.ParserRuleContext{OCURLY(){return this.getToken(d.OCURLY,0)}CCURLY(){return this.getToken(d.CCURLY,0)}queryExtendStatement(e){return e===void 0?this.getRuleContexts(YT):this.getRuleContext(e,YT)}SEMI(e){return e===void 0?this.getTokens(d.SEMI):this.getToken(d.SEMI,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_queryExtendStatementList}enterRule(e){e.enterQueryExtendStatementList&&e.enterQueryExtendStatementList(this)}exitRule(e){e.exitQueryExtendStatementList&&e.exitQueryExtendStatementList(this)}accept(e){return e.visitQueryExtendStatementList?e.visitQueryExtendStatementList(this):e.visitChildren(this)}}w.QueryExtendStatementListContext=Vk;class cE extends pe.ParserRuleContext{joinDef(e){return e===void 0?this.getRuleContexts(C2):this.getRuleContext(e,C2)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_joinList}enterRule(e){e.enterJoinList&&e.enterJoinList(this)}exitRule(e){e.exitJoinList&&e.exitJoinList(this)}accept(e){return e.visitJoinList?e.visitJoinList(this):e.visitChildren(this)}}w.JoinListContext=cE;class Yk extends pe.ParserRuleContext{IS(){return this.getToken(d.IS,0)}sqExpr(){return this.getRuleContext(0,un)}tags(e){return e===void 0?this.getRuleContexts(Yt):this.getRuleContext(e,Yt)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_isExplore}enterRule(e){e.enterIsExplore&&e.enterIsExplore(this)}exitRule(e){e.exitIsExplore&&e.exitIsExplore(this)}accept(e){return e.visitIsExplore?e.visitIsExplore(this):e.visitChildren(this)}}w.IsExploreContext=Yk;class KT extends pe.ParserRuleContext{LEFT(){return this.tryGetToken(d.LEFT,0)}RIGHT(){return this.tryGetToken(d.RIGHT,0)}FULL(){return this.tryGetToken(d.FULL,0)}INNER(){return this.tryGetToken(d.INNER,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_matrixOperation}enterRule(e){e.enterMatrixOperation&&e.enterMatrixOperation(this)}exitRule(e){e.exitMatrixOperation&&e.exitMatrixOperation(this)}accept(e){return e.visitMatrixOperation?e.visitMatrixOperation(this):e.visitChildren(this)}}w.MatrixOperationContext=KT;class JT extends pe.ParserRuleContext{joinNameDef(){return this.getRuleContext(0,jk)}sourceArguments(){return this.tryGetRuleContext(0,HT)}isExplore(){return this.tryGetRuleContext(0,Yk)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_joinFrom}enterRule(e){e.enterJoinFrom&&e.enterJoinFrom(this)}exitRule(e){e.exitJoinFrom&&e.exitJoinFrom(this)}accept(e){return e.visitJoinFrom?e.visitJoinFrom(this):e.visitChildren(this)}}w.JoinFromContext=JT;class C2 extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_joinDef}copyFrom(e){super.copyFrom(e)}}w.JoinDefContext=C2;class Dce extends C2{joinFrom(){return this.getRuleContext(0,JT)}WITH(){return this.getToken(d.WITH,0)}fieldExpr(){return this.getRuleContext(0,Te)}ANNOTATION(e){return e===void 0?this.getTokens(d.ANNOTATION):this.getToken(d.ANNOTATION,e)}matrixOperation(){return this.tryGetRuleContext(0,KT)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterJoinWith&&e.enterJoinWith(this)}exitRule(e){e.exitJoinWith&&e.exitJoinWith(this)}accept(e){return e.visitJoinWith?e.visitJoinWith(this):e.visitChildren(this)}}w.JoinWithContext=Dce;class Oce extends C2{joinFrom(){return this.getRuleContext(0,JT)}ANNOTATION(e){return e===void 0?this.getTokens(d.ANNOTATION):this.getToken(d.ANNOTATION,e)}ON(){return this.tryGetToken(d.ON,0)}joinExpression(){return this.tryGetRuleContext(0,Kk)}matrixOperation(){return this.tryGetRuleContext(0,KT)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterJoinOn&&e.enterJoinOn(this)}exitRule(e){e.exitJoinOn&&e.exitJoinOn(this)}accept(e){return e.visitJoinOn?e.visitJoinOn(this):e.visitChildren(this)}}w.JoinOnContext=Oce;class Kk extends pe.ParserRuleContext{fieldExpr(){return this.getRuleContext(0,Te)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_joinExpression}enterRule(e){e.enterJoinExpression&&e.enterJoinExpression(this)}exitRule(e){e.exitJoinExpression&&e.exitJoinExpression(this)}accept(e){return e.visitJoinExpression?e.visitJoinExpression(this):e.visitChildren(this)}}w.JoinExpressionContext=Kk;class Fce extends pe.ParserRuleContext{whereStatement(){return this.tryGetRuleContext(0,ud)}havingStatement(){return this.tryGetRuleContext(0,tR)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_filterStatement}enterRule(e){e.enterFilterStatement&&e.enterFilterStatement(this)}exitRule(e){e.exitFilterStatement&&e.exitFilterStatement(this)}accept(e){return e.visitFilterStatement?e.visitFilterStatement(this):e.visitChildren(this)}}w.FilterStatementContext=Fce;class Jk extends pe.ParserRuleContext{OCURLY(){return this.getToken(d.OCURLY,0)}CCURLY(){return this.getToken(d.CCURLY,0)}fieldPropertyStatement(e){return e===void 0?this.getRuleContexts(ZT):this.getRuleContext(e,ZT)}SEMI(e){return e===void 0?this.getTokens(d.SEMI):this.getToken(d.SEMI,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_fieldProperties}enterRule(e){e.enterFieldProperties&&e.enterFieldProperties(this)}exitRule(e){e.exitFieldProperties&&e.exitFieldProperties(this)}accept(e){return e.visitFieldProperties?e.visitFieldProperties(this):e.visitChildren(this)}}w.FieldPropertiesContext=Jk;class Xk extends pe.ParserRuleContext{aggregateOrderBySpec(e){return e===void 0?this.getRuleContexts(XT):this.getRuleContext(e,XT)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_aggregateOrdering}enterRule(e){e.enterAggregateOrdering&&e.enterAggregateOrdering(this)}exitRule(e){e.exitAggregateOrdering&&e.exitAggregateOrdering(this)}accept(e){return e.visitAggregateOrdering?e.visitAggregateOrdering(this):e.visitChildren(this)}}w.AggregateOrderingContext=Xk;class XT extends pe.ParserRuleContext{fieldExpr(){return this.tryGetRuleContext(0,Te)}ASC(){return this.tryGetToken(d.ASC,0)}DESC(){return this.tryGetToken(d.DESC,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_aggregateOrderBySpec}enterRule(e){e.enterAggregateOrderBySpec&&e.enterAggregateOrderBySpec(this)}exitRule(e){e.exitAggregateOrderBySpec&&e.exitAggregateOrderBySpec(this)}accept(e){return e.visitAggregateOrderBySpec?e.visitAggregateOrderBySpec(this):e.visitChildren(this)}}w.AggregateOrderBySpecContext=XT;class Zk extends pe.ParserRuleContext{ORDER_BY(){return this.getToken(d.ORDER_BY,0)}aggregateOrdering(){return this.getRuleContext(0,Xk)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_aggregateOrderByStatement}enterRule(e){e.enterAggregateOrderByStatement&&e.enterAggregateOrderByStatement(this)}exitRule(e){e.exitAggregateOrderByStatement&&e.exitAggregateOrderByStatement(this)}accept(e){return e.visitAggregateOrderByStatement?e.visitAggregateOrderByStatement(this):e.visitChildren(this)}}w.AggregateOrderByStatementContext=Zk;class eM extends pe.ParserRuleContext{limitStatement(){return this.getRuleContext(0,oR)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_fieldPropertyLimitStatement}enterRule(e){e.enterFieldPropertyLimitStatement&&e.enterFieldPropertyLimitStatement(this)}exitRule(e){e.exitFieldPropertyLimitStatement&&e.exitFieldPropertyLimitStatement(this)}accept(e){return e.visitFieldPropertyLimitStatement?e.visitFieldPropertyLimitStatement(this):e.visitChildren(this)}}w.FieldPropertyLimitStatementContext=eM;class ZT extends pe.ParserRuleContext{whereStatement(){return this.tryGetRuleContext(0,ud)}partitionByStatement(){return this.tryGetRuleContext(0,cM)}aggregateOrderByStatement(){return this.tryGetRuleContext(0,Zk)}fieldPropertyLimitStatement(){return this.tryGetRuleContext(0,eM)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_fieldPropertyStatement}enterRule(e){e.enterFieldPropertyStatement&&e.enterFieldPropertyStatement(this)}exitRule(e){e.exitFieldPropertyStatement&&e.exitFieldPropertyStatement(this)}accept(e){return e.visitFieldPropertyStatement?e.visitFieldPropertyStatement(this):e.visitChildren(this)}}w.FieldPropertyStatementContext=ZT;class eR extends pe.ParserRuleContext{fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_filterClauseList}enterRule(e){e.enterFilterClauseList&&e.enterFilterClauseList(this)}exitRule(e){e.exitFilterClauseList&&e.exitFilterClauseList(this)}accept(e){return e.visitFilterClauseList?e.visitFilterClauseList(this):e.visitChildren(this)}}w.FilterClauseListContext=eR;class ud extends pe.ParserRuleContext{WHERE(){return this.getToken(d.WHERE,0)}filterClauseList(){return this.getRuleContext(0,eR)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_whereStatement}enterRule(e){e.enterWhereStatement&&e.enterWhereStatement(this)}exitRule(e){e.exitWhereStatement&&e.exitWhereStatement(this)}accept(e){return e.visitWhereStatement?e.visitWhereStatement(this):e.visitChildren(this)}}w.WhereStatementContext=ud;class tR extends pe.ParserRuleContext{HAVING(){return this.getToken(d.HAVING,0)}filterClauseList(){return this.getRuleContext(0,eR)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_havingStatement}enterRule(e){e.enterHavingStatement&&e.enterHavingStatement(this)}exitRule(e){e.exitHavingStatement&&e.exitHavingStatement(this)}accept(e){return e.visitHavingStatement?e.visitHavingStatement(this):e.visitChildren(this)}}w.HavingStatementContext=tR;class tM extends pe.ParserRuleContext{exploreQueryDef(e){return e===void 0?this.getRuleContexts(nR):this.getRuleContext(e,nR)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_subQueryDefList}enterRule(e){e.enterSubQueryDefList&&e.enterSubQueryDefList(this)}exitRule(e){e.exitSubQueryDefList&&e.exitSubQueryDefList(this)}accept(e){return e.visitSubQueryDefList?e.visitSubQueryDefList(this):e.visitChildren(this)}}w.SubQueryDefListContext=tM;class nM extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_exploreQueryNameDef}enterRule(e){e.enterExploreQueryNameDef&&e.enterExploreQueryNameDef(this)}exitRule(e){e.exitExploreQueryNameDef&&e.exitExploreQueryNameDef(this)}accept(e){return e.visitExploreQueryNameDef?e.visitExploreQueryNameDef(this):e.visitChildren(this)}}w.ExploreQueryNameDefContext=nM;class nR extends pe.ParserRuleContext{exploreQueryNameDef(){return this.getRuleContext(0,nM)}isDefine(){return this.getRuleContext(0,e0)}vExpr(){return this.getRuleContext(0,zc)}ANNOTATION(e){return e===void 0?this.getTokens(d.ANNOTATION):this.getToken(d.ANNOTATION,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_exploreQueryDef}enterRule(e){e.enterExploreQueryDef&&e.enterExploreQueryDef(this)}exitRule(e){e.exitExploreQueryDef&&e.exitExploreQueryDef(this)}accept(e){return e.visitExploreQueryDef?e.visitExploreQueryDef(this):e.visitChildren(this)}}w.ExploreQueryDefContext=nR;class rR extends pe.ParserRuleContext{groupByStatement(){return this.tryGetRuleContext(0,iM)}declareStatement(){return this.tryGetRuleContext(0,qT)}queryJoinStatement(){return this.tryGetRuleContext(0,rM)}queryExtend(){return this.tryGetRuleContext(0,qk)}projectStatement(){return this.tryGetRuleContext(0,lM)}indexStatement(){return this.tryGetRuleContext(0,pM)}aggregateStatement(){return this.tryGetRuleContext(0,uM)}calculateStatement(){return this.tryGetRuleContext(0,aM)}topStatement(){return this.tryGetRuleContext(0,dM)}limitStatement(){return this.tryGetRuleContext(0,oR)}orderByStatement(){return this.tryGetRuleContext(0,fM)}whereStatement(){return this.tryGetRuleContext(0,ud)}havingStatement(){return this.tryGetRuleContext(0,tR)}nestStatement(){return this.tryGetRuleContext(0,sM)}sampleStatement(){return this.tryGetRuleContext(0,mM)}timezoneStatement(){return this.tryGetRuleContext(0,aR)}queryAnnotation(){return this.tryGetRuleContext(0,gM)}ignoredModelAnnotations(){return this.tryGetRuleContext(0,LT)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_queryStatement}enterRule(e){e.enterQueryStatement&&e.enterQueryStatement(this)}exitRule(e){e.exitQueryStatement&&e.exitQueryStatement(this)}accept(e){return e.visitQueryStatement?e.visitQueryStatement(this):e.visitChildren(this)}}w.QueryStatementContext=rR;class rM extends pe.ParserRuleContext{joinStatement(){return this.getRuleContext(0,t0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_queryJoinStatement}enterRule(e){e.enterQueryJoinStatement&&e.enterQueryJoinStatement(this)}exitRule(e){e.exitQueryJoinStatement&&e.exitQueryJoinStatement(this)}accept(e){return e.visitQueryJoinStatement?e.visitQueryJoinStatement(this):e.visitChildren(this)}}w.QueryJoinStatementContext=rM;class iM extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}GROUP_BY(){return this.getToken(d.GROUP_BY,0)}queryFieldList(){return this.getRuleContext(0,fE)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_groupByStatement}enterRule(e){e.enterGroupByStatement&&e.enterGroupByStatement(this)}exitRule(e){e.exitGroupByStatement&&e.exitGroupByStatement(this)}accept(e){return e.visitGroupByStatement?e.visitGroupByStatement(this):e.visitChildren(this)}}w.GroupByStatementContext=iM;class fE extends pe.ParserRuleContext{queryFieldEntry(e){return e===void 0?this.getRuleContexts(iR):this.getRuleContext(e,iR)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_queryFieldList}enterRule(e){e.enterQueryFieldList&&e.enterQueryFieldList(this)}exitRule(e){e.exitQueryFieldList&&e.exitQueryFieldList(this)}accept(e){return e.visitQueryFieldList?e.visitQueryFieldList(this):e.visitChildren(this)}}w.QueryFieldListContext=fE;class iR extends pe.ParserRuleContext{taggedRef(){return this.tryGetRuleContext(0,mR)}fieldDef(){return this.tryGetRuleContext(0,v2)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_queryFieldEntry}enterRule(e){e.enterQueryFieldEntry&&e.enterQueryFieldEntry(this)}exitRule(e){e.exitQueryFieldEntry&&e.exitQueryFieldEntry(this)}accept(e){return e.visitQueryFieldEntry?e.visitQueryFieldEntry(this):e.visitChildren(this)}}w.QueryFieldEntryContext=iR;class sM extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}NEST(){return this.getToken(d.NEST,0)}nestedQueryList(){return this.getRuleContext(0,oM)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_nestStatement}enterRule(e){e.enterNestStatement&&e.enterNestStatement(this)}exitRule(e){e.exitNestStatement&&e.exitNestStatement(this)}accept(e){return e.visitNestStatement?e.visitNestStatement(this):e.visitChildren(this)}}w.NestStatementContext=sM;class oM extends pe.ParserRuleContext{nestEntry(e){return e===void 0?this.getRuleContexts(xE):this.getRuleContext(e,xE)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_nestedQueryList}enterRule(e){e.enterNestedQueryList&&e.enterNestedQueryList(this)}exitRule(e){e.exitNestedQueryList&&e.exitNestedQueryList(this)}accept(e){return e.visitNestedQueryList?e.visitNestedQueryList(this):e.visitChildren(this)}}w.NestedQueryListContext=oM;class xE extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_nestEntry}copyFrom(e){super.copyFrom(e)}}w.NestEntryContext=xE;class wce extends xE{tags(){return this.getRuleContext(0,Yt)}vExpr(){return this.getRuleContext(0,zc)}queryName(){return this.tryGetRuleContext(0,$T)}isDefine(){return this.tryGetRuleContext(0,e0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterNestDef&&e.enterNestDef(this)}exitRule(e){e.exitNestDef&&e.exitNestDef(this)}accept(e){return e.visitNestDef?e.visitNestDef(this):e.visitChildren(this)}}w.NestDefContext=wce;class uM extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}AGGREGATE(){return this.getToken(d.AGGREGATE,0)}queryFieldList(){return this.getRuleContext(0,fE)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_aggregateStatement}enterRule(e){e.enterAggregateStatement&&e.enterAggregateStatement(this)}exitRule(e){e.exitAggregateStatement&&e.exitAggregateStatement(this)}accept(e){return e.visitAggregateStatement?e.visitAggregateStatement(this):e.visitChildren(this)}}w.AggregateStatementContext=uM;class aM extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}CALCULATE(){return this.getToken(d.CALCULATE,0)}queryFieldList(){return this.getRuleContext(0,fE)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_calculateStatement}enterRule(e){e.enterCalculateStatement&&e.enterCalculateStatement(this)}exitRule(e){e.exitCalculateStatement&&e.exitCalculateStatement(this)}accept(e){return e.visitCalculateStatement?e.visitCalculateStatement(this):e.visitChildren(this)}}w.CalculateStatementContext=aM;class lM extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}SELECT(){return this.getToken(d.SELECT,0)}fieldCollection(){return this.getRuleContext(0,FM)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_projectStatement}enterRule(e){e.enterProjectStatement&&e.enterProjectStatement(this)}exitRule(e){e.exitProjectStatement&&e.exitProjectStatement(this)}accept(e){return e.visitProjectStatement?e.visitProjectStatement(this):e.visitChildren(this)}}w.ProjectStatementContext=lM;class cM extends pe.ParserRuleContext{PARTITION_BY(){return this.getToken(d.PARTITION_BY,0)}id(e){return e===void 0?this.getRuleContexts(Dn):this.getRuleContext(e,Dn)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_partitionByStatement}enterRule(e){e.enterPartitionByStatement&&e.enterPartitionByStatement(this)}exitRule(e){e.exitPartitionByStatement&&e.exitPartitionByStatement(this)}accept(e){return e.visitPartitionByStatement?e.visitPartitionByStatement(this):e.visitChildren(this)}}w.PartitionByStatementContext=cM;class fM extends pe.ParserRuleContext{ORDER_BY(){return this.getToken(d.ORDER_BY,0)}ordering(){return this.getRuleContext(0,xM)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_orderByStatement}enterRule(e){e.enterOrderByStatement&&e.enterOrderByStatement(this)}exitRule(e){e.exitOrderByStatement&&e.exitOrderByStatement(this)}accept(e){return e.visitOrderByStatement?e.visitOrderByStatement(this):e.visitChildren(this)}}w.OrderByStatementContext=fM;class xM extends pe.ParserRuleContext{orderBySpec(e){return e===void 0?this.getRuleContexts(sR):this.getRuleContext(e,sR)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_ordering}enterRule(e){e.enterOrdering&&e.enterOrdering(this)}exitRule(e){e.exitOrdering&&e.exitOrdering(this)}accept(e){return e.visitOrdering?e.visitOrdering(this):e.visitChildren(this)}}w.OrderingContext=xM;class sR extends pe.ParserRuleContext{INTEGER_LITERAL(){return this.tryGetToken(d.INTEGER_LITERAL,0)}fieldName(){return this.tryGetRuleContext(0,Ur)}ASC(){return this.tryGetToken(d.ASC,0)}DESC(){return this.tryGetToken(d.DESC,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_orderBySpec}enterRule(e){e.enterOrderBySpec&&e.enterOrderBySpec(this)}exitRule(e){e.exitOrderBySpec&&e.exitOrderBySpec(this)}accept(e){return e.visitOrderBySpec?e.visitOrderBySpec(this):e.visitChildren(this)}}w.OrderBySpecContext=sR;class oR extends pe.ParserRuleContext{LIMIT(){return this.getToken(d.LIMIT,0)}INTEGER_LITERAL(){return this.getToken(d.INTEGER_LITERAL,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_limitStatement}enterRule(e){e.enterLimitStatement&&e.enterLimitStatement(this)}exitRule(e){e.exitLimitStatement&&e.exitLimitStatement(this)}accept(e){return e.visitLimitStatement?e.visitLimitStatement(this):e.visitChildren(this)}}w.LimitStatementContext=oR;class Nce extends pe.ParserRuleContext{BY(){return this.getToken(d.BY,0)}fieldName(){return this.tryGetRuleContext(0,Ur)}fieldExpr(){return this.tryGetRuleContext(0,Te)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_bySpec}enterRule(e){e.enterBySpec&&e.enterBySpec(this)}exitRule(e){e.exitBySpec&&e.exitBySpec(this)}accept(e){return e.visitBySpec?e.visitBySpec(this):e.visitChildren(this)}}w.BySpecContext=Nce;class dM extends pe.ParserRuleContext{TOP(){return this.getToken(d.TOP,0)}INTEGER_LITERAL(){return this.getToken(d.INTEGER_LITERAL,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_topStatement}enterRule(e){e.enterTopStatement&&e.enterTopStatement(this)}exitRule(e){e.exitTopStatement&&e.exitTopStatement(this)}accept(e){return e.visitTopStatement?e.visitTopStatement(this):e.visitChildren(this)}}w.TopStatementContext=dM;class uR extends pe.ParserRuleContext{fieldPath(){return this.tryGetRuleContext(0,Na)}DOT(){return this.tryGetToken(d.DOT,0)}STAR(){return this.tryGetToken(d.STAR,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_indexElement}enterRule(e){e.enterIndexElement&&e.enterIndexElement(this)}exitRule(e){e.exitIndexElement&&e.exitIndexElement(this)}accept(e){return e.visitIndexElement?e.visitIndexElement(this):e.visitChildren(this)}}w.IndexElementContext=uR;class hM extends pe.ParserRuleContext{indexElement(e){return e===void 0?this.getRuleContexts(uR):this.getRuleContext(e,uR)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_indexFields}enterRule(e){e.enterIndexFields&&e.enterIndexFields(this)}exitRule(e){e.exitIndexFields&&e.exitIndexFields(this)}accept(e){return e.visitIndexFields?e.visitIndexFields(this):e.visitChildren(this)}}w.IndexFieldsContext=hM;class pM extends pe.ParserRuleContext{INDEX(){return this.getToken(d.INDEX,0)}indexFields(){return this.getRuleContext(0,hM)}BY(){return this.tryGetToken(d.BY,0)}fieldName(){return this.tryGetRuleContext(0,Ur)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_indexStatement}enterRule(e){e.enterIndexStatement&&e.enterIndexStatement(this)}exitRule(e){e.exitIndexStatement&&e.exitIndexStatement(this)}accept(e){return e.visitIndexStatement?e.visitIndexStatement(this):e.visitChildren(this)}}w.IndexStatementContext=pM;class mM extends pe.ParserRuleContext{SAMPLE(){return this.getToken(d.SAMPLE,0)}sampleSpec(){return this.getRuleContext(0,yM)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sampleStatement}enterRule(e){e.enterSampleStatement&&e.enterSampleStatement(this)}exitRule(e){e.exitSampleStatement&&e.exitSampleStatement(this)}accept(e){return e.visitSampleStatement?e.visitSampleStatement(this):e.visitChildren(this)}}w.SampleStatementContext=mM;class aR extends pe.ParserRuleContext{TIMEZONE(){return this.getToken(d.TIMEZONE,0)}string(){return this.getRuleContext(0,Fa)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_timezoneStatement}enterRule(e){e.enterTimezoneStatement&&e.enterTimezoneStatement(this)}exitRule(e){e.exitTimezoneStatement&&e.exitTimezoneStatement(this)}accept(e){return e.visitTimezoneStatement?e.visitTimezoneStatement(this):e.visitChildren(this)}}w.TimezoneStatementContext=aR;class gM extends pe.ParserRuleContext{ANNOTATION(){return this.getToken(d.ANNOTATION,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_queryAnnotation}enterRule(e){e.enterQueryAnnotation&&e.enterQueryAnnotation(this)}exitRule(e){e.exitQueryAnnotation&&e.exitQueryAnnotation(this)}accept(e){return e.visitQueryAnnotation?e.visitQueryAnnotation(this):e.visitChildren(this)}}w.QueryAnnotationContext=gM;class yM extends pe.ParserRuleContext{PERCENT_LITERAL(){return this.tryGetToken(d.PERCENT_LITERAL,0)}INTEGER_LITERAL(){return this.tryGetToken(d.INTEGER_LITERAL,0)}TRUE(){return this.tryGetToken(d.TRUE,0)}FALSE(){return this.tryGetToken(d.FALSE,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sampleSpec}enterRule(e){e.enterSampleSpec&&e.enterSampleSpec(this)}exitRule(e){e.exitSampleSpec&&e.exitSampleSpec(this)}accept(e){return e.visitSampleSpec?e.visitSampleSpec(this):e.visitChildren(this)}}w.SampleSpecContext=yM;class dE extends pe.ParserRuleContext{SUM(){return this.tryGetToken(d.SUM,0)}COUNT(){return this.tryGetToken(d.COUNT,0)}AVG(){return this.tryGetToken(d.AVG,0)}MIN(){return this.tryGetToken(d.MIN,0)}MAX(){return this.tryGetToken(d.MAX,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_aggregate}enterRule(e){e.enterAggregate&&e.enterAggregate(this)}exitRule(e){e.exitAggregate&&e.exitAggregate(this)}accept(e){return e.visitAggregate?e.visitAggregate(this):e.visitChildren(this)}}w.AggregateContext=dE;class hE extends pe.ParserRuleContext{STRING(){return this.tryGetToken(d.STRING,0)}NUMBER(){return this.tryGetToken(d.NUMBER,0)}BOOLEAN(){return this.tryGetToken(d.BOOLEAN,0)}DATE(){return this.tryGetToken(d.DATE,0)}TIMESTAMP(){return this.tryGetToken(d.TIMESTAMP,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_malloyType}enterRule(e){e.enterMalloyType&&e.enterMalloyType(this)}exitRule(e){e.exitMalloyType&&e.exitMalloyType(this)}accept(e){return e.visitMalloyType?e.visitMalloyType(this):e.visitChildren(this)}}w.MalloyTypeContext=hE;class lR extends pe.ParserRuleContext{MATCH(){return this.tryGetToken(d.MATCH,0)}NOT_MATCH(){return this.tryGetToken(d.NOT_MATCH,0)}GT(){return this.tryGetToken(d.GT,0)}LT(){return this.tryGetToken(d.LT,0)}GTE(){return this.tryGetToken(d.GTE,0)}LTE(){return this.tryGetToken(d.LTE,0)}EQ(){return this.tryGetToken(d.EQ,0)}NE(){return this.tryGetToken(d.NE,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_compareOp}enterRule(e){e.enterCompareOp&&e.enterCompareOp(this)}exitRule(e){e.exitCompareOp&&e.exitCompareOp(this)}accept(e){return e.visitCompareOp?e.visitCompareOp(this):e.visitChildren(this)}}w.CompareOpContext=lR;class Fa extends pe.ParserRuleContext{shortString(){return this.tryGetRuleContext(0,cR)}sqlString(){return this.tryGetRuleContext(0,FT)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_string}enterRule(e){e.enterString&&e.enterString(this)}exitRule(e){e.exitString&&e.exitString(this)}accept(e){return e.visitString?e.visitString(this):e.visitChildren(this)}}w.StringContext=Fa;class cR extends pe.ParserRuleContext{SQ_STRING(){return this.tryGetToken(d.SQ_STRING,0)}DQ_STRING(){return this.tryGetToken(d.DQ_STRING,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_shortString}enterRule(e){e.enterShortString&&e.enterShortString(this)}exitRule(e){e.exitShortString&&e.exitShortString(this)}accept(e){return e.visitShortString?e.visitShortString(this):e.visitChildren(this)}}w.ShortStringContext=cR;class EM extends pe.ParserRuleContext{RAW_SQ(){return this.tryGetToken(d.RAW_SQ,0)}RAW_DQ(){return this.tryGetToken(d.RAW_DQ,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_rawString}enterRule(e){e.enterRawString&&e.enterRawString(this)}exitRule(e){e.exitRawString&&e.exitRawString(this)}accept(e){return e.visitRawString?e.visitRawString(this):e.visitChildren(this)}}w.RawStringContext=EM;class AM extends pe.ParserRuleContext{NUMERIC_LITERAL(){return this.tryGetToken(d.NUMERIC_LITERAL,0)}INTEGER_LITERAL(){return this.tryGetToken(d.INTEGER_LITERAL,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_numericLiteral}enterRule(e){e.enterNumericLiteral&&e.enterNumericLiteral(this)}exitRule(e){e.exitNumericLiteral&&e.exitNumericLiteral(this)}accept(e){return e.visitNumericLiteral?e.visitNumericLiteral(this):e.visitChildren(this)}}w.NumericLiteralContext=AM;class _o extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_literal}copyFrom(e){super.copyFrom(e)}}w.LiteralContext=_o;class Lce extends _o{string(){return this.getRuleContext(0,Fa)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprString&&e.enterExprString(this)}exitRule(e){e.exitExprString&&e.exitExprString(this)}accept(e){return e.visitExprString?e.visitExprString(this):e.visitChildren(this)}}w.ExprStringContext=Lce;class Ice extends _o{rawString(){return this.getRuleContext(0,EM)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterStub_rawString&&e.enterStub_rawString(this)}exitRule(e){e.exitStub_rawString&&e.exitStub_rawString(this)}accept(e){return e.visitStub_rawString?e.visitStub_rawString(this):e.visitChildren(this)}}w.Stub_rawStringContext=Ice;class Bce extends _o{numericLiteral(){return this.getRuleContext(0,AM)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprNumber&&e.enterExprNumber(this)}exitRule(e){e.exitExprNumber&&e.exitExprNumber(this)}accept(e){return e.visitExprNumber?e.visitExprNumber(this):e.visitChildren(this)}}w.ExprNumberContext=Bce;class $ce extends _o{dateLiteral(){return this.getRuleContext(0,wa)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprTime&&e.enterExprTime(this)}exitRule(e){e.exitExprTime&&e.exitExprTime(this)}accept(e){return e.visitExprTime?e.visitExprTime(this):e.visitChildren(this)}}w.ExprTimeContext=$ce;class kce extends _o{NULL(){return this.getToken(d.NULL,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprNULL&&e.enterExprNULL(this)}exitRule(e){e.exitExprNULL&&e.exitExprNULL(this)}accept(e){return e.visitExprNULL?e.visitExprNULL(this):e.visitChildren(this)}}w.ExprNULLContext=kce;class Mce extends _o{TRUE(){return this.tryGetToken(d.TRUE,0)}FALSE(){return this.tryGetToken(d.FALSE,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprBool&&e.enterExprBool(this)}exitRule(e){e.exitExprBool&&e.exitExprBool(this)}accept(e){return e.visitExprBool?e.visitExprBool(this):e.visitChildren(this)}}w.ExprBoolContext=Mce;class Pce extends _o{HACKY_REGEX(){return this.getToken(d.HACKY_REGEX,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprRegex&&e.enterExprRegex(this)}exitRule(e){e.exitExprRegex&&e.exitExprRegex(this)}accept(e){return e.visitExprRegex?e.visitExprRegex(this):e.visitChildren(this)}}w.ExprRegexContext=Pce;class Uce extends _o{filterString(){return this.getRuleContext(0,IM)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterFilterString_stub&&e.enterFilterString_stub(this)}exitRule(e){e.exitFilterString_stub&&e.exitFilterString_stub(this)}accept(e){return e.visitFilterString_stub?e.visitFilterString_stub(this):e.visitChildren(this)}}w.FilterString_stubContext=Uce;class jce extends _o{NOW(){return this.getToken(d.NOW,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprNow&&e.enterExprNow(this)}exitRule(e){e.exitExprNow&&e.exitExprNow(this)}accept(e){return e.visitExprNow?e.visitExprNow(this):e.visitChildren(this)}}w.ExprNowContext=jce;class wa extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_dateLiteral}copyFrom(e){super.copyFrom(e)}}w.DateLiteralContext=wa;class qce extends wa{LITERAL_TIMESTAMP(){return this.getToken(d.LITERAL_TIMESTAMP,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterLiteralTimestamp&&e.enterLiteralTimestamp(this)}exitRule(e){e.exitLiteralTimestamp&&e.exitLiteralTimestamp(this)}accept(e){return e.visitLiteralTimestamp?e.visitLiteralTimestamp(this):e.visitChildren(this)}}w.LiteralTimestampContext=qce;class Hce extends wa{LITERAL_HOUR(){return this.getToken(d.LITERAL_HOUR,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterLiteralHour&&e.enterLiteralHour(this)}exitRule(e){e.exitLiteralHour&&e.exitLiteralHour(this)}accept(e){return e.visitLiteralHour?e.visitLiteralHour(this):e.visitChildren(this)}}w.LiteralHourContext=Hce;class Qce extends wa{LITERAL_DAY(){return this.getToken(d.LITERAL_DAY,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterLiteralDay&&e.enterLiteralDay(this)}exitRule(e){e.exitLiteralDay&&e.exitLiteralDay(this)}accept(e){return e.visitLiteralDay?e.visitLiteralDay(this):e.visitChildren(this)}}w.LiteralDayContext=Qce;class zce extends wa{LITERAL_WEEK(){return this.getToken(d.LITERAL_WEEK,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterLiteralWeek&&e.enterLiteralWeek(this)}exitRule(e){e.exitLiteralWeek&&e.exitLiteralWeek(this)}accept(e){return e.visitLiteralWeek?e.visitLiteralWeek(this):e.visitChildren(this)}}w.LiteralWeekContext=zce;class Gce extends wa{LITERAL_MONTH(){return this.getToken(d.LITERAL_MONTH,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterLiteralMonth&&e.enterLiteralMonth(this)}exitRule(e){e.exitLiteralMonth&&e.exitLiteralMonth(this)}accept(e){return e.visitLiteralMonth?e.visitLiteralMonth(this):e.visitChildren(this)}}w.LiteralMonthContext=Gce;class Wce extends wa{LITERAL_QUARTER(){return this.getToken(d.LITERAL_QUARTER,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterLiteralQuarter&&e.enterLiteralQuarter(this)}exitRule(e){e.exitLiteralQuarter&&e.exitLiteralQuarter(this)}accept(e){return e.visitLiteralQuarter?e.visitLiteralQuarter(this):e.visitChildren(this)}}w.LiteralQuarterContext=Wce;class Vce extends wa{LITERAL_YEAR(){return this.getToken(d.LITERAL_YEAR,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterLiteralYear&&e.enterLiteralYear(this)}exitRule(e){e.exitLiteralYear&&e.exitLiteralYear(this)}accept(e){return e.visitLiteralYear?e.visitLiteralYear(this):e.visitChildren(this)}}w.LiteralYearContext=Vce;class _M extends pe.ParserRuleContext{string(){return this.getRuleContext(0,Fa)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_tablePath}enterRule(e){e.enterTablePath&&e.enterTablePath(this)}exitRule(e){e.exitTablePath&&e.exitTablePath(this)}accept(e){return e.visitTablePath?e.visitTablePath(this):e.visitChildren(this)}}w.TablePathContext=_M;class Yce extends pe.ParserRuleContext{string(){return this.getRuleContext(0,Fa)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_tableURI}enterRule(e){e.enterTableURI&&e.enterTableURI(this)}exitRule(e){e.exitTableURI&&e.exitTableURI(this)}accept(e){return e.visitTableURI?e.visitTableURI(this):e.visitChildren(this)}}w.TableURIContext=Yce;class Dn extends pe.ParserRuleContext{IDENTIFIER(){return this.tryGetToken(d.IDENTIFIER,0)}BQ_STRING(){return this.tryGetToken(d.BQ_STRING,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_id}enterRule(e){e.enterId&&e.enterId(this)}exitRule(e){e.exitId&&e.exitId(this)}accept(e){return e.visitId?e.visitId(this):e.visitChildren(this)}}w.IdContext=Dn;class ad extends pe.ParserRuleContext{SECOND(){return this.tryGetToken(d.SECOND,0)}MINUTE(){return this.tryGetToken(d.MINUTE,0)}HOUR(){return this.tryGetToken(d.HOUR,0)}DAY(){return this.tryGetToken(d.DAY,0)}WEEK(){return this.tryGetToken(d.WEEK,0)}MONTH(){return this.tryGetToken(d.MONTH,0)}QUARTER(){return this.tryGetToken(d.QUARTER,0)}YEAR(){return this.tryGetToken(d.YEAR,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_timeframe}enterRule(e){e.enterTimeframe&&e.enterTimeframe(this)}exitRule(e){e.exitTimeframe&&e.exitTimeframe(this)}accept(e){return e.visitTimeframe?e.visitTimeframe(this):e.visitChildren(this)}}w.TimeframeContext=ad;class vM extends pe.ParserRuleContext{ALL(){return this.tryGetToken(d.ALL,0)}EXCLUDE(){return this.tryGetToken(d.EXCLUDE,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_ungroup}enterRule(e){e.enterUngroup&&e.enterUngroup(this)}exitRule(e){e.exitUngroup&&e.exitUngroup(this)}accept(e){return e.visitUngroup?e.visitUngroup(this):e.visitChildren(this)}}w.UngroupContext=vM;class fR extends pe.ParserRuleContext{malloyType(){return this.tryGetRuleContext(0,hE)}string(){return this.tryGetRuleContext(0,Fa)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_malloyOrSQLType}enterRule(e){e.enterMalloyOrSQLType&&e.enterMalloyOrSQLType(this)}exitRule(e){e.exitMalloyOrSQLType&&e.exitMalloyOrSQLType(this)}accept(e){return e.visitMalloyOrSQLType?e.visitMalloyOrSQLType(this):e.visitChildren(this)}}w.MalloyOrSQLTypeContext=fR;class Te extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_fieldExpr}copyFrom(e){super.copyFrom(e)}}w.FieldExprContext=Te;class Kce extends Te{fieldPath(){return this.getRuleContext(0,Na)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprFieldPath&&e.enterExprFieldPath(this)}exitRule(e){e.exitExprFieldPath&&e.exitExprFieldPath(this)}accept(e){return e.visitExprFieldPath?e.visitExprFieldPath(this):e.visitChildren(this)}}w.ExprFieldPathContext=Kce;class Jce extends Te{literal(){return this.getRuleContext(0,_o)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprLiteral&&e.enterExprLiteral(this)}exitRule(e){e.exitExprLiteral&&e.exitExprLiteral(this)}accept(e){return e.visitExprLiteral?e.visitExprLiteral(this):e.visitChildren(this)}}w.ExprLiteralContext=Jce;class Xce extends Te{OBRACK(){return this.getToken(d.OBRACK,0)}fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}CBRACK(){return this.getToken(d.CBRACK,0)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprArrayLiteral&&e.enterExprArrayLiteral(this)}exitRule(e){e.exitExprArrayLiteral&&e.exitExprArrayLiteral(this)}accept(e){return e.visitExprArrayLiteral?e.visitExprArrayLiteral(this):e.visitChildren(this)}}w.ExprArrayLiteralContext=Xce;class Zce extends Te{OCURLY(){return this.getToken(d.OCURLY,0)}recordElement(e){return e===void 0?this.getRuleContexts(S2):this.getRuleContext(e,S2)}CCURLY(){return this.getToken(d.CCURLY,0)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprLiteralRecord&&e.enterExprLiteralRecord(this)}exitRule(e){e.exitExprLiteralRecord&&e.exitExprLiteralRecord(this)}accept(e){return e.visitExprLiteralRecord?e.visitExprLiteralRecord(this):e.visitChildren(this)}}w.ExprLiteralRecordContext=Zce;class efe extends Te{fieldExpr(){return this.getRuleContext(0,Te)}fieldProperties(){return this.getRuleContext(0,Jk)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprFieldProps&&e.enterExprFieldProps(this)}exitRule(e){e.exitExprFieldProps&&e.exitExprFieldProps(this)}accept(e){return e.visitExprFieldProps?e.visitExprFieldProps(this):e.visitChildren(this)}}w.ExprFieldPropsContext=efe;class tfe extends Te{fieldExpr(){return this.getRuleContext(0,Te)}timeframe(){return this.getRuleContext(0,ad)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprDuration&&e.enterExprDuration(this)}exitRule(e){e.exitExprDuration&&e.exitExprDuration(this)}accept(e){return e.visitExprDuration?e.visitExprDuration(this):e.visitChildren(this)}}w.ExprDurationContext=tfe;class nfe extends Te{fieldExpr(){return this.getRuleContext(0,Te)}DOT(){return this.getToken(d.DOT,0)}timeframe(){return this.getRuleContext(0,ad)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprTimeTrunc&&e.enterExprTimeTrunc(this)}exitRule(e){e.exitExprTimeTrunc&&e.exitExprTimeTrunc(this)}accept(e){return e.visitExprTimeTrunc?e.visitExprTimeTrunc(this):e.visitChildren(this)}}w.ExprTimeTruncContext=nfe;class CM extends Te{fieldExpr(){return this.getRuleContext(0,Te)}DOUBLECOLON(){return this.tryGetToken(d.DOUBLECOLON,0)}malloyOrSQLType(){return this.getRuleContext(0,fR)}CAST(){return this.tryGetToken(d.CAST,0)}OPAREN(){return this.tryGetToken(d.OPAREN,0)}AS(){return this.tryGetToken(d.AS,0)}CPAREN(){return this.tryGetToken(d.CPAREN,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprCast&&e.enterExprCast(this)}exitRule(e){e.exitExprCast&&e.exitExprCast(this)}accept(e){return e.visitExprCast?e.visitExprCast(this):e.visitChildren(this)}}w.ExprCastContext=CM;class rfe extends Te{fieldExpr(){return this.getRuleContext(0,Te)}TRIPLECOLON(){return this.getToken(d.TRIPLECOLON,0)}malloyOrSQLType(){return this.getRuleContext(0,fR)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprSafeCast&&e.enterExprSafeCast(this)}exitRule(e){e.exitExprSafeCast&&e.exitExprSafeCast(this)}accept(e){return e.visitExprSafeCast?e.visitExprSafeCast(this):e.visitChildren(this)}}w.ExprSafeCastContext=rfe;class ife extends Te{MINUS(){return this.getToken(d.MINUS,0)}fieldExpr(){return this.getRuleContext(0,Te)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprMinus&&e.enterExprMinus(this)}exitRule(e){e.exitExprMinus&&e.exitExprMinus(this)}accept(e){return e.visitExprMinus?e.visitExprMinus(this):e.visitChildren(this)}}w.ExprMinusContext=ife;class sfe extends Te{fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}STAR(){return this.tryGetToken(d.STAR,0)}SLASH(){return this.tryGetToken(d.SLASH,0)}PERCENT(){return this.tryGetToken(d.PERCENT,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprMulDiv&&e.enterExprMulDiv(this)}exitRule(e){e.exitExprMulDiv&&e.exitExprMulDiv(this)}accept(e){return e.visitExprMulDiv?e.visitExprMulDiv(this):e.visitChildren(this)}}w.ExprMulDivContext=sfe;class ofe extends Te{fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}PLUS(){return this.tryGetToken(d.PLUS,0)}MINUS(){return this.tryGetToken(d.MINUS,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprAddSub&&e.enterExprAddSub(this)}exitRule(e){e.exitExprAddSub&&e.exitExprAddSub(this)}accept(e){return e.visitExprAddSub?e.visitExprAddSub(this):e.visitChildren(this)}}w.ExprAddSubContext=ofe;class ufe extends Te{fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}TO(){return this.getToken(d.TO,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprRange&&e.enterExprRange(this)}exitRule(e){e.exitExprRange&&e.exitExprRange(this)}accept(e){return e.visitExprRange?e.visitExprRange(this):e.visitChildren(this)}}w.ExprRangeContext=ufe;class afe extends Te{FOR(){return this.getToken(d.FOR,0)}timeframe(){return this.getRuleContext(0,ad)}fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprForRange&&e.enterExprForRange(this)}exitRule(e){e.exitExprForRange&&e.exitExprForRange(this)}accept(e){return e.visitExprForRange?e.visitExprForRange(this):e.visitChildren(this)}}w.ExprForRangeContext=afe;class lfe extends Te{fieldExpr(){return this.getRuleContext(0,Te)}AMPER(){return this.getToken(d.AMPER,0)}partialAllowedFieldExpr(){return this.getRuleContext(0,ld)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprAndTree&&e.enterExprAndTree(this)}exitRule(e){e.exitExprAndTree&&e.exitExprAndTree(this)}accept(e){return e.visitExprAndTree?e.visitExprAndTree(this):e.visitChildren(this)}}w.ExprAndTreeContext=lfe;class cfe extends Te{fieldExpr(){return this.getRuleContext(0,Te)}BAR(){return this.getToken(d.BAR,0)}partialAllowedFieldExpr(){return this.getRuleContext(0,ld)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprOrTree&&e.enterExprOrTree(this)}exitRule(e){e.exitExprOrTree&&e.exitExprOrTree(this)}accept(e){return e.visitExprOrTree?e.visitExprOrTree(this):e.visitChildren(this)}}w.ExprOrTreeContext=cfe;class ffe extends Te{fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}compareOp(){return this.getRuleContext(0,lR)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprCompare&&e.enterExprCompare(this)}exitRule(e){e.exitExprCompare&&e.exitExprCompare(this)}accept(e){return e.visitExprCompare?e.visitExprCompare(this):e.visitChildren(this)}}w.ExprCompareContext=ffe;class xfe extends Te{fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}LIKE(){return this.getToken(d.LIKE,0)}NOT(){return this.tryGetToken(d.NOT,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprWarnLike&&e.enterExprWarnLike(this)}exitRule(e){e.exitExprWarnLike&&e.exitExprWarnLike(this)}accept(e){return e.visitExprWarnLike?e.visitExprWarnLike(this):e.visitChildren(this)}}w.ExprWarnLikeContext=xfe;class dfe extends Te{fieldExpr(){return this.getRuleContext(0,Te)}IS(){return this.getToken(d.IS,0)}NULL(){return this.getToken(d.NULL,0)}NOT(){return this.tryGetToken(d.NOT,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprNullCheck&&e.enterExprNullCheck(this)}exitRule(e){e.exitExprNullCheck&&e.exitExprNullCheck(this)}accept(e){return e.visitExprNullCheck?e.visitExprNullCheck(this):e.visitChildren(this)}}w.ExprNullCheckContext=dfe;class hfe extends Te{fieldExpr(){return this.getRuleContext(0,Te)}IN(){return this.getToken(d.IN,0)}OPAREN(){return this.getToken(d.OPAREN,0)}fieldExprList(){return this.getRuleContext(0,TM)}CPAREN(){return this.getToken(d.CPAREN,0)}NOT(){return this.tryGetToken(d.NOT,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprWarnIn&&e.enterExprWarnIn(this)}exitRule(e){e.exitExprWarnIn&&e.exitExprWarnIn(this)}accept(e){return e.visitExprWarnIn?e.visitExprWarnIn(this):e.visitChildren(this)}}w.ExprWarnInContext=hfe;class pfe extends Te{fieldExpr(){return this.getRuleContext(0,Te)}QMARK(){return this.getToken(d.QMARK,0)}partialAllowedFieldExpr(){return this.getRuleContext(0,ld)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprApply&&e.enterExprApply(this)}exitRule(e){e.exitExprApply&&e.exitExprApply(this)}accept(e){return e.visitExprApply?e.visitExprApply(this):e.visitChildren(this)}}w.ExprApplyContext=pfe;class mfe extends Te{NOT(){return this.getToken(d.NOT,0)}fieldExpr(){return this.getRuleContext(0,Te)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprNot&&e.enterExprNot(this)}exitRule(e){e.exitExprNot&&e.exitExprNot(this)}accept(e){return e.visitExprNot?e.visitExprNot(this):e.visitChildren(this)}}w.ExprNotContext=mfe;class gfe extends Te{fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}AND(){return this.getToken(d.AND,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprLogicalAnd&&e.enterExprLogicalAnd(this)}exitRule(e){e.exitExprLogicalAnd&&e.exitExprLogicalAnd(this)}accept(e){return e.visitExprLogicalAnd?e.visitExprLogicalAnd(this):e.visitChildren(this)}}w.ExprLogicalAndContext=gfe;class yfe extends Te{fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}OR(){return this.getToken(d.OR,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprLogicalOr&&e.enterExprLogicalOr(this)}exitRule(e){e.exitExprLogicalOr&&e.exitExprLogicalOr(this)}accept(e){return e.visitExprLogicalOr?e.visitExprLogicalOr(this):e.visitChildren(this)}}w.ExprLogicalOrContext=yfe;class Efe extends Te{fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}DOUBLE_QMARK(){return this.getToken(d.DOUBLE_QMARK,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprCoalesce&&e.enterExprCoalesce(this)}exitRule(e){e.exitExprCoalesce&&e.exitExprCoalesce(this)}accept(e){return e.visitExprCoalesce?e.visitExprCoalesce(this):e.visitChildren(this)}}w.ExprCoalesceContext=Efe;class Afe extends Te{aggregate(){return this.getRuleContext(0,dE)}OPAREN(){return this.getToken(d.OPAREN,0)}CPAREN(){return this.getToken(d.CPAREN,0)}SOURCE_KW(){return this.tryGetToken(d.SOURCE_KW,0)}DOT(){return this.tryGetToken(d.DOT,0)}fieldExpr(){return this.tryGetRuleContext(0,Te)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprPathlessAggregate&&e.enterExprPathlessAggregate(this)}exitRule(e){e.exitExprPathlessAggregate&&e.exitExprPathlessAggregate(this)}accept(e){return e.visitExprPathlessAggregate?e.visitExprPathlessAggregate(this):e.visitChildren(this)}}w.ExprPathlessAggregateContext=Afe;class _fe extends Te{fieldPath(){return this.getRuleContext(0,Na)}DOT(){return this.getToken(d.DOT,0)}aggregate(){return this.getRuleContext(0,dE)}OPAREN(){return this.getToken(d.OPAREN,0)}CPAREN(){return this.getToken(d.CPAREN,0)}fieldExpr(){return this.tryGetRuleContext(0,Te)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprAggregate&&e.enterExprAggregate(this)}exitRule(e){e.exitExprAggregate&&e.exitExprAggregate(this)}accept(e){return e.visitExprAggregate?e.visitExprAggregate(this):e.visitChildren(this)}}w.ExprAggregateContext=_fe;class vfe extends Te{OPAREN(){return this.getToken(d.OPAREN,0)}fieldExpr(){return this.getRuleContext(0,Te)}CPAREN(){return this.getToken(d.CPAREN,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprExpr&&e.enterExprExpr(this)}exitRule(e){e.exitExprExpr&&e.exitExprExpr(this)}accept(e){return e.visitExprExpr?e.visitExprExpr(this):e.visitChildren(this)}}w.ExprExprContext=vfe;class Cfe extends Te{fieldPath(){return this.getRuleContext(0,Na)}DOT(){return this.getToken(d.DOT,0)}id(){return this.getRuleContext(0,Dn)}OPAREN(){return this.getToken(d.OPAREN,0)}CPAREN(){return this.getToken(d.CPAREN,0)}argumentList(){return this.tryGetRuleContext(0,hR)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprAggFunc&&e.enterExprAggFunc(this)}exitRule(e){e.exitExprAggFunc&&e.exitExprAggFunc(this)}accept(e){return e.visitExprAggFunc?e.visitExprAggFunc(this):e.visitChildren(this)}}w.ExprAggFuncContext=Cfe;class Sfe extends Te{OPAREN(){return this.getToken(d.OPAREN,0)}CPAREN(){return this.getToken(d.CPAREN,0)}timeframe(){return this.tryGetRuleContext(0,ad)}id(){return this.tryGetRuleContext(0,Dn)}argumentList(){return this.tryGetRuleContext(0,hR)}EXCLAM(){return this.tryGetToken(d.EXCLAM,0)}malloyType(){return this.tryGetRuleContext(0,hE)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprFunc&&e.enterExprFunc(this)}exitRule(e){e.exitExprFunc&&e.exitExprFunc(this)}accept(e){return e.visitExprFunc?e.visitExprFunc(this):e.visitChildren(this)}}w.ExprFuncContext=Sfe;class bfe extends Te{pickStatement(){return this.getRuleContext(0,RM)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprPick&&e.enterExprPick(this)}exitRule(e){e.exitExprPick&&e.exitExprPick(this)}accept(e){return e.visitExprPick?e.visitExprPick(this):e.visitChildren(this)}}w.ExprPickContext=bfe;class Tfe extends Te{caseStatement(){return this.getRuleContext(0,DM)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprCase&&e.enterExprCase(this)}exitRule(e){e.exitExprCase&&e.exitExprCase(this)}accept(e){return e.visitExprCase?e.visitExprCase(this):e.visitChildren(this)}}w.ExprCaseContext=Tfe;class Rfe extends Te{ungroup(){return this.getRuleContext(0,vM)}OPAREN(){return this.getToken(d.OPAREN,0)}fieldExpr(){return this.getRuleContext(0,Te)}CPAREN(){return this.getToken(d.CPAREN,0)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}fieldName(e){return e===void 0?this.getRuleContexts(Ur):this.getRuleContext(e,Ur)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterExprUngroup&&e.enterExprUngroup(this)}exitRule(e){e.exitExprUngroup&&e.exitExprUngroup(this)}accept(e){return e.visitExprUngroup?e.visitExprUngroup(this):e.visitChildren(this)}}w.ExprUngroupContext=Rfe;class SM extends pe.ParserRuleContext{compareOp(){return this.getRuleContext(0,lR)}fieldExpr(){return this.getRuleContext(0,Te)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_partialCompare}enterRule(e){e.enterPartialCompare&&e.enterPartialCompare(this)}exitRule(e){e.exitPartialCompare&&e.exitPartialCompare(this)}accept(e){return e.visitPartialCompare?e.visitPartialCompare(this):e.visitChildren(this)}}w.PartialCompareContext=SM;class bM extends pe.ParserRuleContext{partialCompare(){return this.tryGetRuleContext(0,SM)}IS(){return this.tryGetToken(d.IS,0)}NULL(){return this.tryGetToken(d.NULL,0)}NOT(){return this.tryGetToken(d.NOT,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_partialTest}enterRule(e){e.enterPartialTest&&e.enterPartialTest(this)}exitRule(e){e.exitPartialTest&&e.exitPartialTest(this)}accept(e){return e.visitPartialTest?e.visitPartialTest(this):e.visitChildren(this)}}w.PartialTestContext=bM;class ld extends pe.ParserRuleContext{partialTest(){return this.tryGetRuleContext(0,bM)}OPAREN(){return this.tryGetToken(d.OPAREN,0)}CPAREN(){return this.tryGetToken(d.CPAREN,0)}fieldExpr(){return this.tryGetRuleContext(0,Te)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_partialAllowedFieldExpr}enterRule(e){e.enterPartialAllowedFieldExpr&&e.enterPartialAllowedFieldExpr(this)}exitRule(e){e.exitPartialAllowedFieldExpr&&e.exitPartialAllowedFieldExpr(this)}accept(e){return e.visitPartialAllowedFieldExpr?e.visitPartialAllowedFieldExpr(this):e.visitChildren(this)}}w.PartialAllowedFieldExprContext=ld;class TM extends pe.ParserRuleContext{fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_fieldExprList}enterRule(e){e.enterFieldExprList&&e.enterFieldExprList(this)}exitRule(e){e.exitFieldExprList&&e.exitFieldExprList(this)}accept(e){return e.visitFieldExprList?e.visitFieldExprList(this):e.visitChildren(this)}}w.FieldExprListContext=TM;class RM extends pe.ParserRuleContext{pick(e){return e===void 0?this.getRuleContexts(xR):this.getRuleContext(e,xR)}ELSE(){return this.tryGetToken(d.ELSE,0)}fieldExpr(){return this.tryGetRuleContext(0,Te)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_pickStatement}enterRule(e){e.enterPickStatement&&e.enterPickStatement(this)}exitRule(e){e.exitPickStatement&&e.exitPickStatement(this)}accept(e){return e.visitPickStatement?e.visitPickStatement(this):e.visitChildren(this)}}w.PickStatementContext=RM;class xR extends pe.ParserRuleContext{PICK(){return this.getToken(d.PICK,0)}WHEN(){return this.getToken(d.WHEN,0)}partialAllowedFieldExpr(){return this.getRuleContext(0,ld)}fieldExpr(){return this.tryGetRuleContext(0,Te)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_pick}enterRule(e){e.enterPick&&e.enterPick(this)}exitRule(e){e.exitPick&&e.exitPick(this)}accept(e){return e.visitPick?e.visitPick(this):e.visitChildren(this)}}w.PickContext=xR;class DM extends pe.ParserRuleContext{CASE(){return this.getToken(d.CASE,0)}END(){return this.getToken(d.END,0)}caseWhen(e){return e===void 0?this.getRuleContexts(dR):this.getRuleContext(e,dR)}ELSE(){return this.tryGetToken(d.ELSE,0)}fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_caseStatement}enterRule(e){e.enterCaseStatement&&e.enterCaseStatement(this)}exitRule(e){e.exitCaseStatement&&e.exitCaseStatement(this)}accept(e){return e.visitCaseStatement?e.visitCaseStatement(this):e.visitChildren(this)}}w.CaseStatementContext=DM;class dR extends pe.ParserRuleContext{WHEN(){return this.getToken(d.WHEN,0)}THEN(){return this.getToken(d.THEN,0)}fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_caseWhen}enterRule(e){e.enterCaseWhen&&e.enterCaseWhen(this)}exitRule(e){e.exitCaseWhen&&e.exitCaseWhen(this)}accept(e){return e.visitCaseWhen?e.visitCaseWhen(this):e.visitChildren(this)}}w.CaseWhenContext=dR;class OM extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_recordKey}enterRule(e){e.enterRecordKey&&e.enterRecordKey(this)}exitRule(e){e.exitRecordKey&&e.exitRecordKey(this)}accept(e){return e.visitRecordKey?e.visitRecordKey(this):e.visitChildren(this)}}w.RecordKeyContext=OM;class S2 extends pe.ParserRuleContext{constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_recordElement}copyFrom(e){super.copyFrom(e)}}w.RecordElementContext=S2;class Dfe extends S2{fieldPath(){return this.getRuleContext(0,Na)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterRecordRef&&e.enterRecordRef(this)}exitRule(e){e.exitRecordRef&&e.exitRecordRef(this)}accept(e){return e.visitRecordRef?e.visitRecordRef(this):e.visitChildren(this)}}w.RecordRefContext=Dfe;class Ofe extends S2{fieldExpr(){return this.getRuleContext(0,Te)}recordKey(){return this.tryGetRuleContext(0,OM)}IS(){return this.tryGetToken(d.IS,0)}constructor(e){super(e.parent,e.invokingState),this.copyFrom(e)}enterRule(e){e.enterRecordExpr&&e.enterRecordExpr(this)}exitRule(e){e.exitRecordExpr&&e.exitRecordExpr(this)}accept(e){return e.visitRecordExpr?e.visitRecordExpr(this):e.visitChildren(this)}}w.RecordExprContext=Ofe;class hR extends pe.ParserRuleContext{fieldExpr(e){return e===void 0?this.getRuleContexts(Te):this.getRuleContext(e,Te)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_argumentList}enterRule(e){e.enterArgumentList&&e.enterArgumentList(this)}exitRule(e){e.exitArgumentList&&e.exitArgumentList(this)}accept(e){return e.visitArgumentList?e.visitArgumentList(this):e.visitChildren(this)}}w.ArgumentListContext=hR;class b2 extends pe.ParserRuleContext{fieldName(e){return e===void 0?this.getRuleContexts(Ur):this.getRuleContext(e,Ur)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_fieldNameList}enterRule(e){e.enterFieldNameList&&e.enterFieldNameList(this)}exitRule(e){e.exitFieldNameList&&e.exitFieldNameList(this)}accept(e){return e.visitFieldNameList?e.visitFieldNameList(this):e.visitChildren(this)}}w.FieldNameListContext=b2;class FM extends pe.ParserRuleContext{collectionMember(e){return e===void 0?this.getRuleContexts(gR):this.getRuleContext(e,gR)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_fieldCollection}enterRule(e){e.enterFieldCollection&&e.enterFieldCollection(this)}exitRule(e){e.exitFieldCollection&&e.exitFieldCollection(this)}accept(e){return e.visitFieldCollection?e.visitFieldCollection(this):e.visitChildren(this)}}w.FieldCollectionContext=FM;class pE extends pe.ParserRuleContext{STAR(){return this.getToken(d.STAR,0)}fieldPath(){return this.tryGetRuleContext(0,Na)}DOT(){return this.tryGetToken(d.DOT,0)}starQualified(){return this.tryGetRuleContext(0,pR)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_collectionWildCard}enterRule(e){e.enterCollectionWildCard&&e.enterCollectionWildCard(this)}exitRule(e){e.exitCollectionWildCard&&e.exitCollectionWildCard(this)}accept(e){return e.visitCollectionWildCard?e.visitCollectionWildCard(this):e.visitChildren(this)}}w.CollectionWildCardContext=pE;class pR extends pe.ParserRuleContext{OCURLY(){return this.getToken(d.OCURLY,0)}CCURLY(){return this.getToken(d.CCURLY,0)}COMMA(e){return e===void 0?this.getTokens(d.COMMA):this.getToken(d.COMMA,e)}EXCEPT(e){return e===void 0?this.getTokens(d.EXCEPT):this.getToken(d.EXCEPT,e)}fieldNameList(e){return e===void 0?this.getRuleContexts(b2):this.getRuleContext(e,b2)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_starQualified}enterRule(e){e.enterStarQualified&&e.enterStarQualified(this)}exitRule(e){e.exitStarQualified&&e.exitStarQualified(this)}accept(e){return e.visitStarQualified?e.visitStarQualified(this):e.visitChildren(this)}}w.StarQualifiedContext=pR;class mR extends pe.ParserRuleContext{tags(){return this.getRuleContext(0,Yt)}fieldPath(){return this.getRuleContext(0,Na)}refExpr(){return this.tryGetRuleContext(0,wM)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_taggedRef}enterRule(e){e.enterTaggedRef&&e.enterTaggedRef(this)}exitRule(e){e.exitTaggedRef&&e.exitTaggedRef(this)}accept(e){return e.visitTaggedRef?e.visitTaggedRef(this):e.visitChildren(this)}}w.TaggedRefContext=mR;class wM extends pe.ParserRuleContext{DOT(){return this.getToken(d.DOT,0)}timeframe(){return this.tryGetRuleContext(0,ad)}aggregate(){return this.tryGetRuleContext(0,dE)}OPAREN(){return this.tryGetToken(d.OPAREN,0)}CPAREN(){return this.tryGetToken(d.CPAREN,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_refExpr}enterRule(e){e.enterRefExpr&&e.enterRefExpr(this)}exitRule(e){e.exitRefExpr&&e.exitRefExpr(this)}accept(e){return e.visitRefExpr?e.visitRefExpr(this):e.visitChildren(this)}}w.RefExprContext=wM;class gR extends pe.ParserRuleContext{taggedRef(){return this.tryGetRuleContext(0,mR)}collectionWildCard(){return this.tryGetRuleContext(0,pE)}fieldDef(){return this.tryGetRuleContext(0,v2)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_collectionMember}enterRule(e){e.enterCollectionMember&&e.enterCollectionMember(this)}exitRule(e){e.exitCollectionMember&&e.exitCollectionMember(this)}accept(e){return e.visitCollectionMember?e.visitCollectionMember(this):e.visitChildren(this)}}w.CollectionMemberContext=gR;class Na extends pe.ParserRuleContext{fieldName(e){return e===void 0?this.getRuleContexts(Ur):this.getRuleContext(e,Ur)}DOT(e){return e===void 0?this.getTokens(d.DOT):this.getToken(d.DOT,e)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_fieldPath}enterRule(e){e.enterFieldPath&&e.enterFieldPath(this)}exitRule(e){e.exitFieldPath&&e.exitFieldPath(this)}accept(e){return e.visitFieldPath?e.visitFieldPath(this):e.visitChildren(this)}}w.FieldPathContext=Na;class Ffe extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_joinName}enterRule(e){e.enterJoinName&&e.enterJoinName(this)}exitRule(e){e.exitJoinName&&e.exitJoinName(this)}accept(e){return e.visitJoinName?e.visitJoinName(this):e.visitChildren(this)}}w.JoinNameContext=Ffe;class Ur extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_fieldName}enterRule(e){e.enterFieldName&&e.enterFieldName(this)}exitRule(e){e.exitFieldName&&e.exitFieldName(this)}accept(e){return e.visitFieldName?e.visitFieldName(this):e.visitChildren(this)}}w.FieldNameContext=Ur;class wfe extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_sqlExploreNameRef}enterRule(e){e.enterSqlExploreNameRef&&e.enterSqlExploreNameRef(this)}exitRule(e){e.exitSqlExploreNameRef&&e.exitSqlExploreNameRef(this)}accept(e){return e.visitSqlExploreNameRef?e.visitSqlExploreNameRef(this):e.visitChildren(this)}}w.SqlExploreNameRefContext=wfe;class Nfe extends pe.ParserRuleContext{id(){return this.getRuleContext(0,Dn)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_nameSQLBlock}enterRule(e){e.enterNameSQLBlock&&e.enterNameSQLBlock(this)}exitRule(e){e.exitNameSQLBlock&&e.exitNameSQLBlock(this)}accept(e){return e.visitNameSQLBlock?e.visitNameSQLBlock(this):e.visitChildren(this)}}w.NameSQLBlockContext=Nfe;class Lfe extends pe.ParserRuleContext{string(){return this.getRuleContext(0,Fa)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_connectionName}enterRule(e){e.enterConnectionName&&e.enterConnectionName(this)}exitRule(e){e.exitConnectionName&&e.exitConnectionName(this)}accept(e){return e.visitConnectionName?e.visitConnectionName(this):e.visitChildren(this)}}w.ConnectionNameContext=Lfe;class NM extends pe.ParserRuleContext{SQ3_FILTER(){return this.tryGetToken(d.SQ3_FILTER,0)}BQ3_FILTER(){return this.tryGetToken(d.BQ3_FILTER,0)}DQ3_FILTER(){return this.tryGetToken(d.DQ3_FILTER,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_tripFilterString}enterRule(e){e.enterTripFilterString&&e.enterTripFilterString(this)}exitRule(e){e.exitTripFilterString&&e.exitTripFilterString(this)}accept(e){return e.visitTripFilterString?e.visitTripFilterString(this):e.visitChildren(this)}}w.TripFilterStringContext=NM;class LM extends pe.ParserRuleContext{SQ_FILTER(){return this.tryGetToken(d.SQ_FILTER,0)}BQ_FILTER(){return this.tryGetToken(d.BQ_FILTER,0)}DQ_FILTER(){return this.tryGetToken(d.DQ_FILTER,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_tickFilterString}enterRule(e){e.enterTickFilterString&&e.enterTickFilterString(this)}exitRule(e){e.exitTickFilterString&&e.exitTickFilterString(this)}accept(e){return e.visitTickFilterString?e.visitTickFilterString(this):e.visitChildren(this)}}w.TickFilterStringContext=LM;class IM extends pe.ParserRuleContext{tripFilterString(){return this.tryGetRuleContext(0,NM)}tickFilterString(){return this.tryGetRuleContext(0,LM)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_filterString}enterRule(e){e.enterFilterString&&e.enterFilterString(this)}exitRule(e){e.exitFilterString&&e.exitFilterString(this)}accept(e){return e.visitFilterString?e.visitFilterString(this):e.visitChildren(this)}}w.FilterStringContext=IM;class Ife extends pe.ParserRuleContext{fieldExpr(){return this.getRuleContext(0,Te)}EOF(){return this.getToken(d.EOF,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_debugExpr}enterRule(e){e.enterDebugExpr&&e.enterDebugExpr(this)}exitRule(e){e.exitDebugExpr&&e.exitDebugExpr(this)}accept(e){return e.visitDebugExpr?e.visitDebugExpr(this):e.visitChildren(this)}}w.DebugExprContext=Ife;class Bfe extends pe.ParserRuleContext{partialAllowedFieldExpr(){return this.getRuleContext(0,ld)}EOF(){return this.getToken(d.EOF,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_debugPartial}enterRule(e){e.enterDebugPartial&&e.enterDebugPartial(this)}exitRule(e){e.exitDebugPartial&&e.exitDebugPartial(this)}accept(e){return e.visitDebugPartial?e.visitDebugPartial(this):e.visitChildren(this)}}w.DebugPartialContext=Bfe;class BM extends pe.ParserRuleContext{SEMI(e){return e===void 0?this.getTokens(d.SEMI):this.getToken(d.SEMI,e)}OBRACK(){return this.getToken(d.OBRACK,0)}string(){return this.getRuleContext(0,Fa)}CBRACK(){return this.getToken(d.CBRACK,0)}constructor(e,r){super(e,r)}get ruleIndex(){return d.RULE_experimentalStatementForTesting}enterRule(e){e.enterExperimentalStatementForTesting&&e.enterExperimentalStatementForTesting(this)}exitRule(e){e.exitExperimentalStatementForTesting&&e.exitExperimentalStatementForTesting(this)}accept(e){return e.visitExperimentalStatementForTesting?e.visitExperimentalStatementForTesting(this):e.visitChildren(this)}}w.ExperimentalStatementForTestingContext=BM;var yR={};Object.defineProperty(yR,"__esModule",{value:!0}),yR.MalloyErrorStrategy=void 0;const xft=py;class dft extends xft.DefaultErrorStrategy{}yR.MalloyErrorStrategy=dft;var $fe={},ER={},kfe={exports:{}};(function(t,e){(function(r){function i(o,u){for(var a in u)u.hasOwnProperty(a)&&(o[a]=u[a]);return o}function s(o,u,a){var l=0,c={caseSensitive:!0},f=i(c,a),x,h;if(o.length===0||u.length===0)return 0;if(f.caseSensitive||(o=o.toUpperCase(),u=u.toUpperCase()),o===u)return 1;var p=Math.floor(Math.max(o.length,u.length)/2)-1,m=new Array(o.length),g=new Array(u.length);for(x=0;x<o.length;x++){var y=x>=p?x-p:0,E=x+p<=u.length-1?x+p:u.length-1;for(h=y;h<=E;h++)if(m[x]!==!0&&g[h]!==!0&&o[x]===u[h]){++l,m[x]=g[h]=!0;break}}if(l===0)return 0;var A=0,_=0;for(x=0;x<o.length;x++)if(m[x]===!0){for(h=A;h<u.length;h++)if(g[h]===!0){A=h+1;break}o[x]!==u[h]&&++_}var v=(l/o.length+l/u.length+(l-_/2)/l)/3,C=0,b=.1;if(v>.7){for(;o[C]===u[C]&&C<4;)++C;v=v+C*b*(1-v)}return v}t.exports=s})()})(kfe);var hft=kfe.exports,pft=T&&T.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ER,"__esModule",{value:!0}),ER.checkCustomErrorMessage=void 0;const Mfe=pft(hft),mft=(t,e,r)=>{var i,s;const o=t.getRuleInvocationStack()[0],u=t.currentToken;for(const a of r){const l=!a.currentToken||u.type===a.currentToken,c=!a.offendingSymbol||(e==null?void 0:e.type)===a.offendingSymbol,f=!a.ruleContextOptions||a.ruleContextOptions.includes(o),x=!a.offendingSymbolTextOptions||a.offendingSymbolTextOptions.includes(((i=e==null?void 0:e.text)===null||i===void 0?void 0:i.toLowerCase())||"");if(l&&c&&f&&x){if(a.lookbackSiblingRuleOptions){const m=t.ruleContext.children;if(!m)continue;const g=m[m.length-1];if(!a.lookbackSiblingRuleOptions.includes(g.ruleIndex))continue}if(a.precedingTokenOptions&&!a.precedingTokenOptions.some(g=>Ufe(t,g,"lookback",e==null?void 0:e.tokenIndex))||a.lookAheadOptions&&!a.lookAheadOptions.some(g=>Ufe(t,g,"lookahead",e==null?void 0:e.tokenIndex)))continue;if(a.predecessorHasAncestorRule){const m=(s=t.ruleContext.children)===null||s===void 0?void 0:s[0];if(!m||!Pfe(m,a.predecessorHasAncestorRule))continue}const h=m=>{const g=m.replace("${currentToken}",u.text||"").replace("${offendingSymbol}",(e==null?void 0:e.text)||"");try{const y=t.inputStream.LT(-1);return g.replace("${previousToken}",y.text||"")}catch{}return g};let p=h(a.errorMessage);if(a.alternatives){const m=h(a.alternatives.replace);let g=a.alternatives.with[0],y=(0,Mfe.default)(g,m);for(const E of a.alternatives.with.slice(1)){const A=(0,Mfe.default)(E,m);A>y&&(y=A,g=E)}p+=` Did you mean '${g}'?`}return p}}return""};ER.checkCustomErrorMessage=mft;const Pfe=(t,e,r=20)=>{var i;if(t.ruleIndex===e)return!0;if(r<=0)return!1;const s=((i=t.children)===null||i===void 0?void 0:i.length)||0;if(t.children&&s>0){const o=t.children[t.children.length-1];return Pfe(o,e,r-1)}return!1},Ufe=(t,e,r,i)=>{var s;try{for(let o=0;o<e.length;o++){let u;if(typeof i=="number"){const a=r==="lookahead"?o+1:-1*(o+1);u=t.inputStream.get(i+a)}else{const a=r==="lookahead"?o+2:-1*(o+1);u=t.inputStream.LT(a)}if(typeof e[o]=="number"){const a=e[o];if(a>=-1&&u.type!==a||a<-1&&u.type===-1*a)return!1}else if(typeof e[o]=="string"&&e[o]!==((s=u.text)===null||s===void 0?void 0:s.toLowerCase()))return!1}return!0}catch{return!1}};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.MalloyParserErrorListener=t.malloyCustomErrorCases=void 0;const e=w,r=ER,i=Yp,s=Vn;t.malloyCustomErrorCases=[{errorMessage:"'view:' must be followed by '<identifier> is {'",ruleContextOptions:["exploreQueryDef"],offendingSymbol:e.MalloyParser.OCURLY,precedingTokenOptions:[[e.MalloyParser.VIEW],[e.MalloyParser.COLON]]},{errorMessage:"Missing '}' at '${offendingSymbol}'",ruleContextOptions:["vExpr"],offendingSymbol:e.MalloyParser.VIEW,currentToken:e.MalloyParser.OCURLY},{errorMessage:"Missing '}' at '${currentToken}'",ruleContextOptions:["exploreProperties","queryProperties","exploreStatement"],offendingSymbolTextOptions:["<eof>","run:","source:"]},{errorMessage:"'aggregate:' entries must include a name (ex: `some_name is count()`)",precedingTokenOptions:[[e.MalloyParser.AGGREGATE]],lookAheadOptions:[[-e.MalloyParser.IS]]},{errorMessage:"Expected ':' following 'source'",offendingSymbol:e.MalloyParser.SOURCE_KW,ruleContextOptions:["malloyDocument"]},{errorMessage:"Expected ':' following '${offendingSymbol}'",offendingSymbolTextOptions:["dimension","measure","where","declare","join_one","join_many","join_cross","primary_key"],ruleContextOptions:["exploreStatement"]},{errorMessage:"Expected 'is' or '(' following identifier '${previousToken}'",ruleContextOptions:["sourceDefinition"],lookbackSiblingRuleOptions:[e.MalloyParser.RULE_sourceNameDef,e.MalloyParser.RULE_sourceParameters]},{errorMessage:"Unexpected '{' following source expression. Expected: 'extend', 'include', '+' or '->'",offendingSymbol:e.MalloyParser.OCURLY,ruleContextOptions:["malloyDocument"],predecessorHasAncestorRule:e.MalloyParser.RULE_sqExplore},{errorMessage:"Unexpected 'join:'. Did you mean 'join_one:', 'join_many:' or 'join_cross:'?",ruleContextOptions:["exploreStatement"],offendingSymbolTextOptions:["join"],lookAheadOptions:[[e.MalloyParser.COLON]]},{errorMessage:"Unexpected '${offendingSymbol}'. Did you mean 'primary_key:'?",ruleContextOptions:["exploreStatement"],offendingSymbolTextOptions:["primarykey","primary"],lookAheadOptions:[[e.MalloyParser.COLON],["key",e.MalloyParser.COLON],["key",e.MalloyParser.IDENTIFIER]]},{errorMessage:"Unexpected '${offendingSymbol}'. Did you mean 'group_by:'?",ruleContextOptions:["queryStatement"],offendingSymbolTextOptions:["groupby","group"],lookAheadOptions:[[e.MalloyParser.COLON],["by",e.MalloyParser.COLON],["by",e.MalloyParser.IDENTIFIER]]},{errorMessage:"Unexpected '${offendingSymbol}'. Did you mean 'order_by:'?",ruleContextOptions:["queryStatement"],offendingSymbolTextOptions:["orderby","order"],lookAheadOptions:[[e.MalloyParser.COLON],["by",e.MalloyParser.COLON],["by",e.MalloyParser.IDENTIFIER]]},{errorMessage:"Expected ':' following '${offendingSymbol}'",offendingSymbolTextOptions:["group_by","declare","join_one","join_many","join_cross","extend","select","project","index","aggregate","calculate","top","limit","order_by","where","having","nest","sample","timezone"],ruleContextOptions:["queryStatement"]},{errorMessage:"Expected a query statement, '${offendingSymbol}:' is not a keyword.",ruleContextOptions:["queryStatement"],offendingSymbol:e.MalloyParser.IDENTIFIER,lookAheadOptions:[[e.MalloyParser.COLON,e.MalloyParser.IDENTIFIER]],alternatives:{replace:"${offendingSymbol}:",with:["group_by:","select:","aggregate:","calculate:","nest:"]}},{errorMessage:"Expected a source statement, '${offendingSymbol}:' is not a keyword.",ruleContextOptions:["exploreStatement"],offendingSymbol:e.MalloyParser.IDENTIFIER,lookAheadOptions:[[e.MalloyParser.COLON,e.MalloyParser.IDENTIFIER]],alternatives:{replace:"${offendingSymbol}:",with:["dimension:","measure:","primary_key:","view:","join:"]}},{errorMessage:"Expected a statement, '${offendingSymbol}:' is not a keyword.",ruleContextOptions:["malloyDocument"],offendingSymbol:e.MalloyParser.IDENTIFIER,lookAheadOptions:[[e.MalloyParser.COLON,e.MalloyParser.IDENTIFIER]],alternatives:{replace:"${offendingSymbol}:",with:["run:","query:","source:"]}}];class o{constructor(a,l,c){this.messages=a,this.sourceURL=l,this.sourceInfo=c}logError(a,l,c){return this.messages.log((0,i.makeLogMessage)(a,l,{severity:"error",...c})),a}syntaxError(a,l,c,f,x,h){const p={line:c-1,character:f},m=l?(0,s.rangeFromToken)(this.sourceInfo,l):{start:p,end:p},g=(0,r.checkCustomErrorMessage)(a,l,t.malloyCustomErrorCases);g&&(x=g),this.logError("syntax-error",{message:x},{at:{url:this.sourceURL,range:m}})}}t.MalloyParserErrorListener=o})($fe),Object.defineProperty(aE,"__esModule",{value:!0}),aE.runMalloyParser=void 0;const jfe=py,gft=RT,yft=w,Eft=yR,Aft=$fe;class _ft extends gft.MalloyLexer{popMode(){return this._modeStack.isEmpty?this._mode:super.popMode()}}function vft(t,e,r,i,s="malloyDocument"){const o=jfe.CharStreams.fromString(t),u=new _ft(o),a=new jfe.CommonTokenStream(u),l=new yft.MalloyParser(a);l.removeErrorListeners(),l.addErrorListener(new Aft.MalloyParserErrorListener(i,e,r)),l.errorHandler=new Eft.MalloyErrorStrategy;const c=l[s];if(!c)throw new Error(`No such parse rule as ${s}`);return{root:c.call(l),tokenStream:a,sourceStream:o,sourceInfo:r,sourceURL:e,malloyVersion:"4.0.0"}}aE.runMalloyParser=vft;var Cft=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Sft=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),bft=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Cft(e,t,r);return Sft(e,t),e};Object.defineProperty(Tc,"__esModule",{value:!0}),Tc.MalloyTranslator=Tc.MalloyChildTranslator=Tc.MalloyTranslation=void 0;const Tft=Xe,qfe=bft(Q4),Rft=gT,Hfe=Yp,Dft=Zl,$M=ET,Oft=AT,Fft=_T,wft=vT,Nft=CT,AR=ST,kM=Vn,Lft=Zo,Ift=bT,Bft=TT,$ft=ui,kft=aE;class Mft{step(e){if(this.response)return this.response;if(!e.urlIsFullPath)return e.fatalResponse();const r=e.root.importZone.getEntry(e.sourceURL);if(r.status!=="present"){if(r.status==="error"){const o=r.firstReference||e.defaultLocation();return e.root.logError("import-error",{message:r.message,url:e.sourceURL},{at:o}),this.response=e.fatalResponse(),this.response}return{urls:[e.sourceURL]}}const i=r.value===""?`
1462
+ `:r.value;this.sourceInfo=(0,kM.getSourceInfo)(i);let s;try{s=this.runParser(i,this.sourceInfo,e)}catch(o){e.root.logError("parse-exception",{message:o.message}),s=void 0}return e.root.logger.hasErrors()?this.response={parse:s,...e.fatalResponse()}:this.response={parse:s},this.response}runParser(e,r,i){return{...(0,kft.runMalloyParser)(e,i.sourceURL,r,i.root.logger,i.grammarRule),importBaseURL:i.importBaseURL||i.sourceURL}}}class Pft{constructor(e){this.parseStep=e,this.parseReferences=void 0}step(e){var r;const i=this.parseStep.step(e);if(i.parse===void 0)return i;if(!this.parseReferences){this.parseReferences=(0,Dft.findReferences)(e,i.parse.tokenStream,i.parse.root);for(const a in this.parseReferences.tables)e.root.schemaZone.reference(a,{url:e.sourceURL,range:this.parseReferences.tables[a].firstReference});for(const a in this.parseReferences.urls){const l=this.parseReferences.urls[a];try{const c=decodeURI(new URL(a,e.importBaseURL||e.sourceURL).toString());e.addChild(c),e.imports.push({importURL:c,location:{url:e.sourceURL,range:l}}),e.root.importZone.reference(c,{url:e.sourceURL,range:l})}catch{e.root.logError("invalid-import-url",`Malformed URL '${a}'"`,{at:{url:e.sourceURL,range:l}})}}}if(e.root.logger.hasErrors())return null;let s={};const o=e.root.schemaZone.getUndefined();if(o){const a={};for(const l of o){const c=this.parseReferences.tables[l];a[l]={connectionName:c.connectionName,tablePath:c.tablePath}}s={tables:a}}const u=((r=e.root.importZone.getUndefined())!==null&&r!==void 0?r:[]).filter(a=>e.root.pretranslatedModels.get(a)===void 0);if(u.length>0&&(s={...s,urls:u}),(0,AR.isNeedResponse)(s))return s;for(const a of e.childTranslators.values()){if(e.root.pretranslatedModels.get(a.sourceURL))continue;const l=a.importsAndTablesStep.step(a);if((0,AR.isNeedResponse)(l))return l}return null}}class Uft{constructor(e){this.importStep=e,this.walked=!1}step(e){if(this.response)return this.response;const r=this.importStep.step(e);if(r)return r;const i=e.parseStep.response;if(e.root.logger.hasErrors())return this.response=e.fatalResponse(),this.response;const s=i==null?void 0:i.parse;if(!s)throw new Error("TRANSLATOR INTERNAL ERROR: Translator parse response had no errors, but also no parser");const o=new Rft.MalloyToAST(s,e.root.logger,e.compilerFlags),u=o.visit(s.root);if(e.compilerFlags=o.compilerFlags,u.elementType==="unimplemented"&&u.logError("untranslated-parse-node","INTERNAL COMPILER ERROR: Untranslated parse node"),!this.walked){for(const a of u.walk())a instanceof qfe.Unimplemented&&a.logError("untranslated-parse-node","INTERNAL COMPILER ERROR: Untranslated parse node");this.walked=!0}if(e.root.logger.hasErrors())return this.response=e.fatalResponse(),this.response;for(const a of e.childTranslators.values()){if(e.root.pretranslatedModels.get(a.sourceURL))continue;const l=a.astStep.step(a);if((0,AR.isNeedResponse)(l))return l}return u.setTranslator(e),this.response={...e.problemResponse(),ast:u,final:!0},this.response}}class jft{constructor(e){this.parseStep=e}step(e){if(!this.response){const r=this.parseStep.step(e);if(r.parse){let i;try{i=(0,Oft.walkForDocumentSymbols)(e,r.parse.tokenStream,r.parse.root)}catch{}this.response={symbols:i,final:!0}}else return r}return this.response}}class qft{constructor(e){this.parseStep=e}step(e,r){const i=this.parseStep.step(e);if(i.parse){let s=[];if(r!==void 0)try{s=(0,Fft.walkForDocumentCompletions)(i.parse.tokenStream,i.parse.root,r)}catch{}return{...i,completions:s}}else return i}}class Hft{constructor(e){this.parseStep=e}step(e,r){const i=this.parseStep.step(e);if(i.parse){let s;if(r!==void 0)try{s=(0,wft.walkForDocumentHelpContext)(i.parse.root,r)}catch{}return{...i,helpContext:s}}else return i}}class Qft{constructor(e){this.parseStep=e}step(e,r){if(!this.response){const i=this.parseStep.step(e);if(!i.parse||i.final)return i;{const s=(0,Ift.walkForModelAnnotation)(e,i.parse.tokenStream,i.parse);this.response={modelAnnotation:{...s,inherits:r==null?void 0:r.annotation}}}}return this.response}}class zft{constructor(e){this.parseStep=e}step(e){if(!this.response){const r=this.parseStep.step(e);if(r.parse){const i=(0,Bft.walkForTablePath)(e,r.parse.tokenStream,r.parse);this.response={pathInfo:i}}else return r}return this.response}}class Gft{constructor(e){this.astStep=e,this.importedAnnotations=!1}step(e,r){if(this.response)return this.response;const i=e.root.pretranslatedModels.get(e.sourceURL);if(i!==void 0)return e.modelDef=i,{modelDef:i,final:!0,fromSources:e.getDependencies()};if(r&&!this.importedAnnotations){const o=(0,$ft.annotationToTag)(r.annotation,{prefix:/^##! /});e.compilerFlags=o.tag,this.importedAnnotations=!0}const s=this.astStep.step(e);if((0,AR.isNeedResponse)(s))return s;if(!s.ast)return this.response=s,this.response;if(e.grammarRule==="malloyDocument")if(s.ast instanceof qfe.Document){const o=s.ast;for(o.initModelDef(r);;){const u=o.compile();if(u.needs)return u.needs;e.modelDef=u.modelDef;break}}else e.root.logError("parsed-non-malloy-document",{url:e.sourceURL},{at:e.defaultLocation()});return e.root.logger.hasErrors()?this.response={fromSources:e.getDependencies(),...e.fatalResponse()}:this.response={modelDef:{...e.modelDef,dependencies:e.getDependencyTree()},fromSources:e.getDependencies(),...e.problemResponse(),final:!0},this.response}}class MM{constructor(e,r=null,i="malloyDocument"){this.sourceURL=e,this.importBaseURL=r,this.grammarRule=i,this.sqlSources=[],this.imports=[],this.compilerFlags=new Lft.Tag,this._urlIsFullPath=void 0,this.dialectAlreadyChecked={},this.allDialectsEnabled=!1,this.childTranslators=new Map,this.modelDef={name:e,exports:[],contents:{},queryList:[],dependencies:{}},this.parseStep=new Mft,this.modelAnnotationStep=new Qft(this.parseStep),this.metadataStep=new jft(this.parseStep),this.completionsStep=new qft(this.parseStep),this.helpContextStep=new Hft(this.parseStep),this.importsAndTablesStep=new Pft(this.parseStep),this.astStep=new Uft(this.importsAndTablesStep),this.tablePathInfoStep=new zft(this.parseStep),this.translateStep=new Gft(this.astStep),this.references=new Nft.ReferenceList(e)}get urlIsFullPath(){if(this._urlIsFullPath===void 0)try{const e=new URL(this.sourceURL);this._urlIsFullPath=!0}catch(e){const r=e instanceof Error?e.message:"";this._urlIsFullPath=!1,this.root.logError("failed-to-compute-absolute-import-url",`Could not compute full path URL: ${r}`)}return this._urlIsFullPath}addChild(e){this.childTranslators.get(e)||this.childTranslators.set(e,new Qfe(e,this.root))}getDependencies(){const e=this.getDependencyTree();return[this.sourceURL,...zfe(e)]}getDependencyTree(){const e=this.root.pretranslatedModels.get(this.sourceURL);if(e!==void 0)return e.dependencies;const r={};for(const[i,s]of this.childTranslators)r[i]=s.getDependencyTree();return r}newlyTranslatedDependencies(){if(this.root.pretranslatedModels.get(this.sourceURL)!==void 0)return[];const r=[];for(const[i,s]of this.childTranslators){if(this.root.pretranslatedModels.get(i)!==void 0)continue;const u=s.translate();u.modelDef&&(r.push({url:i,modelDef:u.modelDef}),r.push(...s.newlyTranslatedDependencies()))}return r}addReference(e){this.references.add(e)}referenceAt(e){return this.references.find(e)}fatalResponse(){return{final:!0,...this.problemResponse()}}problemResponse(){return{problems:this.problems()}}problems(){return[...this.root.logger.getLog()]}getLineMap(e){var r,i;if(e===this.sourceURL)return(r=this.parseStep.sourceInfo)===null||r===void 0?void 0:r.lines;const s=this.childTranslators.get(e);if(s)return(i=s.parseStep.sourceInfo)===null||i===void 0?void 0:i.lines}codeAtLocation(e){const r=this.getLineMap(e.url)||[];if(e.range.start.line===e.range.end.line)return r[e.range.start.line].slice(e.range.start.character,e.range.end.character);let i="";i+=r[e.range.start.line].slice(e.range.start.character);for(let s=e.range.start.line+1;s<e.range.end.line;s++)i+=r[s];return i+=r[e.range.end.line].slice(0,e.range.end.character),i}prettyErrors(){let e="",r="";for(const i of this.root.logger.getLog()){let s=i.message,o=this.sourceURL;if(i.at){o=i.at.url;const u=i.at.range.start.line,a=i.at.range.start.character,l=this.getLineMap(i.at.url);if(l){const c=l[u];s=`line ${u+1}: ${i.message}
1463
1463
  | ${c}`,a>0&&(s=s+`
1464
1464
  | ${" ".repeat(a)}^`)}else s=`line ${u+1}: char ${a}: ${i.message}`}r!==o&&(s=`FILE: ${o}
1465
1465
  `+s,r=o),e!==""?e=`${e}
1466
- ${s}`:e=s}return e}childRequest(e){var r;const i=decodeURI(new URL(e,this.sourceURL).toString()),s=(r=this.childTranslators.get(i))===null||r===void 0?void 0:r.translate();if(s!=null&&s.compileSQL)return{compileSQL:s.compileSQL}}getChildExports(e){const r={},i=decodeURI(new URL(e,this.sourceURL).toString()),s=this.childTranslators.get(i);if(s&&s.translate().modelDef)for(const u of s.modelDef.exports){const a=s.modelDef.contents[u];((0,Sft.isSourceDef)(a)||a.type==="query")&&(r[u]=a)}return r}translate(e){if(this.finalAnswer)return this.finalAnswer;const r=this.translateStep.step(this,e);return r.final&&(this.finalAnswer=r),r}translatorForDependency(e){return this.childTranslators.get(e)}importAt(e){for(let r=0;r<this.imports.length;r++){const i=this.imports[r];if((0,kM.locationContainsPosition)(i.location,e))return i}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return(0,kM.rangeFromContext)(this.parseStep.sourceInfo,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const r=this.compilerFlags.tag("experimental");return r!==void 0&&(r.bare()||r.has("dialect",e))}}Tc.MalloyTranslation=MM;class Qfe extends MM{constructor(e,r){super(e),this.root=r}}Tc.MalloyChildTranslator=Qfe;class zft extends MM{constructor(e,r=null,i=null,s=null){super(e,r),this.eventStream=s,this.schemaZone=new $M.Zone,this.importZone=new $M.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new $M.Zone,this.root=this,this.logger=new Hfe.BaseMessageLogger(s),i&&this.update(i)}update(e){var r,i,s;this.schemaZone.updateFrom(e.tables,(r=e.errors)===null||r===void 0?void 0:r.tables),this.importZone.updateFrom(e.urls,(i=e.errors)===null||i===void 0?void 0:i.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(s=e.errors)===null||s===void 0?void 0:s.compileSQL);for(const o in e.translations)this.pretranslatedModels.set(o,e.translations[o])}logError(e,r,i){return this.logger.log((0,Hfe.makeLogMessage)(e,r,{severity:"error",...i})),e}}Tc.MalloyTranslator=zft;function zfe(t){return[...Object.keys(t),...Object.keys(t).map(e=>zfe(t[e])).flat()]}var T2={};Object.defineProperty(T2,"__esModule",{value:!0}),T2.exploreQueryWalkerBuilder=T2.ExploreQueryWalker=void 0;const Gft=uc;class Gfe{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}filterAtOffset(e){const r=this.exploreQueryAtOffset(e);if(r)return r.filterRefs.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e)}hasFilterListAtOffset(e){const r=this.exploreQueryAtOffset(e);return r?!!r.filterLists.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}T2.ExploreQueryWalker=Gfe;function Wft(t,e){const r=new Gfe(t),i=r;return Gft.ParseTreeWalker.DEFAULT.walk(i,e),r}T2.exploreQueryWalkerBuilder=Wft;var R2={},mE={},La={};Object.defineProperty(La,"__esModule",{value:!0}),La.getResultStructMetadataAnnotation=La.convertFieldInfos=La.modelDefToModelInfo=void 0;const Ia=Pi,PM=Ls,UM=ui,Wfe=Zo;function Vft(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,Ia.isSourceDef)(i)){const s=i.parameters&&Object.entries(i.parameters).length>0?Object.entries(i.parameters).map(([u,a])=>(0,Ia.isAtomic)(a)?{name:u,type:vR(a),default_value:Vfe(a.value)}:{name:u,type:{kind:"filter_expression_type"},default_value:Vfe(a.value)}):void 0,o={kind:"source",name:r,schema:{fields:D2(i,i.fields)},parameters:s,annotations:jM(i)};e.entries.push(o)}else if(i.type==="query"){const s=(0,PM.getResultStructDefForQuery)(t,i),o=jM(i),u=s.resultMetadata?_R(s,s.resultMetadata):void 0,a=[...o??[],...u?[u]:[]],l={kind:"source",name:r,schema:{fields:D2(s,s.fields)},annotations:a.length>0?a:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,PM.getResultStructDefForQuery)(t,r),s=jM(r),o=i.resultMetadata?_R(i,i.resultMetadata):void 0,u=[...s??[],...o?[o]:[]],a={schema:{fields:D2(i,i.fields)},annotations:u.length>0?u:void 0};e.anonymous_queries.push(a)}return e}La.modelDefToModelInfo=Vft;function Vfe(t){if(t!==null)switch(t.node){case"numberLiteral":return{kind:"number_literal",number_value:parseFloat(t.literal)};case"stringLiteral":return{kind:"string_literal",string_value:t.literal};case"filterLiteral":return{kind:"filter_expression_literal",filter_expression_value:t.filterSrc};case"timeLiteral":return{kind:"timestamp_literal",timestamp_value:t.literal};case"true":return{kind:"boolean_literal",boolean_value:!0};case"false":return{kind:"boolean_literal",boolean_value:!1};case"null":return{kind:"null_literal"};default:throw new Error("Invalid parameter default value")}}function jM(t){return(0,UM.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function D2(t,e){var r,i,s;const o=[];for(const u of e){if(!(u.accessModifier===void 0))continue;const c=(0,UM.annotationToTaglines)(u.annotation).map(x=>({value:x})),f=c.length>0?c:void 0;if((0,Ia.isTurtle)(u)){const x=(0,PM.getResultStructDefForView)(t,u),h=x.resultMetadata?_R(x,x.resultMetadata):void 0,p=[...f??[],...h?[h]:[]],m={kind:"view",name:(r=u.as)!==null&&r!==void 0?r:u.name,annotations:p.length>0?p:void 0,schema:{fields:D2(x,x.fields)}};o.push(m)}else if((0,Ia.isAtomic)(u)){const x=(0,Ia.expressionIsAggregate)(u.expressionType),h=(0,Ia.expressionIsScalar)(u.expressionType);if(!x&&!h||u.type==="error")continue;const p=u.resultMetadata?Yfe(u,u.resultMetadata):void 0,m=[...f??[],...p?[p]:[]],g={kind:x?"measure":"dimension",name:(i=u.as)!==null&&i!==void 0?i:u.name,type:vR(u),annotations:m.length>0?m:void 0};o.push(g)}else if((0,Ia.isJoinedSource)(u)){const x={kind:"join",name:(s=u.as)!==null&&s!==void 0?s:u.name,annotations:f,schema:{fields:D2(u,u.fields)},relationship:u.join};o.push(x)}}return o}La.convertFieldInfos=D2;function Yfe(t,e){const r=Wfe.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.filterList){const s=e.filterList.filter(o=>o.expressionType==="scalar").map(o=>o.code);r.set(["drill_filters"],s),i=!0}if(e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:Kft(t.name));r.set(["drill_expression"],o),i=!0}return i?{value:r.toString()}:void 0}function Yft(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function Kft(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${Yft(t)}\``}function _R(t,e){var r,i;const s=Wfe.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList){const u=e.filterList.filter(a=>a.expressionType==="scalar").map(a=>a.code);u.length>0&&(s.set(["drill_filters"],u),o=!0)}if(e.orderBy){for(let u=0;u<e.orderBy.length;u++){const a=e.orderBy[u],l=typeof a.field=="number"?(r=t.fields[a.field-1].as)!==null&&r!==void 0?r:t.fields[a.field-1].name:a.field,c=(i=a.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",u,l],c)}o=!0}return o?{value:s.toString()}:void 0}La.getResultStructMetadataAnnotation=_R;function vR(t){if((0,Ia.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!Jft(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:Xft(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,Ia.isRepeatedRecord)(t))return{kind:"array_type",element_type:Kfe(t)};if(t.type==="record")return Kfe(t);if(t.type==="array")return{kind:"array_type",element_type:vR(t.elementTypeDef)}}throw new Error("Unexpected field type")}function Kfe(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=Yfe(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,UM.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,Ia.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:vR(e)};throw new Error("Expected record type to not have a table as its child")})}}function Jft(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function Xft(t){switch(t){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return t;default:throw new Error(`Invalid date timeframe ${t}`)}}function hht(t){return t}function pht(t){return t}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.mapLogs=t.DEFAULT_LOG_RANGE=t.wrapResult=t.mapData=t.wrapLegacyConnection=t.wrapLegacyInfoConnection=void 0;const e=Zo,r=ui,i=La,s=by;function o(x){return{get dialectName(){return x.dialectName},async fetchSchemaForSQLQuery(h){const p=await x.fetchSchemaForSQLStruct({connection:x.name,selectStr:h},{}),m=p.structDef;if(m===void 0)throw new Error(p.error);return{fields:(0,i.convertFieldInfos)(m,m.fields)}},async fetchSchemaForTable(h){const p=`${x.name}:${h}`,m=await x.fetchSchemaForTables({[p]:h},{}),g=m.schemas[p];if(g===void 0)throw new Error(m.errors[p]);return{fields:(0,i.convertFieldInfos)(g,g.fields)}}}}t.wrapLegacyInfoConnection=o;function u(x){return{...o(x),runSQL:async(h,p)=>{const m=await x.runSQL(h);return l(m.rows,p)}}}t.wrapLegacyConnection=u;function a(x){if(x instanceof Date)return x;if(x.constructor.name==="Date")return new Date(x);if(typeof x=="number")return new Date(x);if(typeof x!="string")return new Date(x.value);{let p=s.DateTime.fromISO(x,{zone:"UTC"});return p.isValid||(p=s.DateTime.fromSQL(x,{zone:"UTC"})),p.toJSDate()}}function l(x,h){function p(y,E){if(y===null)return{kind:"null_cell"};if(E.type.kind==="date_type"||E.type.kind==="timestamp_type"){const A=a(y).toISOString();return E.type.kind==="date_type"?{kind:"date_cell",date_value:A}:{kind:"timestamp_cell",timestamp_value:A}}else if(E.type.kind==="boolean_type"){if(typeof y=="number")return{kind:"boolean_cell",boolean_value:y!==0};if(typeof y!="boolean")throw new Error(`Invalid boolean ${y}`);return{kind:"boolean_cell",boolean_value:y}}else if(E.type.kind==="number_type"){if(typeof y!="number")throw new Error(`Invalid number ${y}`);return{kind:"number_cell",number_value:y}}else if(E.type.kind==="string_type"){if(typeof y!="string")throw new Error(`Invalid string ${y}`);return{kind:"string_cell",string_value:y}}else if(E.type.kind==="array_type"){if(!Array.isArray(y))throw new Error(`Invalid array ${y}`);return{kind:"array_cell",array_value:y.map(A=>p(A,{name:"array_element",type:E.type.element_type}))}}else{if(E.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(y)};if(E.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(y)};{const A=E.type;if(A.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(E)}, ${JSON.stringify(y)}`);return m(y,{kind:"join",relationship:"many",name:"array_element",schema:{fields:A.fields.map(_=>({kind:"dimension",..._}))}})}}}function m(y,E){const A=[];for(const _ of E.schema.fields){const v=y[_.name];if(_.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const C=p(v,_);A.push(C)}return{kind:"record_cell",record_value:A}}const g={kind:"join",schema:h,name:"root",relationship:"one"};return{kind:"array_cell",array_value:x.map(y=>m(y,g))}}t.mapData=l;function c(x){const h=x._queryResult.structs,p=h[h.length-1],m={fields:(0,i.convertFieldInfos)(p,p.fields)},g=(0,r.annotationToTaglines)(x.annotation).map(E=>({value:E})),y=p.resultMetadata?(0,i.getResultStructMetadataAnnotation)(p,p.resultMetadata):void 0;return y&&g.push(y),g.push(...p.resultMetadata?[]:[]),x.sourceExplore&&g.push({value:e.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore.name).toString()}),g.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],x.resultExplore.name).toString()}),{schema:m,data:l(x.data.toObject(),m),connection_name:x.connectionName,annotations:g.length>0?g:void 0,query_timezone:x.data.field.queryTimezone,sql:x.sql}}t.wrapResult=c,t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function f(x,h){return x.map(p=>{var m,g,y,E;return{severity:p.severity,message:p.message,range:(g=(m=p.at)===null||m===void 0?void 0:m.range)!==null&&g!==void 0?g:t.DEFAULT_LOG_RANGE,url:(E=(y=p.at)===null||y===void 0?void 0:y.url)!==null&&E!==void 0?E:h}})}t.mapLogs=f})(mE);var Zft=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),ext=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),txt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Zft(e,t,r);return ext(e,t),e};Object.defineProperty(R2,"__esModule",{value:!0}),R2.malloyToQuery=R2.MalloyToQuery=void 0;const nxt=Kh,On=txt(w),Jfe=Yp,gE=Bn,rxt=Xe,ixt=aE,Xfe=Vn,sxt=mE,qM="Malloy query documents";class Zfe extends nxt.AbstractParseTreeVisitor{constructor(e,r){super(),this.parseInfo=e,this.msgLog=r}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}getLocation(e){return{url:this.parseInfo.sourceURL,range:(0,Xfe.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,Jfe.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}getNumber(e){return Number.parseInt(e.text)}defaultResult(){return null}getAnnotations(e){const r=e.ANNOTATION().map(i=>({value:i.text}));return r.length>0?r:void 0}getIsAnnotations(e){var r,i;if(e===void 0)return;const o=((r=this.getAnnotations(e._beforeIs))!==null&&r!==void 0?r:[]).concat((i=this.getAnnotations(e._afterIs))!==null&&i!==void 0?i:[]);return o.length>0?o:void 0}notAllowed(e,r){this.illegal(e,`${r} are not allowed in ${qM}`)}illegal(e,r){this.contextError(e,"invalid-malloy-query-document",r)}visitMalloyDocument(e){const r=e.malloyStatement();let i;for(const s of r)s.defineSourceStatement()?this.notAllowed(s,"Source definitions"):s.defineQuery()?this.notAllowed(s,"Query definitions"):s.importStatement()?this.notAllowed(s,"Import statements"):s.docAnnotations()?this.notAllowed(s,"Model annotations"):s.ignoredObjectAnnotations()?this.notAllowed(s,"Detatched object annotations"):s.experimentalStatementForTesting()?this.notAllowed(s,"Experimental testing statements"):i===void 0?i=s.runStatement():this.illegal(s,`${qM} may only have one run statement`);return i===void 0?(this.illegal(e,`${qM} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.topLevelAnonQueryDef().tags());return i!==null?{annotations:s,definition:i}:null}getQueryReference(e){if(e.sourceArguments())this.illegal(e,"Queries do not support parameters");else return{name:(0,gE.getId)(e)};return null}getQueryDefinition(e){if(e instanceof On.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof On.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof On.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof On.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof On.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof On.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof On.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof On.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof On.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof On.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof On.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof On.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof On.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,gE.getId)(s.fieldName()),u=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:u,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof On.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const u=this.getAnnotations(o.tags()),a=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,gE.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,u,a)}})}return s}getViewExpression(e){if(e instanceof On.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof On.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.havingStatement()){const r=e.havingStatement(),i=this.getHaving(r);return i===null?null:i.map(s=>({kind:"having",...s}))}else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,gE.getId)(o)),i=r[0],s=r.slice(1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,rxt.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const u=r.refExpr();if(u.timeframe()){const a=this.getTimeframe(u.timeframe());return a===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:a}}}}else u.aggregate()&&this.notAllowed(u,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,gE.getId)(r.fieldNameDef()),u=this.getFieldExpression(r.fieldExpr());return u===null?null:{name:o,field:{expression:u,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof On.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof On.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof On.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const u of s){const a=u.whereStatement();if(a){const l=this.getWhere(a);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}return null}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),u=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(u)return this.stripQuote(u.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),u=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(u)return this.stripQuote(u.text,"'")}return null}getFilterExpr(e){if(e instanceof On.ExprCompareContext&&e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof On.ExprFieldPathContext&&i instanceof On.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=i.literal();if(u instanceof On.FilterString_stubContext){const a=this.getFilterString(u.filterString());return a===null?null:{filter:{kind:"filter_string",field_reference:{name:o,path:s},filter:a}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings"),null}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}getHaving(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}R2.MalloyToQuery=Zfe;function oxt(t){const e=(0,Xfe.getSourceInfo)(t),r=new Jfe.BaseMessageLogger(null),i="internal://query.malloy",s=(0,ixt.runMalloyParser)(t,i,e,r),u=new Zfe(s,r).visit(s.root),a=(0,sxt.mapLogs)(r.getLog(),i);if(u===null)return{logs:a};if(!("definition"in u))throw new Error("Expected a query");return{query:u,logs:a}}R2.malloyToQuery=oxt,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Tc;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=T2;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=R2;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})}(H4);var we={},CR={};Object.defineProperty(CR,"__esModule",{value:!0}),CR.MALLOY_VERSION=void 0,CR.MALLOY_VERSION="0.0.265",Object.defineProperty(we,"__esModule",{value:!0}),we.InMemoryModelCache=we.CacheManager=we.CSVWriter=we.JSONWriter=we.DataWriter=we.DataRecord=we.DataArray=we.Result=we.ExploreMaterializer=we.PreparedResultMaterializer=we.QueryMaterializer=we.ModelMaterializer=we.SingleConnectionRuntime=we.ConnectionRuntime=we.Runtime=we.ExploreField=we.JoinRelationship=we.QueryField=we.Query=we.StringField=we.UnsupportedField=we.JSONField=we.BooleanField=we.NumberField=we.TimestampField=we.DateField=we.TimestampTimeframe=we.DateTimeframe=we.AtomicField=we.AtomicFieldType=we.Explore=we.SourceRelationship=we.FixedConnectionMap=we.InMemoryURLReader=we.EmptyURLReader=we.PreparedResult=we.DocumentCompletion=we.DocumentSymbol=we.DocumentPosition=we.DocumentRange=we.DocumentTablePath=we.Parse=we.PreparedQuery=we.Model=we.MalloyError=we.Malloy=void 0;const exe=H4,li=Pi,txe=by,HM=kp,uxt=CR,axt=Pp,$n=ui,lxt=Yl,nxe="internal://internal.malloy";let n0=class E6{static get version(){return uxt.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(nxe));let u=r;s!=null&&s.importBaseURL&&(u=s==null?void 0:s.importBaseURL);const a=new exe.MalloyTranslator(r.toString(),u.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(a.allDialectsEnabled=!0),new ixe(a,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return E6._parse(i,e,s,o);if(r===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return NR(r,e).then(({contents:u,invalidationKey:a})=>E6._parse(u,e,s,o,a))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:u,refreshSchemaCache:a,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:x}){var h,p,m,g,y;let E;if(a&&(E=typeof a=="number"?a:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(nxe));const A={};if(r===void 0&&x!==void 0){const C=await x.getCachedModelDef(s,e.toString());if(C)return new O2(C.modelDef,[],[e.toString(),...wR(C.modelDef.dependencies)])}f??(f=e);let _;const v=e.toString();if(i!==void 0){_=i._translator;const C=(h=i._invalidationKey)!==null&&h!==void 0?h:await nP(s,e);A[v]=C}else{if(r===void 0){const{contents:C,invalidationKey:b}=await NR(s,e);A[v]=b,r=C}else{const C=await nP(s,e);A[v]=C}_=new exe.MalloyTranslator(v,f.toString(),{urls:{[v]:r}},c)}for(;;){const C=_.translate(u==null?void 0:u._modelDef);if(C.final)if(C.modelDef){await(x==null?void 0:x.setCachedModelDef(e.toString(),{modelDef:C.modelDef,invalidationKeys:A}));for(const b of _.newlyTranslatedDependencies())await(x==null?void 0:x.setCachedModelDef(b.url,{modelDef:b.modelDef,invalidationKeys:A}));return new O2(C.modelDef,C.problems||[],[...(p=u==null?void 0:u.fromSources)!==null&&p!==void 0?p:[],...(m=C.fromSources)!==null&&m!==void 0?m:[]],b=>_.referenceAt(b),b=>_.importAt(b))}else if(l){const b={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},S=(u==null?void 0:u._modelDef)||b;return new O2(S,C.problems||[],[...(g=u==null?void 0:u.fromSources)!==null&&g!==void 0?g:[],...(y=C.fromSources)!==null&&y!==void 0?y:[]],R=>_.referenceAt(R),R=>_.importAt(R))}else{const b=C.problems||[],S=_.prettyErrors();throw new rxe(`Error(s) compiling model:
1467
- ${S}`,b)}else{if(C.urls)for(const S of C.urls)try{if(LR(S))throw new Error("In order to use relative imports, you must compile a file via a URL.");if(x!==void 0){const D=await x.getCachedModelDef(s,S);if(D){for(const k in D.invalidationKeys)A[k]=D.invalidationKeys[k];_.update({translations:{[S]:D.modelDef}});continue}}const{contents:R,invalidationKey:O}=await NR(s,new URL(S)),B={[S]:R};A[S]=O,_.update({urls:B})}catch(R){_.update({errors:{urls:{[S]:R.message}}})}const{modelAnnotation:b}=_.modelAnnotation(u==null?void 0:u._modelDef);if(C.tables){const S=new Map;for(const R in C.tables){const{connectionName:O,tablePath:B}=C.tables[R],D=S.get(O);D===void 0?S.set(O,{[R]:B}):D[R]=B}for(const[R,O]of S)try{const B=await o.lookupConnection(R),{schemas:D,errors:k}=await E6.safelyFetchTableSchema(B,O,{refreshTimestamp:E,modelAnnotation:b});_.update({tables:D,errors:{tables:k}})}catch(B){const D={},k={};for(const q in O)k[q]=B.toString();_.update({tables:D,errors:{tables:k}})}}if(C.compileSQL){const S=C.compileSQL,R=S.connection,O=(0,lxt.sqlKey)(S.connection,S.selectStr);try{const D=await(await o.lookupConnection(R)).fetchSchemaForSQLStruct(S,{refreshTimestamp:E,modelAnnotation:b});D.error&&_.update({errors:{compileSQL:{[O]:D.error}}}),D.structDef&&_.update({compileSQL:{[O]:D.structDef}})}catch(B){const D={};D[O]=B.toString(),_.update({errors:{compileSQL:D}})}}}}}static async safelyFetchTableSchema(e,r,i){const s=await e.fetchSchemaForTables(r,i);for(const o of Object.keys(r))if(s.schemas[o]===void 0&&s.errors[o]===void 0)throw new Error(`Schema fetch error for ${e.name}, no response for ${o} from ${e.dialectName}`);return s}static async run({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(!s){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);s=await e.lookupConnection(u)}if(i){const u=await s.runSQL(i.selectStr);return new AE({structs:[i],sql:i.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:i.name,malloy:"",connectionName:i.connection,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{},queryList:[],dependencies:{}})}else if(r){const u=await s.runSQL(r.sql,o);return new AE({...r._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.profilingUrl},r._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(i===void 0&&r===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);if(s===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");s=await e.lookupConnection(u)}if(!s.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(i)l=new Ps(i),a=i.selectStr;else if(r!==void 0)l=r.resultExplore,a=r.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of s.runSQLStream(a,o))yield new fd(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:r,sqlStruct:i}){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i.selectStr);if(r)return await o.estimateQueryCost(r.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}};we.Malloy=n0;class rxe extends Error{constructor(e,r=[]){super(e),this.problems=r}}we.MalloyError=rxe;class O2{constructor(e,r,i,s=()=>{},o=()=>{}){this.modelDef=e,this.problems=r,this.fromSources=i,this._referenceAt=s,this._importAt=o}tagParse(e){return(0,$n.annotationToTag)(this.modelDef.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this.modelDef.annotation,e)}getReference(e){return this._referenceAt(e)}getImport(e){return this._importAt(e)}getPreparedQueryByName(e){const r=this.modelDef.contents[e];if((r==null?void 0:r.type)==="query")return new F2(r,this.modelDef,this.problems,e);throw new Error("Given query name does not refer to a named query.")}getPreparedQueryByIndex(e){if(e<0)throw new Error(`Invalid index ${e}.`);if(e>=this.modelDef.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new F2(this.modelDef.queryList[e],this.modelDef,this.problems)}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.modelDef.queryList.length===0)throw new Error("Model has no queries.");return new F2(this.modelDef.queryList[this.modelDef.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const r=this.modelDef.contents[e];if((0,li.isSourceDef)(r))return new Ps(r);throw new Error("'name' is not an explore")}get explores(){return Object.values(this.modelDef.contents).filter(li.isSourceDef).map(e=>new Ps(e))}get namedQueries(){const e=r=>r.type==="query";return Object.values(this.modelDef.contents).filter(e)}get exportedExplores(){return this.explores.filter(e=>this.modelDef.exports.includes(e.name))}get _modelDef(){return this.modelDef}}we.Model=O2;class F2{constructor(e,r,i,s){this.problems=i,this.name=s,this._query=e,this._modelDef=r}tagParse(e){const r=(0,$n.annotationToTag)(this._modelDef.annotation).tag;return e=(0,$n.addModelScope)(e,r),(0,$n.annotationToTag)(this._query.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const i=new li.QueryModel(this._modelDef,e==null?void 0:e.eventStream).compileQuery(this._query,e);return new yE({...i,queryName:this.name||i.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,r=typeof e=="string"?this._modelDef.contents[e]:e;if(!(0,li.isSourceDef)(r))throw new Error("Invalid source for query");return r.dialect}getFlattenedQuery(e){return this}}we.PreparedQuery=F2;class ixe{constructor(e,r){this.translator=e,this.invalidationKey=r}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new SR(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(i=>new sxe(i))}get _translator(){return this.translator}get _invalidationKey(){return this.invalidationKey}completions(e){return(this.translator.completions(e).completions||[]).map(r=>new oxe(r))}helpContext(e){return this.translator.helpContext(e).helpContext}}we.Parse=ixe;class sxe{constructor(e){this._range=w2.fromJSON(e.range),this._connectionId=e.connectionId,this._tablePath=e.tablePath}get range(){return this._range}get connectionId(){return this._connectionId}get tablePath(){return this._tablePath}}we.DocumentTablePath=sxe;class w2{constructor(e,r){this._start=e,this._end=r}get start(){return this._start}get end(){return this._end}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}static fromJSON(e){return new w2(new QM(e.start.line,e.start.character),new QM(e.end.line,e.end.character))}}we.DocumentRange=w2;class QM{constructor(e,r){this._line=e,this._character=r}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}we.DocumentPosition=QM;class SR{constructor(e){this._range=w2.fromJSON(e.range),this._lensRange=e.lensRange?w2.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(r=>new SR(r))}get range(){return this._range}get lensRange(){var e;return(e=this._lensRange)!==null&&e!==void 0?e:this._range}get type(){return this._type}get name(){return this._name}get children(){return this._children}}we.DocumentSymbol=SR;class oxe{constructor(e){this.type=e.type,this.text=e.text}}we.DocumentCompletion=oxe;class yE{constructor(e,r){this.modelDef=r,this.inner=e}static fromJson({query:e,modelDef:r}){if(!e||!r)throw new Error("Missing required properties in JSON data");return new yE(e,r)}tagParse(e){const r=(0,$n.annotationToTag)(this.modelDef.annotation).tag;return e=(0,$n.addModelScope)(e,r),(0,$n.annotationToTag)(this.inner.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return(0,$n.annotationToTag)(this.modelDef.annotation).tag}get connectionName(){return this.inner.connectionName}get _rawQuery(){return this.inner}get _modelDef(){return this.modelDef}get sql(){return this.inner.sql}get dependenciesToMaterialize(){return this.inner.dependenciesToMaterialize}get materialization(){return this.inner.materialization}get resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],r={...e,annotation:this.inner.annotation,name:this.inner.queryName||e.name};try{return new Ps(r,this.sourceExplore)}catch{return new Ps(r)}}get sourceExplore(){const e=this.inner.sourceExplore,r=this.modelDef.contents[e];if(r&&(0,li.isSourceDef)(r))return new Ps(r)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}we.PreparedResult=yE;class uxe{async readURL(e){throw new Error("No files.")}async getInvalidationKey(e){throw new Error("No files.")}}we.EmptyURLReader=uxe;class cxt{constructor(e){this.files=e}async readURL(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve({contents:r,invalidationKey:this.invalidationKey(e,r)});throw new Error(`File not found '${e}'`)}async getInvalidationKey(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve(this.invalidationKey(e,r));throw new Error(`File not found '${e}'`)}invalidationKey(e,r){return LR(e.toString())?null:vxe(r)}}we.InMemoryURLReader=cxt;class bR{constructor(e,r){this.connections=e,this.defaultConnectionName=r}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const r=this.connections.get(e);if(r!==void 0)return Promise.resolve(r);throw new Error(`No connection found with name ${e}.`)}listConnections(){return Array.from(this.connections.values())}async lookupConnection(e){return this.getConnection(e)}static fromArray(e){return new bR(new Map(e.map(r=>[r.name,r])))}}we.FixedConnectionMap=bR;var axe;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(axe||(we.SourceRelationship=axe={}));class zM{constructor(e,r,i){this._name=e,this._parent=r,this._source=i}get source(){return this.source}get name(){return this._name}get sourceClasses(){const e=[];return this.source&&e.push(this.source.name),e.push(this.name),e}get fieldPath(){const e=[this.name];let r=this._parent;for(;r;)e.unshift(r.name),r=r._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof Ps}isQuery(){return this instanceof XM}}class Ps extends zM{constructor(e,r,i){super(e.as||e.name,r,i),this._structDef=e,this._parentExplore=r,this.sourceExplore=i}get source(){return this.sourceExplore}isIntrinsic(){return(0,li.isAtomicFieldType)(this._structDef.type)?!("e"in this._structDef):!1}isExploreField(){return!1}tagParse(e){return(0,$n.annotationToTag)(this._structDef.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=(0,$n.annotationToTag)(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const r=this.sourceStructDef;if(!r)throw new Error(`Cannot get query by name from a struct of type ${this.structDef.type}`);const i={type:"query",structRef:r,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new F2(i,this.modelDef,[],e)}get modelDef(){if(!(0,li.isSourceDef)(this.structDef))throw new Error(`Cannot create pseudo model for struct type ${this.structDef.type}`);return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef},queryList:[],dependencies:{}}}getSingleExploreModel(){return new O2(this.modelDef,[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const r=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(i=>{const s=i.as||i.name,o=r.get(i.name);if((0,li.isJoined)(i))return[s,new ZM(i,this,o)];if(i.type==="turtle")return[s,new XM(i,this,o)];if(i.type==="string")return[s,new JM(i,this,o)];if(i.type==="number")return[s,new TR(i,this,o)];if(i.type==="date")return i.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(i.timeframe)?[s,new TR({...i,type:"number"},this,o)]:[s,new GM(i,this,o)];if(i.type==="timestamp")return[s,new WM(i,this,o)];if(i.type==="boolean")return[s,new VM(i,this,o)];if(i.type==="json")return[s,new YM(i,this,o)];if(i.type==="sql native")return[s,new KM(i,this,o)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,r,i;if(!this._allFieldsWithOrder){const s=[...((i=(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.orderBy)===null||i===void 0?void 0:i.map(u=>{if(typeof u.field=="string")return{field:this.fieldMap.get(u.field),dir:u.dir};throw new Error("Does not support mapping order by from number.")}))||[]],o=new Set(s.map(u=>u.field.name));this._allFieldsWithOrder=[...s,...this.allFields.filter(u=>!o.has(u.name)).map(u=>({field:u,dir:"asc"}))]}return this._allFieldsWithOrder}get intrinsicFields(){return[...this.fieldMap.values()].filter(e=>e.isIntrinsic())}get dimensions(){return[...this.allFieldsWithOrder].filter(e=>e.field.isAtomicField()&&e.field.sourceWasDimension())}getFieldByName(e){const r=this.fieldMap.get(e);if(r===void 0)throw new Error(`No such field ${e}.`);return r}getFieldByNameIfExists(e){return this.fieldMap.get(e)}get primaryKey(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.primaryKey}get parentExplore(){return this._parentExplore}hasParentExplore(){return this instanceof ZM}get filters(){var e;return(0,li.isSourceDef)(this.structDef)?((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]:[]}get limit(){var e,r;return(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.limit}get structDef(){return this._structDef}get queryTimezone(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.queryTimezone}get sourceStructDef(){if((0,li.isSourceDef)(this.structDef))return this.structDef}toJSON(){var e,r;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(r=this._parentExplore)===null||r===void 0?void 0:r.toJSON()}}static fromJSON(e){const r=e._parentExplore!==void 0?Ps.fromJSON(e._parentExplore):void 0,i=e.sourceExplore!==void 0?Ps.fromJSON(e.sourceExplore):void 0;return new Ps(e._structDef,r,i)}get location(){return this.structDef.location}}we.Explore=Ps;var Ba;(function(t){t.String="string",t.Number="number",t.Boolean="boolean",t.Date="date",t.Timestamp="timestamp",t.Json="json",t.NativeUnsupported="sql native",t.Error="error"})(Ba||(we.AtomicFieldType=Ba={}));class Gc extends zM{constructor(e,r,i){super(e.as||e.name,r,i),this.fieldTypeDef=e,this.parent=r}get type(){switch(this.fieldTypeDef.type){case"string":return Ba.String;case"boolean":return Ba.Boolean;case"date":return Ba.Date;case"timestamp":return Ba.Timestamp;case"number":return Ba.Number;case"json":return Ba.Json;case"sql native":return Ba.NativeUnsupported;case"error":return Ba.Error;case"record":case"array":throw new Error(`MTOY TODO IMPLEMENT Atomic ${this.fieldTypeDef.type}`);default:{const e=this.fieldTypeDef;throw new Error(`Can't make an atomic field from ${e}`)}}}tagParse(e){return e=(0,$n.addModelScope)(e,this.parent.modelTag),(0,$n.annotationToTag)(this.fieldTypeDef.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,li.fieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,li.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}get referenceId(){var e;return(e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.referenceId}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,r;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((r=this.fieldTypeDef.resultMetadata)===null||r===void 0?void 0:r.fieldKind)==="struct"}sourceWasDimension(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="dimension"}hasParentExplore(){return!0}isString(){return this instanceof JM}isNumber(){return this instanceof TR}isDate(){return this instanceof GM}isBoolean(){return this instanceof VM}isJSON(){return this instanceof YM}isTimestamp(){return this instanceof WM}isUnsupported(){return this instanceof KM}get parentExplore(){return this.parent}get expression(){const e=".",r=this.fieldTypeDef.resultMetadata;return(r==null?void 0:r.sourceExpression)||(r!=null&&r.sourceField.includes(e)?r==null?void 0:r.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}we.AtomicField=Gc;var cd;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(cd||(we.DateTimeframe=cd={}));var $a;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year",t.Second="second",t.Hour="hour",t.Minute="minute"})($a||(we.TimestampTimeframe=$a={}));class GM extends Gc{constructor(e,r,i){super(e,r,i),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return cd.Day;case"week":return cd.Week;case"month":return cd.Month;case"quarter":return cd.Quarter;case"year":return cd.Year}}}we.DateField=GM;class WM extends Gc{constructor(e,r,i){super(e,r,i),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return $a.Day;case"week":return $a.Week;case"month":return $a.Month;case"quarter":return $a.Quarter;case"year":return $a.Year;case"second":return $a.Second;case"hour":return $a.Hour;case"minute":return $a.Minute}}}we.TimestampField=WM;class TR extends Gc{constructor(e,r,i){super(e,r,i),this.fieldNumberDef=e}}we.NumberField=TR;class VM extends Gc{constructor(e,r,i){super(e,r,i),this.fieldBooleanDef=e}}we.BooleanField=VM;class YM extends Gc{constructor(e,r,i){super(e,r,i),this.fieldJSONDef=e}}we.JSONField=YM;class KM extends Gc{constructor(e,r,i){super(e,r,i),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}we.UnsupportedField=KM;class JM extends Gc{constructor(e,r,i){super(e,r,i),this.fieldStringDef=e}}we.StringField=JM;class lxe extends zM{constructor(e,r,i){super(e.as||e.name,r,i),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}we.Query=lxe;class XM extends lxe{constructor(e,r,i){super(e,r,i),this.parent=r}tagParse(e){return e=(0,$n.addModelScope)(e,this.parent.modelTag),(0,$n.annotationToTag)(this.turtleDef.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this.turtleDef.annotation,e)}isQueryField(){return!0}isExploreField(){return!1}isAtomicField(){return!1}get sourceClasses(){const e=this.turtleDef.name||this.turtleDef.as;return e?[e]:[]}hasParentExplore(){return!0}get parentExplore(){return this.parent}get expression(){return this.name}}we.QueryField=XM;var N2;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(N2||(we.JoinRelationship=N2={}));class ZM extends Ps{constructor(e,r,i){super(e,r,i),this._parentExplore=r}get joinRelationship(){if((0,li.isJoined)(this.structDef))switch(this.structDef.join){case"one":return N2.OneToOne;case"many":case"cross":return N2.ManyToOne}throw new Error("A source field must have a join relationship.")}get isRecord(){return this.joinRelationship===N2.OneToOne}get isArray(){return this.joinRelationship!==N2.OneToOne}tagParse(e){return e=(0,$n.addModelScope)(e,this._parentExplore.modelTag),(0,$n.annotationToTag)(this._structDef.annotation,e)}isQueryField(){return!1}isExploreField(){return!0}isAtomicField(){return!1}get parentExplore(){return this._parentExplore}get sourceClasses(){const e=this.structDef.name||this.structDef.as;return e?[e]:[]}}we.ExploreField=ZM;class eP{constructor({urlReader:e,connections:r,connection:i,eventStream:s,cacheManager:o}){if(this.isTestRuntime=!1,r===void 0){if(i===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");r={lookupConnection:()=>Promise.resolve(i)}}e===void 0&&(e=new uxe),this._urlReader=e,this._connections=r,this._eventStream=s,this._cacheManager=o}get cacheManager(){return this._cacheManager}get urlReader(){return this._urlReader}get connections(){return this._connections}get eventStream(){return this._eventStream}loadModel(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};this.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const o=e instanceof URL?{url:e}:{source:e};return new EE(this,async()=>n0.compile({...o,urlReader:this.urlReader,connections:this.connections,refreshSchemaCache:i,noThrowOnError:s,eventStream:this.eventStream,replaceMaterializedReferences:r==null?void 0:r.replaceMaterializedReferences,materializedTablePrefix:r==null?void 0:r.materializedTablePrefix,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,cacheManager:this.cacheManager}),r)}_loadModelFromModelDef(e,r){return new EE(this,async()=>new O2(e,[],[]),r)}loadQuery(e,r){return this.loadModel(e,r).loadFinalQuery()}loadQueryByIndex(e,r,i){return this.loadModel(e,i).loadQueryByIndex(r,i)}loadQueryByName(e,r,i){return this.loadModel(e,i).loadQueryByName(r,i)}getModel(e,r){return this.loadModel(e,r).getModel()}getQuery(e,r){return this.loadQuery(e,r).getPreparedQuery()}getQueryByIndex(e,r,i){return this.loadQueryByIndex(e,r,i).getPreparedQuery()}getQueryByName(e,r,i){return this.loadQueryByName(e,r,i).getPreparedQuery()}}we.Runtime=eP;class fxt extends eP{constructor({urlReader:e,connections:r}){super({connections:bR.fromArray(r),urlReader:e}),this.rawConnections=r}}we.ConnectionRuntime=fxt;class xxt extends eP{constructor({urlReader:e,connection:r,eventStream:i,cacheManager:s}){super({urlReader:e,eventStream:i,cacheManager:s,connection:r}),this.connection=r}get supportsNesting(){return(0,HM.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,HM.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,HM.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}we.SingleConnectionRuntime=xxt;class RR{constructor(e,r){this.runtime=e,this._materialize=r}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e,r){return new cxe(this.runtime,e,r)}makeExploreMaterializer(e,r){return new xxe(this.runtime,e,r)}makePreparedResultMaterializer(e){return new fxe(this.runtime,e)}}class EE extends RR{constructor(e,r,i){super(e,r),this.runtime=e,this.compileQueryOptions=i}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{...this.compileQueryOptions,...e})}loadQueryByIndex(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{...this.compileQueryOptions,...r})}loadQueryByName(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{...this.compileQueryOptions,...r})}loadQuery(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};return this.makeQueryMaterializer(async()=>{const o=this.runtime.urlReader,u=this.runtime.connections;this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const a=e instanceof URL?{url:e}:{source:e},l=await this.getModel();return(await n0.compile({...a,urlReader:o,connections:u,model:l,refreshSchemaCache:i,noThrowOnError:s,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})).preparedQuery})}extendModel(e,r){return this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0}),new EE(this.runtime,async()=>{const i=this.runtime.urlReader,s=this.runtime.connections,o=e instanceof URL?{url:e}:{source:e},u=await this.getModel();return await n0.compile({...o,urlReader:i,connections:s,model:u,refreshSchemaCache:r==null?void 0:r.refreshSchemaCache,noThrowOnError:r==null?void 0:r.noThrowOnError,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})},r)}async search(e,r,i=1e3,s=void 0,o){const u=await this.materialize(),a=new li.QueryModel(u._modelDef,o),l=u.getExploreByName(e).structDef;if(!(0,li.isSourceDef)(l))throw new Error("Source to be searched was unexpectedly, not a source");const c=l.connection,f=await this.runtime.connections.lookupConnection(c);return await a.searchIndex(f,e,r,i,s)}async searchValueMap(e,r=10,i){const o=(await this.materialize()).getExploreByName(e);if(!(0,li.isSourceDef)(o.structDef))throw new Error("Source to be searched was unexpectedly, not a source");let u="{index: *}";o.getFieldByNameIfExists("search_index")&&(u="search_index");const a=`
1466
+ ${s}`:e=s}return e}childRequest(e){var r;const i=decodeURI(new URL(e,this.sourceURL).toString()),s=(r=this.childTranslators.get(i))===null||r===void 0?void 0:r.translate();if(s!=null&&s.compileSQL)return{compileSQL:s.compileSQL}}getChildExports(e){const r={},i=decodeURI(new URL(e,this.sourceURL).toString()),s=this.childTranslators.get(i);if(s&&s.translate().modelDef)for(const u of s.modelDef.exports){const a=s.modelDef.contents[u];((0,Tft.isSourceDef)(a)||a.type==="query")&&(r[u]=a)}return r}translate(e){if(this.finalAnswer)return this.finalAnswer;const r=this.translateStep.step(this,e);return r.final&&(this.finalAnswer=r),r}translatorForDependency(e){return this.childTranslators.get(e)}importAt(e){for(let r=0;r<this.imports.length;r++){const i=this.imports[r];if((0,kM.locationContainsPosition)(i.location,e))return i}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return(0,kM.rangeFromContext)(this.parseStep.sourceInfo,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const r=this.compilerFlags.tag("experimental");return r!==void 0&&(r.bare()||r.has("dialect",e))}}Tc.MalloyTranslation=MM;class Qfe extends MM{constructor(e,r){super(e),this.root=r}}Tc.MalloyChildTranslator=Qfe;class Wft extends MM{constructor(e,r=null,i=null,s=null){super(e,r),this.eventStream=s,this.schemaZone=new $M.Zone,this.importZone=new $M.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new $M.Zone,this.root=this,this.logger=new Hfe.BaseMessageLogger(s),i&&this.update(i)}update(e){var r,i,s;this.schemaZone.updateFrom(e.tables,(r=e.errors)===null||r===void 0?void 0:r.tables),this.importZone.updateFrom(e.urls,(i=e.errors)===null||i===void 0?void 0:i.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(s=e.errors)===null||s===void 0?void 0:s.compileSQL);for(const o in e.translations)this.pretranslatedModels.set(o,e.translations[o])}logError(e,r,i){return this.logger.log((0,Hfe.makeLogMessage)(e,r,{severity:"error",...i})),e}}Tc.MalloyTranslator=Wft;function zfe(t){return[...Object.keys(t),...Object.keys(t).map(e=>zfe(t[e])).flat()]}var T2={};Object.defineProperty(T2,"__esModule",{value:!0}),T2.exploreQueryWalkerBuilder=T2.ExploreQueryWalker=void 0;const Vft=uc;class Gfe{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}filterAtOffset(e){const r=this.exploreQueryAtOffset(e);if(r)return r.filterRefs.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e)}hasFilterListAtOffset(e){const r=this.exploreQueryAtOffset(e);return r?!!r.filterLists.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}T2.ExploreQueryWalker=Gfe;function Yft(t,e){const r=new Gfe(t),i=r;return Vft.ParseTreeWalker.DEFAULT.walk(i,e),r}T2.exploreQueryWalkerBuilder=Yft;var R2={},mE={},La={};Object.defineProperty(La,"__esModule",{value:!0}),La.getResultStructMetadataAnnotation=La.convertFieldInfos=La.modelDefToModelInfo=void 0;const Ia=Pi,PM=Ls,UM=ui,Wfe=Zo;function Kft(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,Ia.isSourceDef)(i)){const s=i.parameters&&Object.entries(i.parameters).length>0?Object.entries(i.parameters).map(([u,a])=>(0,Ia.isAtomic)(a)?{name:u,type:vR(a),default_value:Vfe(a.value)}:{name:u,type:{kind:"filter_expression_type"},default_value:Vfe(a.value)}):void 0,o={kind:"source",name:r,schema:{fields:D2(i,i.fields)},parameters:s,annotations:jM(i)};e.entries.push(o)}else if(i.type==="query"){const s=(0,PM.getResultStructDefForQuery)(t,i),o=jM(i),u=s.resultMetadata?_R(s,s.resultMetadata):void 0,a=[...o??[],...u?[u]:[]],l={kind:"source",name:r,schema:{fields:D2(s,s.fields)},annotations:a.length>0?a:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,PM.getResultStructDefForQuery)(t,r),s=jM(r),o=i.resultMetadata?_R(i,i.resultMetadata):void 0,u=[...s??[],...o?[o]:[]],a={schema:{fields:D2(i,i.fields)},annotations:u.length>0?u:void 0};e.anonymous_queries.push(a)}return e}La.modelDefToModelInfo=Kft;function Vfe(t){if(t!==null)switch(t.node){case"numberLiteral":return{kind:"number_literal",number_value:parseFloat(t.literal)};case"stringLiteral":return{kind:"string_literal",string_value:t.literal};case"filterLiteral":return{kind:"filter_expression_literal",filter_expression_value:t.filterSrc};case"timeLiteral":return{kind:"timestamp_literal",timestamp_value:t.literal};case"true":return{kind:"boolean_literal",boolean_value:!0};case"false":return{kind:"boolean_literal",boolean_value:!1};case"null":return{kind:"null_literal"};default:throw new Error("Invalid parameter default value")}}function jM(t){return(0,UM.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function D2(t,e){var r,i,s;const o=[];for(const u of e){if(!(u.accessModifier===void 0))continue;const c=(0,UM.annotationToTaglines)(u.annotation).map(x=>({value:x})),f=c.length>0?c:void 0;if((0,Ia.isTurtle)(u)){const x=(0,PM.getResultStructDefForView)(t,u),h=x.resultMetadata?_R(x,x.resultMetadata):void 0,p=[...f??[],...h?[h]:[]],m={kind:"view",name:(r=u.as)!==null&&r!==void 0?r:u.name,annotations:p.length>0?p:void 0,schema:{fields:D2(x,x.fields)}};o.push(m)}else if((0,Ia.isAtomic)(u)){const x=(0,Ia.expressionIsAggregate)(u.expressionType),h=(0,Ia.expressionIsScalar)(u.expressionType);if(!x&&!h||u.type==="error")continue;const p=u.resultMetadata?Yfe(u,u.resultMetadata):void 0,m=[...f??[],...p?[p]:[]],g={kind:x?"measure":"dimension",name:(i=u.as)!==null&&i!==void 0?i:u.name,type:vR(u),annotations:m.length>0?m:void 0};o.push(g)}else if((0,Ia.isJoinedSource)(u)){const x={kind:"join",name:(s=u.as)!==null&&s!==void 0?s:u.name,annotations:f,schema:{fields:D2(u,u.fields)},relationship:u.join};o.push(x)}}return o}La.convertFieldInfos=D2;function Yfe(t,e){const r=Wfe.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.filterList){const s=e.filterList.filter(o=>o.expressionType==="scalar").map(o=>o.code);r.set(["drill_filters"],s),i=!0}if(e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:Xft(t.name));r.set(["drill_expression"],o),i=!0}return i?{value:r.toString()}:void 0}function Jft(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function Xft(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${Jft(t)}\``}function _R(t,e){var r,i;const s=Wfe.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList){const u=e.filterList.filter(a=>a.expressionType==="scalar").map(a=>a.code);u.length>0&&(s.set(["drill_filters"],u),o=!0)}if(e.orderBy){for(let u=0;u<e.orderBy.length;u++){const a=e.orderBy[u],l=typeof a.field=="number"?(r=t.fields[a.field-1].as)!==null&&r!==void 0?r:t.fields[a.field-1].name:a.field,c=(i=a.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",u,l],c)}o=!0}return o?{value:s.toString()}:void 0}La.getResultStructMetadataAnnotation=_R;function vR(t){if((0,Ia.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!Zft(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:ext(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,Ia.isRepeatedRecord)(t))return{kind:"array_type",element_type:Kfe(t)};if(t.type==="record")return Kfe(t);if(t.type==="array")return{kind:"array_type",element_type:vR(t.elementTypeDef)}}throw new Error("Unexpected field type")}function Kfe(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=Yfe(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,UM.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,Ia.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:vR(e)};throw new Error("Expected record type to not have a table as its child")})}}function Zft(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function ext(t){switch(t){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return t;default:throw new Error(`Invalid date timeframe ${t}`)}}function mht(t){return t}function ght(t){return t}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.mapLogs=t.DEFAULT_LOG_RANGE=t.wrapResult=t.mapData=t.wrapLegacyConnection=t.wrapLegacyInfoConnection=void 0;const e=Zo,r=ui,i=La,s=by;function o(x){return{get dialectName(){return x.dialectName},async fetchSchemaForSQLQuery(h){const p=await x.fetchSchemaForSQLStruct({connection:x.name,selectStr:h},{}),m=p.structDef;if(m===void 0)throw new Error(p.error);return{fields:(0,i.convertFieldInfos)(m,m.fields)}},async fetchSchemaForTable(h){const p=`${x.name}:${h}`,m=await x.fetchSchemaForTables({[p]:h},{}),g=m.schemas[p];if(g===void 0)throw new Error(m.errors[p]);return{fields:(0,i.convertFieldInfos)(g,g.fields)}}}}t.wrapLegacyInfoConnection=o;function u(x){return{...o(x),runSQL:async(h,p)=>{const m=await x.runSQL(h);return l(m.rows,p)}}}t.wrapLegacyConnection=u;function a(x){if(x instanceof Date)return x;if(x.constructor.name==="Date")return new Date(x);if(typeof x=="number")return new Date(x);if(typeof x!="string")return new Date(x.value);{let p=s.DateTime.fromISO(x,{zone:"UTC"});return p.isValid||(p=s.DateTime.fromSQL(x,{zone:"UTC"})),p.toJSDate()}}function l(x,h){function p(y,E){if(y===null)return{kind:"null_cell"};if(E.type.kind==="date_type"||E.type.kind==="timestamp_type"){const A=a(y).toISOString();return E.type.kind==="date_type"?{kind:"date_cell",date_value:A}:{kind:"timestamp_cell",timestamp_value:A}}else if(E.type.kind==="boolean_type"){if(typeof y=="number")return{kind:"boolean_cell",boolean_value:y!==0};if(typeof y!="boolean")throw new Error(`Invalid boolean ${y}`);return{kind:"boolean_cell",boolean_value:y}}else if(E.type.kind==="number_type"){if(typeof y!="number")throw new Error(`Invalid number ${y}`);return{kind:"number_cell",number_value:y}}else if(E.type.kind==="string_type"){if(typeof y!="string")throw new Error(`Invalid string ${y}`);return{kind:"string_cell",string_value:y}}else if(E.type.kind==="array_type"){if(!Array.isArray(y))throw new Error(`Invalid array ${y}`);return{kind:"array_cell",array_value:y.map(A=>p(A,{name:"array_element",type:E.type.element_type}))}}else{if(E.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(y)};if(E.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(y)};{const A=E.type;if(A.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(E)}, ${JSON.stringify(y)}`);return m(y,{kind:"join",relationship:"many",name:"array_element",schema:{fields:A.fields.map(_=>({kind:"dimension",..._}))}})}}}function m(y,E){const A=[];for(const _ of E.schema.fields){const v=y[_.name];if(_.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const C=p(v,_);A.push(C)}return{kind:"record_cell",record_value:A}}const g={kind:"join",schema:h,name:"root",relationship:"one"};return{kind:"array_cell",array_value:x.map(y=>m(y,g))}}t.mapData=l;function c(x){const h=x._queryResult.structs,p=h[h.length-1],m={fields:(0,i.convertFieldInfos)(p,p.fields)},g=(0,r.annotationToTaglines)(x.annotation).map(E=>({value:E})),y=p.resultMetadata?(0,i.getResultStructMetadataAnnotation)(p,p.resultMetadata):void 0;return y&&g.push(y),g.push(...p.resultMetadata?[]:[]),x.sourceExplore&&g.push({value:e.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore.name).toString()}),g.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],x.resultExplore.name).toString()}),{schema:m,data:l(x.data.toObject(),m),connection_name:x.connectionName,annotations:g.length>0?g:void 0,query_timezone:x.data.field.queryTimezone,sql:x.sql}}t.wrapResult=c,t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function f(x,h){return x.map(p=>{var m,g,y,E;return{severity:p.severity,message:p.message,range:(g=(m=p.at)===null||m===void 0?void 0:m.range)!==null&&g!==void 0?g:t.DEFAULT_LOG_RANGE,url:(E=(y=p.at)===null||y===void 0?void 0:y.url)!==null&&E!==void 0?E:h}})}t.mapLogs=f})(mE);var txt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),nxt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),rxt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&txt(e,t,r);return nxt(e,t),e};Object.defineProperty(R2,"__esModule",{value:!0}),R2.malloyToQuery=R2.MalloyToQuery=void 0;const ixt=Kh,On=rxt(w),Jfe=Yp,gE=Bn,sxt=Xe,oxt=aE,Xfe=Vn,uxt=mE,qM="Malloy query documents";class Zfe extends ixt.AbstractParseTreeVisitor{constructor(e,r){super(),this.parseInfo=e,this.msgLog=r}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}getLocation(e){return{url:this.parseInfo.sourceURL,range:(0,Xfe.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,Jfe.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}getNumber(e){return Number.parseInt(e.text)}defaultResult(){return null}getAnnotations(e){const r=e.ANNOTATION().map(i=>({value:i.text}));return r.length>0?r:void 0}getIsAnnotations(e){var r,i;if(e===void 0)return;const o=((r=this.getAnnotations(e._beforeIs))!==null&&r!==void 0?r:[]).concat((i=this.getAnnotations(e._afterIs))!==null&&i!==void 0?i:[]);return o.length>0?o:void 0}notAllowed(e,r){this.illegal(e,`${r} are not allowed in ${qM}`)}illegal(e,r){this.contextError(e,"invalid-malloy-query-document",r)}visitMalloyDocument(e){const r=e.malloyStatement();let i;for(const s of r)s.defineSourceStatement()?this.notAllowed(s,"Source definitions"):s.defineQuery()?this.notAllowed(s,"Query definitions"):s.importStatement()?this.notAllowed(s,"Import statements"):s.docAnnotations()?this.notAllowed(s,"Model annotations"):s.ignoredObjectAnnotations()?this.notAllowed(s,"Detatched object annotations"):s.experimentalStatementForTesting()?this.notAllowed(s,"Experimental testing statements"):i===void 0?i=s.runStatement():this.illegal(s,`${qM} may only have one run statement`);return i===void 0?(this.illegal(e,`${qM} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.topLevelAnonQueryDef().tags());return i!==null?{annotations:s,definition:i}:null}getQueryReference(e){if(e.sourceArguments())this.illegal(e,"Queries do not support parameters");else return{name:(0,gE.getId)(e)};return null}getQueryDefinition(e){if(e instanceof On.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof On.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof On.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof On.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof On.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof On.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof On.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof On.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof On.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof On.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof On.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof On.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof On.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,gE.getId)(s.fieldName()),u=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:u,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof On.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const u=this.getAnnotations(o.tags()),a=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,gE.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,u,a)}})}return s}getViewExpression(e){if(e instanceof On.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof On.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.havingStatement()){const r=e.havingStatement(),i=this.getHaving(r);return i===null?null:i.map(s=>({kind:"having",...s}))}else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,gE.getId)(o)),i=r[0],s=r.slice(1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,sxt.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const u=r.refExpr();if(u.timeframe()){const a=this.getTimeframe(u.timeframe());return a===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:a}}}}else u.aggregate()&&this.notAllowed(u,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,gE.getId)(r.fieldNameDef()),u=this.getFieldExpression(r.fieldExpr());return u===null?null:{name:o,field:{expression:u,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof On.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof On.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof On.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const u of s){const a=u.whereStatement();if(a){const l=this.getWhere(a);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}return null}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),u=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(u)return this.stripQuote(u.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),u=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(u)return this.stripQuote(u.text,"'")}return null}getFilterExpr(e){if(e instanceof On.ExprCompareContext&&e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof On.ExprFieldPathContext&&i instanceof On.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=i.literal();if(u instanceof On.FilterString_stubContext){const a=this.getFilterString(u.filterString());return a===null?null:{filter:{kind:"filter_string",field_reference:{name:o,path:s},filter:a}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings"),null}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}getHaving(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}R2.MalloyToQuery=Zfe;function axt(t){const e=(0,Xfe.getSourceInfo)(t),r=new Jfe.BaseMessageLogger(null),i="internal://query.malloy",s=(0,oxt.runMalloyParser)(t,i,e,r),u=new Zfe(s,r).visit(s.root),a=(0,uxt.mapLogs)(r.getLog(),i);if(u===null)return{logs:a};if(!("definition"in u))throw new Error("Expected a query");return{query:u,logs:a}}R2.malloyToQuery=axt,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Tc;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=T2;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=R2;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})}(H4);var we={},CR={};Object.defineProperty(CR,"__esModule",{value:!0}),CR.MALLOY_VERSION=void 0,CR.MALLOY_VERSION="0.0.265",Object.defineProperty(we,"__esModule",{value:!0}),we.InMemoryModelCache=we.CacheManager=we.CSVWriter=we.JSONWriter=we.DataWriter=we.DataRecord=we.DataArray=we.Result=we.ExploreMaterializer=we.PreparedResultMaterializer=we.QueryMaterializer=we.ModelMaterializer=we.SingleConnectionRuntime=we.ConnectionRuntime=we.Runtime=we.ExploreField=we.JoinRelationship=we.QueryField=we.Query=we.StringField=we.UnsupportedField=we.JSONField=we.BooleanField=we.NumberField=we.TimestampField=we.DateField=we.TimestampTimeframe=we.DateTimeframe=we.AtomicField=we.AtomicFieldType=we.Explore=we.SourceRelationship=we.FixedConnectionMap=we.InMemoryURLReader=we.EmptyURLReader=we.PreparedResult=we.DocumentCompletion=we.DocumentSymbol=we.DocumentPosition=we.DocumentRange=we.DocumentTablePath=we.Parse=we.PreparedQuery=we.Model=we.MalloyError=we.Malloy=void 0;const exe=H4,li=Pi,txe=by,HM=kp,lxt=CR,cxt=Pp,$n=ui,fxt=Yl,nxe="internal://internal.malloy";let n0=class E6{static get version(){return lxt.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(nxe));let u=r;s!=null&&s.importBaseURL&&(u=s==null?void 0:s.importBaseURL);const a=new exe.MalloyTranslator(r.toString(),u.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(a.allDialectsEnabled=!0),new ixe(a,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return E6._parse(i,e,s,o);if(r===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return NR(r,e).then(({contents:u,invalidationKey:a})=>E6._parse(u,e,s,o,a))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:u,refreshSchemaCache:a,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:x}){var h,p,m,g,y;let E;if(a&&(E=typeof a=="number"?a:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(nxe));const A={};if(r===void 0&&x!==void 0){const C=await x.getCachedModelDef(s,e.toString());if(C)return new O2(C.modelDef,[],[e.toString(),...wR(C.modelDef.dependencies)])}f??(f=e);let _;const v=e.toString();if(i!==void 0){_=i._translator;const C=(h=i._invalidationKey)!==null&&h!==void 0?h:await nP(s,e);A[v]=C}else{if(r===void 0){const{contents:C,invalidationKey:b}=await NR(s,e);A[v]=b,r=C}else{const C=await nP(s,e);A[v]=C}_=new exe.MalloyTranslator(v,f.toString(),{urls:{[v]:r}},c)}for(;;){const C=_.translate(u==null?void 0:u._modelDef);if(C.final)if(C.modelDef){await(x==null?void 0:x.setCachedModelDef(e.toString(),{modelDef:C.modelDef,invalidationKeys:A}));for(const b of _.newlyTranslatedDependencies())await(x==null?void 0:x.setCachedModelDef(b.url,{modelDef:b.modelDef,invalidationKeys:A}));return new O2(C.modelDef,C.problems||[],[...(p=u==null?void 0:u.fromSources)!==null&&p!==void 0?p:[],...(m=C.fromSources)!==null&&m!==void 0?m:[]],b=>_.referenceAt(b),b=>_.importAt(b))}else if(l){const b={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},S=(u==null?void 0:u._modelDef)||b;return new O2(S,C.problems||[],[...(g=u==null?void 0:u.fromSources)!==null&&g!==void 0?g:[],...(y=C.fromSources)!==null&&y!==void 0?y:[]],R=>_.referenceAt(R),R=>_.importAt(R))}else{const b=C.problems||[],S=_.prettyErrors();throw new rxe(`Error(s) compiling model:
1467
+ ${S}`,b)}else{if(C.urls)for(const S of C.urls)try{if(LR(S))throw new Error("In order to use relative imports, you must compile a file via a URL.");if(x!==void 0){const D=await x.getCachedModelDef(s,S);if(D){for(const k in D.invalidationKeys)A[k]=D.invalidationKeys[k];_.update({translations:{[S]:D.modelDef}});continue}}const{contents:R,invalidationKey:O}=await NR(s,new URL(S)),B={[S]:R};A[S]=O,_.update({urls:B})}catch(R){_.update({errors:{urls:{[S]:R.message}}})}const{modelAnnotation:b}=_.modelAnnotation(u==null?void 0:u._modelDef);if(C.tables){const S=new Map;for(const R in C.tables){const{connectionName:O,tablePath:B}=C.tables[R],D=S.get(O);D===void 0?S.set(O,{[R]:B}):D[R]=B}for(const[R,O]of S)try{const B=await o.lookupConnection(R),{schemas:D,errors:k}=await E6.safelyFetchTableSchema(B,O,{refreshTimestamp:E,modelAnnotation:b});_.update({tables:D,errors:{tables:k}})}catch(B){const D={},k={};for(const q in O)k[q]=B.toString();_.update({tables:D,errors:{tables:k}})}}if(C.compileSQL){const S=C.compileSQL,R=S.connection,O=(0,fxt.sqlKey)(S.connection,S.selectStr);try{const D=await(await o.lookupConnection(R)).fetchSchemaForSQLStruct(S,{refreshTimestamp:E,modelAnnotation:b});D.error&&_.update({errors:{compileSQL:{[O]:D.error}}}),D.structDef&&_.update({compileSQL:{[O]:D.structDef}})}catch(B){const D={};D[O]=B.toString(),_.update({errors:{compileSQL:D}})}}}}}static async safelyFetchTableSchema(e,r,i){const s=await e.fetchSchemaForTables(r,i);for(const o of Object.keys(r))if(s.schemas[o]===void 0&&s.errors[o]===void 0)throw new Error(`Schema fetch error for ${e.name}, no response for ${o} from ${e.dialectName}`);return s}static async run({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(!s){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);s=await e.lookupConnection(u)}if(i){const u=await s.runSQL(i.selectStr);return new AE({structs:[i],sql:i.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:i.name,malloy:"",connectionName:i.connection,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{},queryList:[],dependencies:{}})}else if(r){const u=await s.runSQL(r.sql,o);return new AE({...r._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.profilingUrl},r._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(i===void 0&&r===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);if(s===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");s=await e.lookupConnection(u)}if(!s.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(i)l=new Ps(i),a=i.selectStr;else if(r!==void 0)l=r.resultExplore,a=r.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of s.runSQLStream(a,o))yield new fd(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:r,sqlStruct:i}){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i.selectStr);if(r)return await o.estimateQueryCost(r.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}};we.Malloy=n0;class rxe extends Error{constructor(e,r=[]){super(e),this.problems=r}}we.MalloyError=rxe;class O2{constructor(e,r,i,s=()=>{},o=()=>{}){this.modelDef=e,this.problems=r,this.fromSources=i,this._referenceAt=s,this._importAt=o}tagParse(e){return(0,$n.annotationToTag)(this.modelDef.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this.modelDef.annotation,e)}getReference(e){return this._referenceAt(e)}getImport(e){return this._importAt(e)}getPreparedQueryByName(e){const r=this.modelDef.contents[e];if((r==null?void 0:r.type)==="query")return new F2(r,this.modelDef,this.problems,e);throw new Error("Given query name does not refer to a named query.")}getPreparedQueryByIndex(e){if(e<0)throw new Error(`Invalid index ${e}.`);if(e>=this.modelDef.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new F2(this.modelDef.queryList[e],this.modelDef,this.problems)}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.modelDef.queryList.length===0)throw new Error("Model has no queries.");return new F2(this.modelDef.queryList[this.modelDef.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const r=this.modelDef.contents[e];if((0,li.isSourceDef)(r))return new Ps(r);throw new Error("'name' is not an explore")}get explores(){return Object.values(this.modelDef.contents).filter(li.isSourceDef).map(e=>new Ps(e))}get namedQueries(){const e=r=>r.type==="query";return Object.values(this.modelDef.contents).filter(e)}get exportedExplores(){return this.explores.filter(e=>this.modelDef.exports.includes(e.name))}get _modelDef(){return this.modelDef}}we.Model=O2;class F2{constructor(e,r,i,s){this.problems=i,this.name=s,this._query=e,this._modelDef=r}tagParse(e){const r=(0,$n.annotationToTag)(this._modelDef.annotation).tag;return e=(0,$n.addModelScope)(e,r),(0,$n.annotationToTag)(this._query.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const i=new li.QueryModel(this._modelDef,e==null?void 0:e.eventStream).compileQuery(this._query,e);return new yE({...i,queryName:this.name||i.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,r=typeof e=="string"?this._modelDef.contents[e]:e;if(!(0,li.isSourceDef)(r))throw new Error("Invalid source for query");return r.dialect}getFlattenedQuery(e){return this}}we.PreparedQuery=F2;class ixe{constructor(e,r){this.translator=e,this.invalidationKey=r}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new SR(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(i=>new sxe(i))}get _translator(){return this.translator}get _invalidationKey(){return this.invalidationKey}completions(e){return(this.translator.completions(e).completions||[]).map(r=>new oxe(r))}helpContext(e){return this.translator.helpContext(e).helpContext}}we.Parse=ixe;class sxe{constructor(e){this._range=w2.fromJSON(e.range),this._connectionId=e.connectionId,this._tablePath=e.tablePath}get range(){return this._range}get connectionId(){return this._connectionId}get tablePath(){return this._tablePath}}we.DocumentTablePath=sxe;class w2{constructor(e,r){this._start=e,this._end=r}get start(){return this._start}get end(){return this._end}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}static fromJSON(e){return new w2(new QM(e.start.line,e.start.character),new QM(e.end.line,e.end.character))}}we.DocumentRange=w2;class QM{constructor(e,r){this._line=e,this._character=r}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}we.DocumentPosition=QM;class SR{constructor(e){this._range=w2.fromJSON(e.range),this._lensRange=e.lensRange?w2.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(r=>new SR(r))}get range(){return this._range}get lensRange(){var e;return(e=this._lensRange)!==null&&e!==void 0?e:this._range}get type(){return this._type}get name(){return this._name}get children(){return this._children}}we.DocumentSymbol=SR;class oxe{constructor(e){this.type=e.type,this.text=e.text}}we.DocumentCompletion=oxe;class yE{constructor(e,r){this.modelDef=r,this.inner=e}static fromJson({query:e,modelDef:r}){if(!e||!r)throw new Error("Missing required properties in JSON data");return new yE(e,r)}tagParse(e){const r=(0,$n.annotationToTag)(this.modelDef.annotation).tag;return e=(0,$n.addModelScope)(e,r),(0,$n.annotationToTag)(this.inner.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return(0,$n.annotationToTag)(this.modelDef.annotation).tag}get connectionName(){return this.inner.connectionName}get _rawQuery(){return this.inner}get _modelDef(){return this.modelDef}get sql(){return this.inner.sql}get dependenciesToMaterialize(){return this.inner.dependenciesToMaterialize}get materialization(){return this.inner.materialization}get resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],r={...e,annotation:this.inner.annotation,name:this.inner.queryName||e.name};try{return new Ps(r,this.sourceExplore)}catch{return new Ps(r)}}get sourceExplore(){const e=this.inner.sourceExplore,r=this.modelDef.contents[e];if(r&&(0,li.isSourceDef)(r))return new Ps(r)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}we.PreparedResult=yE;class uxe{async readURL(e){throw new Error("No files.")}async getInvalidationKey(e){throw new Error("No files.")}}we.EmptyURLReader=uxe;class xxt{constructor(e){this.files=e}async readURL(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve({contents:r,invalidationKey:this.invalidationKey(e,r)});throw new Error(`File not found '${e}'`)}async getInvalidationKey(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve(this.invalidationKey(e,r));throw new Error(`File not found '${e}'`)}invalidationKey(e,r){return LR(e.toString())?null:vxe(r)}}we.InMemoryURLReader=xxt;class bR{constructor(e,r){this.connections=e,this.defaultConnectionName=r}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const r=this.connections.get(e);if(r!==void 0)return Promise.resolve(r);throw new Error(`No connection found with name ${e}.`)}listConnections(){return Array.from(this.connections.values())}async lookupConnection(e){return this.getConnection(e)}static fromArray(e){return new bR(new Map(e.map(r=>[r.name,r])))}}we.FixedConnectionMap=bR;var axe;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(axe||(we.SourceRelationship=axe={}));class zM{constructor(e,r,i){this._name=e,this._parent=r,this._source=i}get source(){return this.source}get name(){return this._name}get sourceClasses(){const e=[];return this.source&&e.push(this.source.name),e.push(this.name),e}get fieldPath(){const e=[this.name];let r=this._parent;for(;r;)e.unshift(r.name),r=r._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof Ps}isQuery(){return this instanceof XM}}class Ps extends zM{constructor(e,r,i){super(e.as||e.name,r,i),this._structDef=e,this._parentExplore=r,this.sourceExplore=i}get source(){return this.sourceExplore}isIntrinsic(){return(0,li.isAtomicFieldType)(this._structDef.type)?!("e"in this._structDef):!1}isExploreField(){return!1}tagParse(e){return(0,$n.annotationToTag)(this._structDef.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=(0,$n.annotationToTag)(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const r=this.sourceStructDef;if(!r)throw new Error(`Cannot get query by name from a struct of type ${this.structDef.type}`);const i={type:"query",structRef:r,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new F2(i,this.modelDef,[],e)}get modelDef(){if(!(0,li.isSourceDef)(this.structDef))throw new Error(`Cannot create pseudo model for struct type ${this.structDef.type}`);return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef},queryList:[],dependencies:{}}}getSingleExploreModel(){return new O2(this.modelDef,[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const r=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(i=>{const s=i.as||i.name,o=r.get(i.name);if((0,li.isJoined)(i))return[s,new ZM(i,this,o)];if(i.type==="turtle")return[s,new XM(i,this,o)];if(i.type==="string")return[s,new JM(i,this,o)];if(i.type==="number")return[s,new TR(i,this,o)];if(i.type==="date")return i.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(i.timeframe)?[s,new TR({...i,type:"number"},this,o)]:[s,new GM(i,this,o)];if(i.type==="timestamp")return[s,new WM(i,this,o)];if(i.type==="boolean")return[s,new VM(i,this,o)];if(i.type==="json")return[s,new YM(i,this,o)];if(i.type==="sql native")return[s,new KM(i,this,o)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,r,i;if(!this._allFieldsWithOrder){const s=[...((i=(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.orderBy)===null||i===void 0?void 0:i.map(u=>{if(typeof u.field=="string")return{field:this.fieldMap.get(u.field),dir:u.dir};throw new Error("Does not support mapping order by from number.")}))||[]],o=new Set(s.map(u=>u.field.name));this._allFieldsWithOrder=[...s,...this.allFields.filter(u=>!o.has(u.name)).map(u=>({field:u,dir:"asc"}))]}return this._allFieldsWithOrder}get intrinsicFields(){return[...this.fieldMap.values()].filter(e=>e.isIntrinsic())}get dimensions(){return[...this.allFieldsWithOrder].filter(e=>e.field.isAtomicField()&&e.field.sourceWasDimension())}getFieldByName(e){const r=this.fieldMap.get(e);if(r===void 0)throw new Error(`No such field ${e}.`);return r}getFieldByNameIfExists(e){return this.fieldMap.get(e)}get primaryKey(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.primaryKey}get parentExplore(){return this._parentExplore}hasParentExplore(){return this instanceof ZM}get filters(){var e;return(0,li.isSourceDef)(this.structDef)?((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]:[]}get limit(){var e,r;return(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.limit}get structDef(){return this._structDef}get queryTimezone(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.queryTimezone}get sourceStructDef(){if((0,li.isSourceDef)(this.structDef))return this.structDef}toJSON(){var e,r;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(r=this._parentExplore)===null||r===void 0?void 0:r.toJSON()}}static fromJSON(e){const r=e._parentExplore!==void 0?Ps.fromJSON(e._parentExplore):void 0,i=e.sourceExplore!==void 0?Ps.fromJSON(e.sourceExplore):void 0;return new Ps(e._structDef,r,i)}get location(){return this.structDef.location}}we.Explore=Ps;var Ba;(function(t){t.String="string",t.Number="number",t.Boolean="boolean",t.Date="date",t.Timestamp="timestamp",t.Json="json",t.NativeUnsupported="sql native",t.Error="error"})(Ba||(we.AtomicFieldType=Ba={}));class Gc extends zM{constructor(e,r,i){super(e.as||e.name,r,i),this.fieldTypeDef=e,this.parent=r}get type(){switch(this.fieldTypeDef.type){case"string":return Ba.String;case"boolean":return Ba.Boolean;case"date":return Ba.Date;case"timestamp":return Ba.Timestamp;case"number":return Ba.Number;case"json":return Ba.Json;case"sql native":return Ba.NativeUnsupported;case"error":return Ba.Error;case"record":case"array":throw new Error(`MTOY TODO IMPLEMENT Atomic ${this.fieldTypeDef.type}`);default:{const e=this.fieldTypeDef;throw new Error(`Can't make an atomic field from ${e}`)}}}tagParse(e){return e=(0,$n.addModelScope)(e,this.parent.modelTag),(0,$n.annotationToTag)(this.fieldTypeDef.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,li.fieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,li.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}get referenceId(){var e;return(e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.referenceId}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,r;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((r=this.fieldTypeDef.resultMetadata)===null||r===void 0?void 0:r.fieldKind)==="struct"}sourceWasDimension(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="dimension"}hasParentExplore(){return!0}isString(){return this instanceof JM}isNumber(){return this instanceof TR}isDate(){return this instanceof GM}isBoolean(){return this instanceof VM}isJSON(){return this instanceof YM}isTimestamp(){return this instanceof WM}isUnsupported(){return this instanceof KM}get parentExplore(){return this.parent}get expression(){const e=".",r=this.fieldTypeDef.resultMetadata;return(r==null?void 0:r.sourceExpression)||(r!=null&&r.sourceField.includes(e)?r==null?void 0:r.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}we.AtomicField=Gc;var cd;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(cd||(we.DateTimeframe=cd={}));var $a;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year",t.Second="second",t.Hour="hour",t.Minute="minute"})($a||(we.TimestampTimeframe=$a={}));class GM extends Gc{constructor(e,r,i){super(e,r,i),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return cd.Day;case"week":return cd.Week;case"month":return cd.Month;case"quarter":return cd.Quarter;case"year":return cd.Year}}}we.DateField=GM;class WM extends Gc{constructor(e,r,i){super(e,r,i),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return $a.Day;case"week":return $a.Week;case"month":return $a.Month;case"quarter":return $a.Quarter;case"year":return $a.Year;case"second":return $a.Second;case"hour":return $a.Hour;case"minute":return $a.Minute}}}we.TimestampField=WM;class TR extends Gc{constructor(e,r,i){super(e,r,i),this.fieldNumberDef=e}}we.NumberField=TR;class VM extends Gc{constructor(e,r,i){super(e,r,i),this.fieldBooleanDef=e}}we.BooleanField=VM;class YM extends Gc{constructor(e,r,i){super(e,r,i),this.fieldJSONDef=e}}we.JSONField=YM;class KM extends Gc{constructor(e,r,i){super(e,r,i),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}we.UnsupportedField=KM;class JM extends Gc{constructor(e,r,i){super(e,r,i),this.fieldStringDef=e}}we.StringField=JM;class lxe extends zM{constructor(e,r,i){super(e.as||e.name,r,i),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}we.Query=lxe;class XM extends lxe{constructor(e,r,i){super(e,r,i),this.parent=r}tagParse(e){return e=(0,$n.addModelScope)(e,this.parent.modelTag),(0,$n.annotationToTag)(this.turtleDef.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this.turtleDef.annotation,e)}isQueryField(){return!0}isExploreField(){return!1}isAtomicField(){return!1}get sourceClasses(){const e=this.turtleDef.name||this.turtleDef.as;return e?[e]:[]}hasParentExplore(){return!0}get parentExplore(){return this.parent}get expression(){return this.name}}we.QueryField=XM;var N2;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(N2||(we.JoinRelationship=N2={}));class ZM extends Ps{constructor(e,r,i){super(e,r,i),this._parentExplore=r}get joinRelationship(){if((0,li.isJoined)(this.structDef))switch(this.structDef.join){case"one":return N2.OneToOne;case"many":case"cross":return N2.ManyToOne}throw new Error("A source field must have a join relationship.")}get isRecord(){return this.joinRelationship===N2.OneToOne}get isArray(){return this.joinRelationship!==N2.OneToOne}tagParse(e){return e=(0,$n.addModelScope)(e,this._parentExplore.modelTag),(0,$n.annotationToTag)(this._structDef.annotation,e)}isQueryField(){return!1}isExploreField(){return!0}isAtomicField(){return!1}get parentExplore(){return this._parentExplore}get sourceClasses(){const e=this.structDef.name||this.structDef.as;return e?[e]:[]}}we.ExploreField=ZM;class eP{constructor({urlReader:e,connections:r,connection:i,eventStream:s,cacheManager:o}){if(this.isTestRuntime=!1,r===void 0){if(i===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");r={lookupConnection:()=>Promise.resolve(i)}}e===void 0&&(e=new uxe),this._urlReader=e,this._connections=r,this._eventStream=s,this._cacheManager=o}get cacheManager(){return this._cacheManager}get urlReader(){return this._urlReader}get connections(){return this._connections}get eventStream(){return this._eventStream}loadModel(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};this.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const o=e instanceof URL?{url:e}:{source:e};return new EE(this,async()=>n0.compile({...o,urlReader:this.urlReader,connections:this.connections,refreshSchemaCache:i,noThrowOnError:s,eventStream:this.eventStream,replaceMaterializedReferences:r==null?void 0:r.replaceMaterializedReferences,materializedTablePrefix:r==null?void 0:r.materializedTablePrefix,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,cacheManager:this.cacheManager}),r)}_loadModelFromModelDef(e,r){return new EE(this,async()=>new O2(e,[],[]),r)}loadQuery(e,r){return this.loadModel(e,r).loadFinalQuery()}loadQueryByIndex(e,r,i){return this.loadModel(e,i).loadQueryByIndex(r,i)}loadQueryByName(e,r,i){return this.loadModel(e,i).loadQueryByName(r,i)}getModel(e,r){return this.loadModel(e,r).getModel()}getQuery(e,r){return this.loadQuery(e,r).getPreparedQuery()}getQueryByIndex(e,r,i){return this.loadQueryByIndex(e,r,i).getPreparedQuery()}getQueryByName(e,r,i){return this.loadQueryByName(e,r,i).getPreparedQuery()}}we.Runtime=eP;class dxt extends eP{constructor({urlReader:e,connections:r}){super({connections:bR.fromArray(r),urlReader:e}),this.rawConnections=r}}we.ConnectionRuntime=dxt;class hxt extends eP{constructor({urlReader:e,connection:r,eventStream:i,cacheManager:s}){super({urlReader:e,eventStream:i,cacheManager:s,connection:r}),this.connection=r}get supportsNesting(){return(0,HM.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,HM.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,HM.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}we.SingleConnectionRuntime=hxt;class RR{constructor(e,r){this.runtime=e,this._materialize=r}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e,r){return new cxe(this.runtime,e,r)}makeExploreMaterializer(e,r){return new xxe(this.runtime,e,r)}makePreparedResultMaterializer(e){return new fxe(this.runtime,e)}}class EE extends RR{constructor(e,r,i){super(e,r),this.runtime=e,this.compileQueryOptions=i}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{...this.compileQueryOptions,...e})}loadQueryByIndex(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{...this.compileQueryOptions,...r})}loadQueryByName(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{...this.compileQueryOptions,...r})}loadQuery(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};return this.makeQueryMaterializer(async()=>{const o=this.runtime.urlReader,u=this.runtime.connections;this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const a=e instanceof URL?{url:e}:{source:e},l=await this.getModel();return(await n0.compile({...a,urlReader:o,connections:u,model:l,refreshSchemaCache:i,noThrowOnError:s,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})).preparedQuery})}extendModel(e,r){return this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0}),new EE(this.runtime,async()=>{const i=this.runtime.urlReader,s=this.runtime.connections,o=e instanceof URL?{url:e}:{source:e},u=await this.getModel();return await n0.compile({...o,urlReader:i,connections:s,model:u,refreshSchemaCache:r==null?void 0:r.refreshSchemaCache,noThrowOnError:r==null?void 0:r.noThrowOnError,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})},r)}async search(e,r,i=1e3,s=void 0,o){const u=await this.materialize(),a=new li.QueryModel(u._modelDef,o),l=u.getExploreByName(e).structDef;if(!(0,li.isSourceDef)(l))throw new Error("Source to be searched was unexpectedly, not a source");const c=l.connection,f=await this.runtime.connections.lookupConnection(c);return await a.searchIndex(f,e,r,i,s)}async searchValueMap(e,r=10,i){const o=(await this.materialize()).getExploreByName(e);if(!(0,li.isSourceDef)(o.structDef))throw new Error("Source to be searched was unexpectedly, not a source");let u="{index: *}";o.getFieldByNameIfExists("search_index")&&(u="search_index");const a=`
1468
1468
  run: ${e}
1469
1469
  -> ${u}
1470
1470
  -> {
@@ -1478,15 +1478,15 @@ ${S}`,b)}else{if(C.urls)for(const S of C.urls)try{if(LR(S))throw new Error("In o
1478
1478
  }
1479
1479
  limit: 1000
1480
1480
  }
1481
- `;return(await this.loadQuery(a,i).run({rowLimit:1e3}))._queryResult.result}getFinalQuery(){return this.loadFinalQuery().getPreparedQuery()}getQueryByIndex(e){return this.loadQueryByIndex(e).getPreparedQuery()}getQueryByName(e){return this.loadQueryByName(e).getPreparedQuery()}getQuery(e,r){return this.loadQuery(e,r).getPreparedQuery()}_loadQueryFromQueryDef(e,r){return this.makeQueryMaterializer(async()=>{const i=await this.materialize();return new F2(e,i._modelDef,i.problems)},{...this.compileQueryOptions,...r})}loadExploreByName(e){return this.makeExploreMaterializer(async()=>(await this.materialize()).getExploreByName(e),this.compileQueryOptions)}getExploreByName(e){return this.loadExploreByName(e).getExplore()}getModel(){return this.materialize()}}we.ModelMaterializer=EE;class cxe extends RR{constructor(e,r,i){super(e,r),this.runtime=e,this.compileQueryOptions=i}async run(e){const r=this.runtime.connections,i=await this.getPreparedResult(e),s=DR(i,e);return n0.run({connections:r,preparedResult:i,options:s})}async*runStream(e){const r=await this.getPreparedResult(e),i=this.runtime.connections,s=DR(r,e),o=n0.runStream({connections:i,preparedResult:r,options:s});for await(const u of o)yield u}loadPreparedResult(e){return this.makePreparedResultMaterializer(async()=>(await this.materialize()).getPreparedResult({eventStream:this.eventStream,...this.compileQueryOptions,...e}))}getPreparedResult(e){return this.loadPreparedResult(e).getPreparedResult()}async getSQL(e){return(await this.getPreparedResult(e)).sql}getPreparedQuery(){return this.materialize()}async estimateQueryCost(e){const r=this.runtime.connections,i=await this.getPreparedResult(e);return n0.estimateQueryCost({connections:r,preparedResult:i})}get eventStream(){return this.runtime.eventStream}}we.QueryMaterializer=cxe;function DR(t,e){return{queryAnnotation:t.annotation,modelAnnotation:t.modelAnnotation,...e}}class fxe extends RR{async run(e){const r=await this.getPreparedResult(),i=this.runtime.connections,s=DR(r,e);return n0.run({connections:i,preparedResult:r,options:s})}async*runStream(e){const r=await this.getPreparedResult(),i=this.runtime.connections,s=DR(r,e),o=n0.runStream({connections:i,preparedResult:r,options:s});for await(const u of o)yield u}getPreparedResult(){return this.materialize()}async getSQL(){return(await this.getPreparedResult()).sql}}we.PreparedResultMaterializer=fxe;class xxe extends RR{constructor(e,r,i){var s;super(e,r),this.runtime=e,this.replaceMaterializedReferences=(s=i==null?void 0:i.replaceMaterializedReferences)!==null&&s!==void 0?s:!1}loadQueryByName(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getQueryByName(e),r)}getQueryByName(e){return this.loadQueryByName(e).getPreparedQuery()}getExplore(){return this.materialize()}}we.ExploreMaterializer=xxe;class AE extends yE{constructor(e,r){super(e,r),this.inner=e}get _queryResult(){return this.inner}get data(){return new _E(this.inner.result,this.resultExplore,void 0,void 0)}get totalRows(){return this.inner.totalRows}get runStats(){return this.inner.runStats}get profilingUrl(){return this.inner.profilingUrl}toJSON(){return{queryResult:this.inner,modelDef:this._modelDef}}static fromJSON({queryResult:e,modelDef:r}){return new AE(e,r)}}we.Result=AE;class FR{constructor(e,r,i){this.parent=r,this.parentRecord=i,this._field=e}get field(){return this._field}isString(){return this instanceof dxe}get string(){if(this.isString())return this;throw new Error("Not a string.")}isBoolean(){return this instanceof pxe}get boolean(){if(this.isBoolean())return this;throw new Error("Not a boolean.")}isNumber(){return this instanceof mxe}get number(){if(this.isNumber())return this;throw new Error("Not a number.")}isTimestamp(){return this instanceof yxe}get timestamp(){if(this.isTimestamp())return this;throw new Error("Not a timestamp.")}isDate(){return this instanceof Exe}get date(){if(this.isDate())return this;throw new Error("Not a date.")}isNull(){return this instanceof Axe}isBytes(){return this instanceof hxt}get bytes(){if(this.isBytes())return this;throw new Error("Not bytes.")}isRecord(){return this instanceof fd}get record(){if(this.isRecord())return this;throw new Error("Not a record.")}isUnsupported(){return this instanceof hxe}get unsupported(){if(this.isUnsupported())return this;throw new Error("Not unsupported.")}isArray(){return this instanceof _E}get array(){if(this.isArray())return this;throw new Error("Not an array.")}isArrayOrRecord(){if(this instanceof _E||this instanceof fd)return this;throw new Error("No Array or Record")}isScalar(){return!0}}class ka extends FR{constructor(e,r,i,s){super(r,i,s),this._value=e,this._field=r}get value(){return this._value}get field(){return this._field}isScalar(){return this instanceof ka}}class dxe extends ka{constructor(e,r,i,s){super(e,r,i,s),this._field=r}get field(){return this._field}get key(){return this.value}compareTo(e){return this.value.toLocaleLowerCase().localeCompare(e.value.toLocaleLowerCase())}}class hxe extends ka{constructor(e,r,i,s){super(e,r,i,s),this._field=r}get field(){return this._field}get key(){return"<unsupported>"}compareTo(e){return 0}}class pxe extends ka{constructor(e,r,i,s){super(e,r,i,s),this._field=r}get field(){return this._field}get key(){return`${this.value}`}compareTo(e){return this.value===e.value?0:this.value?1:-1}}class dxt extends ka{constructor(e,r,i,s){super(e,r,i,s),this._field=r}get field(){return this._field}get key(){return this.value}compareTo(e){const r=this.value.toString(),i=e.toString();return r===i?0:r>i?1:-1}}class mxe extends ka{constructor(e,r,i,s){super(e,r,i,s),this._field=r}get field(){return this._field}get key(){return`${this.value}`}compareTo(e){const r=this.value-e.value;return r>0?1:r===0?0:-1}}function gxe(t){if(t instanceof Date)return t;if(t.constructor.name==="Date")return new Date(t);if(typeof t=="number")return new Date(t);if(typeof t!="string")return new Date(t.value);{let r=txe.DateTime.fromISO(t,{zone:"UTC"});return r.isValid||(r=txe.DateTime.fromSQL(t,{zone:"UTC"})),r.toJSDate()}}class yxe extends ka{constructor(e,r,i,s){super(e,r,i,s),this._field=r}get value(){return gxe(this._value)}get field(){return this._field}get key(){return`${this.value.toLocaleString()}`}compareTo(e){return this.value>e.value?1:this.value<e.value?-1:0}}class Exe extends ka{constructor(e,r,i,s){super(e,r,i,s),this._field=r}get value(){return gxe(this._value)}get field(){return this._field}get key(){return`${this.value.toLocaleString()}`}compareTo(e){return this.value>e.value?1:this.value<e.value?-1:0}}class hxt extends ka{get key(){return this.value.toString()}compareTo(e){const r=this.value.toString(),i=e.toString();return r===i?0:r>i?1:-1}}class Axe extends FR{get value(){return null}get key(){return"<null>"}}class _E extends FR{constructor(e,r,i,s){super(r,i,s),this.rowCache=new Map,this.queryData=e,this._field=r}get field(){return this._field}toObject(){return this.queryData}path(...e){return _xe(this,e)}row(e){let r=this.rowCache.get(e);return r||(r=new fd(this.queryData[e],e,this.field,this,this.parentRecord),this.rowCache.set(e,r)),r}get rowCount(){return this.queryData.length}get value(){return this.toObject()}[Symbol.iterator](){let e=0;const r=this.queryData,i=s=>this.row(s);return{next(){return e<r.length?{value:i(e++),done:!1}:{value:void 0,done:!0}}}}async*inMemoryStream(){for(let e=0;e<this.queryData.length;e++)yield this.row(e)}}we.DataArray=_E;function _xe(t,e){for(const r of e)typeof r=="number"?t=t.array.row(r):t=t.record.cell(r);return t}class fd extends FR{constructor(e,r,i,s,o){super(i,s,o),this.cellCache=new Map,this.queryDataRow=e,this._field=i,this.index=r}toObject(){return this.queryDataRow}path(...e){return _xe(this,e)}cell(e){const r=typeof e=="string"?e:e.name,i=this._field.getFieldByName(r);let s=this.cellCache.get(r);if(!s){const o=this.queryDataRow[r];o===null?s=new Axe(i,this,this):i.isAtomicField()?i.isBoolean()?s=new pxe(o,i,this,this):i.isDate()?s=new Exe(o,i,this,this):i.isJSON()?s=new dxt(o,i,this,this):i.isTimestamp()?s=new yxe(o,i,this,this):i.isNumber()?s=new mxe(o,i,this,this):i.isString()?s=new dxe(o,i,this,this):i.isUnsupported()&&(s=new hxe(o,i,this,this)):i.isExploreField()&&(Array.isArray(o)?s=new _E(o,i,this,this):s=new fd(o,void 0,i,this,this)),s&&this.cellCache.set(r,s)}if(s)return s;throw new Error(`Internal Error: could not construct data column for field '${r}'.`)}get value(){throw new Error("Not implemented;")}get field(){return this._field}[Symbol.iterator](){let e=!1;const r=()=>this;return{next(){return e?{value:void 0,done:!0}:(e=!0,{value:r(),done:!1})}}}}we.DataRecord=fd;class tP{constructor(e){this.stream=e}}we.DataWriter=tP;class pxt extends tP{async process(e){this.stream.write(`[
1481
+ `;return(await this.loadQuery(a,i).run({rowLimit:1e3}))._queryResult.result}getFinalQuery(){return this.loadFinalQuery().getPreparedQuery()}getQueryByIndex(e){return this.loadQueryByIndex(e).getPreparedQuery()}getQueryByName(e){return this.loadQueryByName(e).getPreparedQuery()}getQuery(e,r){return this.loadQuery(e,r).getPreparedQuery()}_loadQueryFromQueryDef(e,r){return this.makeQueryMaterializer(async()=>{const i=await this.materialize();return new F2(e,i._modelDef,i.problems)},{...this.compileQueryOptions,...r})}loadExploreByName(e){return this.makeExploreMaterializer(async()=>(await this.materialize()).getExploreByName(e),this.compileQueryOptions)}getExploreByName(e){return this.loadExploreByName(e).getExplore()}getModel(){return this.materialize()}}we.ModelMaterializer=EE;class cxe extends RR{constructor(e,r,i){super(e,r),this.runtime=e,this.compileQueryOptions=i}async run(e){const r=this.runtime.connections,i=await this.getPreparedResult(e),s=DR(i,e);return n0.run({connections:r,preparedResult:i,options:s})}async*runStream(e){const r=await this.getPreparedResult(e),i=this.runtime.connections,s=DR(r,e),o=n0.runStream({connections:i,preparedResult:r,options:s});for await(const u of o)yield u}loadPreparedResult(e){return this.makePreparedResultMaterializer(async()=>(await this.materialize()).getPreparedResult({eventStream:this.eventStream,...this.compileQueryOptions,...e}))}getPreparedResult(e){return this.loadPreparedResult(e).getPreparedResult()}async getSQL(e){return(await this.getPreparedResult(e)).sql}getPreparedQuery(){return this.materialize()}async estimateQueryCost(e){const r=this.runtime.connections,i=await this.getPreparedResult(e);return n0.estimateQueryCost({connections:r,preparedResult:i})}get eventStream(){return this.runtime.eventStream}}we.QueryMaterializer=cxe;function DR(t,e){return{queryAnnotation:t.annotation,modelAnnotation:t.modelAnnotation,...e}}class fxe extends RR{async run(e){const r=await this.getPreparedResult(),i=this.runtime.connections,s=DR(r,e);return n0.run({connections:i,preparedResult:r,options:s})}async*runStream(e){const r=await this.getPreparedResult(),i=this.runtime.connections,s=DR(r,e),o=n0.runStream({connections:i,preparedResult:r,options:s});for await(const u of o)yield u}getPreparedResult(){return this.materialize()}async getSQL(){return(await this.getPreparedResult()).sql}}we.PreparedResultMaterializer=fxe;class xxe extends RR{constructor(e,r,i){var s;super(e,r),this.runtime=e,this.replaceMaterializedReferences=(s=i==null?void 0:i.replaceMaterializedReferences)!==null&&s!==void 0?s:!1}loadQueryByName(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getQueryByName(e),r)}getQueryByName(e){return this.loadQueryByName(e).getPreparedQuery()}getExplore(){return this.materialize()}}we.ExploreMaterializer=xxe;class AE extends yE{constructor(e,r){super(e,r),this.inner=e}get _queryResult(){return this.inner}get data(){return new _E(this.inner.result,this.resultExplore,void 0,void 0)}get totalRows(){return this.inner.totalRows}get runStats(){return this.inner.runStats}get profilingUrl(){return this.inner.profilingUrl}toJSON(){return{queryResult:this.inner,modelDef:this._modelDef}}static fromJSON({queryResult:e,modelDef:r}){return new AE(e,r)}}we.Result=AE;class FR{constructor(e,r,i){this.parent=r,this.parentRecord=i,this._field=e}get field(){return this._field}isString(){return this instanceof dxe}get string(){if(this.isString())return this;throw new Error("Not a string.")}isBoolean(){return this instanceof pxe}get boolean(){if(this.isBoolean())return this;throw new Error("Not a boolean.")}isNumber(){return this instanceof mxe}get number(){if(this.isNumber())return this;throw new Error("Not a number.")}isTimestamp(){return this instanceof yxe}get timestamp(){if(this.isTimestamp())return this;throw new Error("Not a timestamp.")}isDate(){return this instanceof Exe}get date(){if(this.isDate())return this;throw new Error("Not a date.")}isNull(){return this instanceof Axe}isBytes(){return this instanceof mxt}get bytes(){if(this.isBytes())return this;throw new Error("Not bytes.")}isRecord(){return this instanceof fd}get record(){if(this.isRecord())return this;throw new Error("Not a record.")}isUnsupported(){return this instanceof hxe}get unsupported(){if(this.isUnsupported())return this;throw new Error("Not unsupported.")}isArray(){return this instanceof _E}get array(){if(this.isArray())return this;throw new Error("Not an array.")}isArrayOrRecord(){if(this instanceof _E||this instanceof fd)return this;throw new Error("No Array or Record")}isScalar(){return!0}}class ka extends FR{constructor(e,r,i,s){super(r,i,s),this._value=e,this._field=r}get value(){return this._value}get field(){return this._field}isScalar(){return this instanceof ka}}class dxe extends ka{constructor(e,r,i,s){super(e,r,i,s),this._field=r}get field(){return this._field}get key(){return this.value}compareTo(e){return this.value.toLocaleLowerCase().localeCompare(e.value.toLocaleLowerCase())}}class hxe extends ka{constructor(e,r,i,s){super(e,r,i,s),this._field=r}get field(){return this._field}get key(){return"<unsupported>"}compareTo(e){return 0}}class pxe extends ka{constructor(e,r,i,s){super(e,r,i,s),this._field=r}get field(){return this._field}get key(){return`${this.value}`}compareTo(e){return this.value===e.value?0:this.value?1:-1}}class pxt extends ka{constructor(e,r,i,s){super(e,r,i,s),this._field=r}get field(){return this._field}get key(){return this.value}compareTo(e){const r=this.value.toString(),i=e.toString();return r===i?0:r>i?1:-1}}class mxe extends ka{constructor(e,r,i,s){super(e,r,i,s),this._field=r}get field(){return this._field}get key(){return`${this.value}`}compareTo(e){const r=this.value-e.value;return r>0?1:r===0?0:-1}}function gxe(t){if(t instanceof Date)return t;if(t.constructor.name==="Date")return new Date(t);if(typeof t=="number")return new Date(t);if(typeof t!="string")return new Date(t.value);{let r=txe.DateTime.fromISO(t,{zone:"UTC"});return r.isValid||(r=txe.DateTime.fromSQL(t,{zone:"UTC"})),r.toJSDate()}}class yxe extends ka{constructor(e,r,i,s){super(e,r,i,s),this._field=r}get value(){return gxe(this._value)}get field(){return this._field}get key(){return`${this.value.toLocaleString()}`}compareTo(e){return this.value>e.value?1:this.value<e.value?-1:0}}class Exe extends ka{constructor(e,r,i,s){super(e,r,i,s),this._field=r}get value(){return gxe(this._value)}get field(){return this._field}get key(){return`${this.value.toLocaleString()}`}compareTo(e){return this.value>e.value?1:this.value<e.value?-1:0}}class mxt extends ka{get key(){return this.value.toString()}compareTo(e){const r=this.value.toString(),i=e.toString();return r===i?0:r>i?1:-1}}class Axe extends FR{get value(){return null}get key(){return"<null>"}}class _E extends FR{constructor(e,r,i,s){super(r,i,s),this.rowCache=new Map,this.queryData=e,this._field=r}get field(){return this._field}toObject(){return this.queryData}path(...e){return _xe(this,e)}row(e){let r=this.rowCache.get(e);return r||(r=new fd(this.queryData[e],e,this.field,this,this.parentRecord),this.rowCache.set(e,r)),r}get rowCount(){return this.queryData.length}get value(){return this.toObject()}[Symbol.iterator](){let e=0;const r=this.queryData,i=s=>this.row(s);return{next(){return e<r.length?{value:i(e++),done:!1}:{value:void 0,done:!0}}}}async*inMemoryStream(){for(let e=0;e<this.queryData.length;e++)yield this.row(e)}}we.DataArray=_E;function _xe(t,e){for(const r of e)typeof r=="number"?t=t.array.row(r):t=t.record.cell(r);return t}class fd extends FR{constructor(e,r,i,s,o){super(i,s,o),this.cellCache=new Map,this.queryDataRow=e,this._field=i,this.index=r}toObject(){return this.queryDataRow}path(...e){return _xe(this,e)}cell(e){const r=typeof e=="string"?e:e.name,i=this._field.getFieldByName(r);let s=this.cellCache.get(r);if(!s){const o=this.queryDataRow[r];o===null?s=new Axe(i,this,this):i.isAtomicField()?i.isBoolean()?s=new pxe(o,i,this,this):i.isDate()?s=new Exe(o,i,this,this):i.isJSON()?s=new pxt(o,i,this,this):i.isTimestamp()?s=new yxe(o,i,this,this):i.isNumber()?s=new mxe(o,i,this,this):i.isString()?s=new dxe(o,i,this,this):i.isUnsupported()&&(s=new hxe(o,i,this,this)):i.isExploreField()&&(Array.isArray(o)?s=new _E(o,i,this,this):s=new fd(o,void 0,i,this,this)),s&&this.cellCache.set(r,s)}if(s)return s;throw new Error(`Internal Error: could not construct data column for field '${r}'.`)}get value(){throw new Error("Not implemented;")}get field(){return this._field}[Symbol.iterator](){let e=!1;const r=()=>this;return{next(){return e?{value:void 0,done:!0}:(e=!0,{value:r(),done:!1})}}}}we.DataRecord=fd;class tP{constructor(e){this.stream=e}}we.DataWriter=tP;class gxt extends tP{async process(e){this.stream.write(`[
1482
1482
  `);for await(const r of e){r.index!==void 0&&r.index>0&&this.stream.write(`,
1483
1483
  `);const s=JSON.stringify(r.toObject(),null,2).split(`
1484
1484
  `);for(let o=0;o<s.length;o++){const u=s[o];this.stream.write(` ${u}`),o<s.length-1&&this.stream.write(`
1485
1485
  `)}}this.stream.write(`
1486
1486
  ]
1487
- `),this.stream.close()}}we.JSONWriter=pxt;class mxt extends tP{constructor(){super(...arguments),this.columnSeparator=",",this.rowSeparator=`
1488
- `,this.quoteCharacter='"',this.includeHeader=!0,this.emptyCell=""}escape(e){const r=e.includes(this.quoteCharacter),i=e.includes(this.columnSeparator),s=e.includes(this.rowSeparator),o=i||r||s;return r&&(e=e.replace(new RegExp(this.quoteCharacter,"g"),this.quoteCharacter+this.quoteCharacter)),o&&(e=this.quoteCharacter+e+this.quoteCharacter),e}stringify(e){return e===null?this.emptyCell:e instanceof Date?e.toISOString():typeof e=="boolean"||typeof e=="number"?JSON.stringify(e):`${e}`}getColWeight(e){let r=e;Array.isArray(e)&&(r=e[0]);let i=0;for(const s in r){i=i+1;const o=r[s];if(Array.isArray(o)){const u=this.getColWeight(o)-1;i=i+u}}return i}getHeaderRow(e){const r=[];let i=0;for(const s in e){r.push(this.escape(s));const o=e[s];if(i++,Array.isArray(o)){const u=this.getColWeight(o)-1;i=i+u;for(let a=0;a<u;a++)r.push(this.emptyCell)}}return{rows:[r.join(this.columnSeparator)],length:1,width:i}}mergeMatrices(e){const r=Math.max(...e.map(o=>o.length)),i=e.reduce((o,u)=>o+u.width,0),s=[];for(let o=0;o<r;o++){const u=[];for(const a of e)if(o<a.length)u.push(a.rows[o]);else{const l=Array(a.width).fill(this.emptyCell);u.push(...l)}s.push(u.join(this.columnSeparator))}return{rows:s,length:r,width:i}}getChildMatrix(e){if(Array.isArray(e)){if(e.length===0)return{rows:[""],length:1,width:1}}else return{rows:["Invalid data found, value is not an array"],length:1,width:1};const r=[],i=this.getHeaderRow(e[0]);r.push(...i.rows);const s=i.width;let o=1;for(const u of e){const a=this.getRowMatrix(u);o=o+a.length,r.push(...a.rows)}return{rows:r,length:o,width:s}}getRowMatrix(e){const r=[];for(const i in e){const s=e[i];if(Array.isArray(s)){const o=this.getChildMatrix(s);r.push(o)}else{const o={rows:[this.stringify(s)],length:1,width:1};r.push(o)}}return this.mergeMatrices(r)}async process(e){let r=!1;for await(const i of e){if(!r&&this.includeHeader){const o=this.getHeaderRow(i.toObject());this.stream.write(o.rows[0]),this.stream.write(this.rowSeparator),r=!0}const s=this.getRowMatrix(i.toObject());for(const o of s.rows)this.stream.write(o),this.stream.write(this.rowSeparator)}this.stream.close()}}we.CSVWriter=mxt;class gxt{constructor(e){this.modelCache=e,this.modelDependencies=new Map,this.modelInvalidationKeys=new Map}async getCachedModelDef(e,r){const i=this.modelDependencies.get(r);if(i===void 0)return;const s=[r,...wR(i)],o={};for(const a of s){const l=this.modelInvalidationKeys.get(a);if(l==null)return;o[a]=l}for(const a of s)if(await nP(e,new URL(a))!==o[a])return;const u=await this.modelCache.getModel(new URL(r));if(u!==void 0){for(const a of s)if(u.invalidationKeys[a]!==o[a])return;return{modelDef:u.modelDef,invalidationKeys:o}}}async setCachedModelDef(e,r){this.modelDependencies.set(e,r.modelDef.dependencies);const i={};for(const o of[e,...wR(r.modelDef.dependencies)]){if(r.invalidationKeys[o]===null)return!1;if(r.invalidationKeys[o]===void 0)throw new Error(`Missing invalidation key for dependency ${o}`);this.modelInvalidationKeys.set(o,r.invalidationKeys[o]),i[o]=r.invalidationKeys[o]}return!!await this.modelCache.setModel(new URL(e),{modelDef:r.modelDef,invalidationKeys:i})}}we.CacheManager=gxt;function wR(t){return[...Object.keys(t),...Object.values(t).map(wR).flat()]}class yxt{constructor(){this.models=new Map}async getModel(e){return Promise.resolve(this.models.get(e.toString()))}async setModel(e,r){return this.models.set(e.toString(),r),Promise.resolve(!0)}}we.InMemoryModelCache=yxt;function vxe(t){return(0,axt.v5)(t,"76c17e9d-f3ce-5f2d-bfde-98ad3d2a37f6")}async function NR(t,e){const r=await t.readURL(e),{contents:i,invalidationKey:s}=typeof r=="string"?{contents:r,invalidationKey:void 0}:r;return{contents:i,invalidationKey:LR(e.toString())?null:s??vxe(i)}}async function nP(t,e){return LR(e.toString())?null:t.getInvalidationKey!==void 0?await t.getInvalidationKey(e):(await NR(t,e)).invalidationKey}function LR(t){return t.startsWith("internal://")}var IR={};Object.defineProperty(IR,"__esModule",{value:!0}),IR.toAsyncGenerator=void 0;async function*Ext(t){let e=!1;function r(s){let o;const u=new Promise(a=>{o=a});return s(a=>{o({done:!0,isError:!0,error:a})},a=>{o({done:!1,value:a,isError:!1,next:new Promise(l=>{o=l})})},()=>{o({done:!0,isError:!1})}),u}let i=r(t);for(;!e;){const s=await i;if(s.done){if(e=!0,s.isError)throw s.error;break}else i=s.next,yield s.value}}IR.toAsyncGenerator=Ext;var Cxe={},Wc={},rP={},vE={};Object.defineProperty(vE,"__esModule",{value:!0}),vE.MALLOY_INTERFACE_TYPES=void 0,vE.MALLOY_INTERFACE_TYPES={Aggregate:{type:"struct",name:"Aggregate",fields:{name:{type:"string",optional:!0,array:!1},field:{type:"Field",optional:!1,array:!1}}},Annotation:{type:"struct",name:"Annotation",fields:{value:{type:"string",optional:!1,array:!1}}},AnonymousQueryInfo:{type:"struct",name:"AnonymousQueryInfo",fields:{schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"Query",optional:!0,array:!1},code:{type:"string",optional:!0,array:!1},location:{type:"Location",optional:!0,array:!1}}},ArrayCell:{type:"struct",name:"ArrayCell",fields:{array_value:{type:"Cell",array:!0,optional:!1}}},ArrayType:{type:"struct",name:"ArrayType",fields:{element_type:{type:"AtomicType",optional:!1,array:!1}}},AtomicType:{type:"union",name:"AtomicType",options:{string_type:"StringType",boolean_type:"BooleanType",number_type:"NumberType",json_type:"JSONType",sql_native_type:"SQLNativeType",date_type:"DateType",timestamp_type:"TimestampType",array_type:"ArrayType",record_type:"RecordType"}},BooleanCell:{type:"struct",name:"BooleanCell",fields:{boolean_value:{type:"boolean",optional:!1,array:!1}}},BooleanLiteral:{type:"struct",name:"BooleanLiteral",fields:{boolean_value:{type:"boolean",optional:!1,array:!1}}},BooleanType:{type:"struct",name:"BooleanType",fields:{}},Cell:{type:"union",name:"Cell",options:{string_cell:"StringCell",boolean_cell:"BooleanCell",date_cell:"DateCell",timestamp_cell:"TimestampCell",number_cell:"NumberCell",json_cell:"JSONCell",record_cell:"RecordCell",array_cell:"ArrayCell",null_cell:"NullCell",sql_native_cell:"SQLNativeCell"}},CompileModelRequest:{type:"struct",name:"CompileModelRequest",fields:{model_url:{type:"string",optional:!1,array:!1},extend_model_url:{type:"string",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileModelResponse:{type:"struct",name:"CompileModelResponse",fields:{model:{type:"ModelInfo",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},translations:{type:"Translation",array:!0,optional:!0}}},CompileQueryRequest:{type:"struct",name:"CompileQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},query:{type:"Query",optional:!1,array:!1},default_row_limit:{type:"number",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileQueryResponse:{type:"struct",name:"CompileQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},default_row_limit_added:{type:"number",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},translations:{type:"Translation",array:!0,optional:!0}}},CompileSourceRequest:{type:"struct",name:"CompileSourceRequest",fields:{model_url:{type:"string",optional:!1,array:!1},name:{type:"string",optional:!1,array:!1},extend_model_url:{type:"string",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileSourceResponse:{type:"struct",name:"CompileSourceResponse",fields:{source:{type:"SourceInfo",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompilerNeeds:{type:"struct",name:"CompilerNeeds",fields:{table_schemas:{type:"SQLTable",array:!0,optional:!0},sql_schemas:{type:"SQLQuery",array:!0,optional:!0},files:{type:"File",array:!0,optional:!0},connections:{type:"Connection",array:!0,optional:!0},translations:{type:"Translation",array:!0,optional:!0}}},Connection:{type:"struct",name:"Connection",fields:{name:{type:"string",optional:!1,array:!1},dialect:{type:"string",optional:!0,array:!1}}},Data:{type:"union",name:"Data",options:{record_cell:"RecordCell",array_cell:"ArrayCell"}},DateCell:{type:"struct",name:"DateCell",fields:{date_value:{type:"string",optional:!1,array:!1}}},DateLiteral:{type:"struct",name:"DateLiteral",fields:{date_value:{type:"string",optional:!1,array:!1},granularity:{type:"DateTimeframe",optional:!0,array:!1}}},DateTimeframe:{type:"enum",name:"DateTimeframe",values:{year:1,quarter:2,month:3,week:4,day:5}},DateType:{type:"struct",name:"DateType",fields:{timeframe:{type:"DateTimeframe",optional:!0,array:!1}}},DimensionInfo:{type:"struct",name:"DimensionInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},DocumentPosition:{type:"struct",name:"DocumentPosition",fields:{line:{type:"number",optional:!1,array:!1},character:{type:"number",optional:!1,array:!1}}},DocumentRange:{type:"struct",name:"DocumentRange",fields:{start:{type:"DocumentPosition",optional:!1,array:!1},end:{type:"DocumentPosition",optional:!1,array:!1}}},Expression:{type:"union",name:"Expression",options:{field_reference:"Reference",time_truncation:"TimeTruncationFieldReference",filtered_field:"FilteredField"}},Field:{type:"struct",name:"Field",fields:{expression:{type:"Expression",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},FieldInfo:{type:"union",name:"FieldInfo",options:{dimension:"DimensionInfo",measure:"MeasureInfo",join:"JoinInfo",view:"ViewInfo"}},File:{type:"struct",name:"File",fields:{url:{type:"string",optional:!1,array:!1},contents:{type:"string",optional:!0,array:!1},invalidation_key:{type:"string",optional:!0,array:!1}}},Filter:{type:"union",name:"Filter",options:{filter_string:"FilterStringApplication"}},FilterExpressionLiteral:{type:"struct",name:"FilterExpressionLiteral",fields:{filter_expression_value:{type:"string",optional:!1,array:!1}}},FilterExpressionType:{type:"struct",name:"FilterExpressionType",fields:{}},FilterOperation:{type:"struct",name:"FilterOperation",fields:{filter:{type:"Filter",optional:!1,array:!1}}},FilterStringApplication:{type:"struct",name:"FilterStringApplication",fields:{field_reference:{type:"Reference",optional:!1,array:!1},filter:{type:"string",optional:!1,array:!1}}},FilteredField:{type:"struct",name:"FilteredField",fields:{field_reference:{type:"Reference",optional:!1,array:!1},where:{type:"FilterOperation",array:!0,optional:!1}}},GroupBy:{type:"struct",name:"GroupBy",fields:{name:{type:"string",optional:!0,array:!1},field:{type:"Field",optional:!1,array:!1}}},JSONCell:{type:"struct",name:"JSONCell",fields:{json_value:{type:"string",optional:!1,array:!1}}},JSONType:{type:"struct",name:"JSONType",fields:{}},JoinInfo:{type:"struct",name:"JoinInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},relationship:{type:"Relationship",optional:!1,array:!1}}},Limit:{type:"struct",name:"Limit",fields:{limit:{type:"number",optional:!1,array:!1}}},LiteralValue:{type:"union",name:"LiteralValue",options:{string_literal:"StringLiteral",number_literal:"NumberLiteral",date_literal:"DateLiteral",timestamp_literal:"TimestampLiteral",boolean_literal:"BooleanLiteral",null_literal:"NullLiteral",filter_expression_literal:"FilterExpressionLiteral"}},Location:{type:"struct",name:"Location",fields:{url:{type:"string",optional:!1,array:!1},range:{type:"Range",optional:!1,array:!1}}},LogMessage:{type:"struct",name:"LogMessage",fields:{url:{type:"string",optional:!1,array:!1},range:{type:"DocumentRange",optional:!1,array:!1},severity:{type:"LogSeverity",optional:!1,array:!1},message:{type:"string",optional:!1,array:!1}}},LogSeverity:{type:"enum",name:"LogSeverity",values:{debug:1,info:2,warn:3,error:4}},MeasureInfo:{type:"struct",name:"MeasureInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},ModelEntryValue:{type:"union",name:"ModelEntryValue",options:{source:"SourceInfo",query:"QueryInfo"}},ModelInfo:{type:"struct",name:"ModelInfo",fields:{entries:{type:"ModelEntryValue",array:!0,optional:!1},annotations:{type:"Annotation",array:!0,optional:!0},anonymous_queries:{type:"AnonymousQueryInfo",array:!0,optional:!1}}},Nest:{type:"struct",name:"Nest",fields:{name:{type:"string",optional:!0,array:!1},view:{type:"View",optional:!1,array:!1}}},NullCell:{type:"struct",name:"NullCell",fields:{}},NullLiteral:{type:"struct",name:"NullLiteral",fields:{}},NumberCell:{type:"struct",name:"NumberCell",fields:{number_value:{type:"number",optional:!1,array:!1}}},NumberLiteral:{type:"struct",name:"NumberLiteral",fields:{number_value:{type:"number",optional:!1,array:!1}}},NumberSubtype:{type:"enum",name:"NumberSubtype",values:{integer:1,decimal:2}},NumberType:{type:"struct",name:"NumberType",fields:{subtype:{type:"NumberSubtype",optional:!0,array:!1}}},OrderBy:{type:"struct",name:"OrderBy",fields:{field_reference:{type:"Reference",optional:!1,array:!1},direction:{type:"OrderByDirection",optional:!0,array:!1}}},OrderByDirection:{type:"enum",name:"OrderByDirection",values:{asc:1,desc:2}},ParameterInfo:{type:"struct",name:"ParameterInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"ParameterType",optional:!1,array:!1},default_value:{type:"LiteralValue",optional:!0,array:!1}}},ParameterType:{type:"union",name:"ParameterType",options:{string_type:"StringType",boolean_type:"BooleanType",number_type:"NumberType",json_type:"JSONType",sql_native_type:"SQLNativeType",date_type:"DateType",timestamp_type:"TimestampType",array_type:"ArrayType",record_type:"RecordType",filter_expression_type:"FilterExpressionType"}},ParameterValue:{type:"struct",name:"ParameterValue",fields:{name:{type:"string",optional:!1,array:!1},value:{type:"LiteralValue",optional:!1,array:!1}}},Position:{type:"struct",name:"Position",fields:{line:{type:"number",optional:!1,array:!1},character:{type:"number",optional:!1,array:!1}}},Query:{type:"struct",name:"Query",fields:{definition:{type:"QueryDefinition",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},QueryArrow:{type:"struct",name:"QueryArrow",fields:{source:{type:"QueryArrowSource",optional:!1,array:!1},view:{type:"ViewDefinition",optional:!1,array:!1}}},QueryArrowSource:{type:"union",name:"QueryArrowSource",options:{refinement:"QueryRefinement",source_reference:"Reference"}},QueryDefinition:{type:"union",name:"QueryDefinition",options:{arrow:"QueryArrow",query_reference:"Reference",refinement:"QueryRefinement"}},QueryInfo:{type:"struct",name:"QueryInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"Query",optional:!0,array:!1},code:{type:"string",optional:!0,array:!1},location:{type:"Location",optional:!0,array:!1}}},QueryRefinement:{type:"struct",name:"QueryRefinement",fields:{base:{type:"QueryDefinition",optional:!1,array:!1},refinement:{type:"ViewDefinition",optional:!1,array:!1}}},Range:{type:"struct",name:"Range",fields:{start:{type:"Position",optional:!1,array:!1},end:{type:"Position",optional:!1,array:!1}}},RecordCell:{type:"struct",name:"RecordCell",fields:{record_value:{type:"Cell",array:!0,optional:!1}}},RecordType:{type:"struct",name:"RecordType",fields:{fields:{type:"DimensionInfo",array:!0,optional:!1}}},Reference:{type:"struct",name:"Reference",fields:{name:{type:"string",optional:!1,array:!1},path:{type:"string",array:!0,optional:!0},parameters:{type:"ParameterValue",array:!0,optional:!0}}},Relationship:{type:"enum",name:"Relationship",values:{one:1,many:2,cross:3}},Result:{type:"struct",name:"Result",fields:{data:{type:"Data",optional:!0,array:!1},schema:{type:"Schema",optional:!1,array:!1},sql:{type:"string",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},model_annotations:{type:"Annotation",array:!0,optional:!0},query_timezone:{type:"string",optional:!0,array:!1}}},RunIndexQueryRequest:{type:"struct",name:"RunIndexQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},source_name:{type:"string",optional:!1,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunIndexQueryResponse:{type:"struct",name:"RunIndexQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunQueryRequest:{type:"struct",name:"RunQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},query:{type:"Query",optional:!1,array:!1},default_row_limit:{type:"number",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunQueryResponse:{type:"struct",name:"RunQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},default_row_limit_added:{type:"number",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},SQLNativeCell:{type:"struct",name:"SQLNativeCell",fields:{sql_native_value:{type:"string",optional:!1,array:!1}}},SQLNativeType:{type:"struct",name:"SQLNativeType",fields:{sql_type:{type:"string",optional:!0,array:!1}}},SQLQuery:{type:"struct",name:"SQLQuery",fields:{sql:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1}}},SQLTable:{type:"struct",name:"SQLTable",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1}}},Schema:{type:"struct",name:"Schema",fields:{fields:{type:"FieldInfo",array:!0,optional:!1}}},SourceInfo:{type:"struct",name:"SourceInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},parameters:{type:"ParameterInfo",array:!0,optional:!0}}},StringCell:{type:"struct",name:"StringCell",fields:{string_value:{type:"string",optional:!1,array:!1}}},StringLiteral:{type:"struct",name:"StringLiteral",fields:{string_value:{type:"string",optional:!1,array:!1}}},StringType:{type:"struct",name:"StringType",fields:{}},TimeTruncationFieldReference:{type:"struct",name:"TimeTruncationFieldReference",fields:{field_reference:{type:"Reference",optional:!1,array:!1},truncation:{type:"TimestampTimeframe",optional:!1,array:!1}}},TimestampCell:{type:"struct",name:"TimestampCell",fields:{timestamp_value:{type:"string",optional:!1,array:!1}}},TimestampLiteral:{type:"struct",name:"TimestampLiteral",fields:{timestamp_value:{type:"string",optional:!1,array:!1},granularity:{type:"TimestampTimeframe",optional:!0,array:!1}}},TimestampTimeframe:{type:"enum",name:"TimestampTimeframe",values:{year:1,quarter:2,month:3,week:4,day:5,hour:6,minute:7,second:8}},TimestampType:{type:"struct",name:"TimestampType",fields:{timeframe:{type:"TimestampTimeframe",optional:!0,array:!1}}},Translation:{type:"struct",name:"Translation",fields:{url:{type:"string",optional:!1,array:!1},compiled_model_json:{type:"string",optional:!0,array:!1}}},View:{type:"struct",name:"View",fields:{definition:{type:"ViewDefinition",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},ViewArrow:{type:"struct",name:"ViewArrow",fields:{source:{type:"ViewDefinition",optional:!1,array:!1},view:{type:"ViewDefinition",optional:!1,array:!1}}},ViewDefinition:{type:"union",name:"ViewDefinition",options:{arrow:"ViewArrow",view_reference:"Reference",refinement:"ViewRefinement",segment:"ViewSegment"}},ViewInfo:{type:"struct",name:"ViewInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"View",optional:!0,array:!1}}},ViewOperation:{type:"union",name:"ViewOperation",options:{group_by:"GroupBy",aggregate:"Aggregate",order_by:"OrderBy",limit:"Limit",where:"FilterOperation",nest:"Nest",having:"FilterOperation"}},ViewRefinement:{type:"struct",name:"ViewRefinement",fields:{base:{type:"ViewDefinition",optional:!1,array:!1},refinement:{type:"ViewDefinition",optional:!1,array:!1}}},ViewSegment:{type:"struct",name:"ViewSegment",fields:{operations:{type:"ViewOperation",array:!0,optional:!1}}}};var BR={},$R={},kR={};Object.defineProperty(kR,"__esModule",{value:!0}),kR.RESERVED_WORDS=void 0,kR.RESERVED_WORDS=["accept","aggregate","declare","dimension","except","explore","group_by","having","index","join_cross","join_one","join_many","limit","measure","nest","order_by","primary_key","project","query","rename","sample","source","sql","turduck","top","where","all","as","asc","avg","boolean","by","case","cast","condition","count","date","day","days","desc","distinct","else","end","exclude","false","for","from","from_sql","has","hour","hours","import","is","json","last","max","min","minute","minutes","month","months","not","now","null","number","on","or","pick","quarter","quarters","second","seconds","string","sum","table","then","this","timestamp","to","true","turtle","week","weeks","when","with","year","years","ungrouped"],Object.defineProperty($R,"__esModule",{value:!0}),$R.maybeQuoteIdentifier=void 0;const Axt=kR;function _xt(t){const e=!t.match(/^[A-Za-z_][A-Za-z_0-9]*$/),r=Axt.RESERVED_WORDS.includes(t.toLowerCase());return e||r}function vxt(t){const e=t.split(".");for(let r=0;r<e.length;r++)_xt(e[r])&&(e[r]=`\`${e[r]}\``);return e.join(".")}$R.maybeQuoteIdentifier=vxt,Object.defineProperty(BR,"__esModule",{value:!0}),BR.queryToMalloy=void 0;const CE=$R;function Cxt(t,{tabWidth:e}={tabWidth:2}){const r=Dxt(t);return bxt(r,{tabWidth:e})}BR.queryToMalloy=Cxt;const iP=Symbol("indent"),yu=Symbol("newline"),sP=Symbol("outdent"),Sxt=Symbol("optional_newline_indent");function bxt(t,{tabWidth:e}={tabWidth:2}){let r="",i=0,s=!0;for(const o of t)if(o===yu)r+=`
1489
- `,s=!0;else if(o===sP)i--;else if(o===iP)i++;else{if(o===Sxt)continue;s&&(r+=" ".repeat(i*e),s=!1),r+=o}return r}function MR(t,e,r,i){var s;if(e.includes(yu))return[t,yu,iP,...e,yu,sP,r];const u=((s=i==null?void 0:i.spaces)!==null&&s!==void 0?s:!0)?" ":"";return[t,u,...e,u,r]}function Txt(t){return{contents:t,quoteCharacter:'"'}}function Rxt(t){var e,r;switch(t.kind){case"filter_expression_literal":return[Dxe(t.filter_expression_value)];case"boolean_literal":return[t.boolean_value.toString()];case"string_literal":{const{contents:i,quoteCharacter:s}=Txt(t.string_value);return[s,i,s]}case"number_literal":return[t.number_value.toString()];case"null_literal":return["null"];case"date_literal":return[bxe(Sxe(t.date_value),(e=t.granularity)!==null&&e!==void 0?e:"day")];case"timestamp_literal":return[bxe(Sxe(t.timestamp_value),(r=t.granularity)!==null&&r!==void 0?r:"second")]}}function Sxe(t){return new Date(t)}function yn(t,e){return t.toString().padStart(e,"0")}function bxe(t,e){switch(e){case"year":return`@${yn(t.getUTCFullYear(),4)}`;case"quarter":{const r=yn(t.getUTCFullYear(),4),i=Math.floor(t.getUTCMonth()/3)+1;return`@${r}-Q${i}`}case"month":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2);return`@${r}-${i}`}case"week":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2);return`@WK${r}-${i}-${s}`}case"day":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2);return`@${r}-${i}-${s}`}case"hour":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2),o=yn(t.getUTCHours(),2);return`@${r}-${i}-${s} ${o}`}case"minute":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2),o=yn(t.getUTCHours(),2),u=yn(t.getUTCMinutes(),2);return`@${r}-${i}-${s} ${o}:${u}`}case"second":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2),o=yn(t.getUTCHours(),2),u=yn(t.getUTCMinutes(),2),a=yn(t.getUTCSeconds(),2);return`@${r}-${i}-${s} ${o}:${u}:${a}`}default:throw new Error("Unknown timeframe.")}}function Vc(t){var e;const r=[];for(const i of(e=t.path)!==null&&e!==void 0?e:[])r.push((0,CE.maybeQuoteIdentifier)(i)),r.push(".");if(r.push((0,CE.maybeQuoteIdentifier)(t.name)),t.parameters){const i=[];for(let s=0;s<t.parameters.length;s++){const o=t.parameters[s];i.push((0,CE.maybeQuoteIdentifier)(o.name)),i.push(" is "),i.push(...Rxt(o.value)),s<t.parameters.length-1&&i.push(",",yu)}r.push(...MR("(",i,")",{spaces:!1}))}return r}function Dxt(t){const e=[];return e.push(...I2(t.annotations)),e.push("run: "),e.push(...oP(t.definition)),e}function Oxt(t){const e=[];switch(t.kind){case"source_reference":{e.push(...Vc(t));break}case"refinement":e.push(...oP(t));break}return e}function oP(t){const e=[];switch(t.kind){case"arrow":{e.push(...Oxt(t.source)),e.push(" -> "),e.push(...xd(t.view));break}case"query_reference":{e.push(...Vc(t));break}case"refinement":{const r=oP(t.base);t.base.kind==="arrow"?e.push(...MR("(",r,")",{spaces:!1})):e.push(...r),e.push(" + "),e.push(...xd(t.refinement));break}}return e}function xd(t){const e=[];switch(t.kind){case"arrow":{e.push(...xd(t.source)),e.push(" -> "),e.push(...xd(t.view));break}case"view_reference":{e.push(...Vc(t));break}case"refinement":{e.push(...xd(t.base)),e.push(" + "),e.push(...xd(t.refinement));break}case"segment":{e.push(...Fxt(t));break}}return e}function Fxt(t){if(t.operations.length===0)return["{ }"];const e=t.operations.length>1,r=[];for(let i=0;i<t.operations.length;i++){const s=t.operations[i],o=[s];for(;i<t.operations.length-1;){const u=t.operations[i+1];if(u.kind===s.kind)o.push(u),i++;else break}r.push(...wxt(o)),e&&i<t.operations.length-1&&r.push(yu)}return MR("{",r,"}")}function wxt(t){switch(t[0].kind){case"aggregate":return Bxt(t);case"group_by":return Ixt(t);case"order_by":return $xt(t);case"nest":return Mxt(t);case"limit":return qxt(t);case"where":return Rxe(t);case"having":return Hxt(t)}}function L2(t,e,r=""){const i=[];i.push(`${t}:`);const s=e.length>1||e.some(o=>o.includes(yu));s?i.push(yu,iP):i.push(" ");for(let o=0;o<e.length;o++){const u=e[o];i.push(...u),e.length>1&&o<e.length-1&&i.push(r),s&&o<e.length-1&&i.push(yu)}return s&&i.push(sP),i}function Nxt(t){const e=[];return e.push(...Lxt(t.expression)),e}function mht(t){return t}function Lxt(t){switch(t.kind){case"field_reference":return Vc(t);case"time_truncation":return[...Vc(t.field_reference),".",t.truncation];case"filtered_field":return[...Vc(t.field_reference),...MR(" {",Rxe(t.where),"}")]}}function Txe(t,e=!1){const r=[];return e||r.push(...I2(t.field.annotations)),t.name&&(r.push((0,CE.maybeQuoteIdentifier)(t.name)),r.push(" is ")),r.push(...Nxt(t.field)),r}function Ixt(t){const e=[],r=t.length===1;return r&&e.push(...I2(t[0].field.annotations)),e.push(...L2("group_by",t.map(i=>Txe(i,r)))),e}function Bxt(t){const e=[],r=t.length===1;return r&&e.push(...I2(t[0].field.annotations)),e.push(...L2("aggregate",t.map(i=>Txe(i,r)))),e}function $xt(t){return L2("order_by",t.map(kxt),",")}function kxt(t){const e=[];return e.push(...Vc(t.field_reference)),t.direction&&(e.push(" "),e.push(t.direction)),e}function Mxt(t){const e=[],r=t.length===1;return r&&e.push(...I2(t[0].view.annotations)),e.push(...L2("nest",t.map(i=>Pxt(i,r)))),e}function Pxt(t,e=!1){const r=[];return e||r.push(...I2(t.view.annotations)),t.name&&(r.push((0,CE.maybeQuoteIdentifier)(t.name)),r.push(" is ")),r.push(...Uxt(t.view)),r}function Uxt(t){return xd(t.definition)}function jxt(t){return[`limit: ${t.limit}`]}function qxt(t){const e=[];for(let r=0;r<t.length;r++)r!==0&&e.push(yu),e.push(...jxt(t[r]));return e}function Rxe(t){return L2("where",t.map(Oxe),",")}function Hxt(t){return L2("having",t.map(Oxe),",")}const Qxt=["`","'",'"'];function Dxe(t){let e,r;for(const i of Qxt){const s=zxt(t,i);if(s===t)return`f${i}${t}${i}`;(r===void 0||s.length<r.length)&&(e=i,r=s)}return`f${e}${r}${e}`}function zxt(t,e){let r="";for(let i=0;i<t.length;i++)t.slice(i).startsWith(e)?(r+="\\"+e,i+=e.length):(r+=t[i],t[i]==="\\"&&(r+=t[++i]));return r}function Oxe(t){switch(t.filter.kind){case"filter_string":return[...Vc(t.filter.field_reference)," ~ ",Dxe(t.filter.filter)]}}function I2(t){return t?t.flatMap(Gxt):[]}function Gxt(t){return[t.value.trim(),yu]}var Ma={};Object.defineProperty(Ma,"__esModule",{value:!0}),Ma.convertToThrift=Ma.convertFromThrift=Ma.unnestUnions=Ma.nestUnions=void 0;const Wxt=vE;function uP(t){if(t==null)return t;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(uP);{const e={};let r;for(const i in t)i==="kind"?r=t[i]:e[i]=uP(t[i]);return r===void 0?e:{[r]:e}}}Ma.nestUnions=uP;function PR(t,e){if(t==null)return t;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(r=>PR(r,e));{const r=B2(e);if(r.type==="union"){for(const i in r.options)if(t[i]!==void 0){const s=PR(t[i],r.options[i]);if(typeof s=="object")return{kind:i,...s}}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=PR(t[s],o.type)}return i}else throw new Error(`Cannot unnest unions in an enum type ${e}`)}}Ma.unnestUnions=PR;function UR(t,e){if(t==null)return t;if(typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number"){if(e==="number")return t;const r=B2(e);if(r.type!=="enum")throw new Error(`Found a number where a ${e} was expected`);const i=Object.entries(r.values).find(([,s])=>s===t);if(i===void 0)throw new Error(`${t} is not a valid enum value for ${e}`);return i[0]}else{if(Array.isArray(t))return t.map(r=>UR(r,e));{const r=B2(e);if(r.type==="union"){for(const i in r.options)if(t[i]!==void 0){const s=UR(t[i],r.options[i]);if(typeof s=="object")return{kind:i,...s}}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=UR(t[s],o.type)}return i}else throw new Error(`Cannot unnest unions in an enum type ${e}`)}}}Ma.convertFromThrift=UR;function B2(t){const e=Wxt.MALLOY_INTERFACE_TYPES[t];if(e===void 0)throw new Error(`Unknown Malloy interface type ${t}`);return e}function jR(t,e){if(t==null)return t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string"){if(e==="string")return t;const r=B2(e);if(r.type==="enum"){const i=r.values[t];if(i===void 0)throw new Error(`${t} is not a valid enum value for ${e}`);return i}}else{if(Array.isArray(t))return t.map(r=>jR(r,e));{const r=B2(e);if(r.type==="union"){const i=t.kind,s=r.options[i];if(s===void 0)throw new Error(`${i} is not a valid union of ${e}`);const o=B2(s);if(o.type!=="struct")throw new Error("Union fields must be structs");const u={};for(const a in t){if(a==="kind")continue;const l=o.fields[a];u[a]=jR(t[a],l.type)}return{[i]:u}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=jR(t[s],o.type)}return i}}}}Ma.convertToThrift=jR,function(t){var e=T&&T.__createBinding||(Object.create?function(o,u,a,l){l===void 0&&(l=a);var c=Object.getOwnPropertyDescriptor(u,a);(!c||("get"in c?!u.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return u[a]}}),Object.defineProperty(o,l,c)}:function(o,u,a,l){l===void 0&&(l=a),o[l]=u[a]}),r=T&&T.__exportStar||function(o,u){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(u,a)&&e(u,o,a)};Object.defineProperty(t,"__esModule",{value:!0}),t.thingy4sddfdfsd=t.thingy4sdfsd=t.thingy4dfdsfs=t.thingy4asdfas=t.thingy4asdfasdf=t.thingy3dfdf=t.thingy3=t.thingy2asdf=t.thingyssdfg=t.thingy123r=t.thingy1=t.res=t.test=t.convertToThrift=t.convertFromThrift=t.unnestUnions=t.nestUnions=t.queryToMalloy=void 0,r(vE,t);var i=BR;Object.defineProperty(t,"queryToMalloy",{enumerable:!0,get:function(){return i.queryToMalloy}});var s=Ma;Object.defineProperty(t,"nestUnions",{enumerable:!0,get:function(){return s.nestUnions}}),Object.defineProperty(t,"unnestUnions",{enumerable:!0,get:function(){return s.unnestUnions}}),Object.defineProperty(t,"convertFromThrift",{enumerable:!0,get:function(){return s.convertFromThrift}}),Object.defineProperty(t,"convertToThrift",{enumerable:!0,get:function(){return s.convertToThrift}}),t.test={entries:[{kind:"source",name:"flights",schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"boolean_type"},annotations:[{value:"# foo=1"}]},{kind:"dimension",name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}},{kind:"dimension",name:"arr_rec",type:{kind:"array_type",element_type:{kind:"record_type",fields:[{name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}}]}}},{kind:"dimension",name:"rec",type:{kind:"record_type",fields:[{name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}}]}},{kind:"join",name:"carriers",relationship:"one",schema:{fields:[{kind:"dimension",name:"code",type:{kind:"string_type"}}]}},{kind:"view",name:"by_carrier",schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"string_type"}},{kind:"dimension",name:"flight_count",type:{kind:"number_type"}}]}}]},parameters:[{name:"param",type:{kind:"number_type"},default_value:{kind:"number_literal",number_value:7}}]}],anonymous_queries:[]},t.res={connection_name:"foo",data:{kind:"array_cell",array_value:[{kind:"record_cell",record_value:[{kind:"string_cell",string_value:"UA"},{kind:"number_cell",number_value:12341234}]},{kind:"record_cell",record_value:[{kind:"string_cell",string_value:"AA"},{kind:"number_cell",number_value:2343}]}]},schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"string_type"}},{kind:"dimension",name:"flight_count",type:{kind:"number_type"}}]},sql:"SELECT * ..."},t.thingy1={definition:{kind:"query_reference",name:"flights_by_carrier"}},t.thingy123r={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"view_reference",name:"by_carrier"}}},t.thingyssdfg={definition:{kind:"refinement",base:{kind:"query_reference",name:"flights"},refinement:{kind:"view_reference",name:"by_carrier"}}},t.thingy2asdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"where",filter:{kind:"filter_string",field_reference:{name:"carrier"},filter:"WN"}}]}}}},t.thingy3={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"group_by",field:{expression:{kind:"field_reference",name:"foo"}}}]}}}},t.thingy3dfdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"view_reference",name:"top10"}}}},t.thingy4asdfasdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"group_by",field:{expression:{kind:"field_reference",name:"foo"}}}]}}},t.thingy4asdfas={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"view_reference",name:"by_carrier"}}},t.thingy4dfdsfs={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"limit",limit:10}]}}}},t.thingy4sdfsd={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"limit",limit:10}]}}},t.thingy4sddfdfsd={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[]}}}}(rP);var nn={},Vxt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Yxt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Kxt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Vxt(e,t,r);return Yxt(e,t),e};Object.defineProperty(nn,"__esModule",{value:!0}),nn.statedCompileQuery=nn.newCompileQueryState=nn.hasErrors=nn.compileSource=nn.compileModel=nn._statedCompileModel=nn.statedCompileSource=nn.statedCompileModel=nn.newCompileSourceState=nn.newCompileModelState=nn.updateCompileModelState=nn.compileQuery=void 0;const Jxt=Kxt(rP),Xxt=H4,Fxe=Pi,Zxt=La,wxe=Yl,edt=ui,Nxe=Zo,dd=mE;function Lxe(t,e){return`${t}:${e}`}function tdt(t,e){return{type:"sql_select",selectStr:t.sql,connection:t.connection_name,dialect:e,fields:t.schema?Bxe(t.schema):[],name:(0,wxe.sqlKey)(t.connection_name,t.sql)}}function ndt(t,e){return{type:"table",tablePath:t.name,connection:t.connection_name,dialect:e,fields:t.schema?Bxe(t.schema):[],name:Lxe(t.connection_name,t.name)}}function rdt(t){if(t!==void 0)return t==="decimal"?"float":"integer"}function Ixe(t){switch(t.kind){case"string_type":return{type:"string"};case"number_type":return{type:"number",numberType:rdt(t.subtype)};case"boolean_type":return{type:"boolean"};case"timestamp_type":return{type:"timestamp",timeframe:t.timeframe};case"date_type":return{type:"date",timeframe:t.timeframe};case"sql_native_type":return{type:"sql native",rawType:t.sql_type};case"json_type":return{type:"json"};case"array_type":{if(t.element_type.kind==="record_type")return{type:"array",elementTypeDef:{type:"record_element"},fields:t.element_type.fields.map(aP)};{const e=Ixe(t.element_type);if(e.type==="record")throw new Error("Arrays of records should be a repeated record type");return{type:"array",elementTypeDef:e}}}case"record_type":return{type:"record",fields:t.fields.map(aP)}}}function aP(t){var e;const r=Ixe(t.type);return{...(0,Fxe.mkFieldDef)(r,t.name),annotation:t.annotations&&t.annotations.length?{notes:(e=t.annotations)===null||e===void 0?void 0:e.map(i=>({text:i.value,at:{url:"~internal~",range:dd.DEFAULT_LOG_RANGE}}))}:void 0}}function idt(t){if(t.kind!=="dimension")throw new Error("Table schemas must only have dimension fields");return aP(t)}function Bxe(t){const e=[];for(const r of t.fields)e.push(idt(r));return e}function $xe(t){var e,r,i,s,o,u;const a={urls:{},tables:{},compileSQL:{},translations:{}};if(t){for(const l of(e=t.files)!==null&&e!==void 0?e:[])l.contents!==void 0&&(a.urls[l.url]=l.contents);for(const l of(r=t.table_schemas)!==null&&r!==void 0?r:[]){const c=(i=t.connections)===null||i===void 0?void 0:i.find(f=>f.name===l.connection_name);c&&l.schema&&c.dialect&&(a.tables[Lxe(l.connection_name,l.name)]=ndt(l,c.dialect))}for(const l of(s=t.sql_schemas)!==null&&s!==void 0?s:[]){const c=(o=t.connections)===null||o===void 0?void 0:o.find(f=>f.name===l.connection_name);c&&c.dialect&&(a.compileSQL[(0,wxe.sqlKey)(l.connection_name,l.sql)]=tdt(l,c.dialect))}for(const l of(u=t.translations)!==null&&u!==void 0?u:[])if(l.compiled_model_json){const c=JSON.parse(l.compiled_model_json);a.translations[l.url]=c}}return a}function kxe(t,e,r){var i,s,o;const u={},a=new Set;if(t!==void 0&&(u.sql_schemas=[{sql:t.selectStr,connection_name:t.connection}],a.add(t.connection)),e!==void 0)for(const l of e)(i=u.files)!==null&&i!==void 0||(u.files=[]),u.files.push({url:l});if(r!==void 0)for(const l in r){const c=r[l],f=(s=c.connectionName)!==null&&s!==void 0?s:"__default__";(o=u.table_schemas)!==null&&o!==void 0||(u.table_schemas=[]),u.table_schemas.push({name:c.tablePath,connection_name:f}),a.add(f)}return a.size>0&&(u.connections=Array.from(a).map(l=>({name:l}))),u}function sdt(t,e){return e??(e=qxe(t)),Hxe(e)}nn.compileQuery=sdt;function odt(t,e){function r(s,o){var u,a,l,c;s.translator.update(o),s.extending&&r(s.extending,o),s.hasSource||(s.hasSource=((a=(u=e==null?void 0:e.files)===null||u===void 0?void 0:u.some(f=>f.url===s.translator.sourceURL))!==null&&a!==void 0?a:!1)||((c=(l=e==null?void 0:e.translations)===null||l===void 0?void 0:l.some(f=>f.url===s.translator.sourceURL))!==null&&c!==void 0?c:!1))}const i=$xe(e);r(t,i)}nn.updateCompileModelState=odt;function qR(t,e,r){var i,s,o,u;const a=new Xxt.MalloyTranslator(t,null,$xe(e)),l=((s=(i=e==null?void 0:e.files)===null||i===void 0?void 0:i.some(c=>c.url===t))!==null&&s!==void 0?s:!1)||((u=(o=e==null?void 0:e.translations)===null||o===void 0?void 0:o.some(c=>c.url===t))!==null&&u!==void 0?u:!1);return r?{extending:qR(r,e),translator:a,done:!1,hasSource:l}:{translator:a,done:!1,hasSource:l}}function Mxe(t){return qR(t.model_url,t.compiler_needs,t.extend_model_url)}nn.newCompileModelState=Mxe;function Pxe(t){return qR(t.model_url,t.compiler_needs,t.extend_model_url)}nn.newCompileSourceState=Pxe;function Uxe(t){return udt(SE(t),t.translator.sourceURL)}nn.statedCompileModel=Uxe;function jxe(t,e){return cdt(SE(t),e,t.translator.sourceURL)}nn.statedCompileSource=jxe;function SE(t){let e;if(t.extending){if(!t.extending.done){const i=SE(t.extending);if(!t.extending.done)return i}e=t.extending.translator.modelDef}if(!t.hasSource)return{compilerNeeds:kxe(void 0,[t.translator.sourceURL],void 0)};const r=t.translator.translate(e);if(r.final){if(t.done=!0,r.modelDef)return{model:(0,Zxt.modelDefToModelInfo)(r.modelDef),modelDef:r.modelDef};if(r.problems===void 0||r.problems.length===0)throw new Error("No problems found, but no model either");return{logs:r.problems}}else return{compilerNeeds:kxe(r.compileSQL,r.urls,r.tables),logs:r.problems}}nn._statedCompileModel=SE;function udt(t,e){const r=t.logs?(0,dd.mapLogs)(t.logs,e):void 0;if(t.compilerNeeds)return{compiler_needs:t.compilerNeeds,logs:r};{let i;return t.modelDef&&(i=[{url:e,compiled_model_json:JSON.stringify(t.modelDef)}]),{model:t.model,logs:r,translations:i}}}function adt(t,e){return e??(e=Mxe(t)),Uxe(e)}nn.compileModel=adt;function ldt(t){const e=Pxe(t);return jxe(e,t.name)}nn.compileSource=ldt;function cdt(t,e,r){const i=t.logs?(0,dd.mapLogs)(t.logs,r):void 0;if(t.model){const s=t.model.entries.find(o=>o.name===e);return s===void 0?{logs:[...i??[],{url:r,severity:"error",message:`Model does not contain a source named ${e}`,range:dd.DEFAULT_LOG_RANGE}]}:{source:s,logs:i}}else return{compiler_needs:t.compilerNeeds,logs:i}}function fdt(t){var e;return(e=t==null?void 0:t.some(r=>r.severity==="error"))!==null&&e!==void 0?e:!1}nn.hasErrors=fdt;function qxe(t){var e,r;const i=Jxt.queryToMalloy(t.query),s={...(e=t.compiler_needs)!==null&&e!==void 0?e:{}},o="internal://query.malloy";return s.files=[{url:o,contents:i},...(r=s.files)!==null&&r!==void 0?r:[]],{...qR(o,s,t.model_url),defaultRowLimit:t.default_row_limit}}nn.newCompileQueryState=qxe;function Hxe(t){var e;const r=SE(t),i=t.translator.sourceURL,s=r.logs?(0,dd.mapLogs)(r.logs,i):void 0;if(r.model){const o=r.modelDef.queryList;if(o.length===0)return{logs:[...s??[],{url:i,severity:"error",message:"Internal error: No queries found",range:dd.DEFAULT_LOG_RANGE}]};const u=o.length-1,a=r.modelDef.queryList[u],l=r.model.anonymous_queries[u].schema,c=(e=r.model.anonymous_queries[u].annotations)!==null&&e!==void 0?e:[];try{const x=new Fxe.QueryModel(r.modelDef).compileQuery(a,{defaultRowLimit:t.defaultRowLimit}),h=(0,edt.annotationToTaglines)(r.modelDef.annotation).map(p=>({value:p}));return c.push({value:Nxe.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore).toString()}),x.queryName&&c.push({value:Nxe.Tag.withPrefix("#(malloy) ").set(["query_name"],x.queryName).toString()}),{result:{sql:x.sql,schema:l,connection_name:x.connectionName,annotations:c.length>0?c:void 0,model_annotations:h.length>0?h:void 0,query_timezone:x.queryTimezone},default_row_limit_added:x.defaultRowLimitAdded}}catch(f){return{logs:[...s??[],{url:i,severity:"error",message:`Internal compiler error: ${f.message}`,range:dd.DEFAULT_LOG_RANGE}]}}}else return{compiler_needs:r.compilerNeeds,logs:s}}nn.statedCompileQuery=Hxe;var xdt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),ddt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Qxe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&xdt(e,t,r);return ddt(e,t),e};Object.defineProperty(Wc,"__esModule",{value:!0}),Wc.compileQuery=Wc.compileSource=Wc.compileModel=void 0;const hdt=Qxe(rP),Pa=Qxe(nn),pdt=Pp;function mdt(t,e){return t.type==="compile_model"?e.type!=="compile_model"?!1:t.modelURL===e.modelURL&&t.extendModelURL===e.extendModelURL:t.type==="compile_source"?e.type!=="compile_source"?!1:t.modelURL===e.modelURL&&t.extendModelURL===e.extendModelURL&&t.name===e.name:e.type!=="compile_query"?!1:t.modelURL===e.modelURL&&t.queryString===e.queryString}class gdt{constructor(){this.sessions=new Map}purgeExpired(e){const r=new Date;for(const i of this.sessions.values())i.sessionId!==(e==null?void 0:e.except)&&i.expires&&i.expires<r&&this.sessions.delete(i.sessionId)}findSession(e,r){const i=this.sessions.get(e);if(i&&mdt(i.sessionInfo,r))return i}getExpires(e){return e instanceof Date?e:new Date(Date.now()+e.seconds*1e3)}newSessionId(){let e;do e=(0,pdt.v4)();while(this.sessions.has(e));return e}newCompileModelSession(e,r,i){const s=i!=null&&i.ttl?this.getExpires(i.ttl):void 0,o=Pa.newCompileModelState(e);return{type:"compile_model",sessionInfo:r,state:o,expires:s,sessionId:this.newSessionId()}}newCompileSourceSession(e,r,i){const s=i!=null&&i.ttl?this.getExpires(i.ttl):void 0,o=Pa.newCompileSourceState(e);return{type:"compile_source",sessionInfo:r,state:o,expires:s,sessionId:this.newSessionId()}}newCompileQuerySession(e,r,i){const s=i!=null&&i.ttl?this.getExpires(i.ttl):void 0,o=Pa.newCompileQueryState(e);return{type:"compile_query",sessionInfo:r,state:o,expires:s,sessionId:this.newSessionId()}}findCompileModelSession(e,r){const i=this.findSession(e,r);if((i==null?void 0:i.type)==="compile_model")return i}killSession(e){this.sessions.delete(e)}hasErrors(e){return Pa.hasErrors(e)}compileModel(e,r){const i={type:"compile_model",modelURL:e.model_url,extendModelURL:e.extend_model_url};let s=(r==null?void 0:r.session_id)&&this.findCompileModelSession(r.session_id,i);this.purgeExpired({except:r==null?void 0:r.session_id}),s?(r!=null&&r.ttl&&(s.expires=this.getExpires(r.ttl)),Pa.updateCompileModelState(s.state,e.compiler_needs)):(s=this.newCompileModelSession(e,i,r),this.sessions.set(s.sessionId,s));const o=Pa.statedCompileModel(s.state);return(o.model||this.hasErrors(o.logs))&&this.killSession(s.sessionId),{...o,session_id:s.sessionId}}findCompileSourceSession(e,r){const i=this.findSession(e,r);if((i==null?void 0:i.type)==="compile_source")return i}compileSource(e,r){const i={type:"compile_source",modelURL:e.model_url,name:e.name,extendModelURL:e.extend_model_url};let s=(r==null?void 0:r.session_id)&&this.findCompileSourceSession(r.session_id,i);this.purgeExpired({except:r==null?void 0:r.session_id}),s?(r!=null&&r.ttl&&(s.expires=this.getExpires(r.ttl)),Pa.updateCompileModelState(s.state,e.compiler_needs)):(s=this.newCompileSourceSession(e,i,r),this.sessions.set(s.sessionId,s));const o=Pa.statedCompileSource(s.state,e.name);return(o.source||this.hasErrors(o.logs))&&this.killSession(s.sessionId),{...o,session_id:s.sessionId}}findCompileQuerySession(e,r){const i=this.findSession(e,r);if((i==null?void 0:i.type)==="compile_query")return i}compileQuery(e,r){const i=hdt.queryToMalloy(e.query),s={type:"compile_query",modelURL:e.model_url,queryString:i,query:e.query};let o=(r==null?void 0:r.session_id)&&this.findCompileQuerySession(r.session_id,s);this.purgeExpired({except:r==null?void 0:r.session_id}),o?(r!=null&&r.ttl&&(o.expires=this.getExpires(r.ttl)),Pa.updateCompileModelState(o.state,e.compiler_needs)):(o=this.newCompileQuerySession(e,s,r),this.sessions.set(o.sessionId,o));const u=Pa.statedCompileQuery(o.state);return(u.result||this.hasErrors(u.logs))&&this.killSession(o.sessionId),{...u,session_id:o.sessionId}}}const lP=new gdt;function ydt(t,e){return lP.compileModel(t,e)}Wc.compileModel=ydt;function Edt(t,e){return lP.compileSource(t,e)}Wc.compileSource=Edt;function Adt(t,e){return lP.compileQuery(t,e)}Wc.compileQuery=Adt;var Yc={},_dt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),vdt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Cdt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&_dt(e,t,r);return vdt(e,t),e};Object.defineProperty(Yc,"__esModule",{value:!0}),Yc.compileQuery=Yc.compileSource=Yc.compileModel=void 0;const cP=Cdt(nn);function Sdt(t){return cP.compileModel(t)}Yc.compileModel=Sdt;function bdt(t){return cP.compileSource(t)}Yc.compileSource=bdt;function Tdt(t){return cP.compileQuery(t)}Yc.compileQuery=Tdt;var Ua={},Rdt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Ddt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Odt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Rdt(e,t,r);return Ddt(e,t),e};Object.defineProperty(Ua,"__esModule",{value:!0}),Ua.runQuery=Ua.compileQuery=Ua.compileSource=Ua.compileModel=void 0;const vo=Odt(nn),zxe=mE;async function fP(t,e){var r,i,s,o,u,a,l,c,f;if(t===void 0)throw new Error("Expected compiler to have needs because it didn't return a result");const x={};if(t.connections)for(const h of t.connections){const p=await e.connections.lookupConnection(h.name);(r=x.connections)!==null&&r!==void 0||(x.connections=[]),x.connections.push({...h,dialect:p.dialectName})}if(t.files)for(const h of t.files){const p=await e.urls.readURL(new URL(h.url));(i=x.files)!==null&&i!==void 0||(x.files=[]),typeof p=="string"?x.files.push({...h,contents:p}):x.files.push({...h,contents:p.contents,invalidation_key:(s=p.invalidationKey)===null||s===void 0?void 0:s.toString()})}if(t.table_schemas){const h={};for(const p of t.table_schemas)(o=h[c=p.connection_name])!==null&&o!==void 0||(h[c]=[]),h[p.connection_name].push(p);for(const p in h){const m=await e.connections.lookupConnection(p),g=h[p].map(E=>E.name),y=await Promise.all(g.map(async E=>({name:E,schema:await m.fetchSchemaForTable(E)})));(u=x.table_schemas)!==null&&u!==void 0||(x.table_schemas=[]);for(const E of y)x.table_schemas.push({connection_name:p,name:E.name,schema:E.schema})}}if(t.sql_schemas){const h={};for(const p of t.sql_schemas)(a=h[f=p.connection_name])!==null&&a!==void 0||(h[f]=[]),h[p.connection_name].push(p);for(const p in h){const m=await e.connections.lookupConnection(p),g=h[p].map(E=>E.sql),y=await Promise.all(g.map(async E=>({sql:E,schema:await m.fetchSchemaForSQLQuery(E)})));(l=x.sql_schemas)!==null&&l!==void 0||(x.sql_schemas=[]);for(const E of y)x.sql_schemas.push({connection_name:p,sql:E.sql,schema:E.schema})}}return x}async function Fdt(t,e){const r=vo.newCompileModelState(t);for(;;){const i=vo.statedCompileModel(r);if(i.model||vo.hasErrors(i.logs))return i;const s=await fP(i.compiler_needs,e);vo.updateCompileModelState(r,s)}}Ua.compileModel=Fdt;async function wdt(t,e){const r=vo.newCompileSourceState(t);for(;;){const i=vo.statedCompileSource(r,t.name);if(i.source||vo.hasErrors(i.logs))return i;const s=await fP(i.compiler_needs,e);vo.updateCompileModelState(r,s)}}Ua.compileSource=wdt;async function Gxe(t,e){const r=vo.newCompileQueryState(t);for(;;){const i=vo.statedCompileQuery(r);if(i.result||vo.hasErrors(i.logs))return i;const s=await fP(i.compiler_needs,e);vo.updateCompileModelState(r,s)}}Ua.compileQuery=Gxe;async function Ndt(t,e){var r,i;const s=await Gxe(t,e);if(s.result===void 0)return s;const o=t.model_url;if(s.result.sql===void 0)return{logs:[...(r=s.logs)!==null&&r!==void 0?r:[],{url:o,severity:"error",message:"Internal error: Compiler did not generate SQL",range:zxe.DEFAULT_LOG_RANGE}]};try{const a=await(await e.connections.lookupConnection(s.result.connection_name)).runSQL(s.result.sql,s.result.schema);return{...s,result:{...s.result,data:a}}}catch(u){return{...s,logs:[...(i=s.logs)!==null&&i!==void 0?i:[],{url:o,severity:"error",message:`Error running SQL: ${u.message}`,range:zxe.DEFAULT_LOG_RANGE}]}}}Ua.runQuery=Ndt;var Wxe={};Object.defineProperty(Wxe,"__esModule",{value:!0}),function(t){var e=T&&T.__createBinding||(Object.create?function(o,u,a,l){l===void 0&&(l=a);var c=Object.getOwnPropertyDescriptor(u,a);(!c||("get"in c?!u.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return u[a]}}),Object.defineProperty(o,l,c)}:function(o,u,a,l){l===void 0&&(l=a),o[l]=u[a]}),r=T&&T.__setModuleDefault||(Object.create?function(o,u){Object.defineProperty(o,"default",{enumerable:!0,value:u})}:function(o,u){o.default=u}),i=T&&T.__importStar||function(o){if(o&&o.__esModule)return o;var u={};if(o!=null)for(var a in o)a!=="default"&&Object.prototype.hasOwnProperty.call(o,a)&&e(u,o,a);return r(u,o),u},s=T&&T.__exportStar||function(o,u){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(u,a)&&e(u,o,a)};Object.defineProperty(t,"__esModule",{value:!0}),t.util=t.asynchronous=t.stateless=t.sessioned=void 0,t.sessioned=i(Wc),t.stateless=i(Yc),t.asynchronous=i(Ua),s(Wxe,t),t.util=i(mE)}(Cxe),function(t){var e=T&&T.__createBinding||(Object.create?function(h,p,m,g){g===void 0&&(g=m);var y=Object.getOwnPropertyDescriptor(p,m);(!y||("get"in y?!p.__esModule:y.writable||y.configurable))&&(y={enumerable:!0,get:function(){return p[m]}}),Object.defineProperty(h,g,y)}:function(h,p,m,g){g===void 0&&(g=m),h[g]=p[m]}),r=T&&T.__setModuleDefault||(Object.create?function(h,p){Object.defineProperty(h,"default",{enumerable:!0,value:p})}:function(h,p){h.default=p}),i=T&&T.__importStar||function(h){if(h&&h.__esModule)return h;var p={};if(h!=null)for(var m in h)m!=="default"&&Object.prototype.hasOwnProperty.call(h,m)&&e(p,h,m);return r(p,h),p};Object.defineProperty(t,"__esModule",{value:!0}),t.EmptyURLReader=t.SingleConnectionRuntime=t.ConnectionRuntime=t.AtomicFieldType=t.Runtime=t.Malloy=t.Model=t.MalloyTranslator=t.malloyToQuery=t.composeSQLExpr=t.indent=t.expressionIsUngroupedAggregate=t.expressionIsScalar=t.expressionIsCalculation=t.expressionIsAnalytic=t.expressionIsAggregate=t.mkFieldDef=t.mkArrayDef=t.isBasicArray=t.isRepeatedRecord=t.isSamplingRows=t.isSamplingPercent=t.isSamplingEnable=t.isJoinedSource=t.isJoined=t.isBasicAtomic=t.Segment=t.isSourceDef=t.TinyParser=t.Dialect=t.spread=t.literal=t.variadicParam=t.param=t.makeParam=t.sql=t.maxScalar=t.minAggregate=t.anyExprType=t.minScalar=t.overload=t.qtz=t.arg=t.registerDialect=t.MySQLDialect=t.SnowflakeDialect=t.PostgresDialect=t.TrinoDialect=t.StandardSQLDialect=t.DuckDBDialect=void 0,t.annotationToTaglines=t.annotationToTag=t.sqlKey=t.API=t.modelDefToModelInfo=t.toAsyncGenerator=t.CacheManager=t.InMemoryModelCache=t.Explore=t.DataWriter=t.Parse=t.JSONWriter=t.CSVWriter=t.QueryMaterializer=t.Result=t.PreparedResult=t.TimestampTimeframe=t.DateTimeframe=t.SourceRelationship=t.JoinRelationship=t.MalloyError=t.FixedConnectionMap=t.InMemoryURLReader=void 0;var s=kp;Object.defineProperty(t,"DuckDBDialect",{enumerable:!0,get:function(){return s.DuckDBDialect}}),Object.defineProperty(t,"StandardSQLDialect",{enumerable:!0,get:function(){return s.StandardSQLDialect}}),Object.defineProperty(t,"TrinoDialect",{enumerable:!0,get:function(){return s.TrinoDialect}}),Object.defineProperty(t,"PostgresDialect",{enumerable:!0,get:function(){return s.PostgresDialect}}),Object.defineProperty(t,"SnowflakeDialect",{enumerable:!0,get:function(){return s.SnowflakeDialect}}),Object.defineProperty(t,"MySQLDialect",{enumerable:!0,get:function(){return s.MySQLDialect}}),Object.defineProperty(t,"registerDialect",{enumerable:!0,get:function(){return s.registerDialect}}),Object.defineProperty(t,"arg",{enumerable:!0,get:function(){return s.arg}}),Object.defineProperty(t,"qtz",{enumerable:!0,get:function(){return s.qtz}}),Object.defineProperty(t,"overload",{enumerable:!0,get:function(){return s.overload}}),Object.defineProperty(t,"minScalar",{enumerable:!0,get:function(){return s.minScalar}}),Object.defineProperty(t,"anyExprType",{enumerable:!0,get:function(){return s.anyExprType}}),Object.defineProperty(t,"minAggregate",{enumerable:!0,get:function(){return s.minAggregate}}),Object.defineProperty(t,"maxScalar",{enumerable:!0,get:function(){return s.maxScalar}}),Object.defineProperty(t,"sql",{enumerable:!0,get:function(){return s.sql}}),Object.defineProperty(t,"makeParam",{enumerable:!0,get:function(){return s.makeParam}}),Object.defineProperty(t,"param",{enumerable:!0,get:function(){return s.param}}),Object.defineProperty(t,"variadicParam",{enumerable:!0,get:function(){return s.variadicParam}}),Object.defineProperty(t,"literal",{enumerable:!0,get:function(){return s.literal}}),Object.defineProperty(t,"spread",{enumerable:!0,get:function(){return s.spread}}),Object.defineProperty(t,"Dialect",{enumerable:!0,get:function(){return s.Dialect}}),Object.defineProperty(t,"TinyParser",{enumerable:!0,get:function(){return s.TinyParser}});var o=Pi;Object.defineProperty(t,"isSourceDef",{enumerable:!0,get:function(){return o.isSourceDef}}),Object.defineProperty(t,"Segment",{enumerable:!0,get:function(){return o.Segment}}),Object.defineProperty(t,"isBasicAtomic",{enumerable:!0,get:function(){return o.isBasicAtomic}}),Object.defineProperty(t,"isJoined",{enumerable:!0,get:function(){return o.isJoined}}),Object.defineProperty(t,"isJoinedSource",{enumerable:!0,get:function(){return o.isJoinedSource}}),Object.defineProperty(t,"isSamplingEnable",{enumerable:!0,get:function(){return o.isSamplingEnable}}),Object.defineProperty(t,"isSamplingPercent",{enumerable:!0,get:function(){return o.isSamplingPercent}}),Object.defineProperty(t,"isSamplingRows",{enumerable:!0,get:function(){return o.isSamplingRows}}),Object.defineProperty(t,"isRepeatedRecord",{enumerable:!0,get:function(){return o.isRepeatedRecord}}),Object.defineProperty(t,"isBasicArray",{enumerable:!0,get:function(){return o.isBasicArray}}),Object.defineProperty(t,"mkArrayDef",{enumerable:!0,get:function(){return o.mkArrayDef}}),Object.defineProperty(t,"mkFieldDef",{enumerable:!0,get:function(){return o.mkFieldDef}}),Object.defineProperty(t,"expressionIsAggregate",{enumerable:!0,get:function(){return o.expressionIsAggregate}}),Object.defineProperty(t,"expressionIsAnalytic",{enumerable:!0,get:function(){return o.expressionIsAnalytic}}),Object.defineProperty(t,"expressionIsCalculation",{enumerable:!0,get:function(){return o.expressionIsCalculation}}),Object.defineProperty(t,"expressionIsScalar",{enumerable:!0,get:function(){return o.expressionIsScalar}}),Object.defineProperty(t,"expressionIsUngroupedAggregate",{enumerable:!0,get:function(){return o.expressionIsUngroupedAggregate}}),Object.defineProperty(t,"indent",{enumerable:!0,get:function(){return o.indent}}),Object.defineProperty(t,"composeSQLExpr",{enumerable:!0,get:function(){return o.composeSQLExpr}});var u=H4;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return u.malloyToQuery}}),Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return u.MalloyTranslator}});var a=we;Object.defineProperty(t,"Model",{enumerable:!0,get:function(){return a.Model}}),Object.defineProperty(t,"Malloy",{enumerable:!0,get:function(){return a.Malloy}}),Object.defineProperty(t,"Runtime",{enumerable:!0,get:function(){return a.Runtime}}),Object.defineProperty(t,"AtomicFieldType",{enumerable:!0,get:function(){return a.AtomicFieldType}}),Object.defineProperty(t,"ConnectionRuntime",{enumerable:!0,get:function(){return a.ConnectionRuntime}}),Object.defineProperty(t,"SingleConnectionRuntime",{enumerable:!0,get:function(){return a.SingleConnectionRuntime}}),Object.defineProperty(t,"EmptyURLReader",{enumerable:!0,get:function(){return a.EmptyURLReader}}),Object.defineProperty(t,"InMemoryURLReader",{enumerable:!0,get:function(){return a.InMemoryURLReader}}),Object.defineProperty(t,"FixedConnectionMap",{enumerable:!0,get:function(){return a.FixedConnectionMap}}),Object.defineProperty(t,"MalloyError",{enumerable:!0,get:function(){return a.MalloyError}}),Object.defineProperty(t,"JoinRelationship",{enumerable:!0,get:function(){return a.JoinRelationship}}),Object.defineProperty(t,"SourceRelationship",{enumerable:!0,get:function(){return a.SourceRelationship}}),Object.defineProperty(t,"DateTimeframe",{enumerable:!0,get:function(){return a.DateTimeframe}}),Object.defineProperty(t,"TimestampTimeframe",{enumerable:!0,get:function(){return a.TimestampTimeframe}}),Object.defineProperty(t,"PreparedResult",{enumerable:!0,get:function(){return a.PreparedResult}}),Object.defineProperty(t,"Result",{enumerable:!0,get:function(){return a.Result}}),Object.defineProperty(t,"QueryMaterializer",{enumerable:!0,get:function(){return a.QueryMaterializer}}),Object.defineProperty(t,"CSVWriter",{enumerable:!0,get:function(){return a.CSVWriter}}),Object.defineProperty(t,"JSONWriter",{enumerable:!0,get:function(){return a.JSONWriter}}),Object.defineProperty(t,"Parse",{enumerable:!0,get:function(){return a.Parse}}),Object.defineProperty(t,"DataWriter",{enumerable:!0,get:function(){return a.DataWriter}}),Object.defineProperty(t,"Explore",{enumerable:!0,get:function(){return a.Explore}}),Object.defineProperty(t,"InMemoryModelCache",{enumerable:!0,get:function(){return a.InMemoryModelCache}}),Object.defineProperty(t,"CacheManager",{enumerable:!0,get:function(){return a.CacheManager}});var l=IR;Object.defineProperty(t,"toAsyncGenerator",{enumerable:!0,get:function(){return l.toAsyncGenerator}});var c=La;Object.defineProperty(t,"modelDefToModelInfo",{enumerable:!0,get:function(){return c.modelDefToModelInfo}}),t.API=i(Cxe);var f=Yl;Object.defineProperty(t,"sqlKey",{enumerable:!0,get:function(){return f.sqlKey}});var x=ui;Object.defineProperty(t,"annotationToTag",{enumerable:!0,get:function(){return x.annotationToTag}}),Object.defineProperty(t,"annotationToTaglines",{enumerable:!0,get:function(){return x.annotationToTaglines}})}(vB);class Ldt{constructor(e){this.document=e}async render(e,r){var l;let i;if(e&&(e instanceof vB.Result||"modelDef"in e)?i=vB.API.util.wrapResult(e):i=e,!r4(i.model_annotations,"## ").has("renderer_legacy"))if(!!((l=this.document.defaultView)!=null&&l.customElements.get("malloy-render"))){const f=this.document.createElement("malloy-render");f.malloyResult=i;const x=r.nextRendererOptions??{};for(const[h,p]of Object.entries(x))f[h]=p;return f}else console.warn("Tried to use the new Malloy renderer, but the malloy-render component was not found. Falling back to the legacy renderer.");const u=xue(i),a=Yxe(u.field,this.document,r,{size:"large"},u.field.queryTimezone,u.field.tag);try{return await a.render(u)}catch(c){return c instanceof Error?Gs(this.document,c):Gs(this.document,"Internal error - Exception not an Error object.")}}}class Idt{constructor(e){this.document=e}async render(e){const r=new mP(this.document);try{return await r.render(e)}catch(i){return i instanceof Error?Gs(this.document,i):Gs(this.document,"Internal error - Exception not an Error object.")}}}const Vxe={shape_map:"shape_map",point_map:"point_map",bar_chart:"bar_chart",image:"image",json:"json",segment_map:"segment_map",dashboard:"dashboard",line_chart:"line_chart",scatter_chart:"scatter_chart",url:"url",list:"list",list_detail:"list_detail",sparkline:"sparkline",sparkline_area:"sparkline",sparkline_column:"sparkline",sparkline_bar:"sparkline"};function Bdt(t,e){const r=e[t.name],{name:i}=t;for(const s in Vxe)if(i.endsWith(`_${s}`)){const o=i.slice(0,i.length-s.length-1);return $dt(s,o,Vxe,r)}return r}function $dt(t,e,r,i){var s;return i?(i.renderer??(i.renderer=r[t]),i.data??(i.data={}),(s=i.data).label??(s.label=e)):i={renderer:r[t],data:{label:e}},i}function HR(t){if(t.isRecordOrRepeatedRecord())return t;throw new Error(`${t.name} does not contain fields and cannot be rendered this way`)}function Yxe(t,e,r,i,s,o){const u=Bdt(t,r.dataStyles);r.dataStyles[t.name]=u;const a=new jL().create(u,o,e,i,r,t,s);if(a)return a;if((u==null?void 0:u.renderer)==="dashboard"||o.has("dashboard"))return QR(AB,e,HR(t),r,o);if((u==null?void 0:u.renderer)==="list"||o.has("list"))return QR(Eue,e,HR(t),r,o);if((u==null?void 0:u.renderer)==="list_detail"||o.has("list_detail"))return QR(mYe,e,HR(t),r,o);if((u==null?void 0:u.renderer)==="table"||o.has("table")||t.isRecordOrRepeatedRecord())return QR(Z2,e,HR(t),r,o);throw new Error(`Could not find a proper renderer for field ${t.name}`)}function QR(t,e,r,i,s){const o=wE.make(t,e,r,i,s),u={};return r.fields.forEach(a=>{u[a.name]=Yxe(a,e,i,o.defaultStylesForChildren,a.root().queryTimezone,a.tag)}),o.childRenderers=u,o}async function kdt(t){const e=await Kxe(t);try{await navigator.clipboard.writeText(e)}catch(r){console.error("Failed to copy text: ",r)}}async function Kxe(t){let e="";const r=t.tableConfig??{},i=Object.assign({disableVirtualization:!0},r);t.tableConfig=i;const s=t.dashboardConfig??{},o=Object.assign({disableVirtualization:!0},s);if(t.dashboardConfig=o,await Mdt(1e3),t.shadowRoot){let u="";for(const a of[...t.shadowRoot.adoptedStyleSheets]){for(let c=0;c<a.cssRules.length;c++){const f=a.cssRules.item(c);f&&(u+=`
1487
+ `),this.stream.close()}}we.JSONWriter=gxt;class yxt extends tP{constructor(){super(...arguments),this.columnSeparator=",",this.rowSeparator=`
1488
+ `,this.quoteCharacter='"',this.includeHeader=!0,this.emptyCell=""}escape(e){const r=e.includes(this.quoteCharacter),i=e.includes(this.columnSeparator),s=e.includes(this.rowSeparator),o=i||r||s;return r&&(e=e.replace(new RegExp(this.quoteCharacter,"g"),this.quoteCharacter+this.quoteCharacter)),o&&(e=this.quoteCharacter+e+this.quoteCharacter),e}stringify(e){return e===null?this.emptyCell:e instanceof Date?e.toISOString():typeof e=="boolean"||typeof e=="number"?JSON.stringify(e):`${e}`}getColWeight(e){let r=e;Array.isArray(e)&&(r=e[0]);let i=0;for(const s in r){i=i+1;const o=r[s];if(Array.isArray(o)){const u=this.getColWeight(o)-1;i=i+u}}return i}getHeaderRow(e){const r=[];let i=0;for(const s in e){r.push(this.escape(s));const o=e[s];if(i++,Array.isArray(o)){const u=this.getColWeight(o)-1;i=i+u;for(let a=0;a<u;a++)r.push(this.emptyCell)}}return{rows:[r.join(this.columnSeparator)],length:1,width:i}}mergeMatrices(e){const r=Math.max(...e.map(o=>o.length)),i=e.reduce((o,u)=>o+u.width,0),s=[];for(let o=0;o<r;o++){const u=[];for(const a of e)if(o<a.length)u.push(a.rows[o]);else{const l=Array(a.width).fill(this.emptyCell);u.push(...l)}s.push(u.join(this.columnSeparator))}return{rows:s,length:r,width:i}}getChildMatrix(e){if(Array.isArray(e)){if(e.length===0)return{rows:[""],length:1,width:1}}else return{rows:["Invalid data found, value is not an array"],length:1,width:1};const r=[],i=this.getHeaderRow(e[0]);r.push(...i.rows);const s=i.width;let o=1;for(const u of e){const a=this.getRowMatrix(u);o=o+a.length,r.push(...a.rows)}return{rows:r,length:o,width:s}}getRowMatrix(e){const r=[];for(const i in e){const s=e[i];if(Array.isArray(s)){const o=this.getChildMatrix(s);r.push(o)}else{const o={rows:[this.stringify(s)],length:1,width:1};r.push(o)}}return this.mergeMatrices(r)}async process(e){let r=!1;for await(const i of e){if(!r&&this.includeHeader){const o=this.getHeaderRow(i.toObject());this.stream.write(o.rows[0]),this.stream.write(this.rowSeparator),r=!0}const s=this.getRowMatrix(i.toObject());for(const o of s.rows)this.stream.write(o),this.stream.write(this.rowSeparator)}this.stream.close()}}we.CSVWriter=yxt;class Ext{constructor(e){this.modelCache=e,this.modelDependencies=new Map,this.modelInvalidationKeys=new Map}async getCachedModelDef(e,r){const i=this.modelDependencies.get(r);if(i===void 0)return;const s=[r,...wR(i)],o={};for(const a of s){const l=this.modelInvalidationKeys.get(a);if(l==null)return;o[a]=l}for(const a of s)if(await nP(e,new URL(a))!==o[a])return;const u=await this.modelCache.getModel(new URL(r));if(u!==void 0){for(const a of s)if(u.invalidationKeys[a]!==o[a])return;return{modelDef:u.modelDef,invalidationKeys:o}}}async setCachedModelDef(e,r){this.modelDependencies.set(e,r.modelDef.dependencies);const i={};for(const o of[e,...wR(r.modelDef.dependencies)]){if(r.invalidationKeys[o]===null)return!1;if(r.invalidationKeys[o]===void 0)throw new Error(`Missing invalidation key for dependency ${o}`);this.modelInvalidationKeys.set(o,r.invalidationKeys[o]),i[o]=r.invalidationKeys[o]}return!!await this.modelCache.setModel(new URL(e),{modelDef:r.modelDef,invalidationKeys:i})}}we.CacheManager=Ext;function wR(t){return[...Object.keys(t),...Object.values(t).map(wR).flat()]}class Axt{constructor(){this.models=new Map}async getModel(e){return Promise.resolve(this.models.get(e.toString()))}async setModel(e,r){return this.models.set(e.toString(),r),Promise.resolve(!0)}}we.InMemoryModelCache=Axt;function vxe(t){return(0,cxt.v5)(t,"76c17e9d-f3ce-5f2d-bfde-98ad3d2a37f6")}async function NR(t,e){const r=await t.readURL(e),{contents:i,invalidationKey:s}=typeof r=="string"?{contents:r,invalidationKey:void 0}:r;return{contents:i,invalidationKey:LR(e.toString())?null:s??vxe(i)}}async function nP(t,e){return LR(e.toString())?null:t.getInvalidationKey!==void 0?await t.getInvalidationKey(e):(await NR(t,e)).invalidationKey}function LR(t){return t.startsWith("internal://")}var IR={};Object.defineProperty(IR,"__esModule",{value:!0}),IR.toAsyncGenerator=void 0;async function*_xt(t){let e=!1;function r(s){let o;const u=new Promise(a=>{o=a});return s(a=>{o({done:!0,isError:!0,error:a})},a=>{o({done:!1,value:a,isError:!1,next:new Promise(l=>{o=l})})},()=>{o({done:!0,isError:!1})}),u}let i=r(t);for(;!e;){const s=await i;if(s.done){if(e=!0,s.isError)throw s.error;break}else i=s.next,yield s.value}}IR.toAsyncGenerator=_xt;var Cxe={},Wc={},rP={},vE={};Object.defineProperty(vE,"__esModule",{value:!0}),vE.MALLOY_INTERFACE_TYPES=void 0,vE.MALLOY_INTERFACE_TYPES={Aggregate:{type:"struct",name:"Aggregate",fields:{name:{type:"string",optional:!0,array:!1},field:{type:"Field",optional:!1,array:!1}}},Annotation:{type:"struct",name:"Annotation",fields:{value:{type:"string",optional:!1,array:!1}}},AnonymousQueryInfo:{type:"struct",name:"AnonymousQueryInfo",fields:{schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"Query",optional:!0,array:!1},code:{type:"string",optional:!0,array:!1},location:{type:"Location",optional:!0,array:!1}}},ArrayCell:{type:"struct",name:"ArrayCell",fields:{array_value:{type:"Cell",array:!0,optional:!1}}},ArrayType:{type:"struct",name:"ArrayType",fields:{element_type:{type:"AtomicType",optional:!1,array:!1}}},AtomicType:{type:"union",name:"AtomicType",options:{string_type:"StringType",boolean_type:"BooleanType",number_type:"NumberType",json_type:"JSONType",sql_native_type:"SQLNativeType",date_type:"DateType",timestamp_type:"TimestampType",array_type:"ArrayType",record_type:"RecordType"}},BooleanCell:{type:"struct",name:"BooleanCell",fields:{boolean_value:{type:"boolean",optional:!1,array:!1}}},BooleanLiteral:{type:"struct",name:"BooleanLiteral",fields:{boolean_value:{type:"boolean",optional:!1,array:!1}}},BooleanType:{type:"struct",name:"BooleanType",fields:{}},Cell:{type:"union",name:"Cell",options:{string_cell:"StringCell",boolean_cell:"BooleanCell",date_cell:"DateCell",timestamp_cell:"TimestampCell",number_cell:"NumberCell",json_cell:"JSONCell",record_cell:"RecordCell",array_cell:"ArrayCell",null_cell:"NullCell",sql_native_cell:"SQLNativeCell"}},CompileModelRequest:{type:"struct",name:"CompileModelRequest",fields:{model_url:{type:"string",optional:!1,array:!1},extend_model_url:{type:"string",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileModelResponse:{type:"struct",name:"CompileModelResponse",fields:{model:{type:"ModelInfo",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},translations:{type:"Translation",array:!0,optional:!0}}},CompileQueryRequest:{type:"struct",name:"CompileQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},query:{type:"Query",optional:!1,array:!1},default_row_limit:{type:"number",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileQueryResponse:{type:"struct",name:"CompileQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},default_row_limit_added:{type:"number",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},translations:{type:"Translation",array:!0,optional:!0}}},CompileSourceRequest:{type:"struct",name:"CompileSourceRequest",fields:{model_url:{type:"string",optional:!1,array:!1},name:{type:"string",optional:!1,array:!1},extend_model_url:{type:"string",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileSourceResponse:{type:"struct",name:"CompileSourceResponse",fields:{source:{type:"SourceInfo",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompilerNeeds:{type:"struct",name:"CompilerNeeds",fields:{table_schemas:{type:"SQLTable",array:!0,optional:!0},sql_schemas:{type:"SQLQuery",array:!0,optional:!0},files:{type:"File",array:!0,optional:!0},connections:{type:"Connection",array:!0,optional:!0},translations:{type:"Translation",array:!0,optional:!0}}},Connection:{type:"struct",name:"Connection",fields:{name:{type:"string",optional:!1,array:!1},dialect:{type:"string",optional:!0,array:!1}}},Data:{type:"union",name:"Data",options:{record_cell:"RecordCell",array_cell:"ArrayCell"}},DateCell:{type:"struct",name:"DateCell",fields:{date_value:{type:"string",optional:!1,array:!1}}},DateLiteral:{type:"struct",name:"DateLiteral",fields:{date_value:{type:"string",optional:!1,array:!1},granularity:{type:"DateTimeframe",optional:!0,array:!1}}},DateTimeframe:{type:"enum",name:"DateTimeframe",values:{year:1,quarter:2,month:3,week:4,day:5}},DateType:{type:"struct",name:"DateType",fields:{timeframe:{type:"DateTimeframe",optional:!0,array:!1}}},DimensionInfo:{type:"struct",name:"DimensionInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},DocumentPosition:{type:"struct",name:"DocumentPosition",fields:{line:{type:"number",optional:!1,array:!1},character:{type:"number",optional:!1,array:!1}}},DocumentRange:{type:"struct",name:"DocumentRange",fields:{start:{type:"DocumentPosition",optional:!1,array:!1},end:{type:"DocumentPosition",optional:!1,array:!1}}},Expression:{type:"union",name:"Expression",options:{field_reference:"Reference",time_truncation:"TimeTruncationFieldReference",filtered_field:"FilteredField"}},Field:{type:"struct",name:"Field",fields:{expression:{type:"Expression",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},FieldInfo:{type:"union",name:"FieldInfo",options:{dimension:"DimensionInfo",measure:"MeasureInfo",join:"JoinInfo",view:"ViewInfo"}},File:{type:"struct",name:"File",fields:{url:{type:"string",optional:!1,array:!1},contents:{type:"string",optional:!0,array:!1},invalidation_key:{type:"string",optional:!0,array:!1}}},Filter:{type:"union",name:"Filter",options:{filter_string:"FilterStringApplication"}},FilterExpressionLiteral:{type:"struct",name:"FilterExpressionLiteral",fields:{filter_expression_value:{type:"string",optional:!1,array:!1}}},FilterExpressionType:{type:"struct",name:"FilterExpressionType",fields:{}},FilterOperation:{type:"struct",name:"FilterOperation",fields:{filter:{type:"Filter",optional:!1,array:!1}}},FilterStringApplication:{type:"struct",name:"FilterStringApplication",fields:{field_reference:{type:"Reference",optional:!1,array:!1},filter:{type:"string",optional:!1,array:!1}}},FilteredField:{type:"struct",name:"FilteredField",fields:{field_reference:{type:"Reference",optional:!1,array:!1},where:{type:"FilterOperation",array:!0,optional:!1}}},GroupBy:{type:"struct",name:"GroupBy",fields:{name:{type:"string",optional:!0,array:!1},field:{type:"Field",optional:!1,array:!1}}},JSONCell:{type:"struct",name:"JSONCell",fields:{json_value:{type:"string",optional:!1,array:!1}}},JSONType:{type:"struct",name:"JSONType",fields:{}},JoinInfo:{type:"struct",name:"JoinInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},relationship:{type:"Relationship",optional:!1,array:!1}}},Limit:{type:"struct",name:"Limit",fields:{limit:{type:"number",optional:!1,array:!1}}},LiteralValue:{type:"union",name:"LiteralValue",options:{string_literal:"StringLiteral",number_literal:"NumberLiteral",date_literal:"DateLiteral",timestamp_literal:"TimestampLiteral",boolean_literal:"BooleanLiteral",null_literal:"NullLiteral",filter_expression_literal:"FilterExpressionLiteral"}},Location:{type:"struct",name:"Location",fields:{url:{type:"string",optional:!1,array:!1},range:{type:"Range",optional:!1,array:!1}}},LogMessage:{type:"struct",name:"LogMessage",fields:{url:{type:"string",optional:!1,array:!1},range:{type:"DocumentRange",optional:!1,array:!1},severity:{type:"LogSeverity",optional:!1,array:!1},message:{type:"string",optional:!1,array:!1}}},LogSeverity:{type:"enum",name:"LogSeverity",values:{debug:1,info:2,warn:3,error:4}},MeasureInfo:{type:"struct",name:"MeasureInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},ModelEntryValue:{type:"union",name:"ModelEntryValue",options:{source:"SourceInfo",query:"QueryInfo"}},ModelInfo:{type:"struct",name:"ModelInfo",fields:{entries:{type:"ModelEntryValue",array:!0,optional:!1},annotations:{type:"Annotation",array:!0,optional:!0},anonymous_queries:{type:"AnonymousQueryInfo",array:!0,optional:!1}}},Nest:{type:"struct",name:"Nest",fields:{name:{type:"string",optional:!0,array:!1},view:{type:"View",optional:!1,array:!1}}},NullCell:{type:"struct",name:"NullCell",fields:{}},NullLiteral:{type:"struct",name:"NullLiteral",fields:{}},NumberCell:{type:"struct",name:"NumberCell",fields:{number_value:{type:"number",optional:!1,array:!1}}},NumberLiteral:{type:"struct",name:"NumberLiteral",fields:{number_value:{type:"number",optional:!1,array:!1}}},NumberSubtype:{type:"enum",name:"NumberSubtype",values:{integer:1,decimal:2}},NumberType:{type:"struct",name:"NumberType",fields:{subtype:{type:"NumberSubtype",optional:!0,array:!1}}},OrderBy:{type:"struct",name:"OrderBy",fields:{field_reference:{type:"Reference",optional:!1,array:!1},direction:{type:"OrderByDirection",optional:!0,array:!1}}},OrderByDirection:{type:"enum",name:"OrderByDirection",values:{asc:1,desc:2}},ParameterInfo:{type:"struct",name:"ParameterInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"ParameterType",optional:!1,array:!1},default_value:{type:"LiteralValue",optional:!0,array:!1}}},ParameterType:{type:"union",name:"ParameterType",options:{string_type:"StringType",boolean_type:"BooleanType",number_type:"NumberType",json_type:"JSONType",sql_native_type:"SQLNativeType",date_type:"DateType",timestamp_type:"TimestampType",array_type:"ArrayType",record_type:"RecordType",filter_expression_type:"FilterExpressionType"}},ParameterValue:{type:"struct",name:"ParameterValue",fields:{name:{type:"string",optional:!1,array:!1},value:{type:"LiteralValue",optional:!1,array:!1}}},Position:{type:"struct",name:"Position",fields:{line:{type:"number",optional:!1,array:!1},character:{type:"number",optional:!1,array:!1}}},Query:{type:"struct",name:"Query",fields:{definition:{type:"QueryDefinition",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},QueryArrow:{type:"struct",name:"QueryArrow",fields:{source:{type:"QueryArrowSource",optional:!1,array:!1},view:{type:"ViewDefinition",optional:!1,array:!1}}},QueryArrowSource:{type:"union",name:"QueryArrowSource",options:{refinement:"QueryRefinement",source_reference:"Reference"}},QueryDefinition:{type:"union",name:"QueryDefinition",options:{arrow:"QueryArrow",query_reference:"Reference",refinement:"QueryRefinement"}},QueryInfo:{type:"struct",name:"QueryInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"Query",optional:!0,array:!1},code:{type:"string",optional:!0,array:!1},location:{type:"Location",optional:!0,array:!1}}},QueryRefinement:{type:"struct",name:"QueryRefinement",fields:{base:{type:"QueryDefinition",optional:!1,array:!1},refinement:{type:"ViewDefinition",optional:!1,array:!1}}},Range:{type:"struct",name:"Range",fields:{start:{type:"Position",optional:!1,array:!1},end:{type:"Position",optional:!1,array:!1}}},RecordCell:{type:"struct",name:"RecordCell",fields:{record_value:{type:"Cell",array:!0,optional:!1}}},RecordType:{type:"struct",name:"RecordType",fields:{fields:{type:"DimensionInfo",array:!0,optional:!1}}},Reference:{type:"struct",name:"Reference",fields:{name:{type:"string",optional:!1,array:!1},path:{type:"string",array:!0,optional:!0},parameters:{type:"ParameterValue",array:!0,optional:!0}}},Relationship:{type:"enum",name:"Relationship",values:{one:1,many:2,cross:3}},Result:{type:"struct",name:"Result",fields:{data:{type:"Data",optional:!0,array:!1},schema:{type:"Schema",optional:!1,array:!1},sql:{type:"string",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},model_annotations:{type:"Annotation",array:!0,optional:!0},query_timezone:{type:"string",optional:!0,array:!1}}},RunIndexQueryRequest:{type:"struct",name:"RunIndexQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},source_name:{type:"string",optional:!1,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunIndexQueryResponse:{type:"struct",name:"RunIndexQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunQueryRequest:{type:"struct",name:"RunQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},query:{type:"Query",optional:!1,array:!1},default_row_limit:{type:"number",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunQueryResponse:{type:"struct",name:"RunQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},default_row_limit_added:{type:"number",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},SQLNativeCell:{type:"struct",name:"SQLNativeCell",fields:{sql_native_value:{type:"string",optional:!1,array:!1}}},SQLNativeType:{type:"struct",name:"SQLNativeType",fields:{sql_type:{type:"string",optional:!0,array:!1}}},SQLQuery:{type:"struct",name:"SQLQuery",fields:{sql:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1}}},SQLTable:{type:"struct",name:"SQLTable",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1}}},Schema:{type:"struct",name:"Schema",fields:{fields:{type:"FieldInfo",array:!0,optional:!1}}},SourceInfo:{type:"struct",name:"SourceInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},parameters:{type:"ParameterInfo",array:!0,optional:!0}}},StringCell:{type:"struct",name:"StringCell",fields:{string_value:{type:"string",optional:!1,array:!1}}},StringLiteral:{type:"struct",name:"StringLiteral",fields:{string_value:{type:"string",optional:!1,array:!1}}},StringType:{type:"struct",name:"StringType",fields:{}},TimeTruncationFieldReference:{type:"struct",name:"TimeTruncationFieldReference",fields:{field_reference:{type:"Reference",optional:!1,array:!1},truncation:{type:"TimestampTimeframe",optional:!1,array:!1}}},TimestampCell:{type:"struct",name:"TimestampCell",fields:{timestamp_value:{type:"string",optional:!1,array:!1}}},TimestampLiteral:{type:"struct",name:"TimestampLiteral",fields:{timestamp_value:{type:"string",optional:!1,array:!1},granularity:{type:"TimestampTimeframe",optional:!0,array:!1}}},TimestampTimeframe:{type:"enum",name:"TimestampTimeframe",values:{year:1,quarter:2,month:3,week:4,day:5,hour:6,minute:7,second:8}},TimestampType:{type:"struct",name:"TimestampType",fields:{timeframe:{type:"TimestampTimeframe",optional:!0,array:!1}}},Translation:{type:"struct",name:"Translation",fields:{url:{type:"string",optional:!1,array:!1},compiled_model_json:{type:"string",optional:!0,array:!1}}},View:{type:"struct",name:"View",fields:{definition:{type:"ViewDefinition",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},ViewArrow:{type:"struct",name:"ViewArrow",fields:{source:{type:"ViewDefinition",optional:!1,array:!1},view:{type:"ViewDefinition",optional:!1,array:!1}}},ViewDefinition:{type:"union",name:"ViewDefinition",options:{arrow:"ViewArrow",view_reference:"Reference",refinement:"ViewRefinement",segment:"ViewSegment"}},ViewInfo:{type:"struct",name:"ViewInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"View",optional:!0,array:!1}}},ViewOperation:{type:"union",name:"ViewOperation",options:{group_by:"GroupBy",aggregate:"Aggregate",order_by:"OrderBy",limit:"Limit",where:"FilterOperation",nest:"Nest",having:"FilterOperation"}},ViewRefinement:{type:"struct",name:"ViewRefinement",fields:{base:{type:"ViewDefinition",optional:!1,array:!1},refinement:{type:"ViewDefinition",optional:!1,array:!1}}},ViewSegment:{type:"struct",name:"ViewSegment",fields:{operations:{type:"ViewOperation",array:!0,optional:!1}}}};var BR={},$R={},kR={};Object.defineProperty(kR,"__esModule",{value:!0}),kR.RESERVED_WORDS=void 0,kR.RESERVED_WORDS=["accept","aggregate","declare","dimension","except","explore","group_by","having","index","join_cross","join_one","join_many","limit","measure","nest","order_by","primary_key","project","query","rename","sample","source","sql","turduck","top","where","all","as","asc","avg","boolean","by","case","cast","condition","count","date","day","days","desc","distinct","else","end","exclude","false","for","from","from_sql","has","hour","hours","import","is","json","last","max","min","minute","minutes","month","months","not","now","null","number","on","or","pick","quarter","quarters","second","seconds","string","sum","table","then","this","timestamp","to","true","turtle","week","weeks","when","with","year","years","ungrouped"],Object.defineProperty($R,"__esModule",{value:!0}),$R.maybeQuoteIdentifier=void 0;const vxt=kR;function Cxt(t){const e=!t.match(/^[A-Za-z_][A-Za-z_0-9]*$/),r=vxt.RESERVED_WORDS.includes(t.toLowerCase());return e||r}function Sxt(t){const e=t.split(".");for(let r=0;r<e.length;r++)Cxt(e[r])&&(e[r]=`\`${e[r]}\``);return e.join(".")}$R.maybeQuoteIdentifier=Sxt,Object.defineProperty(BR,"__esModule",{value:!0}),BR.queryToMalloy=void 0;const CE=$R;function bxt(t,{tabWidth:e}={tabWidth:2}){const r=Fxt(t);return Rxt(r,{tabWidth:e})}BR.queryToMalloy=bxt;const iP=Symbol("indent"),yu=Symbol("newline"),sP=Symbol("outdent"),Txt=Symbol("optional_newline_indent");function Rxt(t,{tabWidth:e}={tabWidth:2}){let r="",i=0,s=!0;for(const o of t)if(o===yu)r+=`
1489
+ `,s=!0;else if(o===sP)i--;else if(o===iP)i++;else{if(o===Txt)continue;s&&(r+=" ".repeat(i*e),s=!1),r+=o}return r}function MR(t,e,r,i){var s;if(e.includes(yu))return[t,yu,iP,...e,yu,sP,r];const u=((s=i==null?void 0:i.spaces)!==null&&s!==void 0?s:!0)?" ":"";return[t,u,...e,u,r]}function Dxt(t){return{contents:t,quoteCharacter:'"'}}function Oxt(t){var e,r;switch(t.kind){case"filter_expression_literal":return[Dxe(t.filter_expression_value)];case"boolean_literal":return[t.boolean_value.toString()];case"string_literal":{const{contents:i,quoteCharacter:s}=Dxt(t.string_value);return[s,i,s]}case"number_literal":return[t.number_value.toString()];case"null_literal":return["null"];case"date_literal":return[bxe(Sxe(t.date_value),(e=t.granularity)!==null&&e!==void 0?e:"day")];case"timestamp_literal":return[bxe(Sxe(t.timestamp_value),(r=t.granularity)!==null&&r!==void 0?r:"second")]}}function Sxe(t){return new Date(t)}function yn(t,e){return t.toString().padStart(e,"0")}function bxe(t,e){switch(e){case"year":return`@${yn(t.getUTCFullYear(),4)}`;case"quarter":{const r=yn(t.getUTCFullYear(),4),i=Math.floor(t.getUTCMonth()/3)+1;return`@${r}-Q${i}`}case"month":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2);return`@${r}-${i}`}case"week":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2);return`@WK${r}-${i}-${s}`}case"day":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2);return`@${r}-${i}-${s}`}case"hour":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2),o=yn(t.getUTCHours(),2);return`@${r}-${i}-${s} ${o}`}case"minute":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2),o=yn(t.getUTCHours(),2),u=yn(t.getUTCMinutes(),2);return`@${r}-${i}-${s} ${o}:${u}`}case"second":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2),o=yn(t.getUTCHours(),2),u=yn(t.getUTCMinutes(),2),a=yn(t.getUTCSeconds(),2);return`@${r}-${i}-${s} ${o}:${u}:${a}`}default:throw new Error("Unknown timeframe.")}}function Vc(t){var e;const r=[];for(const i of(e=t.path)!==null&&e!==void 0?e:[])r.push((0,CE.maybeQuoteIdentifier)(i)),r.push(".");if(r.push((0,CE.maybeQuoteIdentifier)(t.name)),t.parameters){const i=[];for(let s=0;s<t.parameters.length;s++){const o=t.parameters[s];i.push((0,CE.maybeQuoteIdentifier)(o.name)),i.push(" is "),i.push(...Oxt(o.value)),s<t.parameters.length-1&&i.push(",",yu)}r.push(...MR("(",i,")",{spaces:!1}))}return r}function Fxt(t){const e=[];return e.push(...I2(t.annotations)),e.push("run: "),e.push(...oP(t.definition)),e}function wxt(t){const e=[];switch(t.kind){case"source_reference":{e.push(...Vc(t));break}case"refinement":e.push(...oP(t));break}return e}function oP(t){const e=[];switch(t.kind){case"arrow":{e.push(...wxt(t.source)),e.push(" -> "),e.push(...xd(t.view));break}case"query_reference":{e.push(...Vc(t));break}case"refinement":{const r=oP(t.base);t.base.kind==="arrow"?e.push(...MR("(",r,")",{spaces:!1})):e.push(...r),e.push(" + "),e.push(...xd(t.refinement));break}}return e}function xd(t){const e=[];switch(t.kind){case"arrow":{e.push(...xd(t.source)),e.push(" -> "),e.push(...xd(t.view));break}case"view_reference":{e.push(...Vc(t));break}case"refinement":{e.push(...xd(t.base)),e.push(" + "),e.push(...xd(t.refinement));break}case"segment":{e.push(...Nxt(t));break}}return e}function Nxt(t){if(t.operations.length===0)return["{ }"];const e=t.operations.length>1,r=[];for(let i=0;i<t.operations.length;i++){const s=t.operations[i],o=[s];for(;i<t.operations.length-1;){const u=t.operations[i+1];if(u.kind===s.kind)o.push(u),i++;else break}r.push(...Lxt(o)),e&&i<t.operations.length-1&&r.push(yu)}return MR("{",r,"}")}function Lxt(t){switch(t[0].kind){case"aggregate":return kxt(t);case"group_by":return $xt(t);case"order_by":return Mxt(t);case"nest":return Uxt(t);case"limit":return Qxt(t);case"where":return Rxe(t);case"having":return zxt(t)}}function L2(t,e,r=""){const i=[];i.push(`${t}:`);const s=e.length>1||e.some(o=>o.includes(yu));s?i.push(yu,iP):i.push(" ");for(let o=0;o<e.length;o++){const u=e[o];i.push(...u),e.length>1&&o<e.length-1&&i.push(r),s&&o<e.length-1&&i.push(yu)}return s&&i.push(sP),i}function Ixt(t){const e=[];return e.push(...Bxt(t.expression)),e}function yht(t){return t}function Bxt(t){switch(t.kind){case"field_reference":return Vc(t);case"time_truncation":return[...Vc(t.field_reference),".",t.truncation];case"filtered_field":return[...Vc(t.field_reference),...MR(" {",Rxe(t.where),"}")]}}function Txe(t,e=!1){const r=[];return e||r.push(...I2(t.field.annotations)),t.name&&(r.push((0,CE.maybeQuoteIdentifier)(t.name)),r.push(" is ")),r.push(...Ixt(t.field)),r}function $xt(t){const e=[],r=t.length===1;return r&&e.push(...I2(t[0].field.annotations)),e.push(...L2("group_by",t.map(i=>Txe(i,r)))),e}function kxt(t){const e=[],r=t.length===1;return r&&e.push(...I2(t[0].field.annotations)),e.push(...L2("aggregate",t.map(i=>Txe(i,r)))),e}function Mxt(t){return L2("order_by",t.map(Pxt),",")}function Pxt(t){const e=[];return e.push(...Vc(t.field_reference)),t.direction&&(e.push(" "),e.push(t.direction)),e}function Uxt(t){const e=[],r=t.length===1;return r&&e.push(...I2(t[0].view.annotations)),e.push(...L2("nest",t.map(i=>jxt(i,r)))),e}function jxt(t,e=!1){const r=[];return e||r.push(...I2(t.view.annotations)),t.name&&(r.push((0,CE.maybeQuoteIdentifier)(t.name)),r.push(" is ")),r.push(...qxt(t.view)),r}function qxt(t){return xd(t.definition)}function Hxt(t){return[`limit: ${t.limit}`]}function Qxt(t){const e=[];for(let r=0;r<t.length;r++)r!==0&&e.push(yu),e.push(...Hxt(t[r]));return e}function Rxe(t){return L2("where",t.map(Oxe),",")}function zxt(t){return L2("having",t.map(Oxe),",")}const Gxt=["`","'",'"'];function Dxe(t){let e,r;for(const i of Gxt){const s=Wxt(t,i);if(s===t)return`f${i}${t}${i}`;(r===void 0||s.length<r.length)&&(e=i,r=s)}return`f${e}${r}${e}`}function Wxt(t,e){let r="";for(let i=0;i<t.length;i++)t.slice(i).startsWith(e)?(r+="\\"+e,i+=e.length):(r+=t[i],t[i]==="\\"&&(r+=t[++i]));return r}function Oxe(t){switch(t.filter.kind){case"filter_string":return[...Vc(t.filter.field_reference)," ~ ",Dxe(t.filter.filter)]}}function I2(t){return t?t.flatMap(Vxt):[]}function Vxt(t){return[t.value.trim(),yu]}var Ma={};Object.defineProperty(Ma,"__esModule",{value:!0}),Ma.convertToThrift=Ma.convertFromThrift=Ma.unnestUnions=Ma.nestUnions=void 0;const Yxt=vE;function uP(t){if(t==null)return t;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(uP);{const e={};let r;for(const i in t)i==="kind"?r=t[i]:e[i]=uP(t[i]);return r===void 0?e:{[r]:e}}}Ma.nestUnions=uP;function PR(t,e){if(t==null)return t;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(r=>PR(r,e));{const r=B2(e);if(r.type==="union"){for(const i in r.options)if(t[i]!==void 0){const s=PR(t[i],r.options[i]);if(typeof s=="object")return{kind:i,...s}}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=PR(t[s],o.type)}return i}else throw new Error(`Cannot unnest unions in an enum type ${e}`)}}Ma.unnestUnions=PR;function UR(t,e){if(t==null)return t;if(typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number"){if(e==="number")return t;const r=B2(e);if(r.type!=="enum")throw new Error(`Found a number where a ${e} was expected`);const i=Object.entries(r.values).find(([,s])=>s===t);if(i===void 0)throw new Error(`${t} is not a valid enum value for ${e}`);return i[0]}else{if(Array.isArray(t))return t.map(r=>UR(r,e));{const r=B2(e);if(r.type==="union"){for(const i in r.options)if(t[i]!==void 0){const s=UR(t[i],r.options[i]);if(typeof s=="object")return{kind:i,...s}}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=UR(t[s],o.type)}return i}else throw new Error(`Cannot unnest unions in an enum type ${e}`)}}}Ma.convertFromThrift=UR;function B2(t){const e=Yxt.MALLOY_INTERFACE_TYPES[t];if(e===void 0)throw new Error(`Unknown Malloy interface type ${t}`);return e}function jR(t,e){if(t==null)return t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string"){if(e==="string")return t;const r=B2(e);if(r.type==="enum"){const i=r.values[t];if(i===void 0)throw new Error(`${t} is not a valid enum value for ${e}`);return i}}else{if(Array.isArray(t))return t.map(r=>jR(r,e));{const r=B2(e);if(r.type==="union"){const i=t.kind,s=r.options[i];if(s===void 0)throw new Error(`${i} is not a valid union of ${e}`);const o=B2(s);if(o.type!=="struct")throw new Error("Union fields must be structs");const u={};for(const a in t){if(a==="kind")continue;const l=o.fields[a];u[a]=jR(t[a],l.type)}return{[i]:u}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=jR(t[s],o.type)}return i}}}}Ma.convertToThrift=jR,function(t){var e=T&&T.__createBinding||(Object.create?function(o,u,a,l){l===void 0&&(l=a);var c=Object.getOwnPropertyDescriptor(u,a);(!c||("get"in c?!u.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return u[a]}}),Object.defineProperty(o,l,c)}:function(o,u,a,l){l===void 0&&(l=a),o[l]=u[a]}),r=T&&T.__exportStar||function(o,u){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(u,a)&&e(u,o,a)};Object.defineProperty(t,"__esModule",{value:!0}),t.thingy4sddfdfsd=t.thingy4sdfsd=t.thingy4dfdsfs=t.thingy4asdfas=t.thingy4asdfasdf=t.thingy3dfdf=t.thingy3=t.thingy2asdf=t.thingyssdfg=t.thingy123r=t.thingy1=t.res=t.test=t.convertToThrift=t.convertFromThrift=t.unnestUnions=t.nestUnions=t.queryToMalloy=void 0,r(vE,t);var i=BR;Object.defineProperty(t,"queryToMalloy",{enumerable:!0,get:function(){return i.queryToMalloy}});var s=Ma;Object.defineProperty(t,"nestUnions",{enumerable:!0,get:function(){return s.nestUnions}}),Object.defineProperty(t,"unnestUnions",{enumerable:!0,get:function(){return s.unnestUnions}}),Object.defineProperty(t,"convertFromThrift",{enumerable:!0,get:function(){return s.convertFromThrift}}),Object.defineProperty(t,"convertToThrift",{enumerable:!0,get:function(){return s.convertToThrift}}),t.test={entries:[{kind:"source",name:"flights",schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"boolean_type"},annotations:[{value:"# foo=1"}]},{kind:"dimension",name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}},{kind:"dimension",name:"arr_rec",type:{kind:"array_type",element_type:{kind:"record_type",fields:[{name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}}]}}},{kind:"dimension",name:"rec",type:{kind:"record_type",fields:[{name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}}]}},{kind:"join",name:"carriers",relationship:"one",schema:{fields:[{kind:"dimension",name:"code",type:{kind:"string_type"}}]}},{kind:"view",name:"by_carrier",schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"string_type"}},{kind:"dimension",name:"flight_count",type:{kind:"number_type"}}]}}]},parameters:[{name:"param",type:{kind:"number_type"},default_value:{kind:"number_literal",number_value:7}}]}],anonymous_queries:[]},t.res={connection_name:"foo",data:{kind:"array_cell",array_value:[{kind:"record_cell",record_value:[{kind:"string_cell",string_value:"UA"},{kind:"number_cell",number_value:12341234}]},{kind:"record_cell",record_value:[{kind:"string_cell",string_value:"AA"},{kind:"number_cell",number_value:2343}]}]},schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"string_type"}},{kind:"dimension",name:"flight_count",type:{kind:"number_type"}}]},sql:"SELECT * ..."},t.thingy1={definition:{kind:"query_reference",name:"flights_by_carrier"}},t.thingy123r={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"view_reference",name:"by_carrier"}}},t.thingyssdfg={definition:{kind:"refinement",base:{kind:"query_reference",name:"flights"},refinement:{kind:"view_reference",name:"by_carrier"}}},t.thingy2asdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"where",filter:{kind:"filter_string",field_reference:{name:"carrier"},filter:"WN"}}]}}}},t.thingy3={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"group_by",field:{expression:{kind:"field_reference",name:"foo"}}}]}}}},t.thingy3dfdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"view_reference",name:"top10"}}}},t.thingy4asdfasdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"group_by",field:{expression:{kind:"field_reference",name:"foo"}}}]}}},t.thingy4asdfas={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"view_reference",name:"by_carrier"}}},t.thingy4dfdsfs={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"limit",limit:10}]}}}},t.thingy4sdfsd={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"limit",limit:10}]}}},t.thingy4sddfdfsd={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[]}}}}(rP);var nn={},Kxt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Jxt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Xxt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Kxt(e,t,r);return Jxt(e,t),e};Object.defineProperty(nn,"__esModule",{value:!0}),nn.statedCompileQuery=nn.newCompileQueryState=nn.hasErrors=nn.compileSource=nn.compileModel=nn._statedCompileModel=nn.statedCompileSource=nn.statedCompileModel=nn.newCompileSourceState=nn.newCompileModelState=nn.updateCompileModelState=nn.compileQuery=void 0;const Zxt=Xxt(rP),edt=H4,Fxe=Pi,tdt=La,wxe=Yl,ndt=ui,Nxe=Zo,dd=mE;function Lxe(t,e){return`${t}:${e}`}function rdt(t,e){return{type:"sql_select",selectStr:t.sql,connection:t.connection_name,dialect:e,fields:t.schema?Bxe(t.schema):[],name:(0,wxe.sqlKey)(t.connection_name,t.sql)}}function idt(t,e){return{type:"table",tablePath:t.name,connection:t.connection_name,dialect:e,fields:t.schema?Bxe(t.schema):[],name:Lxe(t.connection_name,t.name)}}function sdt(t){if(t!==void 0)return t==="decimal"?"float":"integer"}function Ixe(t){switch(t.kind){case"string_type":return{type:"string"};case"number_type":return{type:"number",numberType:sdt(t.subtype)};case"boolean_type":return{type:"boolean"};case"timestamp_type":return{type:"timestamp",timeframe:t.timeframe};case"date_type":return{type:"date",timeframe:t.timeframe};case"sql_native_type":return{type:"sql native",rawType:t.sql_type};case"json_type":return{type:"json"};case"array_type":{if(t.element_type.kind==="record_type")return{type:"array",elementTypeDef:{type:"record_element"},fields:t.element_type.fields.map(aP)};{const e=Ixe(t.element_type);if(e.type==="record")throw new Error("Arrays of records should be a repeated record type");return{type:"array",elementTypeDef:e}}}case"record_type":return{type:"record",fields:t.fields.map(aP)}}}function aP(t){var e;const r=Ixe(t.type);return{...(0,Fxe.mkFieldDef)(r,t.name),annotation:t.annotations&&t.annotations.length?{notes:(e=t.annotations)===null||e===void 0?void 0:e.map(i=>({text:i.value,at:{url:"~internal~",range:dd.DEFAULT_LOG_RANGE}}))}:void 0}}function odt(t){if(t.kind!=="dimension")throw new Error("Table schemas must only have dimension fields");return aP(t)}function Bxe(t){const e=[];for(const r of t.fields)e.push(odt(r));return e}function $xe(t){var e,r,i,s,o,u;const a={urls:{},tables:{},compileSQL:{},translations:{}};if(t){for(const l of(e=t.files)!==null&&e!==void 0?e:[])l.contents!==void 0&&(a.urls[l.url]=l.contents);for(const l of(r=t.table_schemas)!==null&&r!==void 0?r:[]){const c=(i=t.connections)===null||i===void 0?void 0:i.find(f=>f.name===l.connection_name);c&&l.schema&&c.dialect&&(a.tables[Lxe(l.connection_name,l.name)]=idt(l,c.dialect))}for(const l of(s=t.sql_schemas)!==null&&s!==void 0?s:[]){const c=(o=t.connections)===null||o===void 0?void 0:o.find(f=>f.name===l.connection_name);c&&c.dialect&&(a.compileSQL[(0,wxe.sqlKey)(l.connection_name,l.sql)]=rdt(l,c.dialect))}for(const l of(u=t.translations)!==null&&u!==void 0?u:[])if(l.compiled_model_json){const c=JSON.parse(l.compiled_model_json);a.translations[l.url]=c}}return a}function kxe(t,e,r){var i,s,o;const u={},a=new Set;if(t!==void 0&&(u.sql_schemas=[{sql:t.selectStr,connection_name:t.connection}],a.add(t.connection)),e!==void 0)for(const l of e)(i=u.files)!==null&&i!==void 0||(u.files=[]),u.files.push({url:l});if(r!==void 0)for(const l in r){const c=r[l],f=(s=c.connectionName)!==null&&s!==void 0?s:"__default__";(o=u.table_schemas)!==null&&o!==void 0||(u.table_schemas=[]),u.table_schemas.push({name:c.tablePath,connection_name:f}),a.add(f)}return a.size>0&&(u.connections=Array.from(a).map(l=>({name:l}))),u}function udt(t,e){return e??(e=qxe(t)),Hxe(e)}nn.compileQuery=udt;function adt(t,e){function r(s,o){var u,a,l,c;s.translator.update(o),s.extending&&r(s.extending,o),s.hasSource||(s.hasSource=((a=(u=e==null?void 0:e.files)===null||u===void 0?void 0:u.some(f=>f.url===s.translator.sourceURL))!==null&&a!==void 0?a:!1)||((c=(l=e==null?void 0:e.translations)===null||l===void 0?void 0:l.some(f=>f.url===s.translator.sourceURL))!==null&&c!==void 0?c:!1))}const i=$xe(e);r(t,i)}nn.updateCompileModelState=adt;function qR(t,e,r){var i,s,o,u;const a=new edt.MalloyTranslator(t,null,$xe(e)),l=((s=(i=e==null?void 0:e.files)===null||i===void 0?void 0:i.some(c=>c.url===t))!==null&&s!==void 0?s:!1)||((u=(o=e==null?void 0:e.translations)===null||o===void 0?void 0:o.some(c=>c.url===t))!==null&&u!==void 0?u:!1);return r?{extending:qR(r,e),translator:a,done:!1,hasSource:l}:{translator:a,done:!1,hasSource:l}}function Mxe(t){return qR(t.model_url,t.compiler_needs,t.extend_model_url)}nn.newCompileModelState=Mxe;function Pxe(t){return qR(t.model_url,t.compiler_needs,t.extend_model_url)}nn.newCompileSourceState=Pxe;function Uxe(t){return ldt(SE(t),t.translator.sourceURL)}nn.statedCompileModel=Uxe;function jxe(t,e){return xdt(SE(t),e,t.translator.sourceURL)}nn.statedCompileSource=jxe;function SE(t){let e;if(t.extending){if(!t.extending.done){const i=SE(t.extending);if(!t.extending.done)return i}e=t.extending.translator.modelDef}if(!t.hasSource)return{compilerNeeds:kxe(void 0,[t.translator.sourceURL],void 0)};const r=t.translator.translate(e);if(r.final){if(t.done=!0,r.modelDef)return{model:(0,tdt.modelDefToModelInfo)(r.modelDef),modelDef:r.modelDef};if(r.problems===void 0||r.problems.length===0)throw new Error("No problems found, but no model either");return{logs:r.problems}}else return{compilerNeeds:kxe(r.compileSQL,r.urls,r.tables),logs:r.problems}}nn._statedCompileModel=SE;function ldt(t,e){const r=t.logs?(0,dd.mapLogs)(t.logs,e):void 0;if(t.compilerNeeds)return{compiler_needs:t.compilerNeeds,logs:r};{let i;return t.modelDef&&(i=[{url:e,compiled_model_json:JSON.stringify(t.modelDef)}]),{model:t.model,logs:r,translations:i}}}function cdt(t,e){return e??(e=Mxe(t)),Uxe(e)}nn.compileModel=cdt;function fdt(t){const e=Pxe(t);return jxe(e,t.name)}nn.compileSource=fdt;function xdt(t,e,r){const i=t.logs?(0,dd.mapLogs)(t.logs,r):void 0;if(t.model){const s=t.model.entries.find(o=>o.name===e);return s===void 0?{logs:[...i??[],{url:r,severity:"error",message:`Model does not contain a source named ${e}`,range:dd.DEFAULT_LOG_RANGE}]}:{source:s,logs:i}}else return{compiler_needs:t.compilerNeeds,logs:i}}function ddt(t){var e;return(e=t==null?void 0:t.some(r=>r.severity==="error"))!==null&&e!==void 0?e:!1}nn.hasErrors=ddt;function qxe(t){var e,r;const i=Zxt.queryToMalloy(t.query),s={...(e=t.compiler_needs)!==null&&e!==void 0?e:{}},o="internal://query.malloy";return s.files=[{url:o,contents:i},...(r=s.files)!==null&&r!==void 0?r:[]],{...qR(o,s,t.model_url),defaultRowLimit:t.default_row_limit}}nn.newCompileQueryState=qxe;function Hxe(t){var e;const r=SE(t),i=t.translator.sourceURL,s=r.logs?(0,dd.mapLogs)(r.logs,i):void 0;if(r.model){const o=r.modelDef.queryList;if(o.length===0)return{logs:[...s??[],{url:i,severity:"error",message:"Internal error: No queries found",range:dd.DEFAULT_LOG_RANGE}]};const u=o.length-1,a=r.modelDef.queryList[u],l=r.model.anonymous_queries[u].schema,c=(e=r.model.anonymous_queries[u].annotations)!==null&&e!==void 0?e:[];try{const x=new Fxe.QueryModel(r.modelDef).compileQuery(a,{defaultRowLimit:t.defaultRowLimit}),h=(0,ndt.annotationToTaglines)(r.modelDef.annotation).map(p=>({value:p}));return c.push({value:Nxe.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore).toString()}),x.queryName&&c.push({value:Nxe.Tag.withPrefix("#(malloy) ").set(["query_name"],x.queryName).toString()}),{result:{sql:x.sql,schema:l,connection_name:x.connectionName,annotations:c.length>0?c:void 0,model_annotations:h.length>0?h:void 0,query_timezone:x.queryTimezone},default_row_limit_added:x.defaultRowLimitAdded}}catch(f){return{logs:[...s??[],{url:i,severity:"error",message:`Internal compiler error: ${f.message}`,range:dd.DEFAULT_LOG_RANGE}]}}}else return{compiler_needs:r.compilerNeeds,logs:s}}nn.statedCompileQuery=Hxe;var hdt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),pdt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Qxe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&hdt(e,t,r);return pdt(e,t),e};Object.defineProperty(Wc,"__esModule",{value:!0}),Wc.compileQuery=Wc.compileSource=Wc.compileModel=void 0;const mdt=Qxe(rP),Pa=Qxe(nn),gdt=Pp;function ydt(t,e){return t.type==="compile_model"?e.type!=="compile_model"?!1:t.modelURL===e.modelURL&&t.extendModelURL===e.extendModelURL:t.type==="compile_source"?e.type!=="compile_source"?!1:t.modelURL===e.modelURL&&t.extendModelURL===e.extendModelURL&&t.name===e.name:e.type!=="compile_query"?!1:t.modelURL===e.modelURL&&t.queryString===e.queryString}class Edt{constructor(){this.sessions=new Map}purgeExpired(e){const r=new Date;for(const i of this.sessions.values())i.sessionId!==(e==null?void 0:e.except)&&i.expires&&i.expires<r&&this.sessions.delete(i.sessionId)}findSession(e,r){const i=this.sessions.get(e);if(i&&ydt(i.sessionInfo,r))return i}getExpires(e){return e instanceof Date?e:new Date(Date.now()+e.seconds*1e3)}newSessionId(){let e;do e=(0,gdt.v4)();while(this.sessions.has(e));return e}newCompileModelSession(e,r,i){const s=i!=null&&i.ttl?this.getExpires(i.ttl):void 0,o=Pa.newCompileModelState(e);return{type:"compile_model",sessionInfo:r,state:o,expires:s,sessionId:this.newSessionId()}}newCompileSourceSession(e,r,i){const s=i!=null&&i.ttl?this.getExpires(i.ttl):void 0,o=Pa.newCompileSourceState(e);return{type:"compile_source",sessionInfo:r,state:o,expires:s,sessionId:this.newSessionId()}}newCompileQuerySession(e,r,i){const s=i!=null&&i.ttl?this.getExpires(i.ttl):void 0,o=Pa.newCompileQueryState(e);return{type:"compile_query",sessionInfo:r,state:o,expires:s,sessionId:this.newSessionId()}}findCompileModelSession(e,r){const i=this.findSession(e,r);if((i==null?void 0:i.type)==="compile_model")return i}killSession(e){this.sessions.delete(e)}hasErrors(e){return Pa.hasErrors(e)}compileModel(e,r){const i={type:"compile_model",modelURL:e.model_url,extendModelURL:e.extend_model_url};let s=(r==null?void 0:r.session_id)&&this.findCompileModelSession(r.session_id,i);this.purgeExpired({except:r==null?void 0:r.session_id}),s?(r!=null&&r.ttl&&(s.expires=this.getExpires(r.ttl)),Pa.updateCompileModelState(s.state,e.compiler_needs)):(s=this.newCompileModelSession(e,i,r),this.sessions.set(s.sessionId,s));const o=Pa.statedCompileModel(s.state);return(o.model||this.hasErrors(o.logs))&&this.killSession(s.sessionId),{...o,session_id:s.sessionId}}findCompileSourceSession(e,r){const i=this.findSession(e,r);if((i==null?void 0:i.type)==="compile_source")return i}compileSource(e,r){const i={type:"compile_source",modelURL:e.model_url,name:e.name,extendModelURL:e.extend_model_url};let s=(r==null?void 0:r.session_id)&&this.findCompileSourceSession(r.session_id,i);this.purgeExpired({except:r==null?void 0:r.session_id}),s?(r!=null&&r.ttl&&(s.expires=this.getExpires(r.ttl)),Pa.updateCompileModelState(s.state,e.compiler_needs)):(s=this.newCompileSourceSession(e,i,r),this.sessions.set(s.sessionId,s));const o=Pa.statedCompileSource(s.state,e.name);return(o.source||this.hasErrors(o.logs))&&this.killSession(s.sessionId),{...o,session_id:s.sessionId}}findCompileQuerySession(e,r){const i=this.findSession(e,r);if((i==null?void 0:i.type)==="compile_query")return i}compileQuery(e,r){const i=mdt.queryToMalloy(e.query),s={type:"compile_query",modelURL:e.model_url,queryString:i,query:e.query};let o=(r==null?void 0:r.session_id)&&this.findCompileQuerySession(r.session_id,s);this.purgeExpired({except:r==null?void 0:r.session_id}),o?(r!=null&&r.ttl&&(o.expires=this.getExpires(r.ttl)),Pa.updateCompileModelState(o.state,e.compiler_needs)):(o=this.newCompileQuerySession(e,s,r),this.sessions.set(o.sessionId,o));const u=Pa.statedCompileQuery(o.state);return(u.result||this.hasErrors(u.logs))&&this.killSession(o.sessionId),{...u,session_id:o.sessionId}}}const lP=new Edt;function Adt(t,e){return lP.compileModel(t,e)}Wc.compileModel=Adt;function _dt(t,e){return lP.compileSource(t,e)}Wc.compileSource=_dt;function vdt(t,e){return lP.compileQuery(t,e)}Wc.compileQuery=vdt;var Yc={},Cdt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Sdt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),bdt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Cdt(e,t,r);return Sdt(e,t),e};Object.defineProperty(Yc,"__esModule",{value:!0}),Yc.compileQuery=Yc.compileSource=Yc.compileModel=void 0;const cP=bdt(nn);function Tdt(t){return cP.compileModel(t)}Yc.compileModel=Tdt;function Rdt(t){return cP.compileSource(t)}Yc.compileSource=Rdt;function Ddt(t){return cP.compileQuery(t)}Yc.compileQuery=Ddt;var Ua={},Odt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Fdt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),wdt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Odt(e,t,r);return Fdt(e,t),e};Object.defineProperty(Ua,"__esModule",{value:!0}),Ua.runQuery=Ua.compileQuery=Ua.compileSource=Ua.compileModel=void 0;const vo=wdt(nn),zxe=mE;async function fP(t,e){var r,i,s,o,u,a,l,c,f;if(t===void 0)throw new Error("Expected compiler to have needs because it didn't return a result");const x={};if(t.connections)for(const h of t.connections){const p=await e.connections.lookupConnection(h.name);(r=x.connections)!==null&&r!==void 0||(x.connections=[]),x.connections.push({...h,dialect:p.dialectName})}if(t.files)for(const h of t.files){const p=await e.urls.readURL(new URL(h.url));(i=x.files)!==null&&i!==void 0||(x.files=[]),typeof p=="string"?x.files.push({...h,contents:p}):x.files.push({...h,contents:p.contents,invalidation_key:(s=p.invalidationKey)===null||s===void 0?void 0:s.toString()})}if(t.table_schemas){const h={};for(const p of t.table_schemas)(o=h[c=p.connection_name])!==null&&o!==void 0||(h[c]=[]),h[p.connection_name].push(p);for(const p in h){const m=await e.connections.lookupConnection(p),g=h[p].map(E=>E.name),y=await Promise.all(g.map(async E=>({name:E,schema:await m.fetchSchemaForTable(E)})));(u=x.table_schemas)!==null&&u!==void 0||(x.table_schemas=[]);for(const E of y)x.table_schemas.push({connection_name:p,name:E.name,schema:E.schema})}}if(t.sql_schemas){const h={};for(const p of t.sql_schemas)(a=h[f=p.connection_name])!==null&&a!==void 0||(h[f]=[]),h[p.connection_name].push(p);for(const p in h){const m=await e.connections.lookupConnection(p),g=h[p].map(E=>E.sql),y=await Promise.all(g.map(async E=>({sql:E,schema:await m.fetchSchemaForSQLQuery(E)})));(l=x.sql_schemas)!==null&&l!==void 0||(x.sql_schemas=[]);for(const E of y)x.sql_schemas.push({connection_name:p,sql:E.sql,schema:E.schema})}}return x}async function Ndt(t,e){const r=vo.newCompileModelState(t);for(;;){const i=vo.statedCompileModel(r);if(i.model||vo.hasErrors(i.logs))return i;const s=await fP(i.compiler_needs,e);vo.updateCompileModelState(r,s)}}Ua.compileModel=Ndt;async function Ldt(t,e){const r=vo.newCompileSourceState(t);for(;;){const i=vo.statedCompileSource(r,t.name);if(i.source||vo.hasErrors(i.logs))return i;const s=await fP(i.compiler_needs,e);vo.updateCompileModelState(r,s)}}Ua.compileSource=Ldt;async function Gxe(t,e){const r=vo.newCompileQueryState(t);for(;;){const i=vo.statedCompileQuery(r);if(i.result||vo.hasErrors(i.logs))return i;const s=await fP(i.compiler_needs,e);vo.updateCompileModelState(r,s)}}Ua.compileQuery=Gxe;async function Idt(t,e){var r,i;const s=await Gxe(t,e);if(s.result===void 0)return s;const o=t.model_url;if(s.result.sql===void 0)return{logs:[...(r=s.logs)!==null&&r!==void 0?r:[],{url:o,severity:"error",message:"Internal error: Compiler did not generate SQL",range:zxe.DEFAULT_LOG_RANGE}]};try{const a=await(await e.connections.lookupConnection(s.result.connection_name)).runSQL(s.result.sql,s.result.schema);return{...s,result:{...s.result,data:a}}}catch(u){return{...s,logs:[...(i=s.logs)!==null&&i!==void 0?i:[],{url:o,severity:"error",message:`Error running SQL: ${u.message}`,range:zxe.DEFAULT_LOG_RANGE}]}}}Ua.runQuery=Idt;var Wxe={};Object.defineProperty(Wxe,"__esModule",{value:!0}),function(t){var e=T&&T.__createBinding||(Object.create?function(o,u,a,l){l===void 0&&(l=a);var c=Object.getOwnPropertyDescriptor(u,a);(!c||("get"in c?!u.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return u[a]}}),Object.defineProperty(o,l,c)}:function(o,u,a,l){l===void 0&&(l=a),o[l]=u[a]}),r=T&&T.__setModuleDefault||(Object.create?function(o,u){Object.defineProperty(o,"default",{enumerable:!0,value:u})}:function(o,u){o.default=u}),i=T&&T.__importStar||function(o){if(o&&o.__esModule)return o;var u={};if(o!=null)for(var a in o)a!=="default"&&Object.prototype.hasOwnProperty.call(o,a)&&e(u,o,a);return r(u,o),u},s=T&&T.__exportStar||function(o,u){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(u,a)&&e(u,o,a)};Object.defineProperty(t,"__esModule",{value:!0}),t.util=t.asynchronous=t.stateless=t.sessioned=void 0,t.sessioned=i(Wc),t.stateless=i(Yc),t.asynchronous=i(Ua),s(Wxe,t),t.util=i(mE)}(Cxe),function(t){var e=T&&T.__createBinding||(Object.create?function(h,p,m,g){g===void 0&&(g=m);var y=Object.getOwnPropertyDescriptor(p,m);(!y||("get"in y?!p.__esModule:y.writable||y.configurable))&&(y={enumerable:!0,get:function(){return p[m]}}),Object.defineProperty(h,g,y)}:function(h,p,m,g){g===void 0&&(g=m),h[g]=p[m]}),r=T&&T.__setModuleDefault||(Object.create?function(h,p){Object.defineProperty(h,"default",{enumerable:!0,value:p})}:function(h,p){h.default=p}),i=T&&T.__importStar||function(h){if(h&&h.__esModule)return h;var p={};if(h!=null)for(var m in h)m!=="default"&&Object.prototype.hasOwnProperty.call(h,m)&&e(p,h,m);return r(p,h),p};Object.defineProperty(t,"__esModule",{value:!0}),t.EmptyURLReader=t.SingleConnectionRuntime=t.ConnectionRuntime=t.AtomicFieldType=t.Runtime=t.Malloy=t.Model=t.MalloyTranslator=t.malloyToQuery=t.composeSQLExpr=t.indent=t.expressionIsUngroupedAggregate=t.expressionIsScalar=t.expressionIsCalculation=t.expressionIsAnalytic=t.expressionIsAggregate=t.mkFieldDef=t.mkArrayDef=t.isBasicArray=t.isRepeatedRecord=t.isSamplingRows=t.isSamplingPercent=t.isSamplingEnable=t.isJoinedSource=t.isJoined=t.isBasicAtomic=t.Segment=t.isSourceDef=t.TinyParser=t.Dialect=t.spread=t.literal=t.variadicParam=t.param=t.makeParam=t.sql=t.maxScalar=t.minAggregate=t.anyExprType=t.minScalar=t.overload=t.qtz=t.arg=t.registerDialect=t.MySQLDialect=t.SnowflakeDialect=t.PostgresDialect=t.TrinoDialect=t.StandardSQLDialect=t.DuckDBDialect=void 0,t.annotationToTaglines=t.annotationToTag=t.sqlKey=t.API=t.modelDefToModelInfo=t.toAsyncGenerator=t.CacheManager=t.InMemoryModelCache=t.Explore=t.DataWriter=t.Parse=t.JSONWriter=t.CSVWriter=t.QueryMaterializer=t.Result=t.PreparedResult=t.TimestampTimeframe=t.DateTimeframe=t.SourceRelationship=t.JoinRelationship=t.MalloyError=t.FixedConnectionMap=t.InMemoryURLReader=void 0;var s=kp;Object.defineProperty(t,"DuckDBDialect",{enumerable:!0,get:function(){return s.DuckDBDialect}}),Object.defineProperty(t,"StandardSQLDialect",{enumerable:!0,get:function(){return s.StandardSQLDialect}}),Object.defineProperty(t,"TrinoDialect",{enumerable:!0,get:function(){return s.TrinoDialect}}),Object.defineProperty(t,"PostgresDialect",{enumerable:!0,get:function(){return s.PostgresDialect}}),Object.defineProperty(t,"SnowflakeDialect",{enumerable:!0,get:function(){return s.SnowflakeDialect}}),Object.defineProperty(t,"MySQLDialect",{enumerable:!0,get:function(){return s.MySQLDialect}}),Object.defineProperty(t,"registerDialect",{enumerable:!0,get:function(){return s.registerDialect}}),Object.defineProperty(t,"arg",{enumerable:!0,get:function(){return s.arg}}),Object.defineProperty(t,"qtz",{enumerable:!0,get:function(){return s.qtz}}),Object.defineProperty(t,"overload",{enumerable:!0,get:function(){return s.overload}}),Object.defineProperty(t,"minScalar",{enumerable:!0,get:function(){return s.minScalar}}),Object.defineProperty(t,"anyExprType",{enumerable:!0,get:function(){return s.anyExprType}}),Object.defineProperty(t,"minAggregate",{enumerable:!0,get:function(){return s.minAggregate}}),Object.defineProperty(t,"maxScalar",{enumerable:!0,get:function(){return s.maxScalar}}),Object.defineProperty(t,"sql",{enumerable:!0,get:function(){return s.sql}}),Object.defineProperty(t,"makeParam",{enumerable:!0,get:function(){return s.makeParam}}),Object.defineProperty(t,"param",{enumerable:!0,get:function(){return s.param}}),Object.defineProperty(t,"variadicParam",{enumerable:!0,get:function(){return s.variadicParam}}),Object.defineProperty(t,"literal",{enumerable:!0,get:function(){return s.literal}}),Object.defineProperty(t,"spread",{enumerable:!0,get:function(){return s.spread}}),Object.defineProperty(t,"Dialect",{enumerable:!0,get:function(){return s.Dialect}}),Object.defineProperty(t,"TinyParser",{enumerable:!0,get:function(){return s.TinyParser}});var o=Pi;Object.defineProperty(t,"isSourceDef",{enumerable:!0,get:function(){return o.isSourceDef}}),Object.defineProperty(t,"Segment",{enumerable:!0,get:function(){return o.Segment}}),Object.defineProperty(t,"isBasicAtomic",{enumerable:!0,get:function(){return o.isBasicAtomic}}),Object.defineProperty(t,"isJoined",{enumerable:!0,get:function(){return o.isJoined}}),Object.defineProperty(t,"isJoinedSource",{enumerable:!0,get:function(){return o.isJoinedSource}}),Object.defineProperty(t,"isSamplingEnable",{enumerable:!0,get:function(){return o.isSamplingEnable}}),Object.defineProperty(t,"isSamplingPercent",{enumerable:!0,get:function(){return o.isSamplingPercent}}),Object.defineProperty(t,"isSamplingRows",{enumerable:!0,get:function(){return o.isSamplingRows}}),Object.defineProperty(t,"isRepeatedRecord",{enumerable:!0,get:function(){return o.isRepeatedRecord}}),Object.defineProperty(t,"isBasicArray",{enumerable:!0,get:function(){return o.isBasicArray}}),Object.defineProperty(t,"mkArrayDef",{enumerable:!0,get:function(){return o.mkArrayDef}}),Object.defineProperty(t,"mkFieldDef",{enumerable:!0,get:function(){return o.mkFieldDef}}),Object.defineProperty(t,"expressionIsAggregate",{enumerable:!0,get:function(){return o.expressionIsAggregate}}),Object.defineProperty(t,"expressionIsAnalytic",{enumerable:!0,get:function(){return o.expressionIsAnalytic}}),Object.defineProperty(t,"expressionIsCalculation",{enumerable:!0,get:function(){return o.expressionIsCalculation}}),Object.defineProperty(t,"expressionIsScalar",{enumerable:!0,get:function(){return o.expressionIsScalar}}),Object.defineProperty(t,"expressionIsUngroupedAggregate",{enumerable:!0,get:function(){return o.expressionIsUngroupedAggregate}}),Object.defineProperty(t,"indent",{enumerable:!0,get:function(){return o.indent}}),Object.defineProperty(t,"composeSQLExpr",{enumerable:!0,get:function(){return o.composeSQLExpr}});var u=H4;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return u.malloyToQuery}}),Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return u.MalloyTranslator}});var a=we;Object.defineProperty(t,"Model",{enumerable:!0,get:function(){return a.Model}}),Object.defineProperty(t,"Malloy",{enumerable:!0,get:function(){return a.Malloy}}),Object.defineProperty(t,"Runtime",{enumerable:!0,get:function(){return a.Runtime}}),Object.defineProperty(t,"AtomicFieldType",{enumerable:!0,get:function(){return a.AtomicFieldType}}),Object.defineProperty(t,"ConnectionRuntime",{enumerable:!0,get:function(){return a.ConnectionRuntime}}),Object.defineProperty(t,"SingleConnectionRuntime",{enumerable:!0,get:function(){return a.SingleConnectionRuntime}}),Object.defineProperty(t,"EmptyURLReader",{enumerable:!0,get:function(){return a.EmptyURLReader}}),Object.defineProperty(t,"InMemoryURLReader",{enumerable:!0,get:function(){return a.InMemoryURLReader}}),Object.defineProperty(t,"FixedConnectionMap",{enumerable:!0,get:function(){return a.FixedConnectionMap}}),Object.defineProperty(t,"MalloyError",{enumerable:!0,get:function(){return a.MalloyError}}),Object.defineProperty(t,"JoinRelationship",{enumerable:!0,get:function(){return a.JoinRelationship}}),Object.defineProperty(t,"SourceRelationship",{enumerable:!0,get:function(){return a.SourceRelationship}}),Object.defineProperty(t,"DateTimeframe",{enumerable:!0,get:function(){return a.DateTimeframe}}),Object.defineProperty(t,"TimestampTimeframe",{enumerable:!0,get:function(){return a.TimestampTimeframe}}),Object.defineProperty(t,"PreparedResult",{enumerable:!0,get:function(){return a.PreparedResult}}),Object.defineProperty(t,"Result",{enumerable:!0,get:function(){return a.Result}}),Object.defineProperty(t,"QueryMaterializer",{enumerable:!0,get:function(){return a.QueryMaterializer}}),Object.defineProperty(t,"CSVWriter",{enumerable:!0,get:function(){return a.CSVWriter}}),Object.defineProperty(t,"JSONWriter",{enumerable:!0,get:function(){return a.JSONWriter}}),Object.defineProperty(t,"Parse",{enumerable:!0,get:function(){return a.Parse}}),Object.defineProperty(t,"DataWriter",{enumerable:!0,get:function(){return a.DataWriter}}),Object.defineProperty(t,"Explore",{enumerable:!0,get:function(){return a.Explore}}),Object.defineProperty(t,"InMemoryModelCache",{enumerable:!0,get:function(){return a.InMemoryModelCache}}),Object.defineProperty(t,"CacheManager",{enumerable:!0,get:function(){return a.CacheManager}});var l=IR;Object.defineProperty(t,"toAsyncGenerator",{enumerable:!0,get:function(){return l.toAsyncGenerator}});var c=La;Object.defineProperty(t,"modelDefToModelInfo",{enumerable:!0,get:function(){return c.modelDefToModelInfo}}),t.API=i(Cxe);var f=Yl;Object.defineProperty(t,"sqlKey",{enumerable:!0,get:function(){return f.sqlKey}});var x=ui;Object.defineProperty(t,"annotationToTag",{enumerable:!0,get:function(){return x.annotationToTag}}),Object.defineProperty(t,"annotationToTaglines",{enumerable:!0,get:function(){return x.annotationToTaglines}})}(vB);class Bdt{constructor(e){this.document=e}async render(e,r){var l;let i;if(e&&(e instanceof vB.Result||"modelDef"in e)?i=vB.API.util.wrapResult(e):i=e,!r4(i.model_annotations,"## ").has("renderer_legacy"))if(!!((l=this.document.defaultView)!=null&&l.customElements.get("malloy-render"))){const f=this.document.createElement("malloy-render");f.malloyResult=i;const x=r.nextRendererOptions??{};for(const[h,p]of Object.entries(x))f[h]=p;return f}else console.warn("Tried to use the new Malloy renderer, but the malloy-render component was not found. Falling back to the legacy renderer.");const u=xue(i),a=Yxe(u.field,this.document,r,{size:"large"},u.field.queryTimezone,u.field.tag);try{return await a.render(u)}catch(c){return c instanceof Error?Gs(this.document,c):Gs(this.document,"Internal error - Exception not an Error object.")}}}class $dt{constructor(e){this.document=e}async render(e){const r=new mP(this.document);try{return await r.render(e)}catch(i){return i instanceof Error?Gs(this.document,i):Gs(this.document,"Internal error - Exception not an Error object.")}}}const Vxe={shape_map:"shape_map",point_map:"point_map",bar_chart:"bar_chart",image:"image",json:"json",segment_map:"segment_map",dashboard:"dashboard",line_chart:"line_chart",scatter_chart:"scatter_chart",url:"url",list:"list",list_detail:"list_detail",sparkline:"sparkline",sparkline_area:"sparkline",sparkline_column:"sparkline",sparkline_bar:"sparkline"};function kdt(t,e){const r=e[t.name],{name:i}=t;for(const s in Vxe)if(i.endsWith(`_${s}`)){const o=i.slice(0,i.length-s.length-1);return Mdt(s,o,Vxe,r)}return r}function Mdt(t,e,r,i){var s;return i?(i.renderer??(i.renderer=r[t]),i.data??(i.data={}),(s=i.data).label??(s.label=e)):i={renderer:r[t],data:{label:e}},i}function HR(t){if(t.isRecordOrRepeatedRecord())return t;throw new Error(`${t.name} does not contain fields and cannot be rendered this way`)}function Yxe(t,e,r,i,s,o){const u=kdt(t,r.dataStyles);r.dataStyles[t.name]=u;const a=new jL().create(u,o,e,i,r,t,s);if(a)return a;if((u==null?void 0:u.renderer)==="dashboard"||o.has("dashboard"))return QR(AB,e,HR(t),r,o);if((u==null?void 0:u.renderer)==="list"||o.has("list"))return QR(Eue,e,HR(t),r,o);if((u==null?void 0:u.renderer)==="list_detail"||o.has("list_detail"))return QR(mYe,e,HR(t),r,o);if((u==null?void 0:u.renderer)==="table"||o.has("table")||t.isRecordOrRepeatedRecord())return QR(Z2,e,HR(t),r,o);throw new Error(`Could not find a proper renderer for field ${t.name}`)}function QR(t,e,r,i,s){const o=wE.make(t,e,r,i,s),u={};return r.fields.forEach(a=>{u[a.name]=Yxe(a,e,i,o.defaultStylesForChildren,a.root().queryTimezone,a.tag)}),o.childRenderers=u,o}async function Pdt(t){const e=await Kxe(t);try{await navigator.clipboard.writeText(e)}catch(r){console.error("Failed to copy text: ",r)}}async function Kxe(t){let e="";const r=t.tableConfig??{},i=Object.assign({disableVirtualization:!0},r);t.tableConfig=i;const s=t.dashboardConfig??{},o=Object.assign({disableVirtualization:!0},s);if(t.dashboardConfig=o,await Udt(1e3),t.shadowRoot){let u="";for(const a of[...t.shadowRoot.adoptedStyleSheets]){for(let c=0;c<a.cssRules.length;c++){const f=a.cssRules.item(c);f&&(u+=`
1490
1490
  `+f.cssText)}u=u.replaceAll(":host",".malloy_html_host");const l=t.getAttribute("style");e=`
1491
1491
  <div>
1492
1492
  <style>
@@ -1500,4 +1500,4 @@ ${S}`,b)}else{if(C.urls)for(const S of C.urls)try{if(LR(S))throw new Error("In o
1500
1500
  ${t.shadowRoot.innerHTML}
1501
1501
  </div>
1502
1502
  </div>
1503
- `}}else e=t.innerHTML;return t.tableConfig=r,t.dashboardConfig=s,e}function Mdt(t){return new Promise(e=>{setTimeout(e,t)})}Hi.Currency=Yh,Hi.DataVolumeUnit=sc,Hi.DurationUnit=It,Hi.HTMLView=Ldt,Hi.JSONView=Idt,Hi.copyMalloyRenderHTML=kdt,Hi.getDataTree=xue,Hi.getMalloyRenderHTML=Kxe,Hi.isDurationUnit=Dre,Object.defineProperty(Hi,Symbol.toStringTag,{value:"Module"})});
1503
+ `}}else e=t.innerHTML;return t.tableConfig=r,t.dashboardConfig=s,e}function Udt(t){return new Promise(e=>{setTimeout(e,t)})}Hi.Currency=Yh,Hi.DataVolumeUnit=sc,Hi.DurationUnit=It,Hi.HTMLView=Bdt,Hi.JSONView=$dt,Hi.copyMalloyRenderHTML=Pdt,Hi.getDataTree=xue,Hi.getMalloyRenderHTML=Kxe,Hi.isDurationUnit=Dre,Object.defineProperty(Hi,Symbol.toStringTag,{value:"Module"})});