@dbml/parse 3.4.0 → 3.4.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,12 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I=require("lodash");var u=(t=>(t.SPACE="<space>",t.TAB="<tab>",t.NEWLINE="<newline>",t.COMMA="<comma>",t.LPAREN="<lparen>",t.RPAREN="<rparen>",t.LBRACE="<lbrace>",t.RBRACE="<rbrace>",t.LBRACKET="<lbracket>",t.RBRACKET="<rbracket>",t.LANGLE="<langle>",t.RANGLE="<rangle>",t.OP="<op>",t.EOF="<eof>",t.NUMERIC_LITERAL="<number>",t.STRING_LITERAL="<string>",t.COLOR_LITERAL="<color>",t.FUNCTION_EXPRESSION="<function-expression>",t.QUOTED_STRING="<variable>",t.IDENTIFIER="<identifier>",t.SEMICOLON="<semicolon>",t.COLON="<colon>",t.SINGLE_LINE_COMMENT="<single-line-comment>",t.MULTILINE_COMMENT="<multiline-comment>",t))(u||{});function jt(t){switch(t.kind){case"<newline>":case"<space>":case"<tab>":case"<single-line-comment>":case"<multiline-comment>":return!0;default:return!1}}function rt(t){if(!t)return!1;switch(t){case"+":case"-":case"*":case"/":case"%":case"<":case">":case"=":case"!":case".":case"&":case"|":return!0;default:return!1}}function at(t){return t!==void 0&&t.kind==="<op>"}class B{constructor(e,n,s,i,r){this.kind=e,this.startPos=n,this.endPos=s,this.value=i,this.leadingTrivia=[],this.trailingTrivia=[],this.leadingInvalid=[],this.trailingInvalid=[],this.isInvalid=r,this.start=n.offset,this.end=s.offset}static create(e,n,s,i,r){return new B(e,n,s,i,r)}}function bt(t){return t.trailingTrivia.find(({kind:e})=>e===u.NEWLINE)!==void 0}function ot(t,e){return e.leadingTrivia.find(({kind:s})=>s===u.NEWLINE)!==void 0||bt(t)}function Ce(t){return t.trailingTrivia.find(({kind:e})=>e===u.SPACE)!==void 0}function It(t){return t.trailingTrivia.length===0?t.end:It(I.last(t.trailingTrivia))}function Lt(t){return t.leadingTrivia.length===0?t.start:Lt(t.leadingTrivia[0])}function Wt(t){return[u.SINGLE_LINE_COMMENT,u.MULTILINE_COMMENT].includes(t.kind)}class Yt{constructor(){this.id=0}reset(){this.id=0}nextId(){return this.id++}}class k{constructor(e,n,s){this.id=e,this.kind=n;const i=s.find(a=>a!==void 0&&!Number.isNaN(a.start));i?(this.startPos=i.startPos,this.fullStart=i instanceof B?Lt(i):i.fullStart):(this.startPos={offset:NaN,column:NaN,line:NaN},this.fullStart=NaN);const r=[...s].reverse().find(a=>a!==void 0&&!Number.isNaN(a.end));r?(this.endPos=r.endPos,this.fullEnd=r instanceof B?It(r):r.fullEnd):(this.endPos={offset:NaN,column:NaN,line:NaN},this.fullEnd=NaN),this.start=this.startPos.offset,this.end=this.endPos.offset}}var de=(t=>(t.PROGRAM="<program>",t.ELEMENT_DECLARATION="<element-declaration>",t.ATTRIBUTE="<attribute>",t.IDENTIFIER_STREAM="<identifer-stream>",t.LITERAL="<literal>",t.VARIABLE="<variable>",t.PREFIX_EXPRESSION="<prefix-expression>",t.INFIX_EXPRESSION="<infix-expression>",t.POSTFIX_EXPRESSION="<postfix-expression>",t.FUNCTION_EXPRESSION="<function-expression>",t.FUNCTION_APPLICATION="<function-application>",t.BLOCK_EXPRESSION="<block-expression>",t.LIST_EXPRESSION="<list-expression>",t.TUPLE_EXPRESSION="<tuple-expression>",t.CALL_EXPRESSION="<call-expression>",t.PRIMARY_EXPRESSION="<primary-expression>",t.GROUP_EXPRESSION="<group-expression>",t.DUMMY="<dummy>",t.ARRAY="<array>",t))(de||{});class G extends k{constructor({body:e=[],eof:n},s){super(s,"<program>",[...e,n]),this.body=e,this.eof=n}}class A extends k{constructor({type:e,name:n,as:s,alias:i,attributeList:r,bodyColon:a,body:l},p){if(super(p,"<element-declaration>",[e,n,s,i,r,a,l]),l&&a&&!(l instanceof w||l instanceof A))throw new Error("If an element has a simple body, it must be a function application node");this.type=e,this.name=n,this.as=s,this.alias=i,this.attributeList=r,this.bodyColon=a,this.body=l}}class $ extends k{constructor({identifiers:e=[]},n){super(n,"<identifer-stream>",e||[]),this.identifiers=e}}class se extends k{constructor({name:e,colon:n,value:s},i){super(i,"<attribute>",[e,n,s]),this.name=e,this.value=s,this.colon=n}}class Q extends k{constructor({op:e,expression:n},s){super(s,"<prefix-expression>",[e,n]),this.op=e,this.expression=n}}class H extends k{constructor({op:e,leftExpression:n,rightExpression:s},i){super(i,"<infix-expression>",[n,e,s]),this.op=e,this.leftExpression=n,this.rightExpression=s}}class Pe extends k{constructor({op:e,expression:n},s){super(s,"<postfix-expression>",[n,e]),this.op=e,this.expression=n}}class te extends k{constructor({value:e},n){super(n,"<function-expression>",[e]),this.value=e}}class w extends k{constructor({callee:e,args:n=[]},s){super(s,"<function-application>",[e,...n]),this.callee=e,this.args=n}}class ne extends k{constructor({blockOpenBrace:e,body:n=[],blockCloseBrace:s},i){super(i,"<block-expression>",[e,...n,s]),this.blockOpenBrace=e,this.body=n,this.blockCloseBrace=s}}class P extends k{constructor({listOpenBracket:e,elementList:n=[],commaList:s=[],listCloseBracket:i},r){super(r,"<list-expression>",[e,...gt(n,s),i]),this.listOpenBracket=e,this.elementList=n,this.commaList=s,this.listCloseBracket=i}}class Z extends k{constructor({tupleOpenParen:e,elementList:n=[],commaList:s=[],tupleCloseParen:i},r){super(r,"<tuple-expression>",[e,...gt(n,s),i]),this.tupleOpenParen=e,this.elementList=n,this.commaList=s,this.tupleCloseParen=i}}class je extends Z{constructor({groupOpenParen:e,expression:n,groupCloseParen:s},i){super({tupleOpenParen:e,elementList:n&&[n],commaList:[],tupleCloseParen:s},i),this.kind="<group-expression>"}}class J extends k{constructor({callee:e,argumentList:n},s){super(s,"<call-expression>",[e,n]),this.callee=e,this.argumentList=n}}class Te extends k{constructor({literal:e},n){super(n,"<literal>",[e]),this.literal=e}}class W extends k{constructor({variable:e},n){super(n,"<variable>",[e]),this.variable=e}}class D extends k{constructor({expression:e},n){super(n,"<primary-expression>",[e]),this.expression=e}}class ke extends k{constructor({pre:e},n){const s=B.create(u.SPACE,e.endPos,e.endPos," ",!1);super(n,"<dummy>",[s])}}class ce extends k{constructor({expression:e,indexer:n},s){super(s,"<array>",[e,n]),this.array=e,this.indexer=n}}function gt(t,e){if(!t||t.length===0)return e||[];if(!e||e.length===0)return t||[];const[n]=t,[s]=e;return(n.start<s.start?I.flatten(I.zip(t,e)):I.flatten(I.zip(e,t))).filter(i=>i!==null)}function zt(t,e=!1){return JSON.stringify(t,function(n,s){var i;return!(this instanceof G)&&n==="symbol"?s==null?void 0:s.id:n==="symbol"?{symbolTable:s==null?void 0:s.symbolTable,id:s==null?void 0:s.id,references:s==null?void 0:s.references.map(r=>r.id),declaration:(i=s==null?void 0:s.declaration)==null?void 0:i.id}:n==="referee"||n==="parent"||n==="declaration"?s==null?void 0:s.id:n==="symbolTable"?Object.fromEntries(s.table):s},e?2:0)}class S{constructor(e){this.value=e}unwrap(){return this.value}unwrap_or(e){return this.value}and_then(e){return e(this.value)}map(e){return new S(e(this.value))}isOk(){return!0}}class v{unwrap(){throw new Error("Trying to unwrap a None value")}unwrap_or(e){return e}and_then(e){return new v}map(e){return new v}isOk(){return!1}}var m=(t=>(t.Schema="Schema",t.Table="Table",t.Column="Column",t.TableGroup="TableGroup",t.TableGroupField="TableGroup field",t.Enum="Enum",t.EnumField="Enum field",t.Note="Note",t))(m||{});function We(t){return`Schema:${t}`}function Se(t){return`Table:${t}`}function Ye(t){return`Column:${t}`}function ze(t){return`Enum:${t}`}function qe(t){return`Enum field:${t}`}function Qe(t){return`TableGroup:${t}`}function He(t){return`TableGroup field:${t}`}function qt(t){return`Note:${t}`}function Ve(t,e){switch(e){case"Column":return Ye(t);case"Enum":return ze(t);case"Enum field":return qe(t);case"Schema":return We(t);case"Table":return Se(t);case"TableGroup":return Qe(t);case"TableGroup field":return He(t);default:throw new Error("Unreachable")}}function ie(t){const[e,n]=t.split(":");return Object.values(m).includes(e)?new S({name:n,kind:e}):new v}function Qt(t){const e=ie(t).unwrap_or(void 0);if(!e)return!1;const{kind:n,name:s}=e;return n==="Schema"&&s==="public"}function Ht(t){return[We,Se,ze,Qe,Ye,qe,He].map(e=>e(t))}function Ue(t){return!!t.match(/(\p{L}|_|\p{M})/gu)}function Oe(t){const[e]=t;return e>="0"&&e<="9"}function Jt(t){const[e]=t;return Oe(e)||Ue(e)&&e.toLowerCase()>="a"&&e.toLowerCase()<="f"}function pe(t){return Ue(t)||Oe(t)}function lt(t,e){const n=[],s=Math.min(t.length,e.length);for(let i=0;i<s;i+=1)n.push(t[i],e[i]);return n.push(...t.slice(s),...e.slice(s)),n}function ge(t,e){return t>=e.start&&t<e.end}class Zt{constructor(){this.id=0}reset(){this.id=0}nextId(){return this.id++}}class _t{constructor({symbolTable:e},n){this.references=[],this.id=n,this.symbolTable=e}}class Kt{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class en{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}class At{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class tn{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}class nn{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class sn{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}var o=(t=>(t[t.UNKNOWN_SYMBOL=1e3]="UNKNOWN_SYMBOL",t[t.UNEXPECTED_SYMBOL=1001]="UNEXPECTED_SYMBOL",t[t.UNEXPECTED_EOF=1002]="UNEXPECTED_EOF",t[t.UNEXPECTED_NEWLINE=1003]="UNEXPECTED_NEWLINE",t[t.UNKNOWN_TOKEN=1004]="UNKNOWN_TOKEN",t[t.UNEXPECTED_TOKEN=1005]="UNEXPECTED_TOKEN",t[t.UNEXPECTED_ELEMENT_DECLARATION=1006]="UNEXPECTED_ELEMENT_DECLARATION",t[t.MISSING_SPACES=1007]="MISSING_SPACES",t[t.UNKNOWN_PREFIX_OP=1008]="UNKNOWN_PREFIX_OP",t[t.INVALID_OPERAND=1009]="INVALID_OPERAND",t[t.EMPTY_ATTRIBUTE_NAME=1010]="EMPTY_ATTRIBUTE_NAME",t[t.INVALID_NAME=3e3]="INVALID_NAME",t[t.UNEXPECTED_NAME=3001]="UNEXPECTED_NAME",t[t.NAME_NOT_FOUND=3002]="NAME_NOT_FOUND",t[t.DUPLICATE_NAME=3003]="DUPLICATE_NAME",t[t.INVALID_ALIAS=3004]="INVALID_ALIAS",t[t.UNEXPECTED_ALIAS=3005]="UNEXPECTED_ALIAS",t[t.UNEXPECTED_SETTINGS=3006]="UNEXPECTED_SETTINGS",t[t.INVALID_SETTINGS=3007]="INVALID_SETTINGS",t[t.UNEXPECTED_SIMPLE_BODY=3008]="UNEXPECTED_SIMPLE_BODY",t[t.UNEXPECTED_COMPLEX_BODY=3009]="UNEXPECTED_COMPLEX_BODY",t[t.INVALID_TABLE_CONTEXT=3010]="INVALID_TABLE_CONTEXT",t[t.INVALID_TABLE_SETTING=3011]="INVALID_TABLE_SETTING",t[t.DUPLICATE_TABLE_SETTING=3012]="DUPLICATE_TABLE_SETTING",t[t.INVALID_TABLEGROUP_CONTEXT=3013]="INVALID_TABLEGROUP_CONTEXT",t[t.INVALID_TABLEGROUP_ELEMENT_NAME=3014]="INVALID_TABLEGROUP_ELEMENT_NAME",t[t.DUPLICATE_TABLEGROUP_ELEMENT_NAME=3015]="DUPLICATE_TABLEGROUP_ELEMENT_NAME",t[t.DUPLICATE_TABLEGROUP_FIELD_NAME=3016]="DUPLICATE_TABLEGROUP_FIELD_NAME",t[t.INVALID_TABLEGROUP_FIELD=3017]="INVALID_TABLEGROUP_FIELD",t[t.EMPTY_TABLE=3018]="EMPTY_TABLE",t[t.INVALID_COLUMN=3019]="INVALID_COLUMN",t[t.INVALID_COLUMN_NAME=3020]="INVALID_COLUMN_NAME",t[t.UNKNOWN_COLUMN_SETTING=3021]="UNKNOWN_COLUMN_SETTING",t[t.INVALID_COLUMN_TYPE=3022]="INVALID_COLUMN_TYPE",t[t.DUPLICATE_COLUMN_NAME=3023]="DUPLICATE_COLUMN_NAME",t[t.DUPLICATE_COLUMN_SETTING=3024]="DUPLICATE_COLUMN_SETTING",t[t.INVALID_COLUMN_SETTING_VALUE=3025]="INVALID_COLUMN_SETTING_VALUE",t[t.INVALID_ENUM_CONTEXT=3026]="INVALID_ENUM_CONTEXT",t[t.INVALID_ENUM_ELEMENT_NAME=3027]="INVALID_ENUM_ELEMENT_NAME",t[t.INVALID_ENUM_ELEMENT=3028]="INVALID_ENUM_ELEMENT",t[t.DUPLICATE_ENUM_ELEMENT_NAME=3029]="DUPLICATE_ENUM_ELEMENT_NAME",t[t.UNKNOWN_ENUM_ELEMENT_SETTING=3030]="UNKNOWN_ENUM_ELEMENT_SETTING",t[t.DUPLICATE_ENUM_ELEMENT_SETTING=3031]="DUPLICATE_ENUM_ELEMENT_SETTING",t[t.INVALID_ENUM_ELEMENT_SETTING=3032]="INVALID_ENUM_ELEMENT_SETTING",t[t.EMPTY_ENUM=3033]="EMPTY_ENUM",t[t.INVALID_REF_CONTEXT=3034]="INVALID_REF_CONTEXT",t[t.UNKNOWN_REF_SETTING=3035]="UNKNOWN_REF_SETTING",t[t.DUPLICATE_REF_SETTING=3036]="DUPLICATE_REF_SETTING",t[t.INVALID_REF_SETTING_VALUE=3037]="INVALID_REF_SETTING_VALUE",t[t.INVALID_REF_RELATIONSHIP=3038]="INVALID_REF_RELATIONSHIP",t[t.INVALID_REF_FIELD=3039]="INVALID_REF_FIELD",t[t.EMPTY_REF=3040]="EMPTY_REF",t[t.REF_REDEFINED=3041]="REF_REDEFINED",t[t.INVALID_NOTE_CONTEXT=3042]="INVALID_NOTE_CONTEXT",t[t.INVALID_NOTE=3043]="INVALID_NOTE",t[t.NOTE_REDEFINED=3044]="NOTE_REDEFINED",t[t.NOTE_CONTENT_REDEFINED=3045]="NOTE_CONTENT_REDEFINED",t[t.EMPTY_NOTE=3046]="EMPTY_NOTE",t[t.INVALID_INDEXES_CONTEXT=3047]="INVALID_INDEXES_CONTEXT",t[t.INVALID_INDEXES_FIELD=3048]="INVALID_INDEXES_FIELD",t[t.INVALID_INDEX=3049]="INVALID_INDEX",t[t.UNKNOWN_INDEX_SETTING=3050]="UNKNOWN_INDEX_SETTING",t[t.DUPLICATE_INDEX_SETTING=3051]="DUPLICATE_INDEX_SETTING",t[t.UNEXPECTED_INDEX_SETTING_VALUE=3052]="UNEXPECTED_INDEX_SETTING_VALUE",t[t.INVALID_INDEX_SETTING_VALUE=3053]="INVALID_INDEX_SETTING_VALUE",t[t.INVALID_PROJECT_CONTEXT=3054]="INVALID_PROJECT_CONTEXT",t[t.PROJECT_REDEFINED=3055]="PROJECT_REDEFINED",t[t.INVALID_PROJECT_FIELD=3056]="INVALID_PROJECT_FIELD",t[t.INVALID_CUSTOM_CONTEXT=3057]="INVALID_CUSTOM_CONTEXT",t[t.INVALID_CUSTOM_ELEMENT_VALUE=3058]="INVALID_CUSTOM_ELEMENT_VALUE",t[t.INVALID_ELEMENT_IN_SIMPLE_BODY=3059]="INVALID_ELEMENT_IN_SIMPLE_BODY",t[t.BINDING_ERROR=4e3]="BINDING_ERROR",t[t.UNSUPPORTED=5e3]="UNSUPPORTED",t[t.CIRCULAR_REF=5001]="CIRCULAR_REF",t[t.SAME_ENDPOINT=5002]="SAME_ENDPOINT",t[t.UNEQUAL_FIELDS_BINARY_REF=5003]="UNEQUAL_FIELDS_BINARY_REF",t[t.CONFLICTING_SETTING=5004]="CONFLICTING_SETTING",t[t.TABLE_REAPPEAR_IN_TABLEGROUP=5005]="TABLE_REAPPEAR_IN_TABLEGROUP",t))(o||{});class c extends Error{constructor(e,n,s){super(n),this.code=e,this.diagnostic=n,this.nodeOrToken=s,this.start=s.start,this.end=s.end,this.name=this.constructor.name,Object.setPrototypeOf(this,c.prototype)}}class F{constructor(e,n){this.value=e,this.errors=n===void 0?[]:n}getValue(){return this.value}getErrors(){return this.errors}chain(e){const n=e(this.value),s=[...this.errors,...n.errors];return new F(n.value,s)}map(e){return new F(e(this.value),this.errors)}}function rn(t,e,n){if(!t||!Ne(t)||e.length===0)return new v;const s=[...e],i=Ge(t).unwrap(),r=s.pop();if(!(r instanceof ne))return new v;const a=I.last(s)instanceof P?s.pop():void 0;return s.length===3&&Ge(s[1]).unwrap().value==="as"?new S(n.create(A,{type:i,name:s[0],as:Ge(s[1]).unwrap(),alias:s[2],attributeList:a,body:r})):s.length===1?new S(n.create(A,{type:i,name:s[0],attributeList:a,body:r})):s.length===0?new S(n.create(A,{type:i,attributeList:a,body:r})):new v}function ct(t){return t.kind===u.IDENTIFIER&&t.value==="as"}function E(t){t&&(t instanceof B?an(t):on(t))}function an(t){t.kind!==u.EOF&&(t.isInvalid=!0)}function on(t){if(t instanceof A)E(t.type),E(t.name),E(t.as),E(t.alias),E(t.bodyColon),E(t.attributeList),E(t.body);else if(t instanceof $)t.identifiers.forEach(E);else if(t instanceof se)E(t.name),E(t.colon),E(t.value);else if(t instanceof Q)E(t.op),E(t.expression);else if(t instanceof H)E(t.leftExpression),E(t.op),E(t.rightExpression);else if(t instanceof Pe)E(t.op),E(t.expression);else if(t instanceof ne)E(t.blockOpenBrace),t.body.forEach(E),E(t.blockCloseBrace);else if(t instanceof P)E(t.listOpenBracket),t.commaList.forEach(E),t.elementList.forEach(E),E(t.listCloseBracket);else if(t instanceof Z)E(t.tupleOpenParen),t.commaList.forEach(E),t.elementList.forEach(E),E(t.tupleCloseParen);else if(t instanceof J)E(t.callee),E(t.argumentList);else if(t instanceof w)E(t.callee),t.args.forEach(E);else if(t instanceof D)E(t.expression);else if(t instanceof te)E(t.value);else if(t instanceof W)E(t.variable);else if(t instanceof Te)E(t.literal);else throw t instanceof je?new Error("This case is handled by the TupleExpressionNode case"):new Error("Unreachable case in markInvalidNode")}function vt(t){return!!(t!=null&&t.isInvalid)}function U(...t){return t.filter(e=>e!==void 0)}function ln(t){if(t instanceof G)return U(...t.body,t.eof);if(t instanceof A)return U(t.type,t.name,t.as,t.alias,t.attributeList,t.bodyColon,t.body);if(t instanceof se)return U(t.name,t.colon,t.value);if(t instanceof $)return t.identifiers;if(t instanceof Te)return t.literal?[t.literal]:[];if(t instanceof W)return U(t.variable);if(t instanceof Q)return U(t.op,t.expression);if(t instanceof H)return U(t.leftExpression,t.op,t.rightExpression);if(t instanceof Pe)return U(t.expression,t.op);if(t instanceof te)return U(t.value);if(t instanceof w)return U(t.callee,...t.args);if(t instanceof ne)return U(t.blockOpenBrace,...t.body,t.blockCloseBrace);if(t instanceof P)return U(t.listOpenBracket,...lt(t.elementList,t.commaList),t.listCloseBracket);if(t instanceof Z)return U(t.tupleOpenParen,...lt(t.elementList,t.commaList),t.tupleCloseParen);if(t instanceof J)return U(t.callee,t.argumentList);if(t instanceof D)return U(t.expression);if(t instanceof ce)return U(t.array,t.indexer);throw t instanceof je?new Error("This case is already handled by TupleExpressionNode"):new Error("Unreachable - no other possible cases")}function Ge(t){return M(t)?new S(t.expression.variable):new v}function Y(t){var e;return t instanceof D&&(t.expression instanceof W&&t.expression.variable instanceof B&&t.expression.variable.kind===u.QUOTED_STRING||t.expression instanceof Te&&((e=t.expression.literal)==null?void 0:e.kind)===u.STRING_LITERAL)}function M(t){return t instanceof D&&t.expression instanceof W&&t.expression.variable instanceof B}function Ne(t){var e;return t instanceof D&&t.expression instanceof W&&((e=t.expression.variable)==null?void 0:e.kind)===u.IDENTIFIER}function Je(t){var e;return t instanceof H&&t.leftExpression instanceof k&&t.rightExpression instanceof k&&((e=t.op)==null?void 0:e.value)==="."}function me(t){if(t===void 0)return new v;const e=t.identifiers.map(n=>n.value).join(" ");return e===""?new v:new S(e)}class cn{constructor(e){this.start={offset:0,line:0,column:0},this.current={offset:0,line:0,column:0},this.tokens=[],this.errors=[],this.text=e}isAtEnd(){return this.current.offset>=this.text.length}advance(){const e=this.peek();return this.current={...this.current},e===`
2
- `?(this.current.line+=1,this.current.column=0):this.current.column+=1,this.current.offset+=1,e}peek(e=0){if(!(this.current.offset+e>=this.text.length))return this.text[this.current.offset+e]}check(e){for(let n=0;n<e.length;n+=1)if(e[n]!==this.peek(n))return!1;return!0}match(e){return this.check(e)?(e.split("").forEach(()=>this.advance()),!0):!1}addToken(e,n=!1){this.tokens.push(this.createToken(e,n))}createToken(e,n=!1){return B.create(e,this.start,this.current,this.text.substring(this.start.offset,this.current.offset),n)}lex(){return this.scanTokens(),this.tokens.push(B.create(u.EOF,this.start,this.current,"",!1)),this.gatherTrivia(),this.gatherInvalid(),new F(this.tokens,this.errors)}scanTokens(){for(;!this.isAtEnd();){const e=this.advance();switch(e){case" ":this.addToken(u.SPACE);break;case"\r":break;case`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I=require("lodash");var u=(t=>(t.SPACE="<space>",t.TAB="<tab>",t.NEWLINE="<newline>",t.COMMA="<comma>",t.LPAREN="<lparen>",t.RPAREN="<rparen>",t.LBRACE="<lbrace>",t.RBRACE="<rbrace>",t.LBRACKET="<lbracket>",t.RBRACKET="<rbracket>",t.LANGLE="<langle>",t.RANGLE="<rangle>",t.OP="<op>",t.EOF="<eof>",t.NUMERIC_LITERAL="<number>",t.STRING_LITERAL="<string>",t.COLOR_LITERAL="<color>",t.FUNCTION_EXPRESSION="<function-expression>",t.QUOTED_STRING="<variable>",t.IDENTIFIER="<identifier>",t.SEMICOLON="<semicolon>",t.COLON="<colon>",t.SINGLE_LINE_COMMENT="<single-line-comment>",t.MULTILINE_COMMENT="<multiline-comment>",t))(u||{});function jt(t){switch(t.kind){case"<newline>":case"<space>":case"<tab>":case"<single-line-comment>":case"<multiline-comment>":return!0;default:return!1}}function rt(t){if(!t)return!1;switch(t){case"+":case"-":case"*":case"/":case"%":case"<":case">":case"=":case"!":case".":case"&":case"|":return!0;default:return!1}}function at(t){return t!==void 0&&t.kind==="<op>"}class M{constructor(e,n,s,i,r){this.kind=e,this.startPos=n,this.endPos=s,this.value=i,this.leadingTrivia=[],this.trailingTrivia=[],this.leadingInvalid=[],this.trailingInvalid=[],this.isInvalid=r,this.start=n.offset,this.end=s.offset}static create(e,n,s,i,r){return new M(e,n,s,i,r)}}function bt(t){return t.trailingTrivia.find(({kind:e})=>e===u.NEWLINE)!==void 0}function ot(t,e){return e.leadingTrivia.find(({kind:s})=>s===u.NEWLINE)!==void 0||bt(t)}function Ce(t){return t.trailingTrivia.find(({kind:e})=>e===u.SPACE)!==void 0}function It(t){return t.trailingTrivia.length===0?t.end:It(I.last(t.trailingTrivia))}function Lt(t){return t.leadingTrivia.length===0?t.start:Lt(t.leadingTrivia[0])}function Wt(t){return[u.SINGLE_LINE_COMMENT,u.MULTILINE_COMMENT].includes(t.kind)}class Yt{constructor(){this.id=0}reset(){this.id=0}nextId(){return this.id++}}class k{constructor(e,n,s){this.id=e,this.kind=n;const i=s.find(a=>a!==void 0&&!Number.isNaN(a.start));i?(this.startPos=i.startPos,this.fullStart=i instanceof M?Lt(i):i.fullStart):(this.startPos={offset:NaN,column:NaN,line:NaN},this.fullStart=NaN);const r=[...s].reverse().find(a=>a!==void 0&&!Number.isNaN(a.end));r?(this.endPos=r.endPos,this.fullEnd=r instanceof M?It(r):r.fullEnd):(this.endPos={offset:NaN,column:NaN,line:NaN},this.fullEnd=NaN),this.start=this.startPos.offset,this.end=this.endPos.offset}}var de=(t=>(t.PROGRAM="<program>",t.ELEMENT_DECLARATION="<element-declaration>",t.ATTRIBUTE="<attribute>",t.IDENTIFIER_STREAM="<identifer-stream>",t.LITERAL="<literal>",t.VARIABLE="<variable>",t.PREFIX_EXPRESSION="<prefix-expression>",t.INFIX_EXPRESSION="<infix-expression>",t.POSTFIX_EXPRESSION="<postfix-expression>",t.FUNCTION_EXPRESSION="<function-expression>",t.FUNCTION_APPLICATION="<function-application>",t.BLOCK_EXPRESSION="<block-expression>",t.LIST_EXPRESSION="<list-expression>",t.TUPLE_EXPRESSION="<tuple-expression>",t.CALL_EXPRESSION="<call-expression>",t.PRIMARY_EXPRESSION="<primary-expression>",t.GROUP_EXPRESSION="<group-expression>",t.DUMMY="<dummy>",t.ARRAY="<array>",t))(de||{});class G extends k{constructor({body:e=[],eof:n},s){super(s,"<program>",[...e,n]),this.body=e,this.eof=n}}class A extends k{constructor({type:e,name:n,as:s,alias:i,attributeList:r,bodyColon:a,body:l},p){if(super(p,"<element-declaration>",[e,n,s,i,r,a,l]),l&&a&&!(l instanceof w||l instanceof A))throw new Error("If an element has a simple body, it must be a function application node");this.type=e,this.name=n,this.as=s,this.alias=i,this.attributeList=r,this.bodyColon=a,this.body=l}}class $ extends k{constructor({identifiers:e=[]},n){super(n,"<identifer-stream>",e||[]),this.identifiers=e}}class se extends k{constructor({name:e,colon:n,value:s},i){super(i,"<attribute>",[e,n,s]),this.name=e,this.value=s,this.colon=n}}class q extends k{constructor({op:e,expression:n},s){super(s,"<prefix-expression>",[e,n]),this.op=e,this.expression=n}}class H extends k{constructor({op:e,leftExpression:n,rightExpression:s},i){super(i,"<infix-expression>",[n,e,s]),this.op=e,this.leftExpression=n,this.rightExpression=s}}class Pe extends k{constructor({op:e,expression:n},s){super(s,"<postfix-expression>",[n,e]),this.op=e,this.expression=n}}class te extends k{constructor({value:e},n){super(n,"<function-expression>",[e]),this.value=e}}class w extends k{constructor({callee:e,args:n=[]},s){super(s,"<function-application>",[e,...n]),this.callee=e,this.args=n}}class ne extends k{constructor({blockOpenBrace:e,body:n=[],blockCloseBrace:s},i){super(i,"<block-expression>",[e,...n,s]),this.blockOpenBrace=e,this.body=n,this.blockCloseBrace=s}}class P extends k{constructor({listOpenBracket:e,elementList:n=[],commaList:s=[],listCloseBracket:i},r){super(r,"<list-expression>",[e,...gt(n,s),i]),this.listOpenBracket=e,this.elementList=n,this.commaList=s,this.listCloseBracket=i}}class Z extends k{constructor({tupleOpenParen:e,elementList:n=[],commaList:s=[],tupleCloseParen:i},r){super(r,"<tuple-expression>",[e,...gt(n,s),i]),this.tupleOpenParen=e,this.elementList=n,this.commaList=s,this.tupleCloseParen=i}}class je extends Z{constructor({groupOpenParen:e,expression:n,groupCloseParen:s},i){super({tupleOpenParen:e,elementList:n&&[n],commaList:[],tupleCloseParen:s},i),this.kind="<group-expression>"}}class J extends k{constructor({callee:e,argumentList:n},s){super(s,"<call-expression>",[e,n]),this.callee=e,this.argumentList=n}}class Te extends k{constructor({literal:e},n){super(n,"<literal>",[e]),this.literal=e}}class W extends k{constructor({variable:e},n){super(n,"<variable>",[e]),this.variable=e}}class D extends k{constructor({expression:e},n){super(n,"<primary-expression>",[e]),this.expression=e}}class ke extends k{constructor({pre:e},n){const s=M.create(u.SPACE,e.endPos,e.endPos," ",!1);super(n,"<dummy>",[s])}}class le extends k{constructor({expression:e,indexer:n},s){super(s,"<array>",[e,n]),this.array=e,this.indexer=n}}function gt(t,e){if(!t||t.length===0)return e||[];if(!e||e.length===0)return t||[];const[n]=t,[s]=e;return(n.start<s.start?I.flatten(I.zip(t,e)):I.flatten(I.zip(e,t))).filter(i=>i!==null)}function zt(t,e=!1){return JSON.stringify(t,function(n,s){var i;return!(this instanceof G)&&n==="symbol"?s==null?void 0:s.id:n==="symbol"?{symbolTable:s==null?void 0:s.symbolTable,id:s==null?void 0:s.id,references:s==null?void 0:s.references.map(r=>r.id),declaration:(i=s==null?void 0:s.declaration)==null?void 0:i.id}:n==="referee"||n==="parent"||n==="declaration"?s==null?void 0:s.id:n==="symbolTable"?Object.fromEntries(s.table):s},e?2:0)}class S{constructor(e){this.value=e}unwrap(){return this.value}unwrap_or(e){return this.value}and_then(e){return e(this.value)}map(e){return new S(e(this.value))}isOk(){return!0}}class v{unwrap(){throw new Error("Trying to unwrap a None value")}unwrap_or(e){return e}and_then(e){return new v}map(e){return new v}isOk(){return!1}}var m=(t=>(t.Schema="Schema",t.Table="Table",t.Column="Column",t.TableGroup="TableGroup",t.TableGroupField="TableGroup field",t.Enum="Enum",t.EnumField="Enum field",t.Note="Note",t))(m||{});function We(t){return`Schema:${t}`}function Se(t){return`Table:${t}`}function Ye(t){return`Column:${t}`}function ze(t){return`Enum:${t}`}function Qe(t){return`Enum field:${t}`}function qe(t){return`TableGroup:${t}`}function He(t){return`TableGroup field:${t}`}function Qt(t){return`Note:${t}`}function Ve(t,e){switch(e){case"Column":return Ye(t);case"Enum":return ze(t);case"Enum field":return Qe(t);case"Schema":return We(t);case"Table":return Se(t);case"TableGroup":return qe(t);case"TableGroup field":return He(t);default:throw new Error("Unreachable")}}function ie(t){const[e,n]=t.split(":");return Object.values(m).includes(e)?new S({name:n,kind:e}):new v}function qt(t){const e=ie(t).unwrap_or(void 0);if(!e)return!1;const{kind:n,name:s}=e;return n==="Schema"&&s==="public"}function Ht(t){return[We,Se,ze,qe,Ye,Qe,He].map(e=>e(t))}function Ue(t){return!!t.match(/(\p{L}|_|\p{M})/gu)}function Oe(t){const[e]=t;return e>="0"&&e<="9"}function Jt(t){const[e]=t;return Oe(e)||Ue(e)&&e.toLowerCase()>="a"&&e.toLowerCase()<="f"}function pe(t){return Ue(t)||Oe(t)}function ct(t,e){const n=[],s=Math.min(t.length,e.length);for(let i=0;i<s;i+=1)n.push(t[i],e[i]);return n.push(...t.slice(s),...e.slice(s)),n}function ge(t,e){return t>=e.start&&t<e.end}class Zt{constructor(){this.id=0}reset(){this.id=0}nextId(){return this.id++}}class _t{constructor({symbolTable:e},n){this.references=[],this.id=n,this.symbolTable=e}}class Kt{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class en{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}class At{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class tn{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}class nn{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class sn{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}var o=(t=>(t[t.UNKNOWN_SYMBOL=1e3]="UNKNOWN_SYMBOL",t[t.UNEXPECTED_SYMBOL=1001]="UNEXPECTED_SYMBOL",t[t.UNEXPECTED_EOF=1002]="UNEXPECTED_EOF",t[t.UNEXPECTED_NEWLINE=1003]="UNEXPECTED_NEWLINE",t[t.UNKNOWN_TOKEN=1004]="UNKNOWN_TOKEN",t[t.UNEXPECTED_TOKEN=1005]="UNEXPECTED_TOKEN",t[t.UNEXPECTED_ELEMENT_DECLARATION=1006]="UNEXPECTED_ELEMENT_DECLARATION",t[t.MISSING_SPACES=1007]="MISSING_SPACES",t[t.UNKNOWN_PREFIX_OP=1008]="UNKNOWN_PREFIX_OP",t[t.INVALID_OPERAND=1009]="INVALID_OPERAND",t[t.EMPTY_ATTRIBUTE_NAME=1010]="EMPTY_ATTRIBUTE_NAME",t[t.INVALID_ESCAPE_SEQUENCE=1011]="INVALID_ESCAPE_SEQUENCE",t[t.INVALID_NAME=3e3]="INVALID_NAME",t[t.UNEXPECTED_NAME=3001]="UNEXPECTED_NAME",t[t.NAME_NOT_FOUND=3002]="NAME_NOT_FOUND",t[t.DUPLICATE_NAME=3003]="DUPLICATE_NAME",t[t.INVALID_ALIAS=3004]="INVALID_ALIAS",t[t.UNEXPECTED_ALIAS=3005]="UNEXPECTED_ALIAS",t[t.UNEXPECTED_SETTINGS=3006]="UNEXPECTED_SETTINGS",t[t.INVALID_SETTINGS=3007]="INVALID_SETTINGS",t[t.UNEXPECTED_SIMPLE_BODY=3008]="UNEXPECTED_SIMPLE_BODY",t[t.UNEXPECTED_COMPLEX_BODY=3009]="UNEXPECTED_COMPLEX_BODY",t[t.INVALID_TABLE_CONTEXT=3010]="INVALID_TABLE_CONTEXT",t[t.INVALID_TABLE_SETTING=3011]="INVALID_TABLE_SETTING",t[t.DUPLICATE_TABLE_SETTING=3012]="DUPLICATE_TABLE_SETTING",t[t.INVALID_TABLEGROUP_CONTEXT=3013]="INVALID_TABLEGROUP_CONTEXT",t[t.INVALID_TABLEGROUP_ELEMENT_NAME=3014]="INVALID_TABLEGROUP_ELEMENT_NAME",t[t.DUPLICATE_TABLEGROUP_ELEMENT_NAME=3015]="DUPLICATE_TABLEGROUP_ELEMENT_NAME",t[t.DUPLICATE_TABLEGROUP_FIELD_NAME=3016]="DUPLICATE_TABLEGROUP_FIELD_NAME",t[t.INVALID_TABLEGROUP_FIELD=3017]="INVALID_TABLEGROUP_FIELD",t[t.EMPTY_TABLE=3018]="EMPTY_TABLE",t[t.INVALID_COLUMN=3019]="INVALID_COLUMN",t[t.INVALID_COLUMN_NAME=3020]="INVALID_COLUMN_NAME",t[t.UNKNOWN_COLUMN_SETTING=3021]="UNKNOWN_COLUMN_SETTING",t[t.INVALID_COLUMN_TYPE=3022]="INVALID_COLUMN_TYPE",t[t.DUPLICATE_COLUMN_NAME=3023]="DUPLICATE_COLUMN_NAME",t[t.DUPLICATE_COLUMN_SETTING=3024]="DUPLICATE_COLUMN_SETTING",t[t.INVALID_COLUMN_SETTING_VALUE=3025]="INVALID_COLUMN_SETTING_VALUE",t[t.INVALID_ENUM_CONTEXT=3026]="INVALID_ENUM_CONTEXT",t[t.INVALID_ENUM_ELEMENT_NAME=3027]="INVALID_ENUM_ELEMENT_NAME",t[t.INVALID_ENUM_ELEMENT=3028]="INVALID_ENUM_ELEMENT",t[t.DUPLICATE_ENUM_ELEMENT_NAME=3029]="DUPLICATE_ENUM_ELEMENT_NAME",t[t.UNKNOWN_ENUM_ELEMENT_SETTING=3030]="UNKNOWN_ENUM_ELEMENT_SETTING",t[t.DUPLICATE_ENUM_ELEMENT_SETTING=3031]="DUPLICATE_ENUM_ELEMENT_SETTING",t[t.INVALID_ENUM_ELEMENT_SETTING=3032]="INVALID_ENUM_ELEMENT_SETTING",t[t.EMPTY_ENUM=3033]="EMPTY_ENUM",t[t.INVALID_REF_CONTEXT=3034]="INVALID_REF_CONTEXT",t[t.UNKNOWN_REF_SETTING=3035]="UNKNOWN_REF_SETTING",t[t.DUPLICATE_REF_SETTING=3036]="DUPLICATE_REF_SETTING",t[t.INVALID_REF_SETTING_VALUE=3037]="INVALID_REF_SETTING_VALUE",t[t.INVALID_REF_RELATIONSHIP=3038]="INVALID_REF_RELATIONSHIP",t[t.INVALID_REF_FIELD=3039]="INVALID_REF_FIELD",t[t.EMPTY_REF=3040]="EMPTY_REF",t[t.REF_REDEFINED=3041]="REF_REDEFINED",t[t.INVALID_NOTE_CONTEXT=3042]="INVALID_NOTE_CONTEXT",t[t.INVALID_NOTE=3043]="INVALID_NOTE",t[t.NOTE_REDEFINED=3044]="NOTE_REDEFINED",t[t.NOTE_CONTENT_REDEFINED=3045]="NOTE_CONTENT_REDEFINED",t[t.EMPTY_NOTE=3046]="EMPTY_NOTE",t[t.INVALID_INDEXES_CONTEXT=3047]="INVALID_INDEXES_CONTEXT",t[t.INVALID_INDEXES_FIELD=3048]="INVALID_INDEXES_FIELD",t[t.INVALID_INDEX=3049]="INVALID_INDEX",t[t.UNKNOWN_INDEX_SETTING=3050]="UNKNOWN_INDEX_SETTING",t[t.DUPLICATE_INDEX_SETTING=3051]="DUPLICATE_INDEX_SETTING",t[t.UNEXPECTED_INDEX_SETTING_VALUE=3052]="UNEXPECTED_INDEX_SETTING_VALUE",t[t.INVALID_INDEX_SETTING_VALUE=3053]="INVALID_INDEX_SETTING_VALUE",t[t.INVALID_PROJECT_CONTEXT=3054]="INVALID_PROJECT_CONTEXT",t[t.PROJECT_REDEFINED=3055]="PROJECT_REDEFINED",t[t.INVALID_PROJECT_FIELD=3056]="INVALID_PROJECT_FIELD",t[t.INVALID_CUSTOM_CONTEXT=3057]="INVALID_CUSTOM_CONTEXT",t[t.INVALID_CUSTOM_ELEMENT_VALUE=3058]="INVALID_CUSTOM_ELEMENT_VALUE",t[t.INVALID_ELEMENT_IN_SIMPLE_BODY=3059]="INVALID_ELEMENT_IN_SIMPLE_BODY",t[t.BINDING_ERROR=4e3]="BINDING_ERROR",t[t.UNSUPPORTED=5e3]="UNSUPPORTED",t[t.CIRCULAR_REF=5001]="CIRCULAR_REF",t[t.SAME_ENDPOINT=5002]="SAME_ENDPOINT",t[t.UNEQUAL_FIELDS_BINARY_REF=5003]="UNEQUAL_FIELDS_BINARY_REF",t[t.CONFLICTING_SETTING=5004]="CONFLICTING_SETTING",t[t.TABLE_REAPPEAR_IN_TABLEGROUP=5005]="TABLE_REAPPEAR_IN_TABLEGROUP",t))(o||{});class c extends Error{constructor(e,n,s){super(n),this.code=e,this.diagnostic=n,this.nodeOrToken=s,this.start=s.start,this.end=s.end,this.name=this.constructor.name,Object.setPrototypeOf(this,c.prototype)}}class B{constructor(e,n){this.value=e,this.errors=n===void 0?[]:n}getValue(){return this.value}getErrors(){return this.errors}chain(e){const n=e(this.value),s=[...this.errors,...n.errors];return new B(n.value,s)}map(e){return new B(e(this.value),this.errors)}}function rn(t,e,n){if(!t||!Ne(t)||e.length===0)return new v;const s=[...e],i=Ge(t).unwrap(),r=s.pop();if(!(r instanceof ne))return new v;const a=I.last(s)instanceof P?s.pop():void 0;return s.length===3&&Ge(s[1]).unwrap().value==="as"?new S(n.create(A,{type:i,name:s[0],as:Ge(s[1]).unwrap(),alias:s[2],attributeList:a,body:r})):s.length===1?new S(n.create(A,{type:i,name:s[0],attributeList:a,body:r})):s.length===0?new S(n.create(A,{type:i,attributeList:a,body:r})):new v}function lt(t){return t.kind===u.IDENTIFIER&&t.value==="as"}function E(t){t&&(t instanceof M?an(t):on(t))}function an(t){t.kind!==u.EOF&&(t.isInvalid=!0)}function on(t){if(t instanceof A)E(t.type),E(t.name),E(t.as),E(t.alias),E(t.bodyColon),E(t.attributeList),E(t.body);else if(t instanceof $)t.identifiers.forEach(E);else if(t instanceof se)E(t.name),E(t.colon),E(t.value);else if(t instanceof q)E(t.op),E(t.expression);else if(t instanceof H)E(t.leftExpression),E(t.op),E(t.rightExpression);else if(t instanceof Pe)E(t.op),E(t.expression);else if(t instanceof ne)E(t.blockOpenBrace),t.body.forEach(E),E(t.blockCloseBrace);else if(t instanceof P)E(t.listOpenBracket),t.commaList.forEach(E),t.elementList.forEach(E),E(t.listCloseBracket);else if(t instanceof Z)E(t.tupleOpenParen),t.commaList.forEach(E),t.elementList.forEach(E),E(t.tupleCloseParen);else if(t instanceof J)E(t.callee),E(t.argumentList);else if(t instanceof w)E(t.callee),t.args.forEach(E);else if(t instanceof D)E(t.expression);else if(t instanceof te)E(t.value);else if(t instanceof W)E(t.variable);else if(t instanceof Te)E(t.literal);else throw t instanceof je?new Error("This case is handled by the TupleExpressionNode case"):new Error("Unreachable case in markInvalidNode")}function vt(t){return!!(t!=null&&t.isInvalid)}function U(...t){return t.filter(e=>e!==void 0)}function cn(t){if(t instanceof G)return U(...t.body,t.eof);if(t instanceof A)return U(t.type,t.name,t.as,t.alias,t.attributeList,t.bodyColon,t.body);if(t instanceof se)return U(t.name,t.colon,t.value);if(t instanceof $)return t.identifiers;if(t instanceof Te)return t.literal?[t.literal]:[];if(t instanceof W)return U(t.variable);if(t instanceof q)return U(t.op,t.expression);if(t instanceof H)return U(t.leftExpression,t.op,t.rightExpression);if(t instanceof Pe)return U(t.expression,t.op);if(t instanceof te)return U(t.value);if(t instanceof w)return U(t.callee,...t.args);if(t instanceof ne)return U(t.blockOpenBrace,...t.body,t.blockCloseBrace);if(t instanceof P)return U(t.listOpenBracket,...ct(t.elementList,t.commaList),t.listCloseBracket);if(t instanceof Z)return U(t.tupleOpenParen,...ct(t.elementList,t.commaList),t.tupleCloseParen);if(t instanceof J)return U(t.callee,t.argumentList);if(t instanceof D)return U(t.expression);if(t instanceof le)return U(t.array,t.indexer);throw t instanceof je?new Error("This case is already handled by TupleExpressionNode"):new Error("Unreachable - no other possible cases")}function Ge(t){return F(t)?new S(t.expression.variable):new v}function Y(t){var e;return t instanceof D&&(t.expression instanceof W&&t.expression.variable instanceof M&&t.expression.variable.kind===u.QUOTED_STRING||t.expression instanceof Te&&((e=t.expression.literal)==null?void 0:e.kind)===u.STRING_LITERAL)}function F(t){return t instanceof D&&t.expression instanceof W&&t.expression.variable instanceof M}function Ne(t){var e;return t instanceof D&&t.expression instanceof W&&((e=t.expression.variable)==null?void 0:e.kind)===u.IDENTIFIER}function Je(t){var e;return t instanceof H&&t.leftExpression instanceof k&&t.rightExpression instanceof k&&((e=t.op)==null?void 0:e.value)==="."}function me(t){if(t===void 0)return new v;const e=t.identifiers.map(n=>n.value).join(" ");return e===""?new v:new S(e)}class ln{constructor(e){this.start={offset:0,line:0,column:0},this.current={offset:0,line:0,column:0},this.tokens=[],this.errors=[],this.text=e}isAtEnd(){return this.current.offset>=this.text.length}advance(){const e=this.peek();return this.current={...this.current},e===`
2
+ `?(this.current.line+=1,this.current.column=0):this.current.column+=1,this.current.offset+=1,e}peek(e=0){if(!(this.current.offset+e>=this.text.length))return this.text[this.current.offset+e]}check(e){for(let n=0;n<e.length;n+=1)if(e[n]!==this.peek(n))return!1;return!0}match(e){return this.check(e)?(e.split("").forEach(()=>this.advance()),!0):!1}addToken(e,n=!1){this.tokens.push(this.createToken(e,n))}createToken(e,n=!1){return M.create(e,this.start,this.current,this.text.substring(this.start.offset,this.current.offset),n)}lex(){return this.scanTokens(),this.tokens.push(M.create(u.EOF,this.start,this.current,"",!1)),this.gatherTrivia(),this.gatherInvalid(),new B(this.tokens,this.errors)}scanTokens(){for(;!this.isAtEnd();){const e=this.advance();switch(e){case" ":this.addToken(u.SPACE);break;case"\r":break;case`
3
3
  `:this.addToken(u.NEWLINE);break;case" ":this.addToken(u.TAB);break;case",":this.addToken(u.COMMA);break;case"(":this.addToken(u.LPAREN);break;case")":this.addToken(u.RPAREN);break;case"[":this.addToken(u.LBRACKET);break;case"]":this.addToken(u.RBRACKET);break;case"{":this.addToken(u.LBRACE);break;case"}":this.addToken(u.RBRACE);break;case";":this.addToken(u.SEMICOLON);break;case":":this.addToken(u.COLON);break;case"'":this.match("''")?this.multilineStringLiteral():this.singleLineStringLiteral();break;case'"':this.quotedVariable();break;case"`":this.functionExpression();break;case"#":this.colorLiteral();break;case"/":this.match("/")?this.singleLineComment():this.match("*")?this.multilineComment():this.operator();break;default:if(rt(e)){this.operator();break}if(Ue(e)){this.identifier();break}if(Oe(e)){this.numericLiteralOrIdentifier();break}this.addToken(u.OP,!0),this.errors.push(new c(o.UNKNOWN_SYMBOL,`Unexpected token '${e}'`,this.createToken(u.OP,!0)));break}this.start={...this.current}}}gatherTrivia(){let e=!0,n=[],s;const i=[];for(const r of this.tokens)jt(r)?(n.push(r),r.kind===u.NEWLINE&&s&&(s.trailingTrivia=n,e=!0,s=void 0,n=[])):(e?r.leadingTrivia=n:s.trailingTrivia=n,i.push(r),n=[],s=r,e=!1);this.tokens=i}gatherInvalid(){let e;const n=[],s=[];for(e=0;e<this.tokens.length&&vt(this.tokens[e]);e+=1)s.push(this.tokens[e]);let i=this.tokens[e];for(i.leadingInvalid=[...s,...i.leadingInvalid];e<this.tokens.length;e+=1){const r=this.tokens[e];r.isInvalid?i.trailingInvalid.push(r):(i=r,n.push(r))}this.tokens=n}consumeUntil(e,n,{allowNewline:s,allowEof:i,raw:r,consumeStopSequence:a=!0}){let l="";for(;!this.isAtEnd()&&(s||!this.check(`
4
4
  `))&&!this.check(n);)this.peek()==="\\"&&!r?(this.advance(),l+=this.escapedString()):l+=this.advance();if(this.isAtEnd()&&!i){const p=this.createToken(e,!0);this.tokens.push(p),this.errors.push(new c(o.UNEXPECTED_EOF,"EOF reached while parsing",p));return}if(this.check(`
5
- `)&&!s){const p=this.createToken(e,!0);this.tokens.push(p),this.errors.push(new c(o.UNEXPECTED_NEWLINE,"Invalid newline encountered while parsing",p));return}a&&this.match(n),this.tokens.push(B.create(e,this.start,this.current,l,!1))}singleLineStringLiteral(){this.consumeUntil(u.STRING_LITERAL,"'",{allowNewline:!1,allowEof:!1,raw:!1})}multilineStringLiteral(){this.consumeUntil(u.STRING_LITERAL,"'''",{allowNewline:!0,allowEof:!1,raw:!1})}functionExpression(){this.consumeUntil(u.FUNCTION_EXPRESSION,"`",{allowNewline:!1,allowEof:!1,raw:!0})}quotedVariable(){this.consumeUntil(u.QUOTED_STRING,'"',{allowNewline:!1,allowEof:!1,raw:!1})}singleLineComment(){this.consumeUntil(u.SINGLE_LINE_COMMENT,`
6
- `,{allowNewline:!0,allowEof:!0,raw:!0,consumeStopSequence:!1})}multilineComment(){this.consumeUntil(u.MULTILINE_COMMENT,"*/",{allowNewline:!0,allowEof:!1,raw:!0})}identifier(){for(;!this.isAtEnd()&&pe(this.peek());)this.advance();this.addToken(u.IDENTIFIER)}operator(){for(;rt(this.peek());)this.advance();this.addToken(u.OP)}numericLiteralOrIdentifier(){let e=0;if(this.isAtEnd())return this.addToken(u.NUMERIC_LITERAL);for(;!this.isAtEnd();){const n=this.check(".");if(e+=n?1:0,e>1)break;if(!n&&this.current.offset===this.text.length-1)return this.advance(),this.addToken(u.NUMERIC_LITERAL);if(!n&&!pe(this.peek()))return this.addToken(u.NUMERIC_LITERAL);if(!n&&!Oe(this.peek()))break;this.advance()}if(e>0){for(;!this.isAtEnd()&&(this.check(".")||pe(this.peek()));)this.advance();const n=this.createToken(u.NUMERIC_LITERAL,!0);this.tokens.push(n),this.errors.push(new c(o.UNKNOWN_TOKEN,"Invalid number",n))}else{for(;!this.isAtEnd()&&pe(this.peek());)this.advance();const n=this.createToken(u.IDENTIFIER,!1);this.tokens.push(n)}}colorLiteral(){for(;!this.isAtEnd()&&pe(this.peek());)this.advance();this.addToken(u.COLOR_LITERAL)}escapedString(){if(this.isAtEnd())return"\\";switch(this.advance()){case"t":return" ";case"n":return`
7
- `;case"\\":return"\\";case"r":return"\r";case"'":return"'";case'"':return'"';case"0":return"\0";case"b":return"\b";case"v":return"\v";case"f":return"\f";case"u":{let e="";for(let n=0;n<=3;n+=1){if(this.isAtEnd()||!pe(this.peek()))return`\\u${e}`;e+=this.advance()}return String.fromCharCode(parseInt(e,16))}default:return`\\${this.tokens[this.current.offset-1]}`}}}var xe=(t=>(t[t.ListExpression=0]="ListExpression",t[t.GroupExpression=1]="GroupExpression",t[t.BlockExpression=2]="BlockExpression",t))(xe||{});class un{constructor(){this.stack=[],this.numberOfNestedLParens=0,this.numberOfNestedLBrackets=0,this.numberOfNestedLBraces=0}push(e){this.stack.push(e),e===0&&(this.numberOfNestedLBrackets+=1),e===1&&(this.numberOfNestedLParens+=1),e===2&&(this.numberOfNestedLBraces+=1)}pop(){const e=this.stack.pop();return e===0&&(this.numberOfNestedLBrackets-=1),e===1&&(this.numberOfNestedLParens-=1),e===2&&(this.numberOfNestedLBraces-=1),e}top(){return I.last(this.stack)}isWithinGroupExpressionContext(){return this.numberOfNestedLParens>0}isWithinListExpressionContext(){return this.numberOfNestedLBrackets>0}isWithinBlockExpressionContext(){return this.numberOfNestedLBraces>0}withContextDo(e,n){return()=>{this.push(e);try{return n()}finally{this.pop()}}}findHandlerContext(e,n){if(!(this.numberOfNestedLBraces<=0&&this.numberOfNestedLBrackets<=0&&this.numberOfNestedLParens<=0))for(let s=n;s<e.length-1;s+=1)switch(e[s].kind){case u.COMMA:if(this.isWithinGroupExpressionContext()||this.isWithinListExpressionContext())return[...this.stack].reverse().find(r=>[1,0].includes(r));break;case u.RPAREN:if(this.isWithinGroupExpressionContext())return 1;break;case u.RBRACE:if(this.isWithinBlockExpressionContext())return 2;break;case u.RBRACKET:if(this.isWithinListExpressionContext())return 0;break}}}class hn{constructor(e){this.generator=e}create(e,n){return new e(n,this.generator.nextId())}}class d{constructor(e,n,s){this.token=e,this.partialNode=n,this.handlerContext=s}}class fn{constructor(e,n){this.current=0,this.errors=[],this.contextStack=new un,this.synchronizeProgram=()=>{const s=this.peek();s.kind!==u.EOF?E(this.advance()):(E(this.peek()),this.logError(s,o.UNEXPECTED_EOF,"Unexpected EOF"))},this.synchronizeElementDeclarationName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(ct(s)||this.check(u.COLON,u.LBRACE,u.LBRACKET))break;E(s),this.advance()}},this.synchronizeElementDeclarationAlias=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.COLON,u.LBRACE,u.LBRACKET))break;E(s),this.advance()}},this.blockExpression=this.contextStack.withContextDo(xe.BlockExpression,()=>{const s={body:[]},i=()=>this.nodeFactory.create(ne,s);try{this.consume("Expect an opening brace '{'",u.LBRACE),s.blockOpenBrace=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.blockOpenBrace=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}for(;!this.isAtEnd()&&!this.check(u.RBRACE);)try{s.body.push(this.canBeField()?this.fieldDeclaration():this.expression())}catch(r){if(!(r instanceof d))throw r;if(s.body.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}try{this.consume("Expect a closing brace '}'",u.RBRACE),s.blockCloseBrace=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.blockCloseBrace=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}return i()}),this.synchronizeBlock=()=>{if(!this.check(u.RBRACE))for(E(this.advance());!this.isAtEnd();){const s=this.peek();if(this.check(u.RBRACE)||ot(this.previous(),s))break;E(s),this.advance()}},this.tupleExpression=this.contextStack.withContextDo(xe.GroupExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(je,{groupOpenParen:s.tupleOpenParen,groupCloseParen:s.tupleCloseParen,expression:s.elementList[0]}),r=()=>this.nodeFactory.create(Z,s);try{this.consume("Expect an opening parenthesis '('",u.LPAREN),s.tupleOpenParen=this.previous()}catch(a){if(!(a instanceof d))throw a;if(s.tupleOpenParen=a.partialNode,!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}if(!this.isAtEnd()&&!this.check(u.RPAREN))try{s.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof d))throw a;if(s.elementList.push(a.partialNode),!this.canHandle(a))throw new d(a.token,i(),a.handlerContext);this.synchronizeTuple()}for(;!this.isAtEnd()&&!this.check(u.RPAREN);)try{this.consume("Expect a comma ','",u.COMMA),s.commaList.push(this.previous()),s.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof d))throw a;if(a.partialNode instanceof k&&s.elementList.push(a.partialNode),!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}try{this.consume("Expect a closing parenthesis ')'",u.RPAREN),s.tupleCloseParen=this.previous()}catch(a){if(!(a instanceof d))throw a;if(s.tupleCloseParen=a.partialNode,!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}return s.elementList.length===1?i():r()}),this.synchronizeTuple=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.RPAREN,u.COMMA))break;E(s),this.advance()}},this.listExpression=this.contextStack.withContextDo(xe.ListExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(P,s);try{this.consume("Expect an opening bracket '['",u.LBRACKET),s.listOpenBracket=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.listOpenBracket=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}if(!this.isAtEnd()&&!this.check(u.RBRACKET))try{s.elementList.push(this.attribute())}catch(r){if(!(r instanceof d))throw r;if(s.elementList.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}for(;!this.isAtEnd()&&!this.check(u.RBRACKET);)try{this.consume("Expect a comma ','",u.COMMA),s.commaList.push(this.previous()),s.elementList.push(this.attribute())}catch(r){if(!(r instanceof d))throw r;if(r.partialNode instanceof k&&s.elementList.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}try{this.consume("Expect a closing bracket ']'",u.RBRACKET),s.listCloseBracket=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.listCloseBracket=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}return i()}),this.synchronizeList=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.COMMA,u.RBRACKET))break;E(s),this.advance()}},this.synchronizeAttributeName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.COMMA,u.RBRACKET,u.COLON))break;E(s),this.advance()}},this.synchronizeAttributeValue=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.COMMA,u.RBRACKET))break;E(s),this.advance()}},this.tokens=e,this.nodeFactory=new hn(n)}isAtEnd(){return this.current>=this.tokens.length||this.tokens[this.current].kind===u.EOF}advance(){return this.isAtEnd()?I.last(this.tokens):this.tokens[this.current++]}peek(e=0){return e+this.current>=this.tokens.length?I.last(this.tokens):this.tokens[this.current+e]}match(...e){const n=this.check(...e);return n&&this.advance(),n}check(...e){const n=this.peek();return e.includes(n.kind)}previous(){return this.tokens[this.current-1]}canHandle(e){return e.handlerContext===void 0||e.handlerContext===this.contextStack.top()}consume(e,...n){if(!this.match(...n))throw this.logError(this.peek(),o.UNEXPECTED_TOKEN,e),new d(this.peek(),void 0,this.contextStack.findHandlerContext(this.tokens,this.current))}discardUntil(e,...n){if(this.isAtEnd()||!this.check(...n)){for(E(this.peek()),this.logError(this.advance(),o.UNEXPECTED_TOKEN,e);!this.isAtEnd()&&!this.check(...n);)E(this.advance());return!this.isAtEnd()}return!0}gatherInvalid(){const e=[],n=[];let s,i=0;for(;i<this.tokens.length&&this.tokens[i].isInvalid;i+=1)n.push(this.tokens[i]);for(s=this.tokens[i],s.leadingInvalid=n,e.push(s),i+=1;i<this.tokens.length;i+=1){const r=this.tokens[i];r.isInvalid?s.trailingInvalid.push(r):(s=r,e.push(s))}this.tokens=e}parse(){const e=this.program(),n=this.advance(),s=this.nodeFactory.create(G,{body:e,eof:n});return this.gatherInvalid(),new F({ast:s,tokens:this.tokens},this.errors)}program(){const e=[];for(;!this.isAtEnd();)try{const n=this.elementDeclaration();e.push(n)}catch(n){if(!(n instanceof d))throw n;e.push(n.partialNode),this.synchronizeProgram()}return e}elementDeclaration(){const e={},n=()=>this.nodeFactory.create(A,e);try{this.consume("Expect an identifier",u.IDENTIFIER),e.type=this.previous()}catch(s){throw s instanceof d?(e.type=s.partialNode,new d(s.token,n(),s.handlerContext)):s}if(!this.check(u.COLON,u.LBRACE,u.LBRACKET))try{e.name=this.normalExpression()}catch(s){if(!(s instanceof d))throw s;if(e.name=s.partialNode,!this.canHandle(s))throw new d(s.token,n(),s.handlerContext);this.synchronizeElementDeclarationName()}if(ct(this.peek()))if(e.as=this.advance(),this.check(u.COLON,u.LBRACE,u.LBRACKET))this.logError(this.peek(),o.UNEXPECTED_TOKEN,"Expect an alias");else try{e.alias=this.normalExpression()}catch(s){if(!(s instanceof d))throw s;if(e.alias=s.partialNode,!this.canHandle(s))throw new d(s.token,n(),s.handlerContext);this.synchronizeElementDeclarationAlias()}try{e.attributeList=this.check(u.LBRACKET)?this.listExpression():void 0}catch(s){throw s instanceof d?(e.attributeList=s.partialNode,new d(s.token,n(),s.handlerContext)):s}if(!this.discardUntil("Expect an opening brace '{' or a colon ':'",u.LBRACE,u.COLON))return n();try{if(this.match(u.COLON)){e.bodyColon=this.previous();const s=this.expression();s instanceof A?(E(s),this.logError(s,o.UNEXPECTED_ELEMENT_DECLARATION,"An element's simple body must not be an element declaration")):e.body=s}else e.body=this.blockExpression()}catch(s){throw s instanceof d?(e.body=s.partialNode,new d(s.token,n(),s.handlerContext)):s}return this.nodeFactory.create(A,e)}fieldDeclaration(){const e={},n=()=>this.nodeFactory.create(A,e);try{this.consume("Expect an identifier",u.IDENTIFIER),e.type=this.previous()}catch(s){throw s instanceof d?(e.type=s.partialNode,new d(s.token,n(),s.handlerContext)):s}try{this.consume("Expect a colon ':'",u.COLON),e.bodyColon=this.previous()}catch(s){throw s instanceof d?(e.bodyColon=s.partialNode,new d(s.token,n(),s.handlerContext)):s}try{const s=this.expression();s instanceof A?this.errors.push(new c(o.INVALID_ELEMENT_IN_SIMPLE_BODY,"Simple body cannot be an element declaration",s)):e.body=s}catch(s){throw s instanceof d?(e.body=s.partialNode,new d(s.token,n(),s.handlerContext)):s}return this.nodeFactory.create(A,e)}expression(){const e={args:[]},n=()=>rn(e.callee,e.args,this.nodeFactory).unwrap_or(this.nodeFactory.create(w,e));try{e.callee=this.normalExpression()}catch(i){throw i instanceof d?(e.callee=i.partialNode,new d(i.token,n(),i.handlerContext)):i}if(this.shouldStopExpression())return n();let s=e.callee;for(;!this.shouldStopExpression();){Ce(this.previous())||this.logError(s,o.MISSING_SPACES,"Expect a following space");try{s=this.normalExpression(),e.args.push(s)}catch(i){throw i instanceof d?(s=i.partialNode,e.args.push(s),new d(i.token,n(),i.handlerContext)):i}}return n()}shouldStopExpression(){if(this.isAtEnd()||bt(this.previous()))return!0;const e=this.peek().kind;return e===u.RBRACE||e===u.RBRACKET||e===u.RPAREN||e===u.COMMA||e===u.COLON}normalExpression(){return this.expression_bp(0)}expression_bp(e){let n=this.leftExpression_bp();for(;!this.isAtEnd();){const s=this.peek();if(s.kind===u.LPAREN){const{left:i}=ut(s);if(i<e||ot(this.previous(),s)&&!this.contextStack.isWithinGroupExpressionContext()&&!this.contextStack.isWithinListExpressionContext())break;try{n=this.nodeFactory.create(J,{callee:n,argumentList:this.tupleExpression()})}catch(r){throw r instanceof d?(n=this.nodeFactory.create(J,{callee:n,argumentList:r.partialNode}),new d(r.token,n,r.handlerContext)):r}}else if(s.kind===u.LBRACKET){if(Ce(this.previous()))break;try{n=this.nodeFactory.create(ce,{expression:n,indexer:this.listExpression()})}catch(i){throw i instanceof d?(n=this.nodeFactory.create(ce,{expression:n,indexer:i.partialNode}),new d(i.token,n,i.handlerContext)):i}}else if(at(s)){const i=s,r=ut(i);if(r.left!==null){if(r.left<=e)break;this.advance(),n=this.nodeFactory.create(Pe,{expression:n,op:i})}else{const a=dn(i);if(a.left===null||a.left<=e)break;this.advance();try{n=this.nodeFactory.create(H,{leftExpression:n,op:i,rightExpression:i.value==="."?this.extractOperand():this.expression_bp(a.right)})}catch(l){throw l instanceof d?(n=this.nodeFactory.create(H,{leftExpression:n,op:i,rightExpression:l.partialNode}),new d(l.token,n,l.handlerContext)):l}}}else break}return n}leftExpression_bp(){let e;if(at(this.peek())){const n={};n.op=this.peek();const s=Nn(n.op);if(s.right===null)throw this.logError(n.op,o.UNKNOWN_PREFIX_OP,`Unexpected '${n.op.value}' in an expression`),new d(n.op,this.nodeFactory.create(ke,{pre:n.op}),this.contextStack.findHandlerContext(this.tokens,this.current));this.advance();try{n.expression=this.expression_bp(s.right)}catch(i){throw i instanceof d?(n.expression=i.partialNode,new d(i.token,this.nodeFactory.create(Q,n),i.handlerContext)):i}e=this.nodeFactory.create(Q,n)}else if(e=this.extractOperand(),e instanceof ke)throw new d(this.peek(),this.nodeFactory.create(ke,{pre:this.peek()}),this.contextStack.findHandlerContext(this.tokens,this.current));return e}extractOperand(){return this.check(u.NUMERIC_LITERAL,u.STRING_LITERAL,u.COLOR_LITERAL,u.QUOTED_STRING,u.IDENTIFIER)?this.primaryExpression():this.check(u.FUNCTION_EXPRESSION)?this.functionExpression():this.check(u.LBRACKET)?this.listExpression():this.check(u.LBRACE)?this.blockExpression():this.check(u.LPAREN)?this.tupleExpression():(this.peek().kind===u.EOF?this.logError(this.peek(),o.UNEXPECTED_EOF,"Unexpected EOF"):this.logError(this.peek(),o.INVALID_OPERAND,`Invalid start of operand "${this.peek().value}"`),this.nodeFactory.create(ke,{pre:this.previous()}))}functionExpression(){const e={};try{this.consume("Expect a function expression",u.FUNCTION_EXPRESSION),e.value=this.previous()}catch(n){throw n instanceof d?(e.value=n.partialNode,new d(n.token,this.nodeFactory.create(te,e),n.handlerContext)):n}return this.nodeFactory.create(te,e)}canBeField(){return this.peek().kind===u.IDENTIFIER&&this.peek(1).kind===u.COLON}primaryExpression(){if(this.match(u.COLOR_LITERAL,u.STRING_LITERAL,u.NUMERIC_LITERAL))return this.nodeFactory.create(D,{expression:this.nodeFactory.create(Te,{literal:this.previous()})});if(this.match(u.QUOTED_STRING,u.IDENTIFIER))return this.nodeFactory.create(D,{expression:this.nodeFactory.create(W,{variable:this.previous()})});throw this.logError(this.peek(),o.UNEXPECTED_TOKEN,"Expect a variable or literal"),new d(this.peek(),this.nodeFactory.create(D,{expression:this.nodeFactory.create(W,{})}),this.contextStack.findHandlerContext(this.tokens,this.current))}attribute(){const e={};if(this.check(u.COLON,u.RBRACKET,u.COMMA)){const n=this.peek();this.logError(n,o.EMPTY_ATTRIBUTE_NAME,"Expect a non-empty attribute name"),e.name=this.nodeFactory.create($,{identifiers:[]})}else try{e.name=this.attributeName()}catch(n){if(!(n instanceof d))throw n;if(e.name=n.partialNode,!this.canHandle(n))throw new d(n.token,this.nodeFactory.create(se,e),n.handlerContext);this.synchronizeAttributeName()}return this.match(u.COLON)&&(e.colon=this.previous(),e.value=this.attributeValue()),this.nodeFactory.create(se,e)}attributeValue(){let e;try{e=this.peek().kind===u.IDENTIFIER&&this.peek(1).kind===u.IDENTIFIER?this.attributeName():this.normalExpression()}catch(n){if(!(n instanceof d)||!this.canHandle(n))throw n;e=n.partialNode,this.synchronizeAttributeValue()}return e}attributeName(){const e=[];if(this.peek().kind!==u.IDENTIFIER)return this.primaryExpression();for(;!this.isAtEnd()&&!this.check(u.COLON,u.COMMA,u.RBRACKET);)try{this.consume("Expect an identifier",u.IDENTIFIER),e.push(this.previous())}catch(n){throw n instanceof d?new d(n.token,this.nodeFactory.create($,{identifiers:e}),n.handlerContext):n}return this.nodeFactory.create($,{identifiers:e})}logError(e,n,s){this.errors.push(new c(n,s,e))}}const pn={"+":{left:9,right:10},"*":{left:11,right:12},"-":{left:9,right:10},"/":{left:11,right:12},"%":{left:11,right:12},"<":{left:7,right:8},"<=":{left:7,right:8},">":{left:7,right:8},">=":{left:7,right:8},"<>":{left:7,right:8},"=":{left:2,right:3},"==":{left:4,right:5},"!=":{left:4,right:5},".":{left:16,right:17}};function dn(t){return pn[t.value]||{left:null,right:null}}const En={"+":{left:null,right:15},"-":{left:null,right:15},"<":{left:null,right:15},">":{left:null,right:15},"<>":{left:null,right:15},"!":{left:null,right:15}};function Nn(t){return En[t.value]||{left:null,right:null}}const mn={"(":{left:14,right:null}};function ut(t){return mn[t.value]||{left:null,right:null}}var b=(t=>(t.Table="table",t.Enum="enum",t.Ref="ref",t.Note="note",t.Project="project",t.Indexes="indexes",t.TableGroup="tablegroup",t))(b||{});function ve(t){var n;const e=(n=t==null?void 0:t.type)==null?void 0:n.value.toLowerCase();switch(e){case b.Enum:case b.Table:case b.Indexes:case b.Note:case b.Project:case b.Ref:case b.TableGroup:return new S(e);default:return new v}}function he(t){if(!Je(t))return new S([t]);const e=he(t.leftExpression).unwrap_or(void 0);return e?(e.push(t.rightExpression),new S(e)):new v}function C(t){if(t===void 0)return new v;const e=he(t).unwrap_or(void 0);if(!e)return new v;const n=[];for(const s of e){const i=X(s).unwrap_or(void 0);if(!i)return new v;n.push(i)}return new S(n)}function _e(t){if(t===void 0)return new v;const e=he(t).unwrap_or(void 0);if(!e||e.length===0)return new v;const n=[];let s;if(!M(I.last(e))){const i=e.pop();if(kt(i))s=i.elementList.map(r=>V(r).unwrap());else return new v}for(const i of e){const r=X(i).unwrap_or(void 0);if(!r)return new v;n.push(r)}return new S({variables:n,tupleElements:s})}function X(t){return M(t)?new S(t.expression.variable.value):new v}function Xe(t){if(ht(t))return t instanceof te?new S({functional:[t],nonFunctional:[]}):new S({functional:[],nonFunctional:[t]});if(t instanceof Z&&t.elementList.every(ht)){const e=t.elementList.filter(s=>s instanceof te),n=t.elementList.filter(M);return new S({functional:e,nonFunctional:n})}return new v}function V(t){var n;const e=(n=t==null?void 0:t.expression.variable)==null?void 0:n.value;return e===void 0?new v:new S(e)}function q(t){return Y(t)?t.expression instanceof W?new S(t.expression.variable.value):new S(t.expression.literal.value):new v}function Tn(t){var e;return!(t instanceof H)||!yt((e=t.op)==null?void 0:e.value)?!1:_e(t.leftExpression).and_then(()=>_e(t.rightExpression)).unwrap_or(void 0)!==void 0}function bn(t){const e=_e(t.leftExpression),n=_e(t.rightExpression);if(!e.isOk()||!n.isOk())return!1;const{tupleElements:s}=e.unwrap(),{tupleElements:i}=n.unwrap();return(s==null?void 0:s.length)===(i==null?void 0:i.length)}function ht(t){return t instanceof D&&t.expression instanceof W||t instanceof te}function In(t,e){var i,r,a,l;let n=e;const s=Qt(t);for(;n;){if((r=(i=n.symbol)==null?void 0:i.symbolTable)!=null&&r.has(t))return(a=n.symbol.symbolTable)==null?void 0:a.get(t);if(((l=n.symbol)==null?void 0:l.declaration)instanceof G&&s)return n.symbol;if(n instanceof G)return;n=n.parent}}class Ln{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof G||ve(this.declarationNode.parent).unwrap_or(void 0)!==b.Project?[new c(o.INVALID_CUSTOM_CONTEXT,"A custom element can only appear in a Project",this.declarationNode)]:[]}validateName(e){return e?[new c(o.UNEXPECTED_NAME,"A Custom element shouldn't have a name",e)]:[]}validateAlias(e){return e?[new c(o.UNEXPECTED_NAME,"A Custom element shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"A Custom element shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof ne)return[new c(o.UNEXPECTED_COMPLEX_BODY,"A Custom element can only have an inline field",e)];const n=[];return Y(e.callee)||n.push(new c(o.INVALID_CUSTOM_ELEMENT_VALUE,"A Custom element value can only be a string",e)),e.args.length>0&&n.push(...e.args.map(s=>new c(o.INVALID_CUSTOM_ELEMENT_VALUE,"A Custom element value can only be a string",s))),n}}class we{constructor(){this.table=new Map}has(e){return this.table.has(e)}set(e,n){this.table.set(e,n)}get(e,n){return this.table.get(e)||n!==void 0&&this.set(e,n)||n}entries(){return this.table.entries()}}class gn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof A?[new c(o.INVALID_PROJECT_CONTEXT,"An Enum can only appear top-level",this.declarationNode)]:[]}validateName(e){return e?Ze(e)?[]:[new c(o.INVALID_NAME,"An Enum name must be of the form <enum> or <schema>.<enum>",e)]:[new c(o.NAME_NOT_FOUND,"An Enum must have a name",this.declarationNode)]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}registerElement(){const e=[];this.declarationNode.symbol=this.symbolFactory.create(Kt,{declaration:this.declarationNode,symbolTable:new we});const{name:n}=this.declarationNode,s=C(n);if(s.isOk()){const i=s.unwrap(),r=i.pop(),a=Ke(i,this.publicSymbolTable,this.symbolFactory),l=ze(r);a.has(l)&&e.push(new c(o.DUPLICATE_NAME,`Enum name ${r} already exists in schema '${i.join(".")||"public"}'`,n)),a.set(l,this.declarationNode.symbol)}return e}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"An Enum shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return this.validateFields([e]);const[n,s]=I.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.length===0?[new c(o.EMPTY_ENUM,"An Enum must have at least one element",this.declarationNode)]:e.flatMap(n=>{const s=[];n.callee&&!M(n.callee)&&s.push(new c(o.INVALID_ENUM_ELEMENT_NAME,"An enum field must be an identifier or a quoted identifier",n.callee));const i=[...n.args];return I.last(i)instanceof P?(s.push(...this.validateFieldSettings(I.last(i))),i.pop()):i[0]instanceof P&&(s.push(...this.validateFieldSettings(i[0])),i.shift()),i.length>0&&s.push(...i.map(r=>new c(o.INVALID_ENUM_ELEMENT,"An Enum must have only a field and optionally a setting list",r))),s.push(...this.registerField(n)),s})}validateFieldSettings(e){const n=j(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"note":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_ENUM_ELEMENT_SETTING,"'note' can only appear once",l))),a.forEach(l=>{Y(l.value)||s.push(new c(o.INVALID_ENUM_ELEMENT_SETTING,"'note' must be a string",l))});break;default:a.forEach(l=>s.push(new c(o.UNKNOWN_ENUM_ELEMENT_SETTING,`Unknown enum field setting '${r}'`,l)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=re(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}registerField(e){if(e.callee&&M(e.callee)){const n=V(e.callee).unwrap(),s=qe(n),i=this.symbolFactory.create(en,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(s)){const a=r.get(s);return[new c(o.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,e),new c(o.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,a.declaration)]}r.set(s,i)}return[]}}class _n{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof G||ve(this.declarationNode.parent).unwrap_or(void 0)!==b.Table?[new c(o.INVALID_NOTE_CONTEXT,"An Indexes can only appear inside a Table",this.declarationNode)]:[]}validateName(e){return e?[new c(o.UNEXPECTED_NAME,"An Indexes shouldn't have a name",e)]:[]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"An Indexes shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"An Indexes shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return[new c(o.UNEXPECTED_SIMPLE_BODY,"An Indexes must have a complex body",e)];const[n,s]=I.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.flatMap(n=>{if(!n.callee)return[];const s=[],i=[n.callee,...n.args];return I.last(i)instanceof P&&s.push(...this.validateFieldSetting(i.pop())),i.forEach(r=>{for(;r instanceof J;)r.argumentList&&!Xe(r.argumentList).isOk()&&s.push(new c(o.INVALID_INDEXES_FIELD,"An index field must be an identifier, a quoted identifier, a functional expression or a tuple of such",r.argumentList)),r=r.callee;Xe(r).isOk()||s.push(new c(o.INVALID_INDEXES_FIELD,"An index field must be an identifier, a quoted identifier, a functional expression or a tuple of such",r))}),s})}validateFieldSetting(e){const n=j(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"note":case"name":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_INDEX_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{Y(l.value)||s.push(new c(o.INVALID_INDEX_SETTING_VALUE,`'${r}' must be a string`,l))});break;case"unique":case"pk":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_INDEX_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{le(l.value)||s.push(new c(o.INVALID_INDEX_SETTING_VALUE,`'${r}' must not have a value`,l))});break;case"type":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_INDEX_SETTING,"'type' can only appear once",l))),a.forEach(l=>{M(l.value)||s.push(new c(o.INVALID_INDEX_SETTING_VALUE,`'type' must be "btree" or "hash"`,l))});break;default:a.forEach(l=>s.push(new c(o.UNKNOWN_INDEX_SETTING,`Unknown index setting '${r}'`,l)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=re(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class An{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return!(this.declarationNode.parent instanceof G)&&![b.Table,b.Project].includes(ve(this.declarationNode.parent).unwrap_or(void 0))?[new c(o.INVALID_NOTE_CONTEXT,"A Note can only appear inside a Table or a Project. Sticky note can only appear at the global scope.",this.declarationNode)]:[]}validateName(e){if(!(this.declarationNode.parent instanceof G))return e?[new c(o.UNEXPECTED_NAME,"A Note shouldn't have a name",e)]:[];if(!e)return[new c(o.INVALID_NAME,"Sticky note must have a name",this.declarationNode)];const n=C(e);if(!n.isOk())return[new c(o.INVALID_NAME,"Invalid name for sticky note ",this.declarationNode)];const i=n.unwrap().join("."),r=qt(i);return this.publicSymbolTable.has(r)?[new c(o.DUPLICATE_NAME,`Sticky note "${i}" has already been defined`,e)]:(this.publicSymbolTable.set(r,this.declarationNode.symbol),[])}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"A Note shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return this.validateFields([e]);const[n,s]=I.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){const n=[];return e.length===0?[new c(o.EMPTY_NOTE,"A Note must have a content",this.declarationNode)]:(e.length>1&&e.slice(1).forEach(s=>n.push(new c(o.NOTE_CONTENT_REDEFINED,"A Note can only contain one string",s))),Y(e[0].callee)||n.push(new c(o.INVALID_NOTE,"A Note content must be a quoted string",e[0])),e[0].args.length>0&&n.push(...e[0].args.map(s=>new c(o.INVALID_NOTE,"A Note can only contain one quoted string",s))),n)}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=re(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class vn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof A?[new c(o.INVALID_PROJECT_CONTEXT,"A Project can only appear top-level",this.declarationNode)]:[]}validateName(e){return e?Me(e)?[]:[new c(o.INVALID_NAME,"A Project's name is optional or must be an identifier or a quoted identifer",e)]:[]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A Project shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"A Project shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return[new c(o.UNEXPECTED_SIMPLE_BODY,"A Project's body must be a block",e)];const[n,s]=I.partition(e.body,i=>i instanceof w);return[...n.map(i=>new c(o.INVALID_PROJECT_FIELD,"A Project can not have inline fields",i)),...this.validateSubElements(s)]}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=re(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class wn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof G?[]:[new c(o.INVALID_REF_CONTEXT,"A Ref must appear top-level",this.declarationNode)]}validateName(e){return e?Me(e)?[]:[new c(o.INVALID_NAME,"A Ref's name is optional or must be an identifier or a quoted identifer",e)]:[]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"A Ref shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return this.validateFields([e]);const[n,s]=I.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){if(e.length===0)return[new c(o.EMPTY_REF,"A Ref must have at least one field",this.declarationNode)];const n=[];return e.length>1&&n.push(...e.slice(1).map(s=>new c(o.REF_REDEFINED,"A Ref can only contain one binary relationship",s))),e.forEach(s=>{s.callee&&!Tn(s.callee)&&n.push(new c(o.INVALID_REF_FIELD,"A Ref field must be a binary relationship",s.callee)),s.callee&&!bn(s.callee)&&n.push(new c(o.UNEQUAL_FIELDS_BINARY_REF,"Unequal fields in ref endpoints",s.callee));const i=[...s.args];I.last(i)instanceof P?(this.validateFieldSettings(I.last(i)),i.pop()):i[0]instanceof P&&(n.push(...this.validateFieldSettings(i[0])),i.shift()),i.length>0&&n.push(...i.map(r=>new c(o.INVALID_REF_FIELD,"A Ref field should only have a single binary relationship",r)))}),n}validateFieldSettings(e){const n=j(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"delete":case"update":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_REF_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{yn(l.value)||s.push(new c(o.INVALID_REF_SETTING_VALUE,`'${r}' can only have values "cascade", "no action", "set null", "set default" or "restrict"`,l))});break;default:a.forEach(l=>s.push(new c(o.UNKNOWN_REF_SETTING,`Unknown ref setting '${r}'`,l)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=re(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}function yn(t){if(!(M(t)&&t.expression.variable.kind!==u.QUOTED_STRING)&&!(t instanceof $))return!1;let e;if(t instanceof $?e=me(t).unwrap_or(""):e=t.expression.variable.value,e)switch(e.toLowerCase()){case"cascade":case"no action":case"set null":case"set default":case"restrict":return!0;default:return!1}return!1}class kn{constructor(e,n,s){this.declarationNode=e,this.symbolFactory=s,this.publicSymbolTable=n}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof A?[new c(o.INVALID_TABLE_CONTEXT,"Table must appear top-level",this.declarationNode)]:[]}validateName(e){return e?e instanceof ce?[new c(o.INVALID_NAME,"Invalid array as Table name, maybe you forget to add a space between the name and the setting list?",e)]:Ze(e)?[]:[new c(o.INVALID_NAME,"A Table name must be of the form <table> or <schema>.<table>",e)]:[new c(o.NAME_NOT_FOUND,"A Table must have a name",this.declarationNode)]}validateAlias(e){return e?Rn(e)?[]:[new c(o.INVALID_ALIAS,"Table aliases can only contains alphanumeric and underscore unless surrounded by double quotes",e)]:[]}validateSettingList(e){const n=j(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"headercolor":a.length>1&&s.push(...a.map(l=>new c(o.DUPLICATE_TABLE_SETTING,"'headercolor' can only appear once",l))),a.forEach(l=>{Dn(l.value)||s.push(new c(o.INVALID_TABLE_SETTING,"'headercolor' must be a color literal",l.value||l.name))});break;case"note":a.length>1&&s.push(...a.map(l=>new c(o.DUPLICATE_TABLE_SETTING,"'note' can only appear once",l))),a.forEach(l=>{Y(l.value)||s.push(new c(o.INVALID_TABLE_SETTING,"'note' must be a string literal",l.value||l.name))});break;default:s.push(...a.map(l=>new c(o.INVALID_TABLE_SETTING,`Unknown '${r}' setting`,l)))}}return s}registerElement(){const e=[];this.declarationNode.symbol=this.symbolFactory.create(At,{declaration:this.declarationNode,symbolTable:new we});const{name:n,alias:s}=this.declarationNode,i=C(n);if(i.isOk()){const r=[...i.unwrap()],a=r.pop(),l=Ke(r,this.publicSymbolTable,this.symbolFactory),p=Se(a);l.has(p)&&e.push(new c(o.DUPLICATE_NAME,`Table name '${a}' already exists in schema '${r.join(".")||"public"}'`,n)),l.set(p,this.declarationNode.symbol)}if(s&&Me(s)&&!Sn(s.expression.variable.value,i.unwrap_or([]))){const r=V(s).unwrap(),a=Se(r);this.publicSymbolTable.has(a)&&e.push(new c(o.DUPLICATE_NAME,`Table name '${r}' already exists`,n)),this.publicSymbolTable.set(a,this.declarationNode.symbol)}return e}validateBody(e){if(!e)return[];if(e instanceof w)return[new c(o.UNEXPECTED_SIMPLE_BODY,"A Table's body must be a block",e)];const[n,s]=I.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.length===0?[new c(o.EMPTY_TABLE,"A Table must have at least one column",this.declarationNode)]:e.flatMap(n=>{if(!n.callee)return[];const s=[];n.args.length===0&&s.push(new c(o.INVALID_COLUMN,"A column must have a type",n.callee)),M(n.callee)||s.push(new c(o.INVALID_COLUMN_NAME,"A column name must be an identifier or a quoted identifier",n.callee)),n.args[0]&&!xn(n.args[0])&&s.push(new c(o.INVALID_COLUMN_TYPE,"Invalid column type",n.args[0]));const i=n.args.slice(1);return s.push(...this.validateFieldSetting(i)),s.push(...this.registerField(n)),s})}registerField(e){if(e.callee&&M(e.callee)){const n=V(e.callee).unwrap(),s=Ye(n),i=this.symbolFactory.create(tn,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(s)){const a=r.get(s);return[new c(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,e),new c(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,a.declaration)]}r.set(s,i)}return[]}validateFieldSetting(e){if(!e.slice(0,-1).every(Ne)||!e.slice(-1).every(p=>Ne(p)||p instanceof P))return[...e.map(p=>new c(o.INVALID_COLUMN,"These fields must be some inline settings optionally ended with a setting list",p))];if(e.length===0)return[];let n;I.last(e)instanceof P&&(n=e.pop());const s=j(n),i=s.getErrors(),r=s.getValue();for(const p of e){const h=V(p).unwrap_or("").toLowerCase();if(h!=="pk"&&h!=="unique"){i.push(new c(o.INVALID_SETTINGS,"Inline column settings can only be `pk` or `unique`",p));continue}r[h]===void 0?r[h]=[p]:r[h].push(p)}const a=r.pk||[],l=r["primary key"]||[];a.length>=1&&l.length>=1&&i.push(...[...a,...l].map(p=>new c(o.DUPLICATE_COLUMN_SETTING,"Either one of 'primary key' and 'pk' can appear",p)));for(const p in r){const h=r[p];switch(p){case"note":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_COLUMN_SETTING,"note can only appear once",f))),h.forEach(f=>{Y(f.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'note' must be a quoted string",f.value||f.name))});break;case"ref":h.forEach(f=>{Un(f.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'ref' must be a valid unary relationship",f.value||f.name))});break;case"primary key":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_COLUMN_SETTING,"primary key can only appear once",f))),h.forEach(f=>{le(f.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'primary key' must not have a value",f.value||f.name))});break;case"pk":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_COLUMN_SETTING,"'pk' can only appear once",f))),h.forEach(f=>{f instanceof se&&!le(f.value)&&i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'pk' must not have a value",f.value||f.name))});break;case"not null":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_COLUMN_SETTING,"'not null' can only appear once",f)));const T=r.null||[];h.length>=1&&T.length>=1&&i.push(...[...h,...T].map(f=>new c(o.CONFLICTING_SETTING,"'not null' and 'null' can not be set at the same time",f))),h.forEach(f=>{le(f.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'not null' must not have a value",f.value||f.name))});break;case"null":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_COLUMN_SETTING,"'null' can only appear once",f))),h.forEach(f=>{le(f.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'null' must not have a value",f.value||f.name))});break;case"unique":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_COLUMN_SETTING,"'unique' can only appear once",f))),h.forEach(f=>{f instanceof se&&!le(f.value)&&i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'unique' must not have a value",f.value||f.name))});break;case"increment":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_COLUMN_SETTING,"'increment' can only appear once",f))),h.forEach(f=>{f instanceof se&&!le(f.value)&&i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'increment' must not have a value",f.value||f.name))});break;case"default":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_TABLE_SETTING,"'default' can only appear once",f))),h.forEach(f=>{Pn(f.value)||i.push(new c(o.INVALID_TABLE_SETTING,"'default' must be a string literal, number literal, function expression, true, false or null",f.value||f.name))});break;default:h.forEach(f=>i.push(new c(o.UNKNOWN_COLUMN_SETTING,`Unknown column setting '${p}'`,f)))}}return i}validateSubElements(e){const n=e.flatMap(i=>{if(i.parent=this.declarationNode,!i.type)return[];const r=re(i);return new r(i,this.publicSymbolTable,this.symbolFactory).validate()}),s=e.filter(i=>{var r;return((r=i.type)==null?void 0:r.value.toLowerCase())==="note"});return s.length>1&&(n.push(...s.map(i=>new c(o.NOTE_REDEFINED,"Duplicate notes are defined",i))),n.push()),n}}function xn(t){if(!(t instanceof J||Je(t)||t instanceof D||t instanceof ce))return!1;if(t instanceof J){if(t.callee===void 0||t.argumentList===void 0||!t.argumentList.elementList.every(n=>ue(n)||Y(n)||Ne(n)))return!1;t=t.callee}for(;t instanceof ce;){if(t.array===void 0||t.indexer===void 0||!t.indexer.elementList.every(n=>!n.colon&&!n.value&&ue(n.name)))return!1;t=t.array}const e=C(t).unwrap_or(void 0);return e!==void 0&&e.length>0}function Sn(t,e){return e.length===1&&t===e[0]}class On{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof A?[new c(o.INVALID_TABLEGROUP_CONTEXT,"TableGroup must appear top-level",this.declarationNode)]:[]}validateName(e){return e?Ze(e)?[]:[new c(o.INVALID_NAME,"A TableGroup name must be of the form <tablegroup> or <schema>.<tablegroup>",e)]:[new c(o.NAME_NOT_FOUND,"A TableGroup must have a name",this.declarationNode)]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A TableGroup shouldn't have an alias",e)]:[]}registerElement(){const{name:e}=this.declarationNode;this.declarationNode.symbol=this.symbolFactory.create(nn,{declaration:this.declarationNode,symbolTable:new we});const n=C(e);if(n.isOk()){const s=n.unwrap(),i=s.pop(),r=Ke(s,this.publicSymbolTable,this.symbolFactory),a=Qe(i);if(r.has(a))return[new c(o.DUPLICATE_NAME,`TableGroup name '${i}' already exists in schema '${s.join(".")||"public"}'`,e)];r.set(a,this.declarationNode.symbol)}return[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"A TableGroup shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return[new c(o.UNEXPECTED_SIMPLE_BODY,"A TableGroup's body must be a block",e)];const[n,s]=I.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.flatMap(n=>{const s=[];return n.callee&&!C(n.callee).isOk()&&s.push(new c(o.INVALID_TABLEGROUP_FIELD,"A TableGroup field must be of the form <table> or <schema>.<table>",n.callee)),this.registerField(n),n.args.length>0&&s.push(...n.args.map(i=>new c(o.INVALID_TABLEGROUP_FIELD,"A TableGroup field should only have a single Table name",i))),s})}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=re(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}registerField(e){if(e.callee&&M(e.callee)){const n=V(e.callee).unwrap(),s=He(n),i=this.symbolFactory.create(sn,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(s)){const a=r.get(s);return[new c(o.DUPLICATE_TABLEGROUP_FIELD_NAME,`${n} already exists in the group`,e),new c(o.DUPLICATE_TABLEGROUP_FIELD_NAME,`${n} already exists in the group`,a.declaration)]}r.set(s,i)}return[]}}const wt=["-","+"];function re(t){switch(t.type.value.toLowerCase()){case b.Enum:return gn;case b.Table:return kn;case b.TableGroup:return On;case b.Project:return vn;case b.Ref:return wn;case b.Note:return An;case b.Indexes:return _n;default:return Ln}}function Ze(t){return!!C(t).unwrap_or(!1)}function Rn(t){return Me(t)}function Me(t){return t instanceof D&&t.expression instanceof W}function Ke(t,e,n){var i;t[0]==="public"&&(t=t.slice(1));let s=e;for(const r of t){let a;const l=We(r);if(s.has(l)){if(a=(i=s.get(l))==null?void 0:i.symbolTable,!a)throw new Error("Expect a symbol table in a schema symbol")}else{a=new we;const p=n.create(_t,{symbolTable:a});s.set(l,p)}s=a}return s}function yt(t){return t==="-"||t==="<>"||t===">"||t==="<"}function Dn(t){var n;if(!(t instanceof D)||!(t.expression instanceof Te)||((n=t.expression.literal)==null?void 0:n.kind)!==u.COLOR_LITERAL)return!1;const e=t.expression.literal.value;if(e.length!==4&&e.length!==7||e[0]!=="#")return!1;for(let s=1;s<e.length;s+=1)if(!Jt(e[s]))return!1;return!0}function le(t){return t===void 0}function Pn(t){var e;return!!(Y(t)||ue(t)||Ne(t)&&["true","false","null"].includes(t.expression.variable.value.toLowerCase())||t instanceof Q&&wt.includes((e=t.op)==null?void 0:e.value)&&ue(t.expression)||t instanceof te)}function ue(t){var e;return t instanceof D&&t.expression instanceof Te&&((e=t.expression.literal)==null?void 0:e.kind)===u.NUMERIC_LITERAL}function Un(t){var n;if(!(t instanceof Q)||!yt((n=t.op)==null?void 0:n.value))return!1;const e=C(t.expression).unwrap_or(void 0);return e!==void 0&&e.length>0}function kt(t){return t instanceof Z&&t.elementList.every(M)}function j(t){var s;const e={},n=[];if(!t)return new F({});for(const i of t.elementList){if(!i.name)continue;if(i.name instanceof D){n.push(new c(o.INVALID_SETTINGS,"A setting name must be a stream of identifiers",i.name));continue}const r=(s=me(i.name).unwrap_or(void 0))==null?void 0:s.toLowerCase();r&&(e[r]===void 0?e[r]=[i]:e[r].push(i))}return new F(e,n)}class ft{constructor(e,n){this.ast=e,this.symbolFactory=n,this.publicSchemaSymbol=this.symbolFactory.create(_t,{symbolTable:new we}),this.ast.symbol=this.publicSchemaSymbol,this.ast.symbol.declaration=this.ast}validate(){const e=[];this.ast.body.forEach(s=>{if(s.parent=this.ast,s.type===void 0)return;const i=re(s),r=new i(s,this.publicSchemaSymbol.symbolTable,this.symbolFactory);e.push(...r.validate())});const n=this.ast.body.filter(s=>ve(s).unwrap_or(void 0)===b.Project);return n.length>1&&n.forEach(s=>e.push(new c(o.PROJECT_REDEFINED,"Only one project can exist",s))),new F(this.ast,e)}}class ae{constructor(e,n){this.declarationNode=e,this.errors=n}bind(){this.bindSettingList(this.declarationNode.attributeList,this.settingList),this.bindBody()}bindSettingList(e,n){if(e)for(const s of e.elementList){if(s.name instanceof D)continue;const i=me(s.name).unwrap_or(void 0);if(!i)continue;const r=n[i.toLowerCase()];r!=null&&r.shouldBind&&this.scanAndBind(s.value,r)}}bindBody(){const e=this.declarationNode;if(!e.body)return;const{body:n}=e;if(n instanceof ne)for(const s of n.body)if(s instanceof A){if(!s.type)continue;const i=xt(s);new i(s,this.errors).bind()}else this.bindSubfield(s);else this.bindSubfield(n)}bindSubfield(e){const n=[e.callee,...e.args],s=I.last(n);s instanceof P&&(n.pop(),this.bindSettingList(s,this.subfield.settingList));const{argBinderRules:i}=this.subfield.arg;for(let r=0;r<Math.min(n.length,i.length);r+=1)i[r].shouldBind&&this.scanAndBind(n[r],i[r])}scanAndBind(e,n){var s,i;if(e)if(e instanceof D){if(e.expression instanceof W&&((i=n.keywords)!=null&&i.includes((s=e.expression.variable)==null?void 0:s.value.toLowerCase())))return;this.bindFragments([e],n)}else e instanceof H?Je(e)?this.bindFragments(he(e).unwrap_or([]),n):(this.scanAndBind(e.leftExpression,n),this.scanAndBind(e.rightExpression,n)):e instanceof Q?this.scanAndBind(e.expression,n):e instanceof Pe?this.scanAndBind(e.expression,n):e instanceof Z&&e.elementList.forEach(r=>this.scanAndBind(r,n))}bindFragments(e,n){if(e.length===0)return;const s=[...n.topSubnamesSymbolKind],{remainingSubnamesSymbolKind:i}=n,r=e.findIndex(f=>!M(f)),l=r!==-1&&kt(e[r])?e[r]:void 0,p=r>=0?s.pop():void 0,h=e.slice(0,r===-1?void 0:r);if(h.length===0)return;const T=[];for(;s.length&&h.length;){const f=s.pop(),N=h.pop(),g=V(N).unwrap();T.unshift({index:Ve(g,f),referrer:N})}for(;h.length;){const f=h.pop(),N=V(f).unwrap();T.unshift({index:Ve(N,i),referrer:f})}return l?l.elementList.forEach(f=>this.resolveIndexStack([...T,{index:Ve(V(f).unwrap(),p),referrer:f}],n.ignoreNameNotFound)):this.resolveIndexStack(T,n.ignoreNameNotFound)}resolveIndexStack(e,n){if(e.length===0)throw new Error("Unreachable - An unresolved name must have at least one name component");const[s,...i]=e,r=In(s.index,this.declarationNode);if(r===void 0){const{kind:h,name:T}=ie(s.index).unwrap();this.logError(s.referrer,`Can not find ${h} '${T}'`,n);return}r.references.push(s.referrer),s.referrer.referee=r;let a=r.symbolTable,{kind:l,name:p}=ie(s.index).unwrap();for(const h of i){const{kind:T,name:f}=ie(h.index).unwrap(),N=a.get(h.index);if(!N){this.logError(h.referrer,`${l} '${p}' does not have ${T} '${f}'`,n);return}if(l=T,p=f,h.referrer.referee=N,N.references.push(h.referrer),!N.symbolTable)break;a=N.symbolTable}}logError(e,n,s){s||this.errors.push(new c(o.BINDING_ERROR,n,e))}}class Mn extends ae{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Fn extends ae{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Bn extends ae{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class Vn extends ae{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Gn extends ae{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Cn extends ae{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class Xn extends ae{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Enum],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!0}]},settingList:{ref:{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},default:{shouldBind:!1}}},this.settingList={}}}class $n extends ae{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}function xt(t){switch(t.type.value.toLowerCase()){case b.Enum:return Fn;case b.Table:return Xn;case b.TableGroup:return $n;case b.Project:return Gn;case b.Ref:return Cn;case b.Note:return Vn;case b.Indexes:return Bn;default:return Mn}}class jn{constructor(e){this.ast=e,this.errors=[]}resolve(){for(const e of this.ast.body)if(e.type){const n=xt(e);new n(e,this.errors).bind()}return new F(this.ast,this.errors)}}class Wn{constructor(e){this.generator=e}create(e,n){return new e(n,this.generator.nextId())}}class Yn{constructor(e,n){this.ast=e,this.symbolFactory=new Wn(n)}analyze(){return new ft(this.ast,this.symbolFactory).validate().chain(n=>new jn(n).resolve())}validate(){return new ft(this.ast,this.symbolFactory).validate().chain(n=>new F(n,[]))}}function pt(t,e){const{variables:n,tupleElements:s}=_e(t).unwrap();return s?n.length===0?{schemaName:e.schemaName,tableName:e.name,fieldNames:s}:{tableName:n.pop(),schemaName:n.pop()||null,fieldNames:s}:n.length===1?{schemaName:e.schemaName,tableName:e.name,fieldNames:[n[0]]}:{fieldNames:[n.pop()],tableName:n.pop(),schemaName:n.pop()||null}}function St(t){switch(t){case"<":return["1","*"];case"<>":return["*","*"];case">":return["*","1"];case"-":return["1","1"]}throw new Error("Invalid relation op")}function x(t){return{start:{offset:t.startPos.offset,line:t.startPos.line+1,column:t.startPos.column+1},end:{offset:t.endPos.offset,line:t.endPos.line+1,column:t.endPos.column+1}}}function $e(t){var n;const e=(n=he(t).unwrap_or(void 0))==null?void 0:n.pop();return e instanceof Z?e.elementList.map(s=>s.referee):[e.referee]}function be(t){const e=C(t).unwrap();return{name:e.pop(),schemaName:e}}function Ot(t){return t.expression.literal.value}function Rt(t,e){if(Array.isArray(t)){const i=t.map(({id:a})=>a).sort().join(","),r=e.map(({id:a})=>a).sort().join(",");return i<r?`${i}-${r}`:`${r}-${i}`}const n=t.id.toString(),s=e.id.toString();return n<s?`${n}-${s}`:`${s}-${n}`}function Dt(t,e){if(Array.isArray(t)){const i=t.map(({id:a})=>a).sort(),r=e.map(({id:a})=>a).sort();return I.zip(i,r).every(([a,l])=>a===l)}const n=t.id,s=e.id;return n===s}function Ee(t){const e=t.split(`
8
- `),n=e.filter(i=>i.trimStart()),s=Math.min(...n.map(i=>i.length-i.trimStart().length));return e.map(i=>i.slice(s)).join(`
9
- `)}class Pt{constructor(e,n){this.declarationNode=e,this.env=n,this.table={name:void 0,schemaName:void 0,alias:null,fields:[],token:void 0,indexes:[]},this.pkColumns=[]}interpret(){this.table.token=x(this.declarationNode),this.env.tables.set(this.declarationNode,this.table);const e=[...this.interpretName(this.declarationNode.name),...this.interpretAlias(this.declarationNode.alias),...this.interpretSettingList(this.declarationNode.attributeList),...this.interpretBody(this.declarationNode.body)];return this.pkColumns.length>=2&&(this.table.indexes.push({columns:this.pkColumns.map(({name:n})=>({value:n,type:"column"})),token:{start:{offset:-1,line:-1,column:-1},end:{offset:-1,line:-1,column:-1}},pk:!0}),this.pkColumns.forEach(n=>n.pk=!1)),e}interpretName(e){const{name:n,schemaName:s}=be(e);return s.length>1?(this.table.name=n,this.table.schemaName=s.join("."),[new c(o.UNSUPPORTED,"Nested schema is not supported",e)]):(this.table.name=n,this.table.schemaName=s.length?s[0]:null,[])}interpretAlias(e){if(!e)return[];const n=V(e).unwrap_or(null);return n&&(this.env.aliases.push({name:n,kind:"table",value:{tableName:this.table.name,schemaName:this.table.schemaName}}),this.table.alias=n),[]}interpretSettingList(e){var i,r,a;const n=j(e).getValue();this.table.headerColor=(i=n.headercolor)!=null&&i.length?Ot((a=(r=n.headercolor)==null?void 0:r.at(0))==null?void 0:a.value):void 0;const[s]=n.note||[];return this.table.note=s&&{value:q(s==null?void 0:s.value).map(Ee).unwrap(),token:x(s)},[]}interpretBody(e){const[n,s]=I.partition(e.body,i=>i instanceof w);return[...this.interpretFields(n),...this.interpretSubElements(s)]}interpretSubElements(e){return e.flatMap(n=>{var s;switch((s=n.type)==null?void 0:s.value.toLowerCase()){case"note":return this.table.note={value:q(n.body instanceof ne?n.body.body[0].callee:n.body.callee).map(Ee).unwrap(),token:x(n)},[];case"indexes":return this.interpretIndexes(n)}return[]})}interpretFields(e){return e.flatMap(n=>this.interpretColumn(n))}interpretColumn(e){var a,l,p,h,T,f,N,g;const n=[],s={};s.name=V(e.callee).unwrap();const i=zn(e.args[0]);s.type=i.getValue(),n.push(...i.getErrors()),s.token=x(e),s.inline_refs=[];const r=e.args.slice(1);if(I.last(r)instanceof P){const _=j(r.pop()).getValue();s.pk=!!((a=_.pk)!=null&&a.length)||!!((l=_["primary key"])!=null&&l.length),s.increment=!!((p=_.increment)!=null&&p.length),s.unique=!!((h=_.unique)!=null&&h.length),s.not_null=!!((T=_["not null"])!=null&&T.length)&&!0,s.dbdefault=qn((N=(f=_.default)==null?void 0:f.at(0))==null?void 0:N.value);const K=(g=_.note)==null?void 0:g.at(0);s.note=K&&{value:q(K.value).map(Ee).unwrap(),token:x(K)};const Ie=_.ref||[];s.inline_refs=Ie.flatMap(z=>{const[nt]=$e(z.value.expression);if(Dt(nt,e.symbol))return n.push(new c(o.SAME_ENDPOINT,"Two endpoints are the same",z)),[];const ye=z.value.op,ee=C(z.value.expression).unwrap();let fe;if(ee.length===1){const[oe]=ee;fe={schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[oe],relation:ye.value,token:x(z)}}else if(ee.length===2){const[oe,Le]=ee;fe={schemaName:null,tableName:oe,fieldNames:[Le],relation:ye.value,token:x(z)}}else if(ee.length===3){const[oe,Le,it]=ee;fe={schemaName:oe,tableName:Le,fieldNames:[it],relation:ye.value,token:x(z)}}else{n.push(new c(o.UNSUPPORTED,"Nested schema is not supported",z));const oe=ee.pop(),Le=ee.pop();fe={schemaName:ee.join("."),tableName:Le,fieldNames:[oe],relation:ye.value,token:x(z)}}const st=this.registerInlineRefToEnv(e,nt,fe,z);return n.push(...st),st.length===0?fe:[]})}return s.pk||(s.pk=r.some(_=>X(_).unwrap().toLowerCase()==="pk")),s.unique||(s.unique=r.some(_=>X(_).unwrap().toLowerCase()==="unique")),this.table.fields.push(s),s.pk&&this.pkColumns.push(s),n}interpretIndexes(e){return this.table.indexes.push(...e.body.body.map(n=>{var a,l,p,h,T,f,N;const s={columns:[]},i=n;s.token=x(e);const r=[i.callee,...i.args];if(I.last(r)instanceof P){const g=j(r.pop()).getValue();s.pk=!!((a=g.pk)!=null&&a.length),s.unique=!!((l=g.unique)!=null&&l.length),s.name=q((h=(p=g.name)==null?void 0:p.at(0))==null?void 0:h.value).unwrap_or(void 0);const _=(T=g.note)==null?void 0:T.at(0);s.note=_&&{value:q(_.value).unwrap(),token:x(_)},s.type=X((N=(f=g.type)==null?void 0:f.at(0))==null?void 0:N.value).unwrap_or(void 0)}return r.flatMap(g=>{if(!(g instanceof J))return g;const _=[];for(;g instanceof J;)_.push(g.argumentList),g=g.callee;return _.push(g),_}).forEach(g=>{const{functional:_,nonFunctional:K}=Xe(g).unwrap();s.columns.push(..._.map(Ie=>({value:Ie.value.value,type:"expression"})),...K.map(Ie=>({value:V(Ie).unwrap(),type:"column"})))}),s})),[]}registerInlineRefToEnv(e,n,s,i){const r=Rt(e.symbol,n);if(this.env.refIds[r])return[new c(o.CIRCULAR_REF,"References with same endpoints exist",i),new c(o.CIRCULAR_REF,"References with same endpoints exist",this.env.refIds[r])];const a=St(s.relation);return this.env.refIds[r]=i,this.env.ref.set(i,{name:null,schemaName:null,token:s.token,endpoints:[{...s,relation:a[1]},{schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[X(e.callee).unwrap()],token:x(e),relation:a[0]}]}),[]}}function zn(t){let e=null;t instanceof J&&(e=t.argumentList.elementList.map(r=>ue(r)?r.expression.literal.value:Y(r)?q(r).unwrap():X(r).unwrap()).join(","),t=t.callee);let n="";for(;t instanceof ce;)n=`[${t.indexer.elementList.map(r=>r.name.expression.literal.value).join(",")}]${n}`,t=t.array;const{name:s,schemaName:i}=be(t);return i.length>1?new F({schemaName:i.length===0?null:i[0],type_name:`${s}${n}${e?`(${e})`:""}`,args:e},[new c(o.UNSUPPORTED,"Nested schema is not supported",t)]):new F({schemaName:i.length===0?null:i[0],type_name:`${s}${n}${e?`(${e})`:""}`,args:e})}function qn(t){var e,n,s;if(t){if(Y(t))return{value:q(t).unwrap(),type:"string"};if(ue(t))return{type:"number",value:Number.parseFloat(t.expression.literal.value)};if(Ne(t))return{value:t.expression.variable.value.toLowerCase(),type:"boolean"};if(t instanceof Q&&wt.includes((e=t.op)==null?void 0:e.value)&&ue(t.expression)){const i=Number.parseFloat(t.expression.expression.literal.value);return{value:((n=t.op)==null?void 0:n.value)==="-"?0-i:i,type:"number"}}if(t instanceof te)return{value:(s=t.value)==null?void 0:s.value,type:"expression"};throw new Error("Unreachable")}}class Qn{constructor(e,n){this.declarationNode=e,this.env=n,this.note={name:void 0,content:void 0,token:void 0}}interpret(){return this.note.token=x(this.declarationNode),this.env.notes.set(this.declarationNode,this.note),[...this.interpretName(this.declarationNode.name),...this.interpretSettingList(this.declarationNode.attributeList),...this.interpretBody(this.declarationNode.body)]}interpretName(e){const{name:n}=be(e);return this.note.name=n,[]}interpretSettingList(e){var s,i,r;const n=j(e).getValue();return this.note.headerColor=(s=n.headercolor)!=null&&s.length?Ot((r=(i=n.headercolor)==null?void 0:i.at(0))==null?void 0:r.value):void 0,[]}interpretBody(e){const[n,s]=I.partition(e.body,i=>i instanceof w);return n.length!==1||s.length>0?[new c(o.INVALID_NOTE,"Invalid note syntax",e)]:[...this.interpretNote(n[0])]}interpretNote(e){const n=I.get(e,"callee.expression.literal.value","");return this.note.content=Ee(n),[]}}class Ut{constructor(e,n){this.declarationNode=e,this.env=n,this.container=this.declarationNode.parent instanceof A?this.env.tables.get(this.declarationNode.parent):void 0,this.ref={}}interpret(){return this.ref.token=x(this.declarationNode),this.env.ref.set(this.declarationNode,this.ref),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(e){const n=[],s=C(this.declarationNode.name).unwrap_or([]);return this.ref.name=s.pop()||null,s.length>1&&n.push(new c(o.UNSUPPORTED,"Nested schema is not supported",this.declarationNode.name)),this.ref.schemaName=s.join(".")||null,n}interpretBody(e){return e instanceof w?this.interpretField(e):this.interpretField(e.body[0])}interpretField(e){var h,T,f,N;const n=e.callee.op.value,{leftExpression:s,rightExpression:i}=e.callee,r=$e(s),a=$e(i);if(Dt(r,a))return[new c(o.SAME_ENDPOINT,"Two endpoints are the same",e)];const l=Rt(r,a);if(this.env.refIds[l])return[new c(o.CIRCULAR_REF,"References with same endpoints exist",this.declarationNode),new c(o.CIRCULAR_REF,"References with same endpoints exist",this.env.refIds[l])];if(e.args[0]){const g=j(e.args[0]).getValue(),_=(T=(h=g.delete)==null?void 0:h.at(0))==null?void 0:T.value;this.ref.onDelete=_ instanceof $?me(_).unwrap_or(void 0):X(_).unwrap_or(void 0);const K=(N=(f=g.update)==null?void 0:f.at(0))==null?void 0:N.value;this.ref.onUpdate=K instanceof $?me(K).unwrap_or(void 0):X(K).unwrap_or(void 0)}const p=St(n);return this.ref.endpoints=[{...pt(s,this.container),relation:p[0],token:x(s)},{...pt(i,this.container),relation:p[1],token:x(i)}],this.env.refIds[l]=this.declarationNode,[]}}class Mt{constructor(e,n){this.declarationNode=e,this.env=n,this.tableGroup={tables:[]}}interpret(){const e=[];return this.tableGroup.token=x(this.declarationNode),this.env.tableGroups.set(this.declarationNode,this.tableGroup),e.push(...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)),e}interpretName(e){const n=[],{name:s,schemaName:i}=be(e);return i.length>=2&&(this.tableGroup.name=s,this.tableGroup.schemaName=i.join("."),n.push(new c(o.UNSUPPORTED,"Nested schema is not supported",this.declarationNode.name))),this.tableGroup.name=s,this.tableGroup.schemaName=i[0]||null,n}interpretBody(e){const n=[];return this.tableGroup.tables=this.declarationNode.body.body.map(s=>{const i=C(s.callee).unwrap();i.length>2&&n.push(new c(o.UNSUPPORTED,"Nested schema is not supported",s));const r=he(s.callee).unwrap().pop().referee.id;if(this.env.groupOfTable[r]){const a=this.env.groupOfTable[r],{schemaName:l,name:p}=this.env.tableGroups.get(a),h=l?`${l}.${p}`:p;n.push(new c(o.TABLE_REAPPEAR_IN_TABLEGROUP,`Table "${i.join(".")}" already appears in group "${h}"`,s))}else this.env.groupOfTable[r]=this.declarationNode;return{name:i.pop(),schemaName:i.join(".")}}),n}}class Ft{constructor(e,n){this.declarationNode=e,this.env=n,this.enum={values:[]}}interpret(){return this.enum.token=x(this.declarationNode),this.env.enums.set(this.declarationNode,this.enum),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(e){const{name:n,schemaName:s}=be(e);return s.length>1?(this.enum.name=n,this.enum.schemaName=s.join("."),[new c(o.UNSUPPORTED,"Nested schema is not supported",e)]):(this.enum.name=n,this.enum.schemaName=s.length?s[0]:null,[])}interpretBody(e){return e.body.flatMap(n=>{var l;const s=n,i={};i.token=x(s),i.name=X(s.callee).unwrap();const a=(l=j(s.args[0]).getValue().note)==null?void 0:l.at(0);return i.note=a&&{value:q(a.value).map(Ee).unwrap(),token:x(a)},this.enum.values.push(i),[]})}}class Hn{constructor(e,n){this.declarationNode=e,this.env=n,this.project={enums:[],refs:[],tableGroups:[],tables:[]}}interpret(){return this.env.project.set(this.declarationNode,this.project),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(e){if(!e)return this.project.name=null,[];const{name:n}=be(e);return this.project.name=n,[]}interpretBody(e){return e.body.flatMap(n=>{var i;const s=n;switch((i=s.type)==null?void 0:i.value.toLowerCase()){case"table":{const r=new Pt(s,this.env).interpret();return this.project.tables.push(this.env.tables.get(s)),r}case"ref":{const r=new Ut(s,this.env).interpret();return this.project.refs.push(this.env.ref.get(s)),r}case"tablegroup":{const r=new Mt(s,this.env).interpret();return this.project.tableGroups.push(this.env.tableGroups.get(s)),r}case"enum":{const r=new Ft(s,this.env).interpret();return this.project.enums.push(this.env.enums.get(s)),r}case"note":return this.project.note={value:q(s.body instanceof ne?s.body.body[0].callee:s.body.callee).map(Ee).unwrap(),token:x(s)},[];default:return this.project[s.type.value.toLowerCase()]=q(s.body.callee).unwrap(),[]}})}}class Jn{constructor(e){this.ast=e,this.env={schema:[],tables:new Map,notes:new Map,refIds:{},ref:new Map,enums:new Map,tableGroups:new Map,groupOfTable:{},aliases:[],project:new Map}}interpret(){const e=this.ast.body.flatMap(n=>{switch(ve(n).unwrap_or(void 0)){case b.Table:return new Pt(n,this.env).interpret();case b.Note:return new Qn(n,this.env).interpret();case b.Ref:return new Ut(n,this.env).interpret();case b.TableGroup:return new Mt(n,this.env).interpret();case b.Enum:return new Ft(n,this.env).interpret();case b.Project:return new Hn(n,this.env).interpret();default:return[]}});return new F(Zn(this.env),e)}}function Zn(t){return{schemas:[],tables:Array.from(t.tables.values()),notes:Array.from(t.notes.values()),refs:Array.from(t.ref.values()),enums:Array.from(t.enums.values()),tableGroups:Array.from(t.tableGroups.values()),aliases:t.aliases,project:Array.from(t.project.values())[0]||{}}}var L=(t=>(t[t.Function=1]="Function",t[t.Constructor=2]="Constructor",t[t.Field=3]="Field",t[t.Variable=4]="Variable",t[t.Class=5]="Class",t[t.Struct=6]="Struct",t[t.Interface=7]="Interface",t[t.Module=8]="Module",t[t.Property=9]="Property",t[t.Event=10]="Event",t[t.Operator=11]="Operator",t[t.Unit=12]="Unit",t[t.Value=13]="Value",t[t.Constant=14]="Constant",t[t.Enum=15]="Enum",t[t.EnumMember=16]="EnumMember",t[t.Keyword=17]="Keyword",t[t.Text=18]="Text",t[t.Color=19]="Color",t[t.File=20]="File",t[t.Reference=21]="Reference",t[t.Customcolor=22]="Customcolor",t[t.Folder=23]="Folder",t[t.TypeParameter=24]="TypeParameter",t[t.User=25]="User",t[t.Issue=26]="Issue",t[t.Snippet=27]="Snippet",t))(L||{}),y=(t=>(t[t.None=0]="None",t[t.KeepWhitespace=1]="KeepWhitespace",t[t.InsertAsSnippet=4]="InsertAsSnippet",t))(y||{});function Ae(t){switch(t){case m.Schema:return L.Module;case m.Table:return L.Class;case m.Column:return L.Field;case m.Enum:return L.Enum;case m.EnumField:return L.EnumMember;case m.TableGroup:return L.Struct;case m.TableGroupField:return L.Field;default:return L.Text}}function Re(t,e){if(!t||Ce(t))return!1;for(const n of t.trailingTrivia){if(n.start>e)break;if(n.kind===u.NEWLINE&&n.end<=e)return!1}return!0}function O(){return{suggestions:[]}}function De(t){return{...t,suggestions:t.suggestions.map(e=>({...e,insertText:` ${e.insertText}`}))}}function Fe(t){return{...t,suggestions:t.suggestions.map(e=>({...e,insertText:e.insertText.split("").every(Ue)?e.insertText:`"${e.insertText}"`}))}}function et(t,e){return t.getOffsetAt(e)}class Bt{constructor(e,n=[]){this.compiler=e,this.triggerCharacters=n}provideCompletionItems(e,n){var T,f;const s=et(e,n),i=this.compiler.token.flatStream(),{token:r,index:a}=this.compiler.container.token(s),l=a===void 0?i[0]:i[a+1];if([...(r==null?void 0:r.trailingTrivia)||[],...(r==null?void 0:r.leadingTrivia)||[],...(l==null?void 0:l.leadingTrivia)||[]].find(N=>Wt(N)&&ge(s,N)))return O();if(a===void 0)return Tt();if([u.STRING_LITERAL,u.QUOTED_STRING].includes(r.kind)&&ge(s,r))return O();const p=this.compiler.container.element(s);if(this.compiler.container.scopeKind(s)===R.TOPLEVEL||p instanceof A&&p.type&&p.type.start<=s&&p.type.end>=s)return Tt();const h=[...this.compiler.container.stack(s)].reverse();for(const N of h)if(N instanceof Q)switch((T=N.op)==null?void 0:T.value){case">":case"<":case"<>":case"-":return dt(this.compiler,s,N)}else if(N instanceof H)switch((f=N.op)==null?void 0:f.value){case">":case"<":case"<>":case"-":return dt(this.compiler,s,N);case".":return Vt(this.compiler,s,N)}else{if(N instanceof se)return Et(this.compiler,s,N);if(N instanceof P)return Et(this.compiler,s,N);if(N instanceof Z)return Kn(this.compiler,s);if(N instanceof w)return mt(this.compiler,s,N);if(N instanceof A&&(N.bodyColon&&s>=N.bodyColon.end||N.body&&ge(s,N.body)))return mt(this.compiler,s,void 0)}return O()}}function dt(t,e,n){const s=t.container.scopeKind(e);if([R.REF,R.TABLE].includes(s)){const i=Be(t,e,t.container.element(e),[m.Table,m.Schema,m.Column]);return Re(n.op,e)?De(i):i}return O()}function Be(t,e,n,s){var a;if(n===void 0)return O();let i=n;const r={suggestions:[]};for(;i;){if((a=i==null?void 0:i.symbol)!=null&&a.symbolTable){const{symbol:l}=i;r.suggestions.push(...t.symbol.members(l).filter(({kind:p})=>s.includes(p)).map(({name:p,kind:h})=>({label:p,insertText:p,insertTextRules:y.KeepWhitespace,kind:Ae(h),sortText:Ae(h).toString().padStart(2,"0"),range:void 0})))}i=i instanceof A?i.parent:void 0}return Fe(r)}function Kn(t,e){var s;switch(t.container.scopeKind(e)){case R.INDEXES:return Ct(t,e);case R.REF:{const i=[...t.container.stack(e)];for(;i.length>0;){const r=i.pop();if(r instanceof H&&((s=r.op)==null?void 0:s.value)===".")return Vt(t,e,r)}}return Gt(t,e)}return O()}function Et(t,e,n){const{token:s}=t.container.token(e);if([u.COMMA,u.LBRACKET].includes(s==null?void 0:s.kind)){const i=Nt(t,e);return(s==null?void 0:s.kind)===u.COMMA&&Re(s,e)?De(i):i}if(n.name&&n.name.start<=e&&n.name.end>=e)return Nt(t,e);if(n.name instanceof $){const i=es(t,e,me(n.name).unwrap());return(s==null?void 0:s.kind)===u.COLON&&Re(s,e)?De(i):i}return O()}function Nt(t,e){const n=t.container.element(e),s=t.container.scopeKind(e);if(n instanceof G)return O();if(n.body&&!ge(e,n.body))switch(s){case R.TABLE:return{suggestions:[{label:"headercolor",insertText:"headercolor: ",kind:L.Field,insertTextRules:y.KeepWhitespace,range:void 0},{label:"note",insertText:"note: ",kind:L.Field,insertTextRules:y.KeepWhitespace,range:void 0}]};default:return O()}switch(s){case R.TABLE:return{suggestions:[...["primary key","null","not null","increment","pk","unique"].map(i=>({label:i,insertText:i,kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0})),...["ref","default"].map(i=>({label:i,insertText:`${i}: `,kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0})),{label:"note",insertText:"note: ",kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0}]};case R.ENUM:return{suggestions:[{label:"note",insertText:"note: ",kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0}]};case R.INDEXES:return{suggestions:[...["unique","pk"].map(i=>({label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:L.Property,range:void 0})),...["note","name","type"].map(i=>({label:i,insertText:`${i}: `,kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0}))]};case R.REF:return{suggestions:["update","delete"].map(i=>({label:i,insertText:`${i}: `,kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0}))}}return O()}function es(t,e,n){switch(n==null?void 0:n.toLowerCase()){case"update":case"delete":return{suggestions:["cascade","set default","set null","restrict"].map(s=>({label:s,insertText:s,kind:L.Value,insertTextRules:y.KeepWhitespace,range:void 0}))};case"type":return{suggestions:["btree","hash"].map(s=>({label:s,insertText:`${s}`,kind:L.Value,insertTextRules:y.KeepWhitespace,range:void 0}))}}return O()}function Vt(t,e,n){const s=he(n).unwrap_or([]);if(s.pop(),s.some(r=>!M(r)))return O();const i=s.map(r=>X(r).unwrap());return Fe({suggestions:t.symbol.ofName({nameStack:i,owner:t.container.element(e)}).flatMap(({symbol:r})=>t.symbol.members(r)).map(({kind:r,name:a})=>({label:a,insertText:a,kind:Ae(r),range:void 0}))})}function mt(t,e,n){var i;switch(t.container.scopeKind(e)){case R.TABLE:return ns(t,e,n);case R.PROJECT:return ss(t,e,n);case R.INDEXES:return rs(t,e);case R.ENUM:return ts(t,e,n);case R.REF:{const r=Gt(t,e);return((i=t.container.token(e).token)==null?void 0:i.kind)===u.COLON&&Re(t.container.token(e).token,e)?De(r):r}case R.TABLEGROUP:return is(t);default:return O()}}function Tt(){return{suggestions:["Table","TableGroup","Enum","Project","Ref"].map(t=>({label:t,insertText:t,insertTextRules:y.KeepWhitespace,kind:L.Keyword,range:void 0}))}}function ts(t,e,n){return n!=null&&n.callee&&tt(e,n)===1?Be(t,e,t.container.element(e),[m.Schema,m.Table,m.Column]):O()}function ns(t,e,n){if(!(n!=null&&n.callee))return{suggestions:["Note","indexes"].map(i=>({label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:L.Keyword,range:void 0}))};const s=tt(e,n);return s===0?{suggestions:["Note","indexes"].map(i=>({label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:L.Keyword,range:void 0}))}:s===1?as(t,e):O()}function ss(t,e,n){return n!=null&&n.callee?tt(e,n)===0?{suggestions:["Table","TableGroup","Enum","Note","Ref"].map(i=>({label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:L.Keyword,range:void 0}))}:O():{suggestions:["Table","TableGroup","Enum","Note","Ref"].map(i=>({label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:L.Keyword,range:void 0}))}}function Gt(t,e){return Be(t,e,t.container.element(e),[m.Schema,m.Table,m.Column])}function is(t){return Fe({suggestions:[...t.parse.publicSymbolTable().entries()].flatMap(([e])=>{const n=ie(e).unwrap_or(void 0);if(n===void 0)return[];const{kind:s,name:i}=n;return s!==m.Table&&s!==m.Schema?[]:{label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:Ae(s),range:void 0}})})}function rs(t,e){return Ct(t,e)}function as(t,e){return{suggestions:[...["integer","int","tinyint","smallint","mediumint","bigint","bit","bool","binary","varbinary","logical","char","nchar","varchar","varchar2","nvarchar","nvarchar2","binary_float","binary_double","float","double","decimal","dec","real","money","smallmoney","enum","tinyblob","tinytext","blob","text","mediumblob","mediumtext","longblob","longtext","ntext","set","inet6","uuid","image","date","time","datetime","datetime2","timestamp","year","smalldatetime","datetimeoffset","XML","sql_variant","uniqueidentifier","CURSOR","BFILE","CLOB","NCLOB","RAW"].map(n=>({label:n,insertText:n,insertTextRules:y.KeepWhitespace,kind:L.TypeParameter,sortText:L.TypeParameter.toString().padStart(2,"0"),range:void 0})),...Be(t,e,t.container.element(e),[m.Enum,m.Schema]).suggestions]}}function Ct(t,e){const n=t.container.element(e),s=n==null?void 0:n.parent;if(!((s==null?void 0:s.symbol)instanceof At))return O();const{symbolTable:i}=s.symbol;return Fe({suggestions:[...i.entries()].flatMap(([r])=>{const a=ie(r).unwrap_or(void 0);if(a===void 0)return[];const{name:l}=a;return{label:l,insertText:l,insertTextRules:y.KeepWhitespace,kind:Ae(m.Column),range:void 0}})})}function tt(t,e){if(!e.callee)return-1;const n=[e.callee,...e.args],s=n.findIndex(i=>t<=i.end);return s===-1?n.length:s}class Xt{constructor(e){this.compiler=e}provideDefinition(e,n){var a;const{uri:s}=e,i=et(e,n),r=[...this.compiler.container.stack(i)];for(;r.length!==0;){const l=r.pop();if((a=l==null?void 0:l.referee)!=null&&a.declaration&&[de.PRIMARY_EXPRESSION,de.VARIABLE].includes(l==null?void 0:l.kind)){const{startPos:p,endPos:h}=l.referee.declaration;return[{range:{startColumn:p.column+1,startLineNumber:p.line+1,endColumn:h.column+1,endLineNumber:h.line+1},uri:s}]}}return[]}}class $t{constructor(e){this.compiler=e}provideReferences(e,n){const{uri:s}=e,i=et(e,n),r=[...this.compiler.container.stack(i)];for(;r.length!==0;){const a=r.pop();if(a&&[de.ELEMENT_DECLARATION,de.FUNCTION_APPLICATION,de.PRIMARY_EXPRESSION].includes(a==null?void 0:a.kind)){const{symbol:l}=a;if(l!=null&&l.references.length)return l.references.map(({startPos:p,endPos:h})=>({range:{startColumn:p.column+1,startLineNumber:p.line+1,endColumn:h.column+1,endLineNumber:h.line+1},uri:s}))}}return[]}}const os=Object.freeze(Object.defineProperty({__proto__:null,CompletionItemInsertTextRule:y,CompletionItemKind:L,DBMLCompletionItemProvider:Bt,DBMLDefinitionProvider:Xt,DBMLReferencesProvider:$t},Symbol.toStringTag,{value:"Module"}));var R=(t=>(t[t.TABLE=0]="TABLE",t[t.ENUM=1]="ENUM",t[t.TABLEGROUP=2]="TABLEGROUP",t[t.INDEXES=3]="INDEXES",t[t.NOTE=4]="NOTE",t[t.REF=5]="REF",t[t.PROJECT=6]="PROJECT",t[t.CUSTOM=7]="CUSTOM",t[t.TOPLEVEL=8]="TOPLEVEL",t))(R||{});class ls{constructor(){this.source="",this.cache=new Array(16).fill(null),this.nodeIdGenerator=new Yt,this.symbolIdGenerator=new Zt,this.token={invalidStream:this.createQuery(6,()=>this.parse.tokens().filter(vt)),flatStream:this.createQuery(7,()=>this.parse.tokens().flatMap(e=>[...e.leadingInvalid,e,...e.trailingInvalid]))},this.parse={source:()=>this.source,_:this.createQuery(0,()=>{const e=new cn(this.source).lex().chain(n=>new fn(n,this.nodeIdGenerator).parse()).chain(({ast:n,tokens:s})=>new Yn(n,this.symbolIdGenerator).analyze().map(()=>({ast:n,tokens:s})));return e.getErrors().length>0?e:e.chain(({ast:n,tokens:s})=>new Jn(n).interpret().map(r=>({ast:n,tokens:s,rawDb:r})))}),ast:this.createQuery(1,()=>this.parse._().getValue().ast),errors:this.createQuery(2,()=>this.parse._().getErrors()),tokens:this.createQuery(4,()=>this.parse._().getValue().tokens),rawDb:this.createQuery(3,()=>this.parse._().getValue().rawDb),publicSymbolTable:this.createQuery(5,()=>this.parse._().getValue().ast.symbol.symbolTable)},this.container={stack:this.createQuery(10,e=>{const n=this.parse.tokens();let{index:s}=this.container.token(e);const{token:i}=this.container.token(e);if(s===void 0)return[this.parse.ast()];for(;n[s].isInvalid&&s>=0;)s-=1;if(s===-1)return[this.parse.ast()];const r=n[s].start;let a=this.parse.ast();const l=[a];for(;;){const h=ln(a).find(T=>ge(r,T));if(h===void 0||h instanceof B)break;l.push(h),a=h}if((i==null?void 0:i.kind)===u.COLON)return l;for(;l.length>0;){let p=!1;const h=I.last(l);if(h instanceof w){const T=this.parse.source();for(let f=h.end;f<e;f+=1)T[f]===`
10
- `&&(l.pop(),p=!0)}else h instanceof Q||h instanceof H?this.container.token(e).token!==h.op&&(l.pop(),p=!0):h instanceof P?h.listCloseBracket&&h.end<=e&&(l.pop(),p=!0):h instanceof Z?h.tupleCloseParen&&h.end<=e&&(l.pop(),p=!0):h instanceof ne?h.blockCloseBrace&&h.end<=e&&(l.pop(),p=!0):h instanceof $||h.end<e&&(l.pop(),p=!0);if(p){const T=I.last(l);T instanceof A&&T.end<=e&&l.pop()}if(!p)break}return l}),token:this.createQuery(11,e=>{const n=this.token.flatStream().findIndex(s=>s.start>=e);return n===void 0?{token:void 0,index:void 0}:n<=0?{token:void 0,index:void 0}:{token:this.token.flatStream()[n-1],index:n-1}}),element:this.createQuery(12,e=>{const n=this.container.stack(e);for(let s=n.length-1;s>=0;s-=1)if(n[s]instanceof A)return n[s];return this.parse.ast()}),scope:this.createQuery(14,e=>{var n,s;return(s=(n=this.container.element(e))==null?void 0:n.symbol)==null?void 0:s.symbolTable}),scopeKind:this.createQuery(15,e=>{var s;if(this.container.element(e)instanceof G)return 8;switch((s=this.container.element(e).type)==null?void 0:s.value.toLowerCase()){case"table":return 0;case"enum":return 1;case"ref":return 5;case"tablegroup":return 2;case"indexes":return 3;case"note":return 4;case"project":return 6;default:return 7}})},this.symbol={ofName:this.createQuery(8,({nameStack:e,owner:n=this.parse.ast()})=>{var i;if(e.length===0)return[];const s=[];for(let r=n;r;r=r instanceof A?r.parent:void 0){if(!((i=r.symbol)!=null&&i.symbolTable))continue;const{symbolTable:a}=r.symbol;let l=[a],p=[];for(const h of e)p=l.flatMap(T=>Ht(h).flatMap(f=>{const N=T.get(f),g=ie(f).unwrap_or(void 0);return!N||!g?[]:{...g,symbol:N}})),l=p.flatMap(T=>T.symbol.symbolTable?T.symbol.symbolTable:[]);s.push(...p)}return s},({nameStack:e,owner:n})=>`${e.join(".")}@${n.id}`),members:this.createQuery(9,e=>e.symbolTable?[...e.symbolTable.entries()].map(([n,s])=>({...ie(n).unwrap(),symbol:s})):[])}}createQuery(e,n,s){return i=>{const r=this.cache[e],a=i&&s?s(i):i;if(r!==null){if(!(r instanceof Map))return r;if(r.has(a))return r.get(a)}const l=n(i);return i!==void 0?r instanceof Map?r.set(a,l):(this.cache[e]=new Map,this.cache[e].set(a,l)):this.cache[e]=l,l}}setSource(e){this.source=e,this.cache=new Array(16).fill(null),this.nodeIdGenerator.reset(),this.symbolIdGenerator.reset()}initMonacoServices(){return{definitionProvider:new Xt(this),referenceProvider:new $t(this),autocompletionProvider:new Bt(this)}}}exports.Compiler=ls;exports.serialize=zt;exports.services=os;
5
+ `)&&!s){const p=this.createToken(e,!0);this.tokens.push(p),this.errors.push(new c(o.UNEXPECTED_NEWLINE,"Invalid newline encountered while parsing",p));return}a&&this.match(n),this.tokens.push(M.create(e,this.start,this.current,l,!1))}singleLineStringLiteral(){this.consumeUntil(u.STRING_LITERAL,"'",{allowNewline:!1,allowEof:!1,raw:!1})}multilineStringLiteral(){this.consumeUntil(u.STRING_LITERAL,"'''",{allowNewline:!0,allowEof:!1,raw:!1})}functionExpression(){this.consumeUntil(u.FUNCTION_EXPRESSION,"`",{allowNewline:!1,allowEof:!1,raw:!0})}quotedVariable(){this.consumeUntil(u.QUOTED_STRING,'"',{allowNewline:!1,allowEof:!1,raw:!1})}singleLineComment(){this.consumeUntil(u.SINGLE_LINE_COMMENT,`
6
+ `,{allowNewline:!0,allowEof:!0,raw:!0,consumeStopSequence:!1})}multilineComment(){this.consumeUntil(u.MULTILINE_COMMENT,"*/",{allowNewline:!0,allowEof:!1,raw:!0})}identifier(){for(;!this.isAtEnd()&&pe(this.peek());)this.advance();this.addToken(u.IDENTIFIER)}operator(){for(;rt(this.peek());)this.advance();this.addToken(u.OP)}numericLiteralOrIdentifier(){let e=0;if(this.isAtEnd())return this.addToken(u.NUMERIC_LITERAL);for(;!this.isAtEnd();){const n=this.check(".");if(e+=n?1:0,e>1)break;if(!n&&this.current.offset===this.text.length-1)return this.advance(),this.addToken(u.NUMERIC_LITERAL);if(!n&&!pe(this.peek()))return this.addToken(u.NUMERIC_LITERAL);if(!n&&!Oe(this.peek()))break;this.advance()}if(e>0){for(;!this.isAtEnd()&&(this.check(".")||pe(this.peek()));)this.advance();const n=this.createToken(u.NUMERIC_LITERAL,!0);this.tokens.push(n),this.errors.push(new c(o.UNKNOWN_TOKEN,"Invalid number",n))}else{for(;!this.isAtEnd()&&pe(this.peek());)this.advance();const n=this.createToken(u.IDENTIFIER,!1);this.tokens.push(n)}}colorLiteral(){for(;!this.isAtEnd()&&pe(this.peek());)this.advance();this.addToken(u.COLOR_LITERAL)}escapedString(){const e={column:this.current.column-1,offset:this.current.offset-1,line:this.current.line};if(this.isAtEnd())return"\\";switch(this.advance()){case"\r":return this.check(`
7
+ `)&&this.advance(),"";case`
8
+ `:return"";case"t":return" ";case"n":return`
9
+ `;case"\\":return"\\";case"r":return"\r";case"'":return this.peek()==="'"&&this.peek(1)==="'"?(this.advance(),this.advance(),"'''"):"'";case'"':return'"';case"0":return"\0";case"b":return"\b";case"v":return"\v";case"f":return"\f";case" ":return"\\ ";case"u":{let n="";for(let s=0;s<=3;s+=1){if(this.isAtEnd()||!pe(this.peek()))return this.errors.push(new c(o.INVALID_ESCAPE_SEQUENCE,`Invalid unicode escape sequence '\\u${n}', only unicode escape sequences of the form '\\uHHHH' where H is a hexadecimal number are allowed`,M.create(u.STRING_LITERAL,e,this.current,`\\u${n}`,!0))),`\\u${n}`;n+=this.advance()}return String.fromCharCode(parseInt(n,16))}default:{const n=`\\${this.text[this.current.offset-1]}`;return this.errors.push(new c(o.INVALID_ESCAPE_SEQUENCE,`Invalid escape sequence '${n}'`,M.create(u.STRING_LITERAL,e,this.current,n,!0))),n}}}}var xe=(t=>(t[t.ListExpression=0]="ListExpression",t[t.GroupExpression=1]="GroupExpression",t[t.BlockExpression=2]="BlockExpression",t))(xe||{});class un{constructor(){this.stack=[],this.numberOfNestedLParens=0,this.numberOfNestedLBrackets=0,this.numberOfNestedLBraces=0}push(e){this.stack.push(e),e===0&&(this.numberOfNestedLBrackets+=1),e===1&&(this.numberOfNestedLParens+=1),e===2&&(this.numberOfNestedLBraces+=1)}pop(){const e=this.stack.pop();return e===0&&(this.numberOfNestedLBrackets-=1),e===1&&(this.numberOfNestedLParens-=1),e===2&&(this.numberOfNestedLBraces-=1),e}top(){return I.last(this.stack)}isWithinGroupExpressionContext(){return this.numberOfNestedLParens>0}isWithinListExpressionContext(){return this.numberOfNestedLBrackets>0}isWithinBlockExpressionContext(){return this.numberOfNestedLBraces>0}withContextDo(e,n){return()=>{this.push(e);try{return n()}finally{this.pop()}}}findHandlerContext(e,n){if(!(this.numberOfNestedLBraces<=0&&this.numberOfNestedLBrackets<=0&&this.numberOfNestedLParens<=0))for(let s=n;s<e.length-1;s+=1)switch(e[s].kind){case u.COMMA:if(this.isWithinGroupExpressionContext()||this.isWithinListExpressionContext())return[...this.stack].reverse().find(r=>[1,0].includes(r));break;case u.RPAREN:if(this.isWithinGroupExpressionContext())return 1;break;case u.RBRACE:if(this.isWithinBlockExpressionContext())return 2;break;case u.RBRACKET:if(this.isWithinListExpressionContext())return 0;break}}}class hn{constructor(e){this.generator=e}create(e,n){return new e(n,this.generator.nextId())}}class d{constructor(e,n,s){this.token=e,this.partialNode=n,this.handlerContext=s}}class fn{constructor(e,n){this.current=0,this.errors=[],this.contextStack=new un,this.synchronizeProgram=()=>{const s=this.peek();s.kind!==u.EOF?E(this.advance()):(E(this.peek()),this.logError(s,o.UNEXPECTED_EOF,"Unexpected EOF"))},this.synchronizeElementDeclarationName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(lt(s)||this.check(u.COLON,u.LBRACE,u.LBRACKET))break;E(s),this.advance()}},this.synchronizeElementDeclarationAlias=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.COLON,u.LBRACE,u.LBRACKET))break;E(s),this.advance()}},this.blockExpression=this.contextStack.withContextDo(xe.BlockExpression,()=>{const s={body:[]},i=()=>this.nodeFactory.create(ne,s);try{this.consume("Expect an opening brace '{'",u.LBRACE),s.blockOpenBrace=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.blockOpenBrace=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}for(;!this.isAtEnd()&&!this.check(u.RBRACE);)try{s.body.push(this.canBeField()?this.fieldDeclaration():this.expression())}catch(r){if(!(r instanceof d))throw r;if(s.body.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}try{this.consume("Expect a closing brace '}'",u.RBRACE),s.blockCloseBrace=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.blockCloseBrace=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}return i()}),this.synchronizeBlock=()=>{if(!this.check(u.RBRACE))for(E(this.advance());!this.isAtEnd();){const s=this.peek();if(this.check(u.RBRACE)||ot(this.previous(),s))break;E(s),this.advance()}},this.tupleExpression=this.contextStack.withContextDo(xe.GroupExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(je,{groupOpenParen:s.tupleOpenParen,groupCloseParen:s.tupleCloseParen,expression:s.elementList[0]}),r=()=>this.nodeFactory.create(Z,s);try{this.consume("Expect an opening parenthesis '('",u.LPAREN),s.tupleOpenParen=this.previous()}catch(a){if(!(a instanceof d))throw a;if(s.tupleOpenParen=a.partialNode,!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}if(!this.isAtEnd()&&!this.check(u.RPAREN))try{s.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof d))throw a;if(s.elementList.push(a.partialNode),!this.canHandle(a))throw new d(a.token,i(),a.handlerContext);this.synchronizeTuple()}for(;!this.isAtEnd()&&!this.check(u.RPAREN);)try{this.consume("Expect a comma ','",u.COMMA),s.commaList.push(this.previous()),s.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof d))throw a;if(a.partialNode instanceof k&&s.elementList.push(a.partialNode),!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}try{this.consume("Expect a closing parenthesis ')'",u.RPAREN),s.tupleCloseParen=this.previous()}catch(a){if(!(a instanceof d))throw a;if(s.tupleCloseParen=a.partialNode,!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}return s.elementList.length===1?i():r()}),this.synchronizeTuple=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.RPAREN,u.COMMA))break;E(s),this.advance()}},this.listExpression=this.contextStack.withContextDo(xe.ListExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(P,s);try{this.consume("Expect an opening bracket '['",u.LBRACKET),s.listOpenBracket=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.listOpenBracket=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}if(!this.isAtEnd()&&!this.check(u.RBRACKET))try{s.elementList.push(this.attribute())}catch(r){if(!(r instanceof d))throw r;if(s.elementList.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}for(;!this.isAtEnd()&&!this.check(u.RBRACKET);)try{this.consume("Expect a comma ','",u.COMMA),s.commaList.push(this.previous()),s.elementList.push(this.attribute())}catch(r){if(!(r instanceof d))throw r;if(r.partialNode instanceof k&&s.elementList.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}try{this.consume("Expect a closing bracket ']'",u.RBRACKET),s.listCloseBracket=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.listCloseBracket=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}return i()}),this.synchronizeList=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.COMMA,u.RBRACKET))break;E(s),this.advance()}},this.synchronizeAttributeName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.COMMA,u.RBRACKET,u.COLON))break;E(s),this.advance()}},this.synchronizeAttributeValue=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.COMMA,u.RBRACKET))break;E(s),this.advance()}},this.tokens=e,this.nodeFactory=new hn(n)}isAtEnd(){return this.current>=this.tokens.length||this.tokens[this.current].kind===u.EOF}advance(){return this.isAtEnd()?I.last(this.tokens):this.tokens[this.current++]}peek(e=0){return e+this.current>=this.tokens.length?I.last(this.tokens):this.tokens[this.current+e]}match(...e){const n=this.check(...e);return n&&this.advance(),n}check(...e){const n=this.peek();return e.includes(n.kind)}previous(){return this.tokens[this.current-1]}canHandle(e){return e.handlerContext===void 0||e.handlerContext===this.contextStack.top()}consume(e,...n){if(!this.match(...n))throw this.logError(this.peek(),o.UNEXPECTED_TOKEN,e),new d(this.peek(),void 0,this.contextStack.findHandlerContext(this.tokens,this.current))}discardUntil(e,...n){if(this.isAtEnd()||!this.check(...n)){for(E(this.peek()),this.logError(this.advance(),o.UNEXPECTED_TOKEN,e);!this.isAtEnd()&&!this.check(...n);)E(this.advance());return!this.isAtEnd()}return!0}gatherInvalid(){const e=[],n=[];let s,i=0;for(;i<this.tokens.length&&this.tokens[i].isInvalid;i+=1)n.push(this.tokens[i]);for(s=this.tokens[i],s.leadingInvalid=n,e.push(s),i+=1;i<this.tokens.length;i+=1){const r=this.tokens[i];r.isInvalid?s.trailingInvalid.push(r):(s=r,e.push(s))}this.tokens=e}parse(){const e=this.program(),n=this.advance(),s=this.nodeFactory.create(G,{body:e,eof:n});return this.gatherInvalid(),new B({ast:s,tokens:this.tokens},this.errors)}program(){const e=[];for(;!this.isAtEnd();)try{const n=this.elementDeclaration();e.push(n)}catch(n){if(!(n instanceof d))throw n;e.push(n.partialNode),this.synchronizeProgram()}return e}elementDeclaration(){const e={},n=()=>this.nodeFactory.create(A,e);try{this.consume("Expect an identifier",u.IDENTIFIER),e.type=this.previous()}catch(s){throw s instanceof d?(e.type=s.partialNode,new d(s.token,n(),s.handlerContext)):s}if(!this.check(u.COLON,u.LBRACE,u.LBRACKET))try{e.name=this.normalExpression()}catch(s){if(!(s instanceof d))throw s;if(e.name=s.partialNode,!this.canHandle(s))throw new d(s.token,n(),s.handlerContext);this.synchronizeElementDeclarationName()}if(lt(this.peek()))if(e.as=this.advance(),this.check(u.COLON,u.LBRACE,u.LBRACKET))this.logError(this.peek(),o.UNEXPECTED_TOKEN,"Expect an alias");else try{e.alias=this.normalExpression()}catch(s){if(!(s instanceof d))throw s;if(e.alias=s.partialNode,!this.canHandle(s))throw new d(s.token,n(),s.handlerContext);this.synchronizeElementDeclarationAlias()}try{e.attributeList=this.check(u.LBRACKET)?this.listExpression():void 0}catch(s){throw s instanceof d?(e.attributeList=s.partialNode,new d(s.token,n(),s.handlerContext)):s}if(!this.discardUntil("Expect an opening brace '{' or a colon ':'",u.LBRACE,u.COLON))return n();try{if(this.match(u.COLON)){e.bodyColon=this.previous();const s=this.expression();s instanceof A?(E(s),this.logError(s,o.UNEXPECTED_ELEMENT_DECLARATION,"An element's simple body must not be an element declaration")):e.body=s}else e.body=this.blockExpression()}catch(s){throw s instanceof d?(e.body=s.partialNode,new d(s.token,n(),s.handlerContext)):s}return this.nodeFactory.create(A,e)}fieldDeclaration(){const e={},n=()=>this.nodeFactory.create(A,e);try{this.consume("Expect an identifier",u.IDENTIFIER),e.type=this.previous()}catch(s){throw s instanceof d?(e.type=s.partialNode,new d(s.token,n(),s.handlerContext)):s}try{this.consume("Expect a colon ':'",u.COLON),e.bodyColon=this.previous()}catch(s){throw s instanceof d?(e.bodyColon=s.partialNode,new d(s.token,n(),s.handlerContext)):s}try{const s=this.expression();s instanceof A?this.errors.push(new c(o.INVALID_ELEMENT_IN_SIMPLE_BODY,"Simple body cannot be an element declaration",s)):e.body=s}catch(s){throw s instanceof d?(e.body=s.partialNode,new d(s.token,n(),s.handlerContext)):s}return this.nodeFactory.create(A,e)}expression(){const e={args:[]},n=()=>rn(e.callee,e.args,this.nodeFactory).unwrap_or(this.nodeFactory.create(w,e));try{e.callee=this.normalExpression()}catch(i){throw i instanceof d?(e.callee=i.partialNode,new d(i.token,n(),i.handlerContext)):i}if(this.shouldStopExpression())return n();let s=e.callee;for(;!this.shouldStopExpression();){Ce(this.previous())||this.logError(s,o.MISSING_SPACES,"Expect a following space");try{s=this.normalExpression(),e.args.push(s)}catch(i){throw i instanceof d?(s=i.partialNode,e.args.push(s),new d(i.token,n(),i.handlerContext)):i}}return n()}shouldStopExpression(){if(this.isAtEnd()||bt(this.previous()))return!0;const e=this.peek().kind;return e===u.RBRACE||e===u.RBRACKET||e===u.RPAREN||e===u.COMMA||e===u.COLON}normalExpression(){return this.expression_bp(0)}expression_bp(e){let n=this.leftExpression_bp();for(;!this.isAtEnd();){const s=this.peek();if(s.kind===u.LPAREN){const{left:i}=ut(s);if(i<e||ot(this.previous(),s)&&!this.contextStack.isWithinGroupExpressionContext()&&!this.contextStack.isWithinListExpressionContext())break;try{n=this.nodeFactory.create(J,{callee:n,argumentList:this.tupleExpression()})}catch(r){throw r instanceof d?(n=this.nodeFactory.create(J,{callee:n,argumentList:r.partialNode}),new d(r.token,n,r.handlerContext)):r}}else if(s.kind===u.LBRACKET){if(Ce(this.previous()))break;try{n=this.nodeFactory.create(le,{expression:n,indexer:this.listExpression()})}catch(i){throw i instanceof d?(n=this.nodeFactory.create(le,{expression:n,indexer:i.partialNode}),new d(i.token,n,i.handlerContext)):i}}else if(at(s)){const i=s,r=ut(i);if(r.left!==null){if(r.left<=e)break;this.advance(),n=this.nodeFactory.create(Pe,{expression:n,op:i})}else{const a=dn(i);if(a.left===null||a.left<=e)break;this.advance();try{n=this.nodeFactory.create(H,{leftExpression:n,op:i,rightExpression:i.value==="."?this.extractOperand():this.expression_bp(a.right)})}catch(l){throw l instanceof d?(n=this.nodeFactory.create(H,{leftExpression:n,op:i,rightExpression:l.partialNode}),new d(l.token,n,l.handlerContext)):l}}}else break}return n}leftExpression_bp(){let e;if(at(this.peek())){const n={};n.op=this.peek();const s=Nn(n.op);if(s.right===null)throw this.logError(n.op,o.UNKNOWN_PREFIX_OP,`Unexpected '${n.op.value}' in an expression`),new d(n.op,this.nodeFactory.create(ke,{pre:n.op}),this.contextStack.findHandlerContext(this.tokens,this.current));this.advance();try{n.expression=this.expression_bp(s.right)}catch(i){throw i instanceof d?(n.expression=i.partialNode,new d(i.token,this.nodeFactory.create(q,n),i.handlerContext)):i}e=this.nodeFactory.create(q,n)}else if(e=this.extractOperand(),e instanceof ke)throw new d(this.peek(),this.nodeFactory.create(ke,{pre:this.peek()}),this.contextStack.findHandlerContext(this.tokens,this.current));return e}extractOperand(){return this.check(u.NUMERIC_LITERAL,u.STRING_LITERAL,u.COLOR_LITERAL,u.QUOTED_STRING,u.IDENTIFIER)?this.primaryExpression():this.check(u.FUNCTION_EXPRESSION)?this.functionExpression():this.check(u.LBRACKET)?this.listExpression():this.check(u.LBRACE)?this.blockExpression():this.check(u.LPAREN)?this.tupleExpression():(this.peek().kind===u.EOF?this.logError(this.peek(),o.UNEXPECTED_EOF,"Unexpected EOF"):this.logError(this.peek(),o.INVALID_OPERAND,`Invalid start of operand "${this.peek().value}"`),this.nodeFactory.create(ke,{pre:this.previous()}))}functionExpression(){const e={};try{this.consume("Expect a function expression",u.FUNCTION_EXPRESSION),e.value=this.previous()}catch(n){throw n instanceof d?(e.value=n.partialNode,new d(n.token,this.nodeFactory.create(te,e),n.handlerContext)):n}return this.nodeFactory.create(te,e)}canBeField(){return this.peek().kind===u.IDENTIFIER&&this.peek(1).kind===u.COLON}primaryExpression(){if(this.match(u.COLOR_LITERAL,u.STRING_LITERAL,u.NUMERIC_LITERAL))return this.nodeFactory.create(D,{expression:this.nodeFactory.create(Te,{literal:this.previous()})});if(this.match(u.QUOTED_STRING,u.IDENTIFIER))return this.nodeFactory.create(D,{expression:this.nodeFactory.create(W,{variable:this.previous()})});throw this.logError(this.peek(),o.UNEXPECTED_TOKEN,"Expect a variable or literal"),new d(this.peek(),this.nodeFactory.create(D,{expression:this.nodeFactory.create(W,{})}),this.contextStack.findHandlerContext(this.tokens,this.current))}attribute(){const e={};if(this.check(u.COLON,u.RBRACKET,u.COMMA)){const n=this.peek();this.logError(n,o.EMPTY_ATTRIBUTE_NAME,"Expect a non-empty attribute name"),e.name=this.nodeFactory.create($,{identifiers:[]})}else try{e.name=this.attributeName()}catch(n){if(!(n instanceof d))throw n;if(e.name=n.partialNode,!this.canHandle(n))throw new d(n.token,this.nodeFactory.create(se,e),n.handlerContext);this.synchronizeAttributeName()}return this.match(u.COLON)&&(e.colon=this.previous(),e.value=this.attributeValue()),this.nodeFactory.create(se,e)}attributeValue(){let e;try{e=this.peek().kind===u.IDENTIFIER&&this.peek(1).kind===u.IDENTIFIER?this.attributeName():this.normalExpression()}catch(n){if(!(n instanceof d)||!this.canHandle(n))throw n;e=n.partialNode,this.synchronizeAttributeValue()}return e}attributeName(){const e=[];if(this.peek().kind!==u.IDENTIFIER)return this.primaryExpression();for(;!this.isAtEnd()&&!this.check(u.COLON,u.COMMA,u.RBRACKET);)try{this.consume("Expect an identifier",u.IDENTIFIER),e.push(this.previous())}catch(n){throw n instanceof d?new d(n.token,this.nodeFactory.create($,{identifiers:e}),n.handlerContext):n}return this.nodeFactory.create($,{identifiers:e})}logError(e,n,s){this.errors.push(new c(n,s,e))}}const pn={"+":{left:9,right:10},"*":{left:11,right:12},"-":{left:9,right:10},"/":{left:11,right:12},"%":{left:11,right:12},"<":{left:7,right:8},"<=":{left:7,right:8},">":{left:7,right:8},">=":{left:7,right:8},"<>":{left:7,right:8},"=":{left:2,right:3},"==":{left:4,right:5},"!=":{left:4,right:5},".":{left:16,right:17}};function dn(t){return pn[t.value]||{left:null,right:null}}const En={"+":{left:null,right:15},"-":{left:null,right:15},"<":{left:null,right:15},">":{left:null,right:15},"<>":{left:null,right:15},"!":{left:null,right:15}};function Nn(t){return En[t.value]||{left:null,right:null}}const mn={"(":{left:14,right:null}};function ut(t){return mn[t.value]||{left:null,right:null}}var b=(t=>(t.Table="table",t.Enum="enum",t.Ref="ref",t.Note="note",t.Project="project",t.Indexes="indexes",t.TableGroup="tablegroup",t))(b||{});function ve(t){var n;const e=(n=t==null?void 0:t.type)==null?void 0:n.value.toLowerCase();switch(e){case b.Enum:case b.Table:case b.Indexes:case b.Note:case b.Project:case b.Ref:case b.TableGroup:return new S(e);default:return new v}}function he(t){if(!Je(t))return new S([t]);const e=he(t.leftExpression).unwrap_or(void 0);return e?(e.push(t.rightExpression),new S(e)):new v}function C(t){if(t===void 0)return new v;const e=he(t).unwrap_or(void 0);if(!e)return new v;const n=[];for(const s of e){const i=X(s).unwrap_or(void 0);if(!i)return new v;n.push(i)}return new S(n)}function _e(t){if(t===void 0)return new v;const e=he(t).unwrap_or(void 0);if(!e||e.length===0)return new v;const n=[];let s;if(!F(I.last(e))){const i=e.pop();if(kt(i))s=i.elementList.map(r=>V(r).unwrap());else return new v}for(const i of e){const r=X(i).unwrap_or(void 0);if(!r)return new v;n.push(r)}return new S({variables:n,tupleElements:s})}function X(t){return F(t)?new S(t.expression.variable.value):new v}function Xe(t){if(ht(t))return t instanceof te?new S({functional:[t],nonFunctional:[]}):new S({functional:[],nonFunctional:[t]});if(t instanceof Z&&t.elementList.every(ht)){const e=t.elementList.filter(s=>s instanceof te),n=t.elementList.filter(F);return new S({functional:e,nonFunctional:n})}return new v}function V(t){var n;const e=(n=t==null?void 0:t.expression.variable)==null?void 0:n.value;return e===void 0?new v:new S(e)}function Q(t){return Y(t)?t.expression instanceof W?new S(t.expression.variable.value):new S(t.expression.literal.value):new v}function Tn(t){var e;return!(t instanceof H)||!yt((e=t.op)==null?void 0:e.value)?!1:_e(t.leftExpression).and_then(()=>_e(t.rightExpression)).unwrap_or(void 0)!==void 0}function bn(t){const e=_e(t.leftExpression),n=_e(t.rightExpression);if(!e.isOk()||!n.isOk())return!1;const{tupleElements:s}=e.unwrap(),{tupleElements:i}=n.unwrap();return(s==null?void 0:s.length)===(i==null?void 0:i.length)}function ht(t){return t instanceof D&&t.expression instanceof W||t instanceof te}function In(t,e){var i,r,a,l;let n=e;const s=qt(t);for(;n;){if((r=(i=n.symbol)==null?void 0:i.symbolTable)!=null&&r.has(t))return(a=n.symbol.symbolTable)==null?void 0:a.get(t);if(((l=n.symbol)==null?void 0:l.declaration)instanceof G&&s)return n.symbol;if(n instanceof G)return;n=n.parent}}class Ln{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof G||ve(this.declarationNode.parent).unwrap_or(void 0)!==b.Project?[new c(o.INVALID_CUSTOM_CONTEXT,"A custom element can only appear in a Project",this.declarationNode)]:[]}validateName(e){return e?[new c(o.UNEXPECTED_NAME,"A Custom element shouldn't have a name",e)]:[]}validateAlias(e){return e?[new c(o.UNEXPECTED_NAME,"A Custom element shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"A Custom element shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof ne)return[new c(o.UNEXPECTED_COMPLEX_BODY,"A Custom element can only have an inline field",e)];const n=[];return Y(e.callee)||n.push(new c(o.INVALID_CUSTOM_ELEMENT_VALUE,"A Custom element value can only be a string",e)),e.args.length>0&&n.push(...e.args.map(s=>new c(o.INVALID_CUSTOM_ELEMENT_VALUE,"A Custom element value can only be a string",s))),n}}class we{constructor(){this.table=new Map}has(e){return this.table.has(e)}set(e,n){this.table.set(e,n)}get(e,n){return this.table.get(e)||n!==void 0&&this.set(e,n)||n}entries(){return this.table.entries()}}class gn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof A?[new c(o.INVALID_PROJECT_CONTEXT,"An Enum can only appear top-level",this.declarationNode)]:[]}validateName(e){return e?Ze(e)?[]:[new c(o.INVALID_NAME,"An Enum name must be of the form <enum> or <schema>.<enum>",e)]:[new c(o.NAME_NOT_FOUND,"An Enum must have a name",this.declarationNode)]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}registerElement(){const e=[];this.declarationNode.symbol=this.symbolFactory.create(Kt,{declaration:this.declarationNode,symbolTable:new we});const{name:n}=this.declarationNode,s=C(n);if(s.isOk()){const i=s.unwrap(),r=i.pop(),a=Ke(i,this.publicSymbolTable,this.symbolFactory),l=ze(r);a.has(l)&&e.push(new c(o.DUPLICATE_NAME,`Enum name ${r} already exists in schema '${i.join(".")||"public"}'`,n)),a.set(l,this.declarationNode.symbol)}return e}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"An Enum shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return this.validateFields([e]);const[n,s]=I.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.length===0?[new c(o.EMPTY_ENUM,"An Enum must have at least one element",this.declarationNode)]:e.flatMap(n=>{const s=[];n.callee&&!F(n.callee)&&s.push(new c(o.INVALID_ENUM_ELEMENT_NAME,"An enum field must be an identifier or a quoted identifier",n.callee));const i=[...n.args];return I.last(i)instanceof P?(s.push(...this.validateFieldSettings(I.last(i))),i.pop()):i[0]instanceof P&&(s.push(...this.validateFieldSettings(i[0])),i.shift()),i.length>0&&s.push(...i.map(r=>new c(o.INVALID_ENUM_ELEMENT,"An Enum must have only a field and optionally a setting list",r))),s.push(...this.registerField(n)),s})}validateFieldSettings(e){const n=j(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"note":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_ENUM_ELEMENT_SETTING,"'note' can only appear once",l))),a.forEach(l=>{Y(l.value)||s.push(new c(o.INVALID_ENUM_ELEMENT_SETTING,"'note' must be a string",l))});break;default:a.forEach(l=>s.push(new c(o.UNKNOWN_ENUM_ELEMENT_SETTING,`Unknown enum field setting '${r}'`,l)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=re(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}registerField(e){if(e.callee&&F(e.callee)){const n=V(e.callee).unwrap(),s=Qe(n),i=this.symbolFactory.create(en,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(s)){const a=r.get(s);return[new c(o.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,e),new c(o.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,a.declaration)]}r.set(s,i)}return[]}}class _n{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof G||ve(this.declarationNode.parent).unwrap_or(void 0)!==b.Table?[new c(o.INVALID_NOTE_CONTEXT,"An Indexes can only appear inside a Table",this.declarationNode)]:[]}validateName(e){return e?[new c(o.UNEXPECTED_NAME,"An Indexes shouldn't have a name",e)]:[]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"An Indexes shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"An Indexes shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return[new c(o.UNEXPECTED_SIMPLE_BODY,"An Indexes must have a complex body",e)];const[n,s]=I.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.flatMap(n=>{if(!n.callee)return[];const s=[],i=[n.callee,...n.args];return I.last(i)instanceof P&&s.push(...this.validateFieldSetting(i.pop())),i.forEach(r=>{for(;r instanceof J;)r.argumentList&&!Xe(r.argumentList).isOk()&&s.push(new c(o.INVALID_INDEXES_FIELD,"An index field must be an identifier, a quoted identifier, a functional expression or a tuple of such",r.argumentList)),r=r.callee;Xe(r).isOk()||s.push(new c(o.INVALID_INDEXES_FIELD,"An index field must be an identifier, a quoted identifier, a functional expression or a tuple of such",r))}),s})}validateFieldSetting(e){const n=j(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"note":case"name":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_INDEX_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{Y(l.value)||s.push(new c(o.INVALID_INDEX_SETTING_VALUE,`'${r}' must be a string`,l))});break;case"unique":case"pk":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_INDEX_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{ce(l.value)||s.push(new c(o.INVALID_INDEX_SETTING_VALUE,`'${r}' must not have a value`,l))});break;case"type":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_INDEX_SETTING,"'type' can only appear once",l))),a.forEach(l=>{F(l.value)||s.push(new c(o.INVALID_INDEX_SETTING_VALUE,`'type' must be "btree" or "hash"`,l))});break;default:a.forEach(l=>s.push(new c(o.UNKNOWN_INDEX_SETTING,`Unknown index setting '${r}'`,l)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=re(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class An{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return!(this.declarationNode.parent instanceof G)&&![b.Table,b.Project].includes(ve(this.declarationNode.parent).unwrap_or(void 0))?[new c(o.INVALID_NOTE_CONTEXT,"A Note can only appear inside a Table or a Project. Sticky note can only appear at the global scope.",this.declarationNode)]:[]}validateName(e){if(!(this.declarationNode.parent instanceof G))return e?[new c(o.UNEXPECTED_NAME,"A Note shouldn't have a name",e)]:[];if(!e)return[new c(o.INVALID_NAME,"Sticky note must have a name",this.declarationNode)];const n=C(e);if(!n.isOk())return[new c(o.INVALID_NAME,"Invalid name for sticky note ",this.declarationNode)];const i=n.unwrap().join("."),r=Qt(i);return this.publicSymbolTable.has(r)?[new c(o.DUPLICATE_NAME,`Sticky note "${i}" has already been defined`,e)]:(this.publicSymbolTable.set(r,this.declarationNode.symbol),[])}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"A Note shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return this.validateFields([e]);const[n,s]=I.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){const n=[];return e.length===0?[new c(o.EMPTY_NOTE,"A Note must have a content",this.declarationNode)]:(e.length>1&&e.slice(1).forEach(s=>n.push(new c(o.NOTE_CONTENT_REDEFINED,"A Note can only contain one string",s))),Y(e[0].callee)||n.push(new c(o.INVALID_NOTE,"A Note content must be a quoted string",e[0])),e[0].args.length>0&&n.push(...e[0].args.map(s=>new c(o.INVALID_NOTE,"A Note can only contain one quoted string",s))),n)}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=re(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class vn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof A?[new c(o.INVALID_PROJECT_CONTEXT,"A Project can only appear top-level",this.declarationNode)]:[]}validateName(e){return e?Me(e)?[]:[new c(o.INVALID_NAME,"A Project's name is optional or must be an identifier or a quoted identifer",e)]:[]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A Project shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"A Project shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return[new c(o.UNEXPECTED_SIMPLE_BODY,"A Project's body must be a block",e)];const[n,s]=I.partition(e.body,i=>i instanceof w);return[...n.map(i=>new c(o.INVALID_PROJECT_FIELD,"A Project can not have inline fields",i)),...this.validateSubElements(s)]}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=re(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class wn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof G?[]:[new c(o.INVALID_REF_CONTEXT,"A Ref must appear top-level",this.declarationNode)]}validateName(e){return e?Me(e)?[]:[new c(o.INVALID_NAME,"A Ref's name is optional or must be an identifier or a quoted identifer",e)]:[]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"A Ref shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return this.validateFields([e]);const[n,s]=I.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){if(e.length===0)return[new c(o.EMPTY_REF,"A Ref must have at least one field",this.declarationNode)];const n=[];return e.length>1&&n.push(...e.slice(1).map(s=>new c(o.REF_REDEFINED,"A Ref can only contain one binary relationship",s))),e.forEach(s=>{s.callee&&!Tn(s.callee)&&n.push(new c(o.INVALID_REF_FIELD,"A Ref field must be a binary relationship",s.callee)),s.callee&&!bn(s.callee)&&n.push(new c(o.UNEQUAL_FIELDS_BINARY_REF,"Unequal fields in ref endpoints",s.callee));const i=[...s.args];I.last(i)instanceof P?(this.validateFieldSettings(I.last(i)),i.pop()):i[0]instanceof P&&(n.push(...this.validateFieldSettings(i[0])),i.shift()),i.length>0&&n.push(...i.map(r=>new c(o.INVALID_REF_FIELD,"A Ref field should only have a single binary relationship",r)))}),n}validateFieldSettings(e){const n=j(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"delete":case"update":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_REF_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{yn(l.value)||s.push(new c(o.INVALID_REF_SETTING_VALUE,`'${r}' can only have values "cascade", "no action", "set null", "set default" or "restrict"`,l))});break;default:a.forEach(l=>s.push(new c(o.UNKNOWN_REF_SETTING,`Unknown ref setting '${r}'`,l)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=re(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}function yn(t){if(!(F(t)&&t.expression.variable.kind!==u.QUOTED_STRING)&&!(t instanceof $))return!1;let e;if(t instanceof $?e=me(t).unwrap_or(""):e=t.expression.variable.value,e)switch(e.toLowerCase()){case"cascade":case"no action":case"set null":case"set default":case"restrict":return!0;default:return!1}return!1}class kn{constructor(e,n,s){this.declarationNode=e,this.symbolFactory=s,this.publicSymbolTable=n}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof A?[new c(o.INVALID_TABLE_CONTEXT,"Table must appear top-level",this.declarationNode)]:[]}validateName(e){return e?e instanceof le?[new c(o.INVALID_NAME,"Invalid array as Table name, maybe you forget to add a space between the name and the setting list?",e)]:Ze(e)?[]:[new c(o.INVALID_NAME,"A Table name must be of the form <table> or <schema>.<table>",e)]:[new c(o.NAME_NOT_FOUND,"A Table must have a name",this.declarationNode)]}validateAlias(e){return e?Rn(e)?[]:[new c(o.INVALID_ALIAS,"Table aliases can only contains alphanumeric and underscore unless surrounded by double quotes",e)]:[]}validateSettingList(e){const n=j(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"headercolor":a.length>1&&s.push(...a.map(l=>new c(o.DUPLICATE_TABLE_SETTING,"'headercolor' can only appear once",l))),a.forEach(l=>{Dn(l.value)||s.push(new c(o.INVALID_TABLE_SETTING,"'headercolor' must be a color literal",l.value||l.name))});break;case"note":a.length>1&&s.push(...a.map(l=>new c(o.DUPLICATE_TABLE_SETTING,"'note' can only appear once",l))),a.forEach(l=>{Y(l.value)||s.push(new c(o.INVALID_TABLE_SETTING,"'note' must be a string literal",l.value||l.name))});break;default:s.push(...a.map(l=>new c(o.INVALID_TABLE_SETTING,`Unknown '${r}' setting`,l)))}}return s}registerElement(){const e=[];this.declarationNode.symbol=this.symbolFactory.create(At,{declaration:this.declarationNode,symbolTable:new we});const{name:n,alias:s}=this.declarationNode,i=C(n);if(i.isOk()){const r=[...i.unwrap()],a=r.pop(),l=Ke(r,this.publicSymbolTable,this.symbolFactory),p=Se(a);l.has(p)&&e.push(new c(o.DUPLICATE_NAME,`Table name '${a}' already exists in schema '${r.join(".")||"public"}'`,n)),l.set(p,this.declarationNode.symbol)}if(s&&Me(s)&&!Sn(s.expression.variable.value,i.unwrap_or([]))){const r=V(s).unwrap(),a=Se(r);this.publicSymbolTable.has(a)&&e.push(new c(o.DUPLICATE_NAME,`Table name '${r}' already exists`,n)),this.publicSymbolTable.set(a,this.declarationNode.symbol)}return e}validateBody(e){if(!e)return[];if(e instanceof w)return[new c(o.UNEXPECTED_SIMPLE_BODY,"A Table's body must be a block",e)];const[n,s]=I.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.length===0?[new c(o.EMPTY_TABLE,"A Table must have at least one column",this.declarationNode)]:e.flatMap(n=>{if(!n.callee)return[];const s=[];n.args.length===0&&s.push(new c(o.INVALID_COLUMN,"A column must have a type",n.callee)),F(n.callee)||s.push(new c(o.INVALID_COLUMN_NAME,"A column name must be an identifier or a quoted identifier",n.callee)),n.args[0]&&!xn(n.args[0])&&s.push(new c(o.INVALID_COLUMN_TYPE,"Invalid column type",n.args[0]));const i=n.args.slice(1);return s.push(...this.validateFieldSetting(i)),s.push(...this.registerField(n)),s})}registerField(e){if(e.callee&&F(e.callee)){const n=V(e.callee).unwrap(),s=Ye(n),i=this.symbolFactory.create(tn,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(s)){const a=r.get(s);return[new c(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,e),new c(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,a.declaration)]}r.set(s,i)}return[]}validateFieldSetting(e){if(!e.slice(0,-1).every(Ne)||!e.slice(-1).every(p=>Ne(p)||p instanceof P))return[...e.map(p=>new c(o.INVALID_COLUMN,"These fields must be some inline settings optionally ended with a setting list",p))];if(e.length===0)return[];let n;I.last(e)instanceof P&&(n=e.pop());const s=j(n),i=s.getErrors(),r=s.getValue();for(const p of e){const h=V(p).unwrap_or("").toLowerCase();if(h!=="pk"&&h!=="unique"){i.push(new c(o.INVALID_SETTINGS,"Inline column settings can only be `pk` or `unique`",p));continue}r[h]===void 0?r[h]=[p]:r[h].push(p)}const a=r.pk||[],l=r["primary key"]||[];a.length>=1&&l.length>=1&&i.push(...[...a,...l].map(p=>new c(o.DUPLICATE_COLUMN_SETTING,"Either one of 'primary key' and 'pk' can appear",p)));for(const p in r){const h=r[p];switch(p){case"note":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_COLUMN_SETTING,"note can only appear once",f))),h.forEach(f=>{Y(f.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'note' must be a quoted string",f.value||f.name))});break;case"ref":h.forEach(f=>{Un(f.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'ref' must be a valid unary relationship",f.value||f.name))});break;case"primary key":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_COLUMN_SETTING,"primary key can only appear once",f))),h.forEach(f=>{ce(f.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'primary key' must not have a value",f.value||f.name))});break;case"pk":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_COLUMN_SETTING,"'pk' can only appear once",f))),h.forEach(f=>{f instanceof se&&!ce(f.value)&&i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'pk' must not have a value",f.value||f.name))});break;case"not null":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_COLUMN_SETTING,"'not null' can only appear once",f)));const T=r.null||[];h.length>=1&&T.length>=1&&i.push(...[...h,...T].map(f=>new c(o.CONFLICTING_SETTING,"'not null' and 'null' can not be set at the same time",f))),h.forEach(f=>{ce(f.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'not null' must not have a value",f.value||f.name))});break;case"null":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_COLUMN_SETTING,"'null' can only appear once",f))),h.forEach(f=>{ce(f.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'null' must not have a value",f.value||f.name))});break;case"unique":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_COLUMN_SETTING,"'unique' can only appear once",f))),h.forEach(f=>{f instanceof se&&!ce(f.value)&&i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'unique' must not have a value",f.value||f.name))});break;case"increment":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_COLUMN_SETTING,"'increment' can only appear once",f))),h.forEach(f=>{f instanceof se&&!ce(f.value)&&i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'increment' must not have a value",f.value||f.name))});break;case"default":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_TABLE_SETTING,"'default' can only appear once",f))),h.forEach(f=>{Pn(f.value)||i.push(new c(o.INVALID_TABLE_SETTING,"'default' must be a string literal, number literal, function expression, true, false or null",f.value||f.name))});break;default:h.forEach(f=>i.push(new c(o.UNKNOWN_COLUMN_SETTING,`Unknown column setting '${p}'`,f)))}}return i}validateSubElements(e){const n=e.flatMap(i=>{if(i.parent=this.declarationNode,!i.type)return[];const r=re(i);return new r(i,this.publicSymbolTable,this.symbolFactory).validate()}),s=e.filter(i=>{var r;return((r=i.type)==null?void 0:r.value.toLowerCase())==="note"});return s.length>1&&(n.push(...s.map(i=>new c(o.NOTE_REDEFINED,"Duplicate notes are defined",i))),n.push()),n}}function xn(t){if(!(t instanceof J||Je(t)||t instanceof D||t instanceof le))return!1;if(t instanceof J){if(t.callee===void 0||t.argumentList===void 0||!t.argumentList.elementList.every(n=>ue(n)||Y(n)||Ne(n)))return!1;t=t.callee}for(;t instanceof le;){if(t.array===void 0||t.indexer===void 0||!t.indexer.elementList.every(n=>!n.colon&&!n.value&&ue(n.name)))return!1;t=t.array}const e=C(t).unwrap_or(void 0);return e!==void 0&&e.length>0}function Sn(t,e){return e.length===1&&t===e[0]}class On{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof A?[new c(o.INVALID_TABLEGROUP_CONTEXT,"TableGroup must appear top-level",this.declarationNode)]:[]}validateName(e){return e?Ze(e)?[]:[new c(o.INVALID_NAME,"A TableGroup name must be of the form <tablegroup> or <schema>.<tablegroup>",e)]:[new c(o.NAME_NOT_FOUND,"A TableGroup must have a name",this.declarationNode)]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A TableGroup shouldn't have an alias",e)]:[]}registerElement(){const{name:e}=this.declarationNode;this.declarationNode.symbol=this.symbolFactory.create(nn,{declaration:this.declarationNode,symbolTable:new we});const n=C(e);if(n.isOk()){const s=n.unwrap(),i=s.pop(),r=Ke(s,this.publicSymbolTable,this.symbolFactory),a=qe(i);if(r.has(a))return[new c(o.DUPLICATE_NAME,`TableGroup name '${i}' already exists in schema '${s.join(".")||"public"}'`,e)];r.set(a,this.declarationNode.symbol)}return[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"A TableGroup shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return[new c(o.UNEXPECTED_SIMPLE_BODY,"A TableGroup's body must be a block",e)];const[n,s]=I.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.flatMap(n=>{const s=[];return n.callee&&!C(n.callee).isOk()&&s.push(new c(o.INVALID_TABLEGROUP_FIELD,"A TableGroup field must be of the form <table> or <schema>.<table>",n.callee)),this.registerField(n),n.args.length>0&&s.push(...n.args.map(i=>new c(o.INVALID_TABLEGROUP_FIELD,"A TableGroup field should only have a single Table name",i))),s})}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=re(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}registerField(e){if(e.callee&&F(e.callee)){const n=V(e.callee).unwrap(),s=He(n),i=this.symbolFactory.create(sn,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(s)){const a=r.get(s);return[new c(o.DUPLICATE_TABLEGROUP_FIELD_NAME,`${n} already exists in the group`,e),new c(o.DUPLICATE_TABLEGROUP_FIELD_NAME,`${n} already exists in the group`,a.declaration)]}r.set(s,i)}return[]}}const wt=["-","+"];function re(t){switch(t.type.value.toLowerCase()){case b.Enum:return gn;case b.Table:return kn;case b.TableGroup:return On;case b.Project:return vn;case b.Ref:return wn;case b.Note:return An;case b.Indexes:return _n;default:return Ln}}function Ze(t){return!!C(t).unwrap_or(!1)}function Rn(t){return Me(t)}function Me(t){return t instanceof D&&t.expression instanceof W}function Ke(t,e,n){var i;t[0]==="public"&&(t=t.slice(1));let s=e;for(const r of t){let a;const l=We(r);if(s.has(l)){if(a=(i=s.get(l))==null?void 0:i.symbolTable,!a)throw new Error("Expect a symbol table in a schema symbol")}else{a=new we;const p=n.create(_t,{symbolTable:a});s.set(l,p)}s=a}return s}function yt(t){return t==="-"||t==="<>"||t===">"||t==="<"}function Dn(t){var n;if(!(t instanceof D)||!(t.expression instanceof Te)||((n=t.expression.literal)==null?void 0:n.kind)!==u.COLOR_LITERAL)return!1;const e=t.expression.literal.value;if(e.length!==4&&e.length!==7||e[0]!=="#")return!1;for(let s=1;s<e.length;s+=1)if(!Jt(e[s]))return!1;return!0}function ce(t){return t===void 0}function Pn(t){var e;return!!(Y(t)||ue(t)||Ne(t)&&["true","false","null"].includes(t.expression.variable.value.toLowerCase())||t instanceof q&&wt.includes((e=t.op)==null?void 0:e.value)&&ue(t.expression)||t instanceof te)}function ue(t){var e;return t instanceof D&&t.expression instanceof Te&&((e=t.expression.literal)==null?void 0:e.kind)===u.NUMERIC_LITERAL}function Un(t){var n;if(!(t instanceof q)||!yt((n=t.op)==null?void 0:n.value))return!1;const e=C(t.expression).unwrap_or(void 0);return e!==void 0&&e.length>0}function kt(t){return t instanceof Z&&t.elementList.every(F)}function j(t){var s;const e={},n=[];if(!t)return new B({});for(const i of t.elementList){if(!i.name)continue;if(i.name instanceof D){n.push(new c(o.INVALID_SETTINGS,"A setting name must be a stream of identifiers",i.name));continue}const r=(s=me(i.name).unwrap_or(void 0))==null?void 0:s.toLowerCase();r&&(e[r]===void 0?e[r]=[i]:e[r].push(i))}return new B(e,n)}class ft{constructor(e,n){this.ast=e,this.symbolFactory=n,this.publicSchemaSymbol=this.symbolFactory.create(_t,{symbolTable:new we}),this.ast.symbol=this.publicSchemaSymbol,this.ast.symbol.declaration=this.ast}validate(){const e=[];this.ast.body.forEach(s=>{if(s.parent=this.ast,s.type===void 0)return;const i=re(s),r=new i(s,this.publicSchemaSymbol.symbolTable,this.symbolFactory);e.push(...r.validate())});const n=this.ast.body.filter(s=>ve(s).unwrap_or(void 0)===b.Project);return n.length>1&&n.forEach(s=>e.push(new c(o.PROJECT_REDEFINED,"Only one project can exist",s))),new B(this.ast,e)}}class ae{constructor(e,n){this.declarationNode=e,this.errors=n}bind(){this.bindSettingList(this.declarationNode.attributeList,this.settingList),this.bindBody()}bindSettingList(e,n){if(e)for(const s of e.elementList){if(s.name instanceof D)continue;const i=me(s.name).unwrap_or(void 0);if(!i)continue;const r=n[i.toLowerCase()];r!=null&&r.shouldBind&&this.scanAndBind(s.value,r)}}bindBody(){const e=this.declarationNode;if(!e.body)return;const{body:n}=e;if(n instanceof ne)for(const s of n.body)if(s instanceof A){if(!s.type)continue;const i=xt(s);new i(s,this.errors).bind()}else this.bindSubfield(s);else this.bindSubfield(n)}bindSubfield(e){const n=[e.callee,...e.args],s=I.last(n);s instanceof P&&(n.pop(),this.bindSettingList(s,this.subfield.settingList));const{argBinderRules:i}=this.subfield.arg;for(let r=0;r<Math.min(n.length,i.length);r+=1)i[r].shouldBind&&this.scanAndBind(n[r],i[r])}scanAndBind(e,n){var s,i;if(e)if(e instanceof D){if(e.expression instanceof W&&((i=n.keywords)!=null&&i.includes((s=e.expression.variable)==null?void 0:s.value.toLowerCase())))return;this.bindFragments([e],n)}else e instanceof H?Je(e)?this.bindFragments(he(e).unwrap_or([]),n):(this.scanAndBind(e.leftExpression,n),this.scanAndBind(e.rightExpression,n)):e instanceof q?this.scanAndBind(e.expression,n):e instanceof Pe?this.scanAndBind(e.expression,n):e instanceof Z&&e.elementList.forEach(r=>this.scanAndBind(r,n))}bindFragments(e,n){if(e.length===0)return;const s=[...n.topSubnamesSymbolKind],{remainingSubnamesSymbolKind:i}=n,r=e.findIndex(f=>!F(f)),l=r!==-1&&kt(e[r])?e[r]:void 0,p=r>=0?s.pop():void 0,h=e.slice(0,r===-1?void 0:r);if(h.length===0)return;const T=[];for(;s.length&&h.length;){const f=s.pop(),N=h.pop(),g=V(N).unwrap();T.unshift({index:Ve(g,f),referrer:N})}for(;h.length;){const f=h.pop(),N=V(f).unwrap();T.unshift({index:Ve(N,i),referrer:f})}return l?l.elementList.forEach(f=>this.resolveIndexStack([...T,{index:Ve(V(f).unwrap(),p),referrer:f}],n.ignoreNameNotFound)):this.resolveIndexStack(T,n.ignoreNameNotFound)}resolveIndexStack(e,n){if(e.length===0)throw new Error("Unreachable - An unresolved name must have at least one name component");const[s,...i]=e,r=In(s.index,this.declarationNode);if(r===void 0){const{kind:h,name:T}=ie(s.index).unwrap();this.logError(s.referrer,`Can not find ${h} '${T}'`,n);return}r.references.push(s.referrer),s.referrer.referee=r;let a=r.symbolTable,{kind:l,name:p}=ie(s.index).unwrap();for(const h of i){const{kind:T,name:f}=ie(h.index).unwrap(),N=a.get(h.index);if(!N){this.logError(h.referrer,`${l} '${p}' does not have ${T} '${f}'`,n);return}if(l=T,p=f,h.referrer.referee=N,N.references.push(h.referrer),!N.symbolTable)break;a=N.symbolTable}}logError(e,n,s){s||this.errors.push(new c(o.BINDING_ERROR,n,e))}}class Mn extends ae{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Fn extends ae{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Bn extends ae{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class Vn extends ae{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Gn extends ae{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Cn extends ae{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class Xn extends ae{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Enum],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!0}]},settingList:{ref:{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},default:{shouldBind:!1}}},this.settingList={}}}class $n extends ae{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}function xt(t){switch(t.type.value.toLowerCase()){case b.Enum:return Fn;case b.Table:return Xn;case b.TableGroup:return $n;case b.Project:return Gn;case b.Ref:return Cn;case b.Note:return Vn;case b.Indexes:return Bn;default:return Mn}}class jn{constructor(e){this.ast=e,this.errors=[]}resolve(){for(const e of this.ast.body)if(e.type){const n=xt(e);new n(e,this.errors).bind()}return new B(this.ast,this.errors)}}class Wn{constructor(e){this.generator=e}create(e,n){return new e(n,this.generator.nextId())}}class Yn{constructor(e,n){this.ast=e,this.symbolFactory=new Wn(n)}analyze(){return new ft(this.ast,this.symbolFactory).validate().chain(n=>new jn(n).resolve())}validate(){return new ft(this.ast,this.symbolFactory).validate().chain(n=>new B(n,[]))}}function pt(t,e){const{variables:n,tupleElements:s}=_e(t).unwrap();return s?n.length===0?{schemaName:e.schemaName,tableName:e.name,fieldNames:s}:{tableName:n.pop(),schemaName:n.pop()||null,fieldNames:s}:n.length===1?{schemaName:e.schemaName,tableName:e.name,fieldNames:[n[0]]}:{fieldNames:[n.pop()],tableName:n.pop(),schemaName:n.pop()||null}}function St(t){switch(t){case"<":return["1","*"];case"<>":return["*","*"];case">":return["*","1"];case"-":return["1","1"]}throw new Error("Invalid relation op")}function x(t){return{start:{offset:t.startPos.offset,line:t.startPos.line+1,column:t.startPos.column+1},end:{offset:t.endPos.offset,line:t.endPos.line+1,column:t.endPos.column+1}}}function $e(t){var n;const e=(n=he(t).unwrap_or(void 0))==null?void 0:n.pop();return e instanceof Z?e.elementList.map(s=>s.referee):[e.referee]}function be(t){const e=C(t).unwrap();return{name:e.pop(),schemaName:e}}function Ot(t){return t.expression.literal.value}function Rt(t,e){if(Array.isArray(t)){const i=t.map(({id:a})=>a).sort().join(","),r=e.map(({id:a})=>a).sort().join(",");return i<r?`${i}-${r}`:`${r}-${i}`}const n=t.id.toString(),s=e.id.toString();return n<s?`${n}-${s}`:`${s}-${n}`}function Dt(t,e){if(Array.isArray(t)){const i=t.map(({id:a})=>a).sort(),r=e.map(({id:a})=>a).sort();return I.zip(i,r).every(([a,l])=>a===l)}const n=t.id,s=e.id;return n===s}function Ee(t){const e=t.split(`
10
+ `),n=e.slice(e.findIndex(r=>r.trimStart()!=="")),s=n.filter(r=>r.trimStart()),i=Math.min(...s.map(r=>r.length-r.trimStart().length));return n.map(r=>r.slice(i)).join(`
11
+ `)}class Pt{constructor(e,n){this.declarationNode=e,this.env=n,this.table={name:void 0,schemaName:void 0,alias:null,fields:[],token:void 0,indexes:[]},this.pkColumns=[]}interpret(){this.table.token=x(this.declarationNode),this.env.tables.set(this.declarationNode,this.table);const e=[...this.interpretName(this.declarationNode.name),...this.interpretAlias(this.declarationNode.alias),...this.interpretSettingList(this.declarationNode.attributeList),...this.interpretBody(this.declarationNode.body)];return this.pkColumns.length>=2&&(this.table.indexes.push({columns:this.pkColumns.map(({name:n})=>({value:n,type:"column"})),token:{start:{offset:-1,line:-1,column:-1},end:{offset:-1,line:-1,column:-1}},pk:!0}),this.pkColumns.forEach(n=>n.pk=!1)),e}interpretName(e){const{name:n,schemaName:s}=be(e);return s.length>1?(this.table.name=n,this.table.schemaName=s.join("."),[new c(o.UNSUPPORTED,"Nested schema is not supported",e)]):(this.table.name=n,this.table.schemaName=s.length?s[0]:null,[])}interpretAlias(e){if(!e)return[];const n=V(e).unwrap_or(null);return n&&(this.env.aliases.push({name:n,kind:"table",value:{tableName:this.table.name,schemaName:this.table.schemaName}}),this.table.alias=n),[]}interpretSettingList(e){var i,r,a;const n=j(e).getValue();this.table.headerColor=(i=n.headercolor)!=null&&i.length?Ot((a=(r=n.headercolor)==null?void 0:r.at(0))==null?void 0:a.value):void 0;const[s]=n.note||[];return this.table.note=s&&{value:Q(s==null?void 0:s.value).map(Ee).unwrap(),token:x(s)},[]}interpretBody(e){const[n,s]=I.partition(e.body,i=>i instanceof w);return[...this.interpretFields(n),...this.interpretSubElements(s)]}interpretSubElements(e){return e.flatMap(n=>{var s;switch((s=n.type)==null?void 0:s.value.toLowerCase()){case"note":return this.table.note={value:Q(n.body instanceof ne?n.body.body[0].callee:n.body.callee).map(Ee).unwrap(),token:x(n)},[];case"indexes":return this.interpretIndexes(n)}return[]})}interpretFields(e){return e.flatMap(n=>this.interpretColumn(n))}interpretColumn(e){var a,l,p,h,T,f,N,g;const n=[],s={};s.name=V(e.callee).unwrap();const i=zn(e.args[0]);s.type=i.getValue(),n.push(...i.getErrors()),s.token=x(e),s.inline_refs=[];const r=e.args.slice(1);if(I.last(r)instanceof P){const _=j(r.pop()).getValue();s.pk=!!((a=_.pk)!=null&&a.length)||!!((l=_["primary key"])!=null&&l.length),s.increment=!!((p=_.increment)!=null&&p.length),s.unique=!!((h=_.unique)!=null&&h.length),s.not_null=!!((T=_["not null"])!=null&&T.length)&&!0,s.dbdefault=Qn((N=(f=_.default)==null?void 0:f.at(0))==null?void 0:N.value);const K=(g=_.note)==null?void 0:g.at(0);s.note=K&&{value:Q(K.value).map(Ee).unwrap(),token:x(K)};const Ie=_.ref||[];s.inline_refs=Ie.flatMap(z=>{const[nt]=$e(z.value.expression);if(Dt(nt,e.symbol))return n.push(new c(o.SAME_ENDPOINT,"Two endpoints are the same",z)),[];const ye=z.value.op,ee=C(z.value.expression).unwrap();let fe;if(ee.length===1){const[oe]=ee;fe={schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[oe],relation:ye.value,token:x(z)}}else if(ee.length===2){const[oe,Le]=ee;fe={schemaName:null,tableName:oe,fieldNames:[Le],relation:ye.value,token:x(z)}}else if(ee.length===3){const[oe,Le,it]=ee;fe={schemaName:oe,tableName:Le,fieldNames:[it],relation:ye.value,token:x(z)}}else{n.push(new c(o.UNSUPPORTED,"Nested schema is not supported",z));const oe=ee.pop(),Le=ee.pop();fe={schemaName:ee.join("."),tableName:Le,fieldNames:[oe],relation:ye.value,token:x(z)}}const st=this.registerInlineRefToEnv(e,nt,fe,z);return n.push(...st),st.length===0?fe:[]})}return s.pk||(s.pk=r.some(_=>X(_).unwrap().toLowerCase()==="pk")),s.unique||(s.unique=r.some(_=>X(_).unwrap().toLowerCase()==="unique")),this.table.fields.push(s),s.pk&&this.pkColumns.push(s),n}interpretIndexes(e){return this.table.indexes.push(...e.body.body.map(n=>{var a,l,p,h,T,f,N;const s={columns:[]},i=n;s.token=x(e);const r=[i.callee,...i.args];if(I.last(r)instanceof P){const g=j(r.pop()).getValue();s.pk=!!((a=g.pk)!=null&&a.length),s.unique=!!((l=g.unique)!=null&&l.length),s.name=Q((h=(p=g.name)==null?void 0:p.at(0))==null?void 0:h.value).unwrap_or(void 0);const _=(T=g.note)==null?void 0:T.at(0);s.note=_&&{value:Q(_.value).unwrap(),token:x(_)},s.type=X((N=(f=g.type)==null?void 0:f.at(0))==null?void 0:N.value).unwrap_or(void 0)}return r.flatMap(g=>{if(!(g instanceof J))return g;const _=[];for(;g instanceof J;)_.push(g.argumentList),g=g.callee;return _.push(g),_}).forEach(g=>{const{functional:_,nonFunctional:K}=Xe(g).unwrap();s.columns.push(..._.map(Ie=>({value:Ie.value.value,type:"expression"})),...K.map(Ie=>({value:V(Ie).unwrap(),type:"column"})))}),s})),[]}registerInlineRefToEnv(e,n,s,i){const r=Rt(e.symbol,n);if(this.env.refIds[r])return[new c(o.CIRCULAR_REF,"References with same endpoints exist",i),new c(o.CIRCULAR_REF,"References with same endpoints exist",this.env.refIds[r])];const a=St(s.relation);return this.env.refIds[r]=i,this.env.ref.set(i,{name:null,schemaName:null,token:s.token,endpoints:[{...s,relation:a[1]},{schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[X(e.callee).unwrap()],token:x(e),relation:a[0]}]}),[]}}function zn(t){let e=null;t instanceof J&&(e=t.argumentList.elementList.map(r=>ue(r)?r.expression.literal.value:Y(r)?Q(r).unwrap():X(r).unwrap()).join(","),t=t.callee);let n="";for(;t instanceof le;)n=`[${t.indexer.elementList.map(r=>r.name.expression.literal.value).join(",")}]${n}`,t=t.array;const{name:s,schemaName:i}=be(t);return i.length>1?new B({schemaName:i.length===0?null:i[0],type_name:`${s}${n}${e?`(${e})`:""}`,args:e},[new c(o.UNSUPPORTED,"Nested schema is not supported",t)]):new B({schemaName:i.length===0?null:i[0],type_name:`${s}${n}${e?`(${e})`:""}`,args:e})}function Qn(t){var e,n,s;if(t){if(Y(t))return{value:Q(t).unwrap(),type:"string"};if(ue(t))return{type:"number",value:Number.parseFloat(t.expression.literal.value)};if(Ne(t))return{value:t.expression.variable.value.toLowerCase(),type:"boolean"};if(t instanceof q&&wt.includes((e=t.op)==null?void 0:e.value)&&ue(t.expression)){const i=Number.parseFloat(t.expression.expression.literal.value);return{value:((n=t.op)==null?void 0:n.value)==="-"?0-i:i,type:"number"}}if(t instanceof te)return{value:(s=t.value)==null?void 0:s.value,type:"expression"};throw new Error("Unreachable")}}class qn{constructor(e,n){this.declarationNode=e,this.env=n,this.note={name:void 0,content:void 0,token:void 0}}interpret(){return this.note.token=x(this.declarationNode),this.env.notes.set(this.declarationNode,this.note),[...this.interpretName(this.declarationNode.name),...this.interpretSettingList(this.declarationNode.attributeList),...this.interpretBody(this.declarationNode.body)]}interpretName(e){const{name:n}=be(e);return this.note.name=n,[]}interpretSettingList(e){var s,i,r;const n=j(e).getValue();return this.note.headerColor=(s=n.headercolor)!=null&&s.length?Ot((r=(i=n.headercolor)==null?void 0:i.at(0))==null?void 0:r.value):void 0,[]}interpretBody(e){const[n,s]=I.partition(e.body,i=>i instanceof w);return n.length!==1||s.length>0?[new c(o.INVALID_NOTE,"Invalid note syntax",e)]:[...this.interpretNote(n[0])]}interpretNote(e){const n=I.get(e,"callee.expression.literal.value","");return this.note.content=Ee(n),[]}}class Ut{constructor(e,n){this.declarationNode=e,this.env=n,this.container=this.declarationNode.parent instanceof A?this.env.tables.get(this.declarationNode.parent):void 0,this.ref={}}interpret(){return this.ref.token=x(this.declarationNode),this.env.ref.set(this.declarationNode,this.ref),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(e){const n=[],s=C(this.declarationNode.name).unwrap_or([]);return this.ref.name=s.pop()||null,s.length>1&&n.push(new c(o.UNSUPPORTED,"Nested schema is not supported",this.declarationNode.name)),this.ref.schemaName=s.join(".")||null,n}interpretBody(e){return e instanceof w?this.interpretField(e):this.interpretField(e.body[0])}interpretField(e){var h,T,f,N;const n=e.callee.op.value,{leftExpression:s,rightExpression:i}=e.callee,r=$e(s),a=$e(i);if(Dt(r,a))return[new c(o.SAME_ENDPOINT,"Two endpoints are the same",e)];const l=Rt(r,a);if(this.env.refIds[l])return[new c(o.CIRCULAR_REF,"References with same endpoints exist",this.declarationNode),new c(o.CIRCULAR_REF,"References with same endpoints exist",this.env.refIds[l])];if(e.args[0]){const g=j(e.args[0]).getValue(),_=(T=(h=g.delete)==null?void 0:h.at(0))==null?void 0:T.value;this.ref.onDelete=_ instanceof $?me(_).unwrap_or(void 0):X(_).unwrap_or(void 0);const K=(N=(f=g.update)==null?void 0:f.at(0))==null?void 0:N.value;this.ref.onUpdate=K instanceof $?me(K).unwrap_or(void 0):X(K).unwrap_or(void 0)}const p=St(n);return this.ref.endpoints=[{...pt(s,this.container),relation:p[0],token:x(s)},{...pt(i,this.container),relation:p[1],token:x(i)}],this.env.refIds[l]=this.declarationNode,[]}}class Mt{constructor(e,n){this.declarationNode=e,this.env=n,this.tableGroup={tables:[]}}interpret(){const e=[];return this.tableGroup.token=x(this.declarationNode),this.env.tableGroups.set(this.declarationNode,this.tableGroup),e.push(...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)),e}interpretName(e){const n=[],{name:s,schemaName:i}=be(e);return i.length>=2&&(this.tableGroup.name=s,this.tableGroup.schemaName=i.join("."),n.push(new c(o.UNSUPPORTED,"Nested schema is not supported",this.declarationNode.name))),this.tableGroup.name=s,this.tableGroup.schemaName=i[0]||null,n}interpretBody(e){const n=[];return this.tableGroup.tables=this.declarationNode.body.body.map(s=>{const i=C(s.callee).unwrap();i.length>2&&n.push(new c(o.UNSUPPORTED,"Nested schema is not supported",s));const r=he(s.callee).unwrap().pop().referee.id;if(this.env.groupOfTable[r]){const a=this.env.groupOfTable[r],{schemaName:l,name:p}=this.env.tableGroups.get(a),h=l?`${l}.${p}`:p;n.push(new c(o.TABLE_REAPPEAR_IN_TABLEGROUP,`Table "${i.join(".")}" already appears in group "${h}"`,s))}else this.env.groupOfTable[r]=this.declarationNode;return{name:i.pop(),schemaName:i.join(".")}}),n}}class Ft{constructor(e,n){this.declarationNode=e,this.env=n,this.enum={values:[]}}interpret(){return this.enum.token=x(this.declarationNode),this.env.enums.set(this.declarationNode,this.enum),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(e){const{name:n,schemaName:s}=be(e);return s.length>1?(this.enum.name=n,this.enum.schemaName=s.join("."),[new c(o.UNSUPPORTED,"Nested schema is not supported",e)]):(this.enum.name=n,this.enum.schemaName=s.length?s[0]:null,[])}interpretBody(e){return e.body.flatMap(n=>{var l;const s=n,i={};i.token=x(s),i.name=X(s.callee).unwrap();const a=(l=j(s.args[0]).getValue().note)==null?void 0:l.at(0);return i.note=a&&{value:Q(a.value).map(Ee).unwrap(),token:x(a)},this.enum.values.push(i),[]})}}class Hn{constructor(e,n){this.declarationNode=e,this.env=n,this.project={enums:[],refs:[],tableGroups:[],tables:[]}}interpret(){return this.env.project.set(this.declarationNode,this.project),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(e){if(!e)return this.project.name=null,[];const{name:n}=be(e);return this.project.name=n,[]}interpretBody(e){return e.body.flatMap(n=>{var i;const s=n;switch((i=s.type)==null?void 0:i.value.toLowerCase()){case"table":{const r=new Pt(s,this.env).interpret();return this.project.tables.push(this.env.tables.get(s)),r}case"ref":{const r=new Ut(s,this.env).interpret();return this.project.refs.push(this.env.ref.get(s)),r}case"tablegroup":{const r=new Mt(s,this.env).interpret();return this.project.tableGroups.push(this.env.tableGroups.get(s)),r}case"enum":{const r=new Ft(s,this.env).interpret();return this.project.enums.push(this.env.enums.get(s)),r}case"note":return this.project.note={value:Q(s.body instanceof ne?s.body.body[0].callee:s.body.callee).map(Ee).unwrap(),token:x(s)},[];default:return this.project[s.type.value.toLowerCase()]=Q(s.body.callee).unwrap(),[]}})}}class Jn{constructor(e){this.ast=e,this.env={schema:[],tables:new Map,notes:new Map,refIds:{},ref:new Map,enums:new Map,tableGroups:new Map,groupOfTable:{},aliases:[],project:new Map}}interpret(){const e=this.ast.body.flatMap(n=>{switch(ve(n).unwrap_or(void 0)){case b.Table:return new Pt(n,this.env).interpret();case b.Note:return new qn(n,this.env).interpret();case b.Ref:return new Ut(n,this.env).interpret();case b.TableGroup:return new Mt(n,this.env).interpret();case b.Enum:return new Ft(n,this.env).interpret();case b.Project:return new Hn(n,this.env).interpret();default:return[]}});return new B(Zn(this.env),e)}}function Zn(t){return{schemas:[],tables:Array.from(t.tables.values()),notes:Array.from(t.notes.values()),refs:Array.from(t.ref.values()),enums:Array.from(t.enums.values()),tableGroups:Array.from(t.tableGroups.values()),aliases:t.aliases,project:Array.from(t.project.values())[0]||{}}}var L=(t=>(t[t.Function=1]="Function",t[t.Constructor=2]="Constructor",t[t.Field=3]="Field",t[t.Variable=4]="Variable",t[t.Class=5]="Class",t[t.Struct=6]="Struct",t[t.Interface=7]="Interface",t[t.Module=8]="Module",t[t.Property=9]="Property",t[t.Event=10]="Event",t[t.Operator=11]="Operator",t[t.Unit=12]="Unit",t[t.Value=13]="Value",t[t.Constant=14]="Constant",t[t.Enum=15]="Enum",t[t.EnumMember=16]="EnumMember",t[t.Keyword=17]="Keyword",t[t.Text=18]="Text",t[t.Color=19]="Color",t[t.File=20]="File",t[t.Reference=21]="Reference",t[t.Customcolor=22]="Customcolor",t[t.Folder=23]="Folder",t[t.TypeParameter=24]="TypeParameter",t[t.User=25]="User",t[t.Issue=26]="Issue",t[t.Snippet=27]="Snippet",t))(L||{}),y=(t=>(t[t.None=0]="None",t[t.KeepWhitespace=1]="KeepWhitespace",t[t.InsertAsSnippet=4]="InsertAsSnippet",t))(y||{});function Ae(t){switch(t){case m.Schema:return L.Module;case m.Table:return L.Class;case m.Column:return L.Field;case m.Enum:return L.Enum;case m.EnumField:return L.EnumMember;case m.TableGroup:return L.Struct;case m.TableGroupField:return L.Field;default:return L.Text}}function Re(t,e){if(!t||Ce(t))return!1;for(const n of t.trailingTrivia){if(n.start>e)break;if(n.kind===u.NEWLINE&&n.end<=e)return!1}return!0}function O(){return{suggestions:[]}}function De(t){return{...t,suggestions:t.suggestions.map(e=>({...e,insertText:` ${e.insertText}`}))}}function Fe(t){return{...t,suggestions:t.suggestions.map(e=>({...e,insertText:e.insertText.split("").every(Ue)?e.insertText:`"${e.insertText}"`}))}}function et(t,e){return t.getOffsetAt(e)}class Bt{constructor(e,n=[]){this.compiler=e,this.triggerCharacters=n}provideCompletionItems(e,n){var T,f;const s=et(e,n),i=this.compiler.token.flatStream(),{token:r,index:a}=this.compiler.container.token(s),l=a===void 0?i[0]:i[a+1];if([...(r==null?void 0:r.trailingTrivia)||[],...(r==null?void 0:r.leadingTrivia)||[],...(l==null?void 0:l.leadingTrivia)||[]].find(N=>Wt(N)&&ge(s,N)))return O();if(a===void 0)return Tt();if([u.STRING_LITERAL,u.QUOTED_STRING].includes(r.kind)&&ge(s,r))return O();const p=this.compiler.container.element(s);if(this.compiler.container.scopeKind(s)===R.TOPLEVEL||p instanceof A&&p.type&&p.type.start<=s&&p.type.end>=s)return Tt();const h=[...this.compiler.container.stack(s)].reverse();for(const N of h)if(N instanceof q)switch((T=N.op)==null?void 0:T.value){case">":case"<":case"<>":case"-":return dt(this.compiler,s,N)}else if(N instanceof H)switch((f=N.op)==null?void 0:f.value){case">":case"<":case"<>":case"-":return dt(this.compiler,s,N);case".":return Vt(this.compiler,s,N)}else{if(N instanceof se)return Et(this.compiler,s,N);if(N instanceof P)return Et(this.compiler,s,N);if(N instanceof Z)return Kn(this.compiler,s);if(N instanceof w)return mt(this.compiler,s,N);if(N instanceof A&&(N.bodyColon&&s>=N.bodyColon.end||N.body&&ge(s,N.body)))return mt(this.compiler,s,void 0)}return O()}}function dt(t,e,n){const s=t.container.scopeKind(e);if([R.REF,R.TABLE].includes(s)){const i=Be(t,e,t.container.element(e),[m.Table,m.Schema,m.Column]);return Re(n.op,e)?De(i):i}return O()}function Be(t,e,n,s){var a;if(n===void 0)return O();let i=n;const r={suggestions:[]};for(;i;){if((a=i==null?void 0:i.symbol)!=null&&a.symbolTable){const{symbol:l}=i;r.suggestions.push(...t.symbol.members(l).filter(({kind:p})=>s.includes(p)).map(({name:p,kind:h})=>({label:p,insertText:p,insertTextRules:y.KeepWhitespace,kind:Ae(h),sortText:Ae(h).toString().padStart(2,"0"),range:void 0})))}i=i instanceof A?i.parent:void 0}return Fe(r)}function Kn(t,e){var s;switch(t.container.scopeKind(e)){case R.INDEXES:return Ct(t,e);case R.REF:{const i=[...t.container.stack(e)];for(;i.length>0;){const r=i.pop();if(r instanceof H&&((s=r.op)==null?void 0:s.value)===".")return Vt(t,e,r)}}return Gt(t,e)}return O()}function Et(t,e,n){const{token:s}=t.container.token(e);if([u.COMMA,u.LBRACKET].includes(s==null?void 0:s.kind)){const i=Nt(t,e);return(s==null?void 0:s.kind)===u.COMMA&&Re(s,e)?De(i):i}if(n.name&&n.name.start<=e&&n.name.end>=e)return Nt(t,e);if(n.name instanceof $){const i=es(t,e,me(n.name).unwrap());return(s==null?void 0:s.kind)===u.COLON&&Re(s,e)?De(i):i}return O()}function Nt(t,e){const n=t.container.element(e),s=t.container.scopeKind(e);if(n instanceof G)return O();if(n.body&&!ge(e,n.body))switch(s){case R.TABLE:return{suggestions:[{label:"headercolor",insertText:"headercolor: ",kind:L.Field,insertTextRules:y.KeepWhitespace,range:void 0},{label:"note",insertText:"note: ",kind:L.Field,insertTextRules:y.KeepWhitespace,range:void 0}]};default:return O()}switch(s){case R.TABLE:return{suggestions:[...["primary key","null","not null","increment","pk","unique"].map(i=>({label:i,insertText:i,kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0})),...["ref","default"].map(i=>({label:i,insertText:`${i}: `,kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0})),{label:"note",insertText:"note: ",kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0}]};case R.ENUM:return{suggestions:[{label:"note",insertText:"note: ",kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0}]};case R.INDEXES:return{suggestions:[...["unique","pk"].map(i=>({label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:L.Property,range:void 0})),...["note","name","type"].map(i=>({label:i,insertText:`${i}: `,kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0}))]};case R.REF:return{suggestions:["update","delete"].map(i=>({label:i,insertText:`${i}: `,kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0}))}}return O()}function es(t,e,n){switch(n==null?void 0:n.toLowerCase()){case"update":case"delete":return{suggestions:["cascade","set default","set null","restrict"].map(s=>({label:s,insertText:s,kind:L.Value,insertTextRules:y.KeepWhitespace,range:void 0}))};case"type":return{suggestions:["btree","hash"].map(s=>({label:s,insertText:`${s}`,kind:L.Value,insertTextRules:y.KeepWhitespace,range:void 0}))}}return O()}function Vt(t,e,n){const s=he(n).unwrap_or([]);if(s.pop(),s.some(r=>!F(r)))return O();const i=s.map(r=>X(r).unwrap());return Fe({suggestions:t.symbol.ofName({nameStack:i,owner:t.container.element(e)}).flatMap(({symbol:r})=>t.symbol.members(r)).map(({kind:r,name:a})=>({label:a,insertText:a,kind:Ae(r),range:void 0}))})}function mt(t,e,n){var i;switch(t.container.scopeKind(e)){case R.TABLE:return ns(t,e,n);case R.PROJECT:return ss(t,e,n);case R.INDEXES:return rs(t,e);case R.ENUM:return ts(t,e,n);case R.REF:{const r=Gt(t,e);return((i=t.container.token(e).token)==null?void 0:i.kind)===u.COLON&&Re(t.container.token(e).token,e)?De(r):r}case R.TABLEGROUP:return is(t);default:return O()}}function Tt(){return{suggestions:["Table","TableGroup","Enum","Project","Ref"].map(t=>({label:t,insertText:t,insertTextRules:y.KeepWhitespace,kind:L.Keyword,range:void 0}))}}function ts(t,e,n){return n!=null&&n.callee&&tt(e,n)===1?Be(t,e,t.container.element(e),[m.Schema,m.Table,m.Column]):O()}function ns(t,e,n){if(!(n!=null&&n.callee))return{suggestions:["Note","indexes"].map(i=>({label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:L.Keyword,range:void 0}))};const s=tt(e,n);return s===0?{suggestions:["Note","indexes"].map(i=>({label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:L.Keyword,range:void 0}))}:s===1?as(t,e):O()}function ss(t,e,n){return n!=null&&n.callee?tt(e,n)===0?{suggestions:["Table","TableGroup","Enum","Note","Ref"].map(i=>({label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:L.Keyword,range:void 0}))}:O():{suggestions:["Table","TableGroup","Enum","Note","Ref"].map(i=>({label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:L.Keyword,range:void 0}))}}function Gt(t,e){return Be(t,e,t.container.element(e),[m.Schema,m.Table,m.Column])}function is(t){return Fe({suggestions:[...t.parse.publicSymbolTable().entries()].flatMap(([e])=>{const n=ie(e).unwrap_or(void 0);if(n===void 0)return[];const{kind:s,name:i}=n;return s!==m.Table&&s!==m.Schema?[]:{label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:Ae(s),range:void 0}})})}function rs(t,e){return Ct(t,e)}function as(t,e){return{suggestions:[...["integer","int","tinyint","smallint","mediumint","bigint","bit","bool","binary","varbinary","logical","char","nchar","varchar","varchar2","nvarchar","nvarchar2","binary_float","binary_double","float","double","decimal","dec","real","money","smallmoney","enum","tinyblob","tinytext","blob","text","mediumblob","mediumtext","longblob","longtext","ntext","set","inet6","uuid","image","date","time","datetime","datetime2","timestamp","year","smalldatetime","datetimeoffset","XML","sql_variant","uniqueidentifier","CURSOR","BFILE","CLOB","NCLOB","RAW"].map(n=>({label:n,insertText:n,insertTextRules:y.KeepWhitespace,kind:L.TypeParameter,sortText:L.TypeParameter.toString().padStart(2,"0"),range:void 0})),...Be(t,e,t.container.element(e),[m.Enum,m.Schema]).suggestions]}}function Ct(t,e){const n=t.container.element(e),s=n==null?void 0:n.parent;if(!((s==null?void 0:s.symbol)instanceof At))return O();const{symbolTable:i}=s.symbol;return Fe({suggestions:[...i.entries()].flatMap(([r])=>{const a=ie(r).unwrap_or(void 0);if(a===void 0)return[];const{name:l}=a;return{label:l,insertText:l,insertTextRules:y.KeepWhitespace,kind:Ae(m.Column),range:void 0}})})}function tt(t,e){if(!e.callee)return-1;const n=[e.callee,...e.args],s=n.findIndex(i=>t<=i.end);return s===-1?n.length:s}class Xt{constructor(e){this.compiler=e}provideDefinition(e,n){var a;const{uri:s}=e,i=et(e,n),r=[...this.compiler.container.stack(i)];for(;r.length!==0;){const l=r.pop();if((a=l==null?void 0:l.referee)!=null&&a.declaration&&[de.PRIMARY_EXPRESSION,de.VARIABLE].includes(l==null?void 0:l.kind)){const{startPos:p,endPos:h}=l.referee.declaration;return[{range:{startColumn:p.column+1,startLineNumber:p.line+1,endColumn:h.column+1,endLineNumber:h.line+1},uri:s}]}}return[]}}class $t{constructor(e){this.compiler=e}provideReferences(e,n){const{uri:s}=e,i=et(e,n),r=[...this.compiler.container.stack(i)];for(;r.length!==0;){const a=r.pop();if(a&&[de.ELEMENT_DECLARATION,de.FUNCTION_APPLICATION,de.PRIMARY_EXPRESSION].includes(a==null?void 0:a.kind)){const{symbol:l}=a;if(l!=null&&l.references.length)return l.references.map(({startPos:p,endPos:h})=>({range:{startColumn:p.column+1,startLineNumber:p.line+1,endColumn:h.column+1,endLineNumber:h.line+1},uri:s}))}}return[]}}const os=Object.freeze(Object.defineProperty({__proto__:null,CompletionItemInsertTextRule:y,CompletionItemKind:L,DBMLCompletionItemProvider:Bt,DBMLDefinitionProvider:Xt,DBMLReferencesProvider:$t},Symbol.toStringTag,{value:"Module"}));var R=(t=>(t[t.TABLE=0]="TABLE",t[t.ENUM=1]="ENUM",t[t.TABLEGROUP=2]="TABLEGROUP",t[t.INDEXES=3]="INDEXES",t[t.NOTE=4]="NOTE",t[t.REF=5]="REF",t[t.PROJECT=6]="PROJECT",t[t.CUSTOM=7]="CUSTOM",t[t.TOPLEVEL=8]="TOPLEVEL",t))(R||{});class cs{constructor(){this.source="",this.cache=new Array(16).fill(null),this.nodeIdGenerator=new Yt,this.symbolIdGenerator=new Zt,this.token={invalidStream:this.createQuery(6,()=>this.parse.tokens().filter(vt)),flatStream:this.createQuery(7,()=>this.parse.tokens().flatMap(e=>[...e.leadingInvalid,e,...e.trailingInvalid]))},this.parse={source:()=>this.source,_:this.createQuery(0,()=>{const e=new ln(this.source).lex().chain(n=>new fn(n,this.nodeIdGenerator).parse()).chain(({ast:n,tokens:s})=>new Yn(n,this.symbolIdGenerator).analyze().map(()=>({ast:n,tokens:s})));return e.getErrors().length>0?e:e.chain(({ast:n,tokens:s})=>new Jn(n).interpret().map(r=>({ast:n,tokens:s,rawDb:r})))}),ast:this.createQuery(1,()=>this.parse._().getValue().ast),errors:this.createQuery(2,()=>this.parse._().getErrors()),tokens:this.createQuery(4,()=>this.parse._().getValue().tokens),rawDb:this.createQuery(3,()=>this.parse._().getValue().rawDb),publicSymbolTable:this.createQuery(5,()=>this.parse._().getValue().ast.symbol.symbolTable)},this.container={stack:this.createQuery(10,e=>{const n=this.parse.tokens();let{index:s}=this.container.token(e);const{token:i}=this.container.token(e);if(s===void 0)return[this.parse.ast()];for(;n[s].isInvalid&&s>=0;)s-=1;if(s===-1)return[this.parse.ast()];const r=n[s].start;let a=this.parse.ast();const l=[a];for(;;){const h=cn(a).find(T=>ge(r,T));if(h===void 0||h instanceof M)break;l.push(h),a=h}if((i==null?void 0:i.kind)===u.COLON)return l;for(;l.length>0;){let p=!1;const h=I.last(l);if(h instanceof w){const T=this.parse.source();for(let f=h.end;f<e;f+=1)T[f]===`
12
+ `&&(l.pop(),p=!0)}else h instanceof q||h instanceof H?this.container.token(e).token!==h.op&&(l.pop(),p=!0):h instanceof P?h.listCloseBracket&&h.end<=e&&(l.pop(),p=!0):h instanceof Z?h.tupleCloseParen&&h.end<=e&&(l.pop(),p=!0):h instanceof ne?h.blockCloseBrace&&h.end<=e&&(l.pop(),p=!0):h instanceof $||h.end<e&&(l.pop(),p=!0);if(p){const T=I.last(l);T instanceof A&&T.end<=e&&l.pop()}if(!p)break}return l}),token:this.createQuery(11,e=>{const n=this.token.flatStream().findIndex(s=>s.start>=e);return n===void 0?{token:void 0,index:void 0}:n<=0?{token:void 0,index:void 0}:{token:this.token.flatStream()[n-1],index:n-1}}),element:this.createQuery(12,e=>{const n=this.container.stack(e);for(let s=n.length-1;s>=0;s-=1)if(n[s]instanceof A)return n[s];return this.parse.ast()}),scope:this.createQuery(14,e=>{var n,s;return(s=(n=this.container.element(e))==null?void 0:n.symbol)==null?void 0:s.symbolTable}),scopeKind:this.createQuery(15,e=>{var s;if(this.container.element(e)instanceof G)return 8;switch((s=this.container.element(e).type)==null?void 0:s.value.toLowerCase()){case"table":return 0;case"enum":return 1;case"ref":return 5;case"tablegroup":return 2;case"indexes":return 3;case"note":return 4;case"project":return 6;default:return 7}})},this.symbol={ofName:this.createQuery(8,({nameStack:e,owner:n=this.parse.ast()})=>{var i;if(e.length===0)return[];const s=[];for(let r=n;r;r=r instanceof A?r.parent:void 0){if(!((i=r.symbol)!=null&&i.symbolTable))continue;const{symbolTable:a}=r.symbol;let l=[a],p=[];for(const h of e)p=l.flatMap(T=>Ht(h).flatMap(f=>{const N=T.get(f),g=ie(f).unwrap_or(void 0);return!N||!g?[]:{...g,symbol:N}})),l=p.flatMap(T=>T.symbol.symbolTable?T.symbol.symbolTable:[]);s.push(...p)}return s},({nameStack:e,owner:n})=>`${e.join(".")}@${n.id}`),members:this.createQuery(9,e=>e.symbolTable?[...e.symbolTable.entries()].map(([n,s])=>({...ie(n).unwrap(),symbol:s})):[])}}createQuery(e,n,s){return i=>{const r=this.cache[e],a=i&&s?s(i):i;if(r!==null){if(!(r instanceof Map))return r;if(r.has(a))return r.get(a)}const l=n(i);return i!==void 0?r instanceof Map?r.set(a,l):(this.cache[e]=new Map,this.cache[e].set(a,l)):this.cache[e]=l,l}}setSource(e){this.source=e,this.cache=new Array(16).fill(null),this.nodeIdGenerator.reset(),this.symbolIdGenerator.reset()}initMonacoServices(){return{definitionProvider:new Xt(this),referenceProvider:new $t(this),autocompletionProvider:new Bt(this)}}}exports.Compiler=cs;exports.serialize=zt;exports.services=os;
@@ -36,12 +36,12 @@ function rt(t) {
36
36
  function at(t) {
37
37
  return t !== void 0 && t.kind === "<op>";
38
38
  }
39
- class B {
39
+ class M {
40
40
  constructor(e, n, s, i, r) {
41
41
  this.kind = e, this.startPos = n, this.endPos = s, this.value = i, this.leadingTrivia = [], this.trailingTrivia = [], this.leadingInvalid = [], this.trailingInvalid = [], this.isInvalid = r, this.start = n.offset, this.end = s.offset;
42
42
  }
43
43
  static create(e, n, s, i, r) {
44
- return new B(e, n, s, i, r);
44
+ return new M(e, n, s, i, r);
45
45
  }
46
46
  }
47
47
  function bt(t) {
@@ -81,13 +81,13 @@ class k {
81
81
  constructor(e, n, s) {
82
82
  this.id = e, this.kind = n;
83
83
  const i = s.find((a) => a !== void 0 && !Number.isNaN(a.start));
84
- i ? (this.startPos = i.startPos, this.fullStart = i instanceof B ? Lt(i) : i.fullStart) : (this.startPos = {
84
+ i ? (this.startPos = i.startPos, this.fullStart = i instanceof M ? Lt(i) : i.fullStart) : (this.startPos = {
85
85
  offset: NaN,
86
86
  column: NaN,
87
87
  line: NaN
88
88
  }, this.fullStart = NaN);
89
89
  const r = [...s].reverse().find((a) => a !== void 0 && !Number.isNaN(a.end));
90
- r ? (this.endPos = r.endPos, this.fullEnd = r instanceof B ? It(r) : r.fullEnd) : (this.endPos = {
90
+ r ? (this.endPos = r.endPos, this.fullEnd = r instanceof M ? It(r) : r.fullEnd) : (this.endPos = {
91
91
  offset: NaN,
92
92
  column: NaN,
93
93
  line: NaN
@@ -245,11 +245,11 @@ class D extends k {
245
245
  }
246
246
  class ke extends k {
247
247
  constructor({ pre: e }, n) {
248
- const s = B.create(u.SPACE, e.endPos, e.endPos, " ", !1);
248
+ const s = M.create(u.SPACE, e.endPos, e.endPos, " ", !1);
249
249
  super(n, "<dummy>", [s]);
250
250
  }
251
251
  }
252
- class ce extends k {
252
+ class le extends k {
253
253
  constructor({ expression: e, indexer: n }, s) {
254
254
  super(s, "<array>", [e, n]), this.array = e, this.indexer = n;
255
255
  }
@@ -418,7 +418,7 @@ function Ht(t) {
418
418
  function pe(t) {
419
419
  return Ue(t) || Oe(t);
420
420
  }
421
- function lt(t, e) {
421
+ function ct(t, e) {
422
422
  const n = [], s = Math.min(t.length, e.length);
423
423
  for (let i = 0; i < s; i += 1)
424
424
  n.push(t[i], e[i]);
@@ -473,13 +473,13 @@ class nn {
473
473
  this.references = [], this.id = n, this.declaration = e;
474
474
  }
475
475
  }
476
- var o = /* @__PURE__ */ ((t) => (t[t.UNKNOWN_SYMBOL = 1e3] = "UNKNOWN_SYMBOL", t[t.UNEXPECTED_SYMBOL = 1001] = "UNEXPECTED_SYMBOL", t[t.UNEXPECTED_EOF = 1002] = "UNEXPECTED_EOF", t[t.UNEXPECTED_NEWLINE = 1003] = "UNEXPECTED_NEWLINE", t[t.UNKNOWN_TOKEN = 1004] = "UNKNOWN_TOKEN", t[t.UNEXPECTED_TOKEN = 1005] = "UNEXPECTED_TOKEN", t[t.UNEXPECTED_ELEMENT_DECLARATION = 1006] = "UNEXPECTED_ELEMENT_DECLARATION", t[t.MISSING_SPACES = 1007] = "MISSING_SPACES", t[t.UNKNOWN_PREFIX_OP = 1008] = "UNKNOWN_PREFIX_OP", t[t.INVALID_OPERAND = 1009] = "INVALID_OPERAND", t[t.EMPTY_ATTRIBUTE_NAME = 1010] = "EMPTY_ATTRIBUTE_NAME", t[t.INVALID_NAME = 3e3] = "INVALID_NAME", t[t.UNEXPECTED_NAME = 3001] = "UNEXPECTED_NAME", t[t.NAME_NOT_FOUND = 3002] = "NAME_NOT_FOUND", t[t.DUPLICATE_NAME = 3003] = "DUPLICATE_NAME", t[t.INVALID_ALIAS = 3004] = "INVALID_ALIAS", t[t.UNEXPECTED_ALIAS = 3005] = "UNEXPECTED_ALIAS", t[t.UNEXPECTED_SETTINGS = 3006] = "UNEXPECTED_SETTINGS", t[t.INVALID_SETTINGS = 3007] = "INVALID_SETTINGS", t[t.UNEXPECTED_SIMPLE_BODY = 3008] = "UNEXPECTED_SIMPLE_BODY", t[t.UNEXPECTED_COMPLEX_BODY = 3009] = "UNEXPECTED_COMPLEX_BODY", t[t.INVALID_TABLE_CONTEXT = 3010] = "INVALID_TABLE_CONTEXT", t[t.INVALID_TABLE_SETTING = 3011] = "INVALID_TABLE_SETTING", t[t.DUPLICATE_TABLE_SETTING = 3012] = "DUPLICATE_TABLE_SETTING", t[t.INVALID_TABLEGROUP_CONTEXT = 3013] = "INVALID_TABLEGROUP_CONTEXT", t[t.INVALID_TABLEGROUP_ELEMENT_NAME = 3014] = "INVALID_TABLEGROUP_ELEMENT_NAME", t[t.DUPLICATE_TABLEGROUP_ELEMENT_NAME = 3015] = "DUPLICATE_TABLEGROUP_ELEMENT_NAME", t[t.DUPLICATE_TABLEGROUP_FIELD_NAME = 3016] = "DUPLICATE_TABLEGROUP_FIELD_NAME", t[t.INVALID_TABLEGROUP_FIELD = 3017] = "INVALID_TABLEGROUP_FIELD", t[t.EMPTY_TABLE = 3018] = "EMPTY_TABLE", t[t.INVALID_COLUMN = 3019] = "INVALID_COLUMN", t[t.INVALID_COLUMN_NAME = 3020] = "INVALID_COLUMN_NAME", t[t.UNKNOWN_COLUMN_SETTING = 3021] = "UNKNOWN_COLUMN_SETTING", t[t.INVALID_COLUMN_TYPE = 3022] = "INVALID_COLUMN_TYPE", t[t.DUPLICATE_COLUMN_NAME = 3023] = "DUPLICATE_COLUMN_NAME", t[t.DUPLICATE_COLUMN_SETTING = 3024] = "DUPLICATE_COLUMN_SETTING", t[t.INVALID_COLUMN_SETTING_VALUE = 3025] = "INVALID_COLUMN_SETTING_VALUE", t[t.INVALID_ENUM_CONTEXT = 3026] = "INVALID_ENUM_CONTEXT", t[t.INVALID_ENUM_ELEMENT_NAME = 3027] = "INVALID_ENUM_ELEMENT_NAME", t[t.INVALID_ENUM_ELEMENT = 3028] = "INVALID_ENUM_ELEMENT", t[t.DUPLICATE_ENUM_ELEMENT_NAME = 3029] = "DUPLICATE_ENUM_ELEMENT_NAME", t[t.UNKNOWN_ENUM_ELEMENT_SETTING = 3030] = "UNKNOWN_ENUM_ELEMENT_SETTING", t[t.DUPLICATE_ENUM_ELEMENT_SETTING = 3031] = "DUPLICATE_ENUM_ELEMENT_SETTING", t[t.INVALID_ENUM_ELEMENT_SETTING = 3032] = "INVALID_ENUM_ELEMENT_SETTING", t[t.EMPTY_ENUM = 3033] = "EMPTY_ENUM", t[t.INVALID_REF_CONTEXT = 3034] = "INVALID_REF_CONTEXT", t[t.UNKNOWN_REF_SETTING = 3035] = "UNKNOWN_REF_SETTING", t[t.DUPLICATE_REF_SETTING = 3036] = "DUPLICATE_REF_SETTING", t[t.INVALID_REF_SETTING_VALUE = 3037] = "INVALID_REF_SETTING_VALUE", t[t.INVALID_REF_RELATIONSHIP = 3038] = "INVALID_REF_RELATIONSHIP", t[t.INVALID_REF_FIELD = 3039] = "INVALID_REF_FIELD", t[t.EMPTY_REF = 3040] = "EMPTY_REF", t[t.REF_REDEFINED = 3041] = "REF_REDEFINED", t[t.INVALID_NOTE_CONTEXT = 3042] = "INVALID_NOTE_CONTEXT", t[t.INVALID_NOTE = 3043] = "INVALID_NOTE", t[t.NOTE_REDEFINED = 3044] = "NOTE_REDEFINED", t[t.NOTE_CONTENT_REDEFINED = 3045] = "NOTE_CONTENT_REDEFINED", t[t.EMPTY_NOTE = 3046] = "EMPTY_NOTE", t[t.INVALID_INDEXES_CONTEXT = 3047] = "INVALID_INDEXES_CONTEXT", t[t.INVALID_INDEXES_FIELD = 3048] = "INVALID_INDEXES_FIELD", t[t.INVALID_INDEX = 3049] = "INVALID_INDEX", t[t.UNKNOWN_INDEX_SETTING = 3050] = "UNKNOWN_INDEX_SETTING", t[t.DUPLICATE_INDEX_SETTING = 3051] = "DUPLICATE_INDEX_SETTING", t[t.UNEXPECTED_INDEX_SETTING_VALUE = 3052] = "UNEXPECTED_INDEX_SETTING_VALUE", t[t.INVALID_INDEX_SETTING_VALUE = 3053] = "INVALID_INDEX_SETTING_VALUE", t[t.INVALID_PROJECT_CONTEXT = 3054] = "INVALID_PROJECT_CONTEXT", t[t.PROJECT_REDEFINED = 3055] = "PROJECT_REDEFINED", t[t.INVALID_PROJECT_FIELD = 3056] = "INVALID_PROJECT_FIELD", t[t.INVALID_CUSTOM_CONTEXT = 3057] = "INVALID_CUSTOM_CONTEXT", t[t.INVALID_CUSTOM_ELEMENT_VALUE = 3058] = "INVALID_CUSTOM_ELEMENT_VALUE", t[t.INVALID_ELEMENT_IN_SIMPLE_BODY = 3059] = "INVALID_ELEMENT_IN_SIMPLE_BODY", t[t.BINDING_ERROR = 4e3] = "BINDING_ERROR", t[t.UNSUPPORTED = 5e3] = "UNSUPPORTED", t[t.CIRCULAR_REF = 5001] = "CIRCULAR_REF", t[t.SAME_ENDPOINT = 5002] = "SAME_ENDPOINT", t[t.UNEQUAL_FIELDS_BINARY_REF = 5003] = "UNEQUAL_FIELDS_BINARY_REF", t[t.CONFLICTING_SETTING = 5004] = "CONFLICTING_SETTING", t[t.TABLE_REAPPEAR_IN_TABLEGROUP = 5005] = "TABLE_REAPPEAR_IN_TABLEGROUP", t))(o || {});
476
+ var o = /* @__PURE__ */ ((t) => (t[t.UNKNOWN_SYMBOL = 1e3] = "UNKNOWN_SYMBOL", t[t.UNEXPECTED_SYMBOL = 1001] = "UNEXPECTED_SYMBOL", t[t.UNEXPECTED_EOF = 1002] = "UNEXPECTED_EOF", t[t.UNEXPECTED_NEWLINE = 1003] = "UNEXPECTED_NEWLINE", t[t.UNKNOWN_TOKEN = 1004] = "UNKNOWN_TOKEN", t[t.UNEXPECTED_TOKEN = 1005] = "UNEXPECTED_TOKEN", t[t.UNEXPECTED_ELEMENT_DECLARATION = 1006] = "UNEXPECTED_ELEMENT_DECLARATION", t[t.MISSING_SPACES = 1007] = "MISSING_SPACES", t[t.UNKNOWN_PREFIX_OP = 1008] = "UNKNOWN_PREFIX_OP", t[t.INVALID_OPERAND = 1009] = "INVALID_OPERAND", t[t.EMPTY_ATTRIBUTE_NAME = 1010] = "EMPTY_ATTRIBUTE_NAME", t[t.INVALID_ESCAPE_SEQUENCE = 1011] = "INVALID_ESCAPE_SEQUENCE", t[t.INVALID_NAME = 3e3] = "INVALID_NAME", t[t.UNEXPECTED_NAME = 3001] = "UNEXPECTED_NAME", t[t.NAME_NOT_FOUND = 3002] = "NAME_NOT_FOUND", t[t.DUPLICATE_NAME = 3003] = "DUPLICATE_NAME", t[t.INVALID_ALIAS = 3004] = "INVALID_ALIAS", t[t.UNEXPECTED_ALIAS = 3005] = "UNEXPECTED_ALIAS", t[t.UNEXPECTED_SETTINGS = 3006] = "UNEXPECTED_SETTINGS", t[t.INVALID_SETTINGS = 3007] = "INVALID_SETTINGS", t[t.UNEXPECTED_SIMPLE_BODY = 3008] = "UNEXPECTED_SIMPLE_BODY", t[t.UNEXPECTED_COMPLEX_BODY = 3009] = "UNEXPECTED_COMPLEX_BODY", t[t.INVALID_TABLE_CONTEXT = 3010] = "INVALID_TABLE_CONTEXT", t[t.INVALID_TABLE_SETTING = 3011] = "INVALID_TABLE_SETTING", t[t.DUPLICATE_TABLE_SETTING = 3012] = "DUPLICATE_TABLE_SETTING", t[t.INVALID_TABLEGROUP_CONTEXT = 3013] = "INVALID_TABLEGROUP_CONTEXT", t[t.INVALID_TABLEGROUP_ELEMENT_NAME = 3014] = "INVALID_TABLEGROUP_ELEMENT_NAME", t[t.DUPLICATE_TABLEGROUP_ELEMENT_NAME = 3015] = "DUPLICATE_TABLEGROUP_ELEMENT_NAME", t[t.DUPLICATE_TABLEGROUP_FIELD_NAME = 3016] = "DUPLICATE_TABLEGROUP_FIELD_NAME", t[t.INVALID_TABLEGROUP_FIELD = 3017] = "INVALID_TABLEGROUP_FIELD", t[t.EMPTY_TABLE = 3018] = "EMPTY_TABLE", t[t.INVALID_COLUMN = 3019] = "INVALID_COLUMN", t[t.INVALID_COLUMN_NAME = 3020] = "INVALID_COLUMN_NAME", t[t.UNKNOWN_COLUMN_SETTING = 3021] = "UNKNOWN_COLUMN_SETTING", t[t.INVALID_COLUMN_TYPE = 3022] = "INVALID_COLUMN_TYPE", t[t.DUPLICATE_COLUMN_NAME = 3023] = "DUPLICATE_COLUMN_NAME", t[t.DUPLICATE_COLUMN_SETTING = 3024] = "DUPLICATE_COLUMN_SETTING", t[t.INVALID_COLUMN_SETTING_VALUE = 3025] = "INVALID_COLUMN_SETTING_VALUE", t[t.INVALID_ENUM_CONTEXT = 3026] = "INVALID_ENUM_CONTEXT", t[t.INVALID_ENUM_ELEMENT_NAME = 3027] = "INVALID_ENUM_ELEMENT_NAME", t[t.INVALID_ENUM_ELEMENT = 3028] = "INVALID_ENUM_ELEMENT", t[t.DUPLICATE_ENUM_ELEMENT_NAME = 3029] = "DUPLICATE_ENUM_ELEMENT_NAME", t[t.UNKNOWN_ENUM_ELEMENT_SETTING = 3030] = "UNKNOWN_ENUM_ELEMENT_SETTING", t[t.DUPLICATE_ENUM_ELEMENT_SETTING = 3031] = "DUPLICATE_ENUM_ELEMENT_SETTING", t[t.INVALID_ENUM_ELEMENT_SETTING = 3032] = "INVALID_ENUM_ELEMENT_SETTING", t[t.EMPTY_ENUM = 3033] = "EMPTY_ENUM", t[t.INVALID_REF_CONTEXT = 3034] = "INVALID_REF_CONTEXT", t[t.UNKNOWN_REF_SETTING = 3035] = "UNKNOWN_REF_SETTING", t[t.DUPLICATE_REF_SETTING = 3036] = "DUPLICATE_REF_SETTING", t[t.INVALID_REF_SETTING_VALUE = 3037] = "INVALID_REF_SETTING_VALUE", t[t.INVALID_REF_RELATIONSHIP = 3038] = "INVALID_REF_RELATIONSHIP", t[t.INVALID_REF_FIELD = 3039] = "INVALID_REF_FIELD", t[t.EMPTY_REF = 3040] = "EMPTY_REF", t[t.REF_REDEFINED = 3041] = "REF_REDEFINED", t[t.INVALID_NOTE_CONTEXT = 3042] = "INVALID_NOTE_CONTEXT", t[t.INVALID_NOTE = 3043] = "INVALID_NOTE", t[t.NOTE_REDEFINED = 3044] = "NOTE_REDEFINED", t[t.NOTE_CONTENT_REDEFINED = 3045] = "NOTE_CONTENT_REDEFINED", t[t.EMPTY_NOTE = 3046] = "EMPTY_NOTE", t[t.INVALID_INDEXES_CONTEXT = 3047] = "INVALID_INDEXES_CONTEXT", t[t.INVALID_INDEXES_FIELD = 3048] = "INVALID_INDEXES_FIELD", t[t.INVALID_INDEX = 3049] = "INVALID_INDEX", t[t.UNKNOWN_INDEX_SETTING = 3050] = "UNKNOWN_INDEX_SETTING", t[t.DUPLICATE_INDEX_SETTING = 3051] = "DUPLICATE_INDEX_SETTING", t[t.UNEXPECTED_INDEX_SETTING_VALUE = 3052] = "UNEXPECTED_INDEX_SETTING_VALUE", t[t.INVALID_INDEX_SETTING_VALUE = 3053] = "INVALID_INDEX_SETTING_VALUE", t[t.INVALID_PROJECT_CONTEXT = 3054] = "INVALID_PROJECT_CONTEXT", t[t.PROJECT_REDEFINED = 3055] = "PROJECT_REDEFINED", t[t.INVALID_PROJECT_FIELD = 3056] = "INVALID_PROJECT_FIELD", t[t.INVALID_CUSTOM_CONTEXT = 3057] = "INVALID_CUSTOM_CONTEXT", t[t.INVALID_CUSTOM_ELEMENT_VALUE = 3058] = "INVALID_CUSTOM_ELEMENT_VALUE", t[t.INVALID_ELEMENT_IN_SIMPLE_BODY = 3059] = "INVALID_ELEMENT_IN_SIMPLE_BODY", t[t.BINDING_ERROR = 4e3] = "BINDING_ERROR", t[t.UNSUPPORTED = 5e3] = "UNSUPPORTED", t[t.CIRCULAR_REF = 5001] = "CIRCULAR_REF", t[t.SAME_ENDPOINT = 5002] = "SAME_ENDPOINT", t[t.UNEQUAL_FIELDS_BINARY_REF = 5003] = "UNEQUAL_FIELDS_BINARY_REF", t[t.CONFLICTING_SETTING = 5004] = "CONFLICTING_SETTING", t[t.TABLE_REAPPEAR_IN_TABLEGROUP = 5005] = "TABLE_REAPPEAR_IN_TABLEGROUP", t))(o || {});
477
477
  class c extends Error {
478
478
  constructor(e, n, s) {
479
479
  super(n), this.code = e, this.diagnostic = n, this.nodeOrToken = s, this.start = s.start, this.end = s.end, this.name = this.constructor.name, Object.setPrototypeOf(this, c.prototype);
480
480
  }
481
481
  }
482
- class F {
482
+ class B {
483
483
  constructor(e, n) {
484
484
  this.value = e, this.errors = n === void 0 ? [] : n;
485
485
  }
@@ -491,10 +491,10 @@ class F {
491
491
  }
492
492
  chain(e) {
493
493
  const n = e(this.value), s = [...this.errors, ...n.errors];
494
- return new F(n.value, s);
494
+ return new B(n.value, s);
495
495
  }
496
496
  map(e) {
497
- return new F(e(this.value), this.errors);
497
+ return new B(e(this.value), this.errors);
498
498
  }
499
499
  }
500
500
  function sn(t, e, n) {
@@ -528,11 +528,11 @@ function sn(t, e, n) {
528
528
  })
529
529
  ) : new v();
530
530
  }
531
- function ct(t) {
531
+ function lt(t) {
532
532
  return t.kind === u.IDENTIFIER && t.value === "as";
533
533
  }
534
534
  function E(t) {
535
- t && (t instanceof B ? rn(t) : an(t));
535
+ t && (t instanceof M ? rn(t) : an(t));
536
536
  }
537
537
  function rn(t) {
538
538
  t.kind !== u.EOF && (t.isInvalid = !0);
@@ -613,20 +613,20 @@ function on(t) {
613
613
  if (t instanceof P)
614
614
  return U(
615
615
  t.listOpenBracket,
616
- ...lt(t.elementList, t.commaList),
616
+ ...ct(t.elementList, t.commaList),
617
617
  t.listCloseBracket
618
618
  );
619
619
  if (t instanceof Z)
620
620
  return U(
621
621
  t.tupleOpenParen,
622
- ...lt(t.elementList, t.commaList),
622
+ ...ct(t.elementList, t.commaList),
623
623
  t.tupleCloseParen
624
624
  );
625
625
  if (t instanceof J)
626
626
  return U(t.callee, t.argumentList);
627
627
  if (t instanceof D)
628
628
  return U(t.expression);
629
- if (t instanceof ce)
629
+ if (t instanceof le)
630
630
  return U(
631
631
  t.array,
632
632
  t.indexer
@@ -634,14 +634,14 @@ function on(t) {
634
634
  throw t instanceof We ? new Error("This case is already handled by TupleExpressionNode") : new Error("Unreachable - no other possible cases");
635
635
  }
636
636
  function Ge(t) {
637
- return M(t) ? new S(t.expression.variable) : new v();
637
+ return F(t) ? new S(t.expression.variable) : new v();
638
638
  }
639
639
  function Y(t) {
640
640
  var e;
641
- return t instanceof D && (t.expression instanceof j && t.expression.variable instanceof B && t.expression.variable.kind === u.QUOTED_STRING || t.expression instanceof Te && ((e = t.expression.literal) == null ? void 0 : e.kind) === u.STRING_LITERAL);
641
+ return t instanceof D && (t.expression instanceof j && t.expression.variable instanceof M && t.expression.variable.kind === u.QUOTED_STRING || t.expression instanceof Te && ((e = t.expression.literal) == null ? void 0 : e.kind) === u.STRING_LITERAL);
642
642
  }
643
- function M(t) {
644
- return t instanceof D && t.expression instanceof j && t.expression.variable instanceof B;
643
+ function F(t) {
644
+ return t instanceof D && t.expression instanceof j && t.expression.variable instanceof M;
645
645
  }
646
646
  function Ne(t) {
647
647
  var e;
@@ -657,7 +657,7 @@ function me(t) {
657
657
  const e = t.identifiers.map((n) => n.value).join(" ");
658
658
  return e === "" ? new v() : new S(e);
659
659
  }
660
- class ln {
660
+ class cn {
661
661
  // list of errors during lexing
662
662
  constructor(e) {
663
663
  this.start = {
@@ -697,7 +697,7 @@ class ln {
697
697
  this.tokens.push(this.createToken(e, n));
698
698
  }
699
699
  createToken(e, n = !1) {
700
- return B.create(
700
+ return M.create(
701
701
  e,
702
702
  this.start,
703
703
  this.current,
@@ -706,7 +706,7 @@ class ln {
706
706
  );
707
707
  }
708
708
  lex() {
709
- return this.scanTokens(), this.tokens.push(B.create(u.EOF, this.start, this.current, "", !1)), this.gatherTrivia(), this.gatherInvalid(), new F(this.tokens, this.errors);
709
+ return this.scanTokens(), this.tokens.push(M.create(u.EOF, this.start, this.current, "", !1)), this.gatherTrivia(), this.gatherInvalid(), new B(this.tokens, this.errors);
710
710
  }
711
711
  scanTokens() {
712
712
  for (; !this.isAtEnd(); ) {
@@ -843,7 +843,7 @@ class ln {
843
843
  );
844
844
  return;
845
845
  }
846
- a && this.match(n), this.tokens.push(B.create(e, this.start, this.current, l, !1));
846
+ a && this.match(n), this.tokens.push(M.create(e, this.start, this.current, l, !1));
847
847
  }
848
848
  singleLineStringLiteral() {
849
849
  this.consumeUntil(u.STRING_LITERAL, "'", {
@@ -934,9 +934,16 @@ class ln {
934
934
  this.addToken(u.COLOR_LITERAL);
935
935
  }
936
936
  escapedString() {
937
+ const e = { column: this.current.column - 1, offset: this.current.offset - 1, line: this.current.line };
937
938
  if (this.isAtEnd())
938
939
  return "\\";
939
940
  switch (this.advance()) {
941
+ case "\r":
942
+ return this.check(`
943
+ `) && this.advance(), "";
944
+ case `
945
+ `:
946
+ return "";
940
947
  case "t":
941
948
  return " ";
942
949
  case "n":
@@ -947,7 +954,7 @@ class ln {
947
954
  case "r":
948
955
  return "\r";
949
956
  case "'":
950
- return "'";
957
+ return this.peek() === "'" && this.peek(1) === "'" ? (this.advance(), this.advance(), "'''") : "'";
951
958
  case '"':
952
959
  return '"';
953
960
  case "0":
@@ -958,22 +965,26 @@ class ln {
958
965
  return "\v";
959
966
  case "f":
960
967
  return "\f";
968
+ case " ":
969
+ return "\\ ";
961
970
  case "u": {
962
- let e = "";
963
- for (let n = 0; n <= 3; n += 1) {
971
+ let n = "";
972
+ for (let s = 0; s <= 3; s += 1) {
964
973
  if (this.isAtEnd() || !pe(this.peek()))
965
- return `\\u${e}`;
966
- e += this.advance();
974
+ return this.errors.push(new c(o.INVALID_ESCAPE_SEQUENCE, `Invalid unicode escape sequence '\\u${n}', only unicode escape sequences of the form '\\uHHHH' where H is a hexadecimal number are allowed`, M.create(u.STRING_LITERAL, e, this.current, `\\u${n}`, !0))), `\\u${n}`;
975
+ n += this.advance();
967
976
  }
968
- return String.fromCharCode(parseInt(e, 16));
977
+ return String.fromCharCode(parseInt(n, 16));
978
+ }
979
+ default: {
980
+ const n = `\\${this.text[this.current.offset - 1]}`;
981
+ return this.errors.push(new c(o.INVALID_ESCAPE_SEQUENCE, `Invalid escape sequence '${n}'`, M.create(u.STRING_LITERAL, e, this.current, n, !0))), n;
969
982
  }
970
- default:
971
- return `\\${this.tokens[this.current.offset - 1]}`;
972
983
  }
973
984
  }
974
985
  }
975
986
  var xe = /* @__PURE__ */ ((t) => (t[t.ListExpression = 0] = "ListExpression", t[t.GroupExpression = 1] = "GroupExpression", t[t.BlockExpression = 2] = "BlockExpression", t))(xe || {});
976
- class cn {
987
+ class ln {
977
988
  constructor() {
978
989
  this.stack = [], this.numberOfNestedLParens = 0, this.numberOfNestedLBrackets = 0, this.numberOfNestedLBraces = 0;
979
990
  }
@@ -1054,13 +1065,13 @@ class d {
1054
1065
  }
1055
1066
  class hn {
1056
1067
  constructor(e, n) {
1057
- this.current = 0, this.errors = [], this.contextStack = new cn(), this.synchronizeProgram = () => {
1068
+ this.current = 0, this.errors = [], this.contextStack = new ln(), this.synchronizeProgram = () => {
1058
1069
  const s = this.peek();
1059
1070
  s.kind !== u.EOF ? E(this.advance()) : (E(this.peek()), this.logError(s, o.UNEXPECTED_EOF, "Unexpected EOF"));
1060
1071
  }, this.synchronizeElementDeclarationName = () => {
1061
1072
  for (; !this.isAtEnd(); ) {
1062
1073
  const s = this.peek();
1063
- if (ct(s) || this.check(u.COLON, u.LBRACE, u.LBRACKET))
1074
+ if (lt(s) || this.check(u.COLON, u.LBRACE, u.LBRACKET))
1064
1075
  break;
1065
1076
  E(s), this.advance();
1066
1077
  }
@@ -1281,7 +1292,7 @@ class hn {
1281
1292
  }
1282
1293
  parse() {
1283
1294
  const e = this.program(), n = this.advance(), s = this.nodeFactory.create(G, { body: e, eof: n });
1284
- return this.gatherInvalid(), new F({ ast: s, tokens: this.tokens }, this.errors);
1295
+ return this.gatherInvalid(), new B({ ast: s, tokens: this.tokens }, this.errors);
1285
1296
  }
1286
1297
  /* Parsing and synchronizing ProgramNode */
1287
1298
  program() {
@@ -1315,7 +1326,7 @@ class hn {
1315
1326
  throw new d(s.token, n(), s.handlerContext);
1316
1327
  this.synchronizeElementDeclarationName();
1317
1328
  }
1318
- if (ct(this.peek()))
1329
+ if (lt(this.peek()))
1319
1330
  if (e.as = this.advance(), this.check(u.COLON, u.LBRACE, u.LBRACKET))
1320
1331
  this.logError(this.peek(), o.UNEXPECTED_TOKEN, "Expect an alias");
1321
1332
  else
@@ -1437,12 +1448,12 @@ class hn {
1437
1448
  if (Ce(this.previous()))
1438
1449
  break;
1439
1450
  try {
1440
- n = this.nodeFactory.create(ce, {
1451
+ n = this.nodeFactory.create(le, {
1441
1452
  expression: n,
1442
1453
  indexer: this.listExpression()
1443
1454
  });
1444
1455
  } catch (i) {
1445
- throw i instanceof d ? (n = this.nodeFactory.create(ce, {
1456
+ throw i instanceof d ? (n = this.nodeFactory.create(le, {
1446
1457
  expression: n,
1447
1458
  indexer: i.partialNode
1448
1459
  }), new d(i.token, n, i.handlerContext)) : i;
@@ -1713,7 +1724,7 @@ function _e(t) {
1713
1724
  return new v();
1714
1725
  const n = [];
1715
1726
  let s;
1716
- if (!M(I.last(e))) {
1727
+ if (!F(I.last(e))) {
1717
1728
  const i = e.pop();
1718
1729
  if (kt(i))
1719
1730
  s = i.elementList.map(
@@ -1734,7 +1745,7 @@ function _e(t) {
1734
1745
  });
1735
1746
  }
1736
1747
  function X(t) {
1737
- return M(t) ? new S(t.expression.variable.value) : new v();
1748
+ return F(t) ? new S(t.expression.variable.value) : new v();
1738
1749
  }
1739
1750
  function Xe(t) {
1740
1751
  if (ht(t))
@@ -1742,7 +1753,7 @@ function Xe(t) {
1742
1753
  if (t instanceof Z && t.elementList.every(ht)) {
1743
1754
  const e = t.elementList.filter(
1744
1755
  (s) => s instanceof te
1745
- ), n = t.elementList.filter(M);
1756
+ ), n = t.elementList.filter(F);
1746
1757
  return new S({ functional: e, nonFunctional: n });
1747
1758
  }
1748
1759
  return new v();
@@ -1868,7 +1879,7 @@ class Ln {
1868
1879
  validateFields(e) {
1869
1880
  return e.length === 0 ? [new c(o.EMPTY_ENUM, "An Enum must have at least one element", this.declarationNode)] : e.flatMap((n) => {
1870
1881
  const s = [];
1871
- n.callee && !M(n.callee) && s.push(new c(o.INVALID_ENUM_ELEMENT_NAME, "An enum field must be an identifier or a quoted identifier", n.callee));
1882
+ n.callee && !F(n.callee) && s.push(new c(o.INVALID_ENUM_ELEMENT_NAME, "An enum field must be an identifier or a quoted identifier", n.callee));
1872
1883
  const i = [...n.args];
1873
1884
  return I.last(i) instanceof P ? (s.push(...this.validateFieldSettings(I.last(i))), i.pop()) : i[0] instanceof P && (s.push(...this.validateFieldSettings(i[0])), i.shift()), i.length > 0 && s.push(...i.map((r) => new c(o.INVALID_ENUM_ELEMENT, "An Enum must have only a field and optionally a setting list", r))), s.push(...this.registerField(n)), s;
1874
1885
  });
@@ -1898,7 +1909,7 @@ class Ln {
1898
1909
  });
1899
1910
  }
1900
1911
  registerField(e) {
1901
- if (e.callee && M(e.callee)) {
1912
+ if (e.callee && F(e.callee)) {
1902
1913
  const n = V(e.callee).unwrap(), s = Qe(n), i = this.symbolFactory.create(Kt, { declaration: e });
1903
1914
  e.symbol = i;
1904
1915
  const r = this.declarationNode.symbol.symbolTable;
@@ -1967,12 +1978,12 @@ class gn {
1967
1978
  case "unique":
1968
1979
  case "pk":
1969
1980
  a.length > 1 && a.forEach((l) => s.push(new c(o.DUPLICATE_INDEX_SETTING, `'${r}' can only appear once`, l))), a.forEach((l) => {
1970
- le(l.value) || s.push(new c(o.INVALID_INDEX_SETTING_VALUE, `'${r}' must not have a value`, l));
1981
+ ce(l.value) || s.push(new c(o.INVALID_INDEX_SETTING_VALUE, `'${r}' must not have a value`, l));
1971
1982
  });
1972
1983
  break;
1973
1984
  case "type":
1974
1985
  a.length > 1 && a.forEach((l) => s.push(new c(o.DUPLICATE_INDEX_SETTING, "'type' can only appear once", l))), a.forEach((l) => {
1975
- M(l.value) || s.push(new c(o.INVALID_INDEX_SETTING_VALUE, `'type' must be "btree" or "hash"`, l));
1986
+ F(l.value) || s.push(new c(o.INVALID_INDEX_SETTING_VALUE, `'type' must be "btree" or "hash"`, l));
1976
1987
  });
1977
1988
  break;
1978
1989
  default:
@@ -2141,7 +2152,7 @@ class vn {
2141
2152
  }
2142
2153
  }
2143
2154
  function wn(t) {
2144
- if (!(M(t) && t.expression.variable.kind !== u.QUOTED_STRING) && !(t instanceof $))
2155
+ if (!(F(t) && t.expression.variable.kind !== u.QUOTED_STRING) && !(t instanceof $))
2145
2156
  return !1;
2146
2157
  let e;
2147
2158
  if (t instanceof $ ? e = me(t).unwrap_or("") : e = t.expression.variable.value, e)
@@ -2168,7 +2179,7 @@ class yn {
2168
2179
  return this.declarationNode.parent instanceof A ? [new c(o.INVALID_TABLE_CONTEXT, "Table must appear top-level", this.declarationNode)] : [];
2169
2180
  }
2170
2181
  validateName(e) {
2171
- return e ? e instanceof ce ? [new c(o.INVALID_NAME, "Invalid array as Table name, maybe you forget to add a space between the name and the setting list?", e)] : Ze(e) ? [] : [new c(o.INVALID_NAME, "A Table name must be of the form <table> or <schema>.<table>", e)] : [new c(o.NAME_NOT_FOUND, "A Table must have a name", this.declarationNode)];
2182
+ return e ? e instanceof le ? [new c(o.INVALID_NAME, "Invalid array as Table name, maybe you forget to add a space between the name and the setting list?", e)] : Ze(e) ? [] : [new c(o.INVALID_NAME, "A Table name must be of the form <table> or <schema>.<table>", e)] : [new c(o.NAME_NOT_FOUND, "A Table must have a name", this.declarationNode)];
2172
2183
  }
2173
2184
  validateAlias(e) {
2174
2185
  return e ? On(e) ? [] : [new c(o.INVALID_ALIAS, "Table aliases can only contains alphanumeric and underscore unless surrounded by double quotes", e)] : [];
@@ -2221,13 +2232,13 @@ class yn {
2221
2232
  if (!n.callee)
2222
2233
  return [];
2223
2234
  const s = [];
2224
- n.args.length === 0 && s.push(new c(o.INVALID_COLUMN, "A column must have a type", n.callee)), M(n.callee) || s.push(new c(o.INVALID_COLUMN_NAME, "A column name must be an identifier or a quoted identifier", n.callee)), n.args[0] && !kn(n.args[0]) && s.push(new c(o.INVALID_COLUMN_TYPE, "Invalid column type", n.args[0]));
2235
+ n.args.length === 0 && s.push(new c(o.INVALID_COLUMN, "A column must have a type", n.callee)), F(n.callee) || s.push(new c(o.INVALID_COLUMN_NAME, "A column name must be an identifier or a quoted identifier", n.callee)), n.args[0] && !kn(n.args[0]) && s.push(new c(o.INVALID_COLUMN_TYPE, "Invalid column type", n.args[0]));
2225
2236
  const i = n.args.slice(1);
2226
2237
  return s.push(...this.validateFieldSetting(i)), s.push(...this.registerField(n)), s;
2227
2238
  });
2228
2239
  }
2229
2240
  registerField(e) {
2230
- if (e.callee && M(e.callee)) {
2241
+ if (e.callee && F(e.callee)) {
2231
2242
  const n = V(e.callee).unwrap(), s = Ye(n), i = this.symbolFactory.create(en, { declaration: e });
2232
2243
  e.symbol = i;
2233
2244
  const r = this.declarationNode.symbol.symbolTable;
@@ -2276,34 +2287,34 @@ class yn {
2276
2287
  break;
2277
2288
  case "primary key":
2278
2289
  h.length > 1 && i.push(...h.map((f) => new c(o.DUPLICATE_COLUMN_SETTING, "primary key can only appear once", f))), h.forEach((f) => {
2279
- le(f.value) || i.push(new c(o.INVALID_COLUMN_SETTING_VALUE, "'primary key' must not have a value", f.value || f.name));
2290
+ ce(f.value) || i.push(new c(o.INVALID_COLUMN_SETTING_VALUE, "'primary key' must not have a value", f.value || f.name));
2280
2291
  });
2281
2292
  break;
2282
2293
  case "pk":
2283
2294
  h.length > 1 && i.push(...h.map((f) => new c(o.DUPLICATE_COLUMN_SETTING, "'pk' can only appear once", f))), h.forEach((f) => {
2284
- f instanceof se && !le(f.value) && i.push(new c(o.INVALID_COLUMN_SETTING_VALUE, "'pk' must not have a value", f.value || f.name));
2295
+ f instanceof se && !ce(f.value) && i.push(new c(o.INVALID_COLUMN_SETTING_VALUE, "'pk' must not have a value", f.value || f.name));
2285
2296
  });
2286
2297
  break;
2287
2298
  case "not null":
2288
2299
  h.length > 1 && i.push(...h.map((f) => new c(o.DUPLICATE_COLUMN_SETTING, "'not null' can only appear once", f)));
2289
2300
  const T = r.null || [];
2290
2301
  h.length >= 1 && T.length >= 1 && i.push(...[...h, ...T].map((f) => new c(o.CONFLICTING_SETTING, "'not null' and 'null' can not be set at the same time", f))), h.forEach((f) => {
2291
- le(f.value) || i.push(new c(o.INVALID_COLUMN_SETTING_VALUE, "'not null' must not have a value", f.value || f.name));
2302
+ ce(f.value) || i.push(new c(o.INVALID_COLUMN_SETTING_VALUE, "'not null' must not have a value", f.value || f.name));
2292
2303
  });
2293
2304
  break;
2294
2305
  case "null":
2295
2306
  h.length > 1 && i.push(...h.map((f) => new c(o.DUPLICATE_COLUMN_SETTING, "'null' can only appear once", f))), h.forEach((f) => {
2296
- le(f.value) || i.push(new c(o.INVALID_COLUMN_SETTING_VALUE, "'null' must not have a value", f.value || f.name));
2307
+ ce(f.value) || i.push(new c(o.INVALID_COLUMN_SETTING_VALUE, "'null' must not have a value", f.value || f.name));
2297
2308
  });
2298
2309
  break;
2299
2310
  case "unique":
2300
2311
  h.length > 1 && i.push(...h.map((f) => new c(o.DUPLICATE_COLUMN_SETTING, "'unique' can only appear once", f))), h.forEach((f) => {
2301
- f instanceof se && !le(f.value) && i.push(new c(o.INVALID_COLUMN_SETTING_VALUE, "'unique' must not have a value", f.value || f.name));
2312
+ f instanceof se && !ce(f.value) && i.push(new c(o.INVALID_COLUMN_SETTING_VALUE, "'unique' must not have a value", f.value || f.name));
2302
2313
  });
2303
2314
  break;
2304
2315
  case "increment":
2305
2316
  h.length > 1 && i.push(...h.map((f) => new c(o.DUPLICATE_COLUMN_SETTING, "'increment' can only appear once", f))), h.forEach((f) => {
2306
- f instanceof se && !le(f.value) && i.push(new c(o.INVALID_COLUMN_SETTING_VALUE, "'increment' must not have a value", f.value || f.name));
2317
+ f instanceof se && !ce(f.value) && i.push(new c(o.INVALID_COLUMN_SETTING_VALUE, "'increment' must not have a value", f.value || f.name));
2307
2318
  });
2308
2319
  break;
2309
2320
  case "default":
@@ -2331,14 +2342,14 @@ class yn {
2331
2342
  }
2332
2343
  }
2333
2344
  function kn(t) {
2334
- if (!(t instanceof J || Je(t) || t instanceof D || t instanceof ce))
2345
+ if (!(t instanceof J || Je(t) || t instanceof D || t instanceof le))
2335
2346
  return !1;
2336
2347
  if (t instanceof J) {
2337
2348
  if (t.callee === void 0 || t.argumentList === void 0 || !t.argumentList.elementList.every((n) => ue(n) || Y(n) || Ne(n)))
2338
2349
  return !1;
2339
2350
  t = t.callee;
2340
2351
  }
2341
- for (; t instanceof ce; ) {
2352
+ for (; t instanceof le; ) {
2342
2353
  if (t.array === void 0 || t.indexer === void 0 || !t.indexer.elementList.every((n) => !n.colon && !n.value && ue(n.name)))
2343
2354
  return !1;
2344
2355
  t = t.array;
@@ -2403,7 +2414,7 @@ class Sn {
2403
2414
  });
2404
2415
  }
2405
2416
  registerField(e) {
2406
- if (e.callee && M(e.callee)) {
2417
+ if (e.callee && F(e.callee)) {
2407
2418
  const n = V(e.callee).unwrap(), s = He(n), i = this.symbolFactory.create(nn, { declaration: e });
2408
2419
  e.symbol = i;
2409
2420
  const r = this.declarationNode.symbol.symbolTable;
@@ -2483,7 +2494,7 @@ function Rn(t) {
2483
2494
  return !1;
2484
2495
  return !0;
2485
2496
  }
2486
- function le(t) {
2497
+ function ce(t) {
2487
2498
  return t === void 0;
2488
2499
  }
2489
2500
  function Dn(t) {
@@ -2502,13 +2513,13 @@ function Pn(t) {
2502
2513
  return e !== void 0 && e.length > 0;
2503
2514
  }
2504
2515
  function kt(t) {
2505
- return t instanceof Z && t.elementList.every(M);
2516
+ return t instanceof Z && t.elementList.every(F);
2506
2517
  }
2507
2518
  function W(t) {
2508
2519
  var s;
2509
2520
  const e = {}, n = [];
2510
2521
  if (!t)
2511
- return new F({});
2522
+ return new B({});
2512
2523
  for (const i of t.elementList) {
2513
2524
  if (!i.name)
2514
2525
  continue;
@@ -2519,7 +2530,7 @@ function W(t) {
2519
2530
  const r = (s = me(i.name).unwrap_or(void 0)) == null ? void 0 : s.toLowerCase();
2520
2531
  r && (e[r] === void 0 ? e[r] = [i] : e[r].push(i));
2521
2532
  }
2522
- return new F(e, n);
2533
+ return new B(e, n);
2523
2534
  }
2524
2535
  class ft {
2525
2536
  constructor(e, n) {
@@ -2540,7 +2551,7 @@ class ft {
2540
2551
  e.push(...r.validate());
2541
2552
  });
2542
2553
  const n = this.ast.body.filter((s) => ve(s).unwrap_or(void 0) === b.Project);
2543
- return n.length > 1 && n.forEach((s) => e.push(new c(o.PROJECT_REDEFINED, "Only one project can exist", s))), new F(this.ast, e);
2554
+ return n.length > 1 && n.forEach((s) => e.push(new c(o.PROJECT_REDEFINED, "Only one project can exist", s))), new B(this.ast, e);
2544
2555
  }
2545
2556
  }
2546
2557
  class ae {
@@ -2603,7 +2614,7 @@ class ae {
2603
2614
  bindFragments(e, n) {
2604
2615
  if (e.length === 0)
2605
2616
  return;
2606
- const s = [...n.topSubnamesSymbolKind], { remainingSubnamesSymbolKind: i } = n, r = e.findIndex((f) => !M(f)), l = r !== -1 && kt(e[r]) ? e[r] : void 0, p = r >= 0 ? s.pop() : void 0, h = e.slice(
2617
+ const s = [...n.topSubnamesSymbolKind], { remainingSubnamesSymbolKind: i } = n, r = e.findIndex((f) => !F(f)), l = r !== -1 && kt(e[r]) ? e[r] : void 0, p = r >= 0 ? s.pop() : void 0, h = e.slice(
2607
2618
  0,
2608
2619
  r === -1 ? void 0 : r
2609
2620
  );
@@ -2839,7 +2850,7 @@ class $n {
2839
2850
  const n = xt(e);
2840
2851
  new n(e, this.errors).bind();
2841
2852
  }
2842
- return new F(this.ast, this.errors);
2853
+ return new B(this.ast, this.errors);
2843
2854
  }
2844
2855
  }
2845
2856
  class Wn {
@@ -2860,7 +2871,7 @@ class jn {
2860
2871
  }
2861
2872
  // For invoking the validator only
2862
2873
  validate() {
2863
- return new ft(this.ast, this.symbolFactory).validate().chain((n) => new F(n, []));
2874
+ return new ft(this.ast, this.symbolFactory).validate().chain((n) => new B(n, []));
2864
2875
  }
2865
2876
  }
2866
2877
  function pt(t, e) {
@@ -2939,8 +2950,8 @@ function Dt(t, e) {
2939
2950
  }
2940
2951
  function Ee(t) {
2941
2952
  const e = t.split(`
2942
- `), n = e.filter((i) => i.trimStart()), s = Math.min(...n.map((i) => i.length - i.trimStart().length));
2943
- return e.map((i) => i.slice(s)).join(`
2953
+ `), n = e.slice(e.findIndex((r) => r.trimStart() !== "")), s = n.filter((r) => r.trimStart()), i = Math.min(...s.map((r) => r.length - r.trimStart().length));
2954
+ return n.map((r) => r.slice(i)).join(`
2944
2955
  `);
2945
2956
  }
2946
2957
  class Pt {
@@ -3150,17 +3161,17 @@ function Yn(t) {
3150
3161
  let e = null;
3151
3162
  t instanceof J && (e = t.argumentList.elementList.map((r) => ue(r) ? r.expression.literal.value : Y(r) ? Q(r).unwrap() : X(r).unwrap()).join(","), t = t.callee);
3152
3163
  let n = "";
3153
- for (; t instanceof ce; )
3164
+ for (; t instanceof le; )
3154
3165
  n = `[${t.indexer.elementList.map((r) => r.name.expression.literal.value).join(",")}]${n}`, t = t.array;
3155
3166
  const { name: s, schemaName: i } = be(t);
3156
- return i.length > 1 ? new F(
3167
+ return i.length > 1 ? new B(
3157
3168
  {
3158
3169
  schemaName: i.length === 0 ? null : i[0],
3159
3170
  type_name: `${s}${n}${e ? `(${e})` : ""}`,
3160
3171
  args: e
3161
3172
  },
3162
3173
  [new c(o.UNSUPPORTED, "Nested schema is not supported", t)]
3163
- ) : new F({
3174
+ ) : new B({
3164
3175
  schemaName: i.length === 0 ? null : i[0],
3165
3176
  type_name: `${s}${n}${e ? `(${e})` : ""}`,
3166
3177
  args: e
@@ -3412,7 +3423,7 @@ class Hn {
3412
3423
  return [];
3413
3424
  }
3414
3425
  });
3415
- return new F(Jn(this.env), e);
3426
+ return new B(Jn(this.env), e);
3416
3427
  }
3417
3428
  }
3418
3429
  function Jn(t) {
@@ -3755,7 +3766,7 @@ function Kn(t, e, n) {
3755
3766
  }
3756
3767
  function Vt(t, e, n) {
3757
3768
  const s = he(n).unwrap_or([]);
3758
- if (s.pop(), s.some((r) => !M(r)))
3769
+ if (s.pop(), s.some((r) => !F(r)))
3759
3770
  return O();
3760
3771
  const i = s.map((r) => X(r).unwrap());
3761
3772
  return Fe({
@@ -4032,7 +4043,7 @@ class $t {
4032
4043
  return [];
4033
4044
  }
4034
4045
  }
4035
- const ls = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
4046
+ const cs = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
4036
4047
  __proto__: null,
4037
4048
  CompletionItemInsertTextRule: y,
4038
4049
  CompletionItemKind: L,
@@ -4041,7 +4052,7 @@ const ls = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
4041
4052
  DBMLReferencesProvider: $t
4042
4053
  }, Symbol.toStringTag, { value: "Module" }));
4043
4054
  var R = /* @__PURE__ */ ((t) => (t[t.TABLE = 0] = "TABLE", t[t.ENUM = 1] = "ENUM", t[t.TABLEGROUP = 2] = "TABLEGROUP", t[t.INDEXES = 3] = "INDEXES", t[t.NOTE = 4] = "NOTE", t[t.REF = 5] = "REF", t[t.PROJECT = 6] = "PROJECT", t[t.CUSTOM = 7] = "CUSTOM", t[t.TOPLEVEL = 8] = "TOPLEVEL", t))(R || {});
4044
- class cs {
4055
+ class ls {
4045
4056
  constructor() {
4046
4057
  this.source = "", this.cache = new Array(
4047
4058
  16
@@ -4061,7 +4072,7 @@ class cs {
4061
4072
  _: this.createQuery(
4062
4073
  0,
4063
4074
  () => {
4064
- const e = new ln(this.source).lex().chain((n) => new hn(n, this.nodeIdGenerator).parse()).chain(({ ast: n, tokens: s }) => new jn(n, this.symbolIdGenerator).analyze().map(() => ({ ast: n, tokens: s })));
4075
+ const e = new cn(this.source).lex().chain((n) => new hn(n, this.nodeIdGenerator).parse()).chain(({ ast: n, tokens: s }) => new jn(n, this.symbolIdGenerator).analyze().map(() => ({ ast: n, tokens: s })));
4065
4076
  return e.getErrors().length > 0 ? e : e.chain(({ ast: n, tokens: s }) => new Hn(n).interpret().map((r) => ({ ast: n, tokens: s, rawDb: r })));
4066
4077
  }
4067
4078
  ),
@@ -4100,7 +4111,7 @@ class cs {
4100
4111
  const l = [a];
4101
4112
  for (; ; ) {
4102
4113
  const h = on(a).find((T) => ge(r, T));
4103
- if (h === void 0 || h instanceof B)
4114
+ if (h === void 0 || h instanceof M)
4104
4115
  break;
4105
4116
  l.push(h), a = h;
4106
4117
  }
@@ -4248,7 +4259,7 @@ class cs {
4248
4259
  }
4249
4260
  }
4250
4261
  export {
4251
- cs as Compiler,
4262
+ ls as Compiler,
4252
4263
  os as serialize,
4253
- ls as services
4264
+ cs as services
4254
4265
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dbml/parse",
3
- "version": "3.4.0",
3
+ "version": "3.4.1-alpha.0",
4
4
  "description": "> TODO: description",
5
5
  "author": "Holistics <dev@holistics.io>",
6
6
  "license": "Apache-2.0",
@@ -45,5 +45,5 @@
45
45
  "peerDependencies": {
46
46
  "lodash": "^4.17.21"
47
47
  },
48
- "gitHead": "d46067f19bf80a245c77576106dac68bec5cbe5a"
48
+ "gitHead": "452294fcc48326294bf66a76daa418668d6ba8a9"
49
49
  }