@dbml/parse 3.13.2 → 3.13.3-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/dbml-parse.js +8 -8
- package/dist/dbml-parse.mjs +782 -828
- package/dist/src/lib/interpreter/utils.d.ts +8 -1
- package/package.json +2 -2
package/dist/dbml-parse.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const A=require("lodash");var h=(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.TILDE="<tilde>",t.SINGLE_LINE_COMMENT="<single-line-comment>",t.MULTILINE_COMMENT="<multiline-comment>",t))(h||{});function tn(t){switch(t.kind){case"<newline>":case"<space>":case"<tab>":case"<single-line-comment>":case"<multiline-comment>":return!0;default:return!1}}function pt(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 dt(t){return t!==void 0&&t.kind==="<op>"}class K{constructor(e,n,s,i,a){this.kind=e,this.startPos=n,this.endPos=s,this.value=i,this.leadingTrivia=[],this.trailingTrivia=[],this.leadingInvalid=[],this.trailingInvalid=[],this.isInvalid=a,this.start=n.offset,this.end=s.offset}static create(e,n,s,i,a){return new K(e,n,s,i,a)}}function kt(t){return t.trailingTrivia.find(({kind:e})=>e===h.NEWLINE)!==void 0}function Et(t,e){return e.leadingTrivia.find(({kind:s})=>s===h.NEWLINE)!==void 0||kt(t)}function Ze(t){return t.trailingTrivia.find(({kind:e})=>[h.SPACE,h.TAB].includes(e))!==void 0}function Pt(t){return t.trailingTrivia.length===0?t.end:Pt(A.last(t.trailingTrivia))}function St(t){return t.leadingTrivia.length===0?t.start:St(t.leadingTrivia[0])}function nn(t){return[h.SINGLE_LINE_COMMENT,h.MULTILINE_COMMENT].includes(t.kind)}class sn{constructor(){this.id=0}reset(){this.id=0}nextId(){return this.id++}}class D{constructor(e,n,s){this.id=e,this.kind=n;const i=s.find(r=>r!==void 0&&!Number.isNaN(r.start));i?(this.startPos=i.startPos,this.fullStart=i instanceof K?St(i):i.fullStart):(this.startPos={offset:NaN,column:NaN,line:NaN},this.fullStart=NaN);const a=[...s].reverse().find(r=>r!==void 0&&!Number.isNaN(r.end));a?(this.endPos=a.endPos,this.fullEnd=a instanceof K?Pt(a):a.fullEnd):(this.endPos={offset:NaN,column:NaN,line:NaN},this.fullEnd=NaN),this.start=this.startPos.offset,this.end=this.endPos.offset}}var Le=(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.PARTIAL_INJECTION="<partial-injection>",t))(Le||{});class Z extends D{constructor({body:e=[],eof:n},s){super(s,"<program>",[...e,n]),this.body=e,this.eof=n}}class y extends D{constructor({type:e,name:n,as:s,alias:i,attributeList:a,bodyColon:r,body:c},p){if(super(p,"<element-declaration>",[e,n,s,i,a,r,c]),c&&r&&!(c instanceof w||c instanceof y))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=a,this.bodyColon=r,this.body=c}}class ne extends D{constructor({identifiers:e=[]},n){super(n,"<identifer-stream>",e||[]),this.identifiers=e}}class se extends D{constructor({name:e,colon:n,value:s},i){super(i,"<attribute>",[e,n,s]),this.name=e,this.value=s,this.colon=n}}class ae extends D{constructor({op:e,expression:n},s){super(s,"<prefix-expression>",[e,n]),this.op=e,this.expression=n}}class ce extends D{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 We extends D{constructor({op:e,expression:n},s){super(s,"<postfix-expression>",[n,e]),this.op=e,this.expression=n}}class ue extends D{constructor({value:e},n){super(n,"<function-expression>",[e]),this.value=e}}class w extends D{constructor({callee:e,args:n=[]},s){super(s,"<function-application>",[e,...n]),this.callee=e,this.args=n}}class oe extends D{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 Ae extends D{constructor({op:e,partial:n},s){super(s,"<partial-injection>",[e,n]),this.partial=n}}class M extends D{constructor({listOpenBracket:e,elementList:n=[],commaList:s=[],listCloseBracket:i},a){super(a,"<list-expression>",[e,...xt(n,s),i]),this.listOpenBracket=e,this.elementList=n,this.commaList=s,this.listCloseBracket=i}}class pe extends D{constructor({tupleOpenParen:e,elementList:n=[],commaList:s=[],tupleCloseParen:i},a){super(a,"<tuple-expression>",[e,...xt(n,s),i]),this.tupleOpenParen=e,this.elementList=n,this.commaList=s,this.tupleCloseParen=i}}class et extends pe{constructor({groupOpenParen:e,expression:n,groupCloseParen:s},i){super({tupleOpenParen:e,elementList:n&&[n],commaList:[],tupleCloseParen:s},i),this.kind="<group-expression>"}}class Y extends D{constructor({callee:e,argumentList:n},s){super(s,"<call-expression>",[e,n]),this.callee=e,this.argumentList=n}}class ye extends D{constructor({literal:e},n){super(n,"<literal>",[e]),this.literal=e}}class re extends D{constructor({variable:e},n){super(n,"<variable>",[e]),this.variable=e}}class j extends D{constructor({expression:e},n){super(n,"<primary-expression>",[e]),this.expression=e}}class Me extends D{constructor({pre:e},n){const s=K.create(h.SPACE,e.endPos,e.endPos," ",!1);super(n,"<dummy>",[s])}}class he extends D{constructor({expression:e,indexer:n},s){super(s,"<array>",[e,n]),this.array=e,this.indexer=n}}function xt(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?A.flatten(A.zip(t,e)):A.flatten(A.zip(e,t))).filter(i=>i!==null)}function an(t,e=!1){return JSON.stringify(t,function(n,s){var i;return!(this instanceof Z)&&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(a=>a.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 U{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 U(e(this.value))}isOk(){return!0}}class S{unwrap(){throw new Error("Trying to unwrap a None value")}unwrap_or(e){return e}and_then(e){return new S}map(e){return new S}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.TablePartial="TablePartial",t.TablePartialInjection="TablePartialInjection",t))(m||{});function tt(t){return`Schema:${t}`}function Ve(t){return`Table:${t}`}function qe(t){return`Column:${t}`}function nt(t){return`Enum:${t}`}function st(t){return`Enum field:${t}`}function it(t){return`TableGroup:${t}`}function at(t){return`TableGroup field:${t}`}function rn(t){return`Note:${t}`}function rt(t){return`TablePartial:${t}`}function Dt(t){return`TablePartialInjection:${t}`}function Fe(t,e){switch(e){case"Column":return qe(t);case"Enum":return nt(t);case"Enum field":return st(t);case"Schema":return tt(t);case"Table":return Ve(t);case"TableGroup":return it(t);case"TableGroup field":return at(t);case"TablePartial":return rt(t);default:throw new Error("Unreachable")}}function le(t){const[e,n]=t.split(":");return Object.values(m).includes(e)?new U({name:n,kind:e}):new S}function on(t){const e=le(t).unwrap_or(void 0);if(!e)return!1;const{kind:n,name:s}=e;return n==="Schema"&&s==="public"}function ln(t){const e=le(t).unwrap_or(void 0);if(!e)return!1;const{kind:n}=e;return n==="TablePartialInjection"}function cn(t){const e=le(t).unwrap_or(void 0);if(!e)return null;const{kind:n,name:s}=e;return n==="TablePartialInjection"?Fe(s,"TablePartial"):null}class un{constructor(){this.id=0}reset(){this.id=0}nextId(){return this.id++}}class Ot{constructor({symbolTable:e},n){this.references=[],this.id=n,this.symbolTable=e}}class hn{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class fn{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}class Rt{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class ot{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}class pn{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class dn{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}class En{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class Nn{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}class Tn{constructor({injectorFieldSymbol:e,injectorDeclaration:n},s){this.references=[],this.id=s,this.injectorDeclaration=n,this.injectorFieldSymbol=e}}function mn(t){return[tt,Ve,nt,it,qe,st,at,rt,Dt].map(e=>e(t))}function bn(t){return t instanceof ot?Tn:null}function Ye(t){return!!t.match(/(\p{L}|_|\p{M})/gu)}function Ge(t){const[e]=t;return e>="0"&&e<="9"}function In(t){const[e]=t;return Ge(e)||Ye(e)&&e.toLowerCase()>="a"&&e.toLowerCase()<="f"}function ve(t){return Ye(t)||Ge(t)}function Nt(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 Se(t,e){return t>=e.start&&t<e.end}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.INVALID_TABLE_PARTIAL_CONTEXT=3060]="INVALID_TABLE_PARTIAL_CONTEXT",t[t.INVALID_TABLE_PARTIAL_ELEMENT_NAME=3061]="INVALID_TABLE_PARTIAL_ELEMENT_NAME",t[t.INVALID_TABLE_PARTIAL_SETTING=3062]="INVALID_TABLE_PARTIAL_SETTING",t[t.DUPLICATE_TABLE_PARTIAL_ELEMENT_NAME=3063]="DUPLICATE_TABLE_PARTIAL_ELEMENT_NAME",t[t.DUPLICATE_TABLE_PARTIAL_SETTING=3064]="DUPLICATE_TABLE_PARTIAL_SETTING",t[t.INVALID_TABLE_PARTIAL_INJECTION=3065]="INVALID_TABLE_PARTIAL_INJECTION",t[t.INVALID_TABLE_PARTIAL_INJECTION_OP=3066]="INVALID_TABLE_PARTIAL_INJECTION_OP",t[t.INVALID_TABLE_PARTIAL_INJECTION_NAME=3067]="INVALID_TABLE_PARTIAL_INJECTION_NAME",t[t.DUPLICATE_TABLE_PARTIAL_INJECTION_NAME=3068]="DUPLICATE_TABLE_PARTIAL_INJECTION_NAME",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 l 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,l.prototype)}}class z{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 z(n.value,s)}map(e){return new z(e(this.value),this.errors)}}function Ln(t,e,n){if(!t||!fe(t)||e.length===0)return new S;const s=[...e],i=Ke(t).unwrap(),a=s.pop();if(!(a instanceof oe))return new S;const r=A.last(s)instanceof M?s.pop():void 0;return s.length===3&&Ke(s[1]).unwrap().value==="as"?new U(n.create(y,{type:i,name:s[0],as:Ke(s[1]).unwrap(),alias:s[2],attributeList:r,body:a})):s.length===1?new U(n.create(y,{type:i,name:s[0],attributeList:r,body:a})):s.length===0?new U(n.create(y,{type:i,attributeList:r,body:a})):new S}function Tt(t){return t.kind===h.IDENTIFIER&&t.value==="as"}function b(t){t&&(t instanceof K?An(t):_n(t))}function An(t){t.kind!==h.EOF&&(t.isInvalid=!0)}function _n(t){if(t instanceof y)b(t.type),b(t.name),b(t.as),b(t.alias),b(t.bodyColon),b(t.attributeList),b(t.body);else if(t instanceof ne)t.identifiers.forEach(b);else if(t instanceof se)b(t.name),b(t.colon),b(t.value);else if(t instanceof ae)b(t.op),b(t.expression);else if(t instanceof ce)b(t.leftExpression),b(t.op),b(t.rightExpression);else if(t instanceof We)b(t.op),b(t.expression);else if(t instanceof oe)b(t.blockOpenBrace),t.body.forEach(b),b(t.blockCloseBrace);else if(t instanceof M)b(t.listOpenBracket),t.commaList.forEach(b),t.elementList.forEach(b),b(t.listCloseBracket);else if(t instanceof pe)b(t.tupleOpenParen),t.commaList.forEach(b),t.elementList.forEach(b),b(t.tupleCloseParen);else if(t instanceof Y)b(t.callee),b(t.argumentList);else if(t instanceof w)b(t.callee),t.args.forEach(b);else if(t instanceof j)b(t.expression);else if(t instanceof ue)b(t.value);else if(t instanceof re)b(t.variable);else if(t instanceof ye)b(t.literal);else throw t instanceof et?new Error("This case is handled by the TupleExpressionNode case"):new Error("Unreachable case in markInvalidNode")}function Ut(t){return!!(t!=null&&t.isInvalid)}function X(...t){return t.filter(e=>e!==void 0)}function gn(t){if(t instanceof Z)return X(...t.body,t.eof);if(t instanceof y)return X(t.type,t.name,t.as,t.alias,t.attributeList,t.bodyColon,t.body);if(t instanceof se)return X(t.name,t.colon,t.value);if(t instanceof ne)return t.identifiers;if(t instanceof ye)return t.literal?[t.literal]:[];if(t instanceof re)return X(t.variable);if(t instanceof ae)return X(t.op,t.expression);if(t instanceof ce)return X(t.leftExpression,t.op,t.rightExpression);if(t instanceof We)return X(t.expression,t.op);if(t instanceof ue)return X(t.value);if(t instanceof w)return X(t.callee,...t.args);if(t instanceof oe)return X(t.blockOpenBrace,...t.body,t.blockCloseBrace);if(t instanceof M)return X(t.listOpenBracket,...Nt(t.elementList,t.commaList),t.listCloseBracket);if(t instanceof pe)return X(t.tupleOpenParen,...Nt(t.elementList,t.commaList),t.tupleCloseParen);if(t instanceof Y)return X(t.callee,t.argumentList);if(t instanceof j)return X(t.expression);if(t instanceof he)return X(t.array,t.indexer);if(t instanceof Ae)return X(t.partial);throw t instanceof et?new Error("This case is already handled by TupleExpressionNode"):new Error("Unreachable - no other possible cases")}function Ke(t){return W(t)?new U(t.expression.variable):new S}function C(t){var e;return t instanceof j&&(t.expression instanceof re&&t.expression.variable instanceof K&&t.expression.variable.kind===h.QUOTED_STRING||t.expression instanceof ye&&((e=t.expression.literal)==null?void 0:e.kind)===h.STRING_LITERAL)}function W(t){return t instanceof j&&t.expression instanceof re&&t.expression.variable instanceof K}function fe(t){var e;return t instanceof j&&t.expression instanceof re&&((e=t.expression.variable)==null?void 0:e.kind)===h.IDENTIFIER}function ze(t){var e;return t instanceof ce&&t.leftExpression instanceof D&&t.rightExpression instanceof D&&((e=t.op)==null?void 0:e.value)==="."}function we(t){if(t===void 0)return new S;const e=t.identifiers.map(n=>n.value).join(" ");return e===""?new S:new U(e)}class vn{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
|
|
3
|
-
`:this.addToken(h.NEWLINE);break;case" ":this.addToken(h.TAB);break;case",":this.addToken(h.COMMA);break;case"(":this.addToken(h.LPAREN);break;case")":this.addToken(h.RPAREN);break;case"[":this.addToken(h.LBRACKET);break;case"]":this.addToken(h.RBRACKET);break;case"{":this.addToken(h.LBRACE);break;case"}":this.addToken(h.RBRACE);break;case";":this.addToken(h.SEMICOLON);break;case":":this.addToken(h.COLON);break;case"~":this.addToken(h.TILDE);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(
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const A=require("lodash");var h=(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.TILDE="<tilde>",t.SINGLE_LINE_COMMENT="<single-line-comment>",t.MULTILINE_COMMENT="<multiline-comment>",t))(h||{});function sn(t){switch(t.kind){case"<newline>":case"<space>":case"<tab>":case"<single-line-comment>":case"<multiline-comment>":return!0;default:return!1}}function ft(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 pt(t){return t!==void 0&&t.kind==="<op>"}class J{constructor(e,n,s,i,a){this.kind=e,this.startPos=n,this.endPos=s,this.value=i,this.leadingTrivia=[],this.trailingTrivia=[],this.leadingInvalid=[],this.trailingInvalid=[],this.isInvalid=a,this.start=n.offset,this.end=s.offset}static create(e,n,s,i,a){return new J(e,n,s,i,a)}}function yt(t){return t.trailingTrivia.find(({kind:e})=>e===h.NEWLINE)!==void 0}function dt(t,e){return e.leadingTrivia.find(({kind:s})=>s===h.NEWLINE)!==void 0||yt(t)}function Ze(t){return t.trailingTrivia.find(({kind:e})=>[h.SPACE,h.TAB].includes(e))!==void 0}function Pt(t){return t.trailingTrivia.length===0?t.end:Pt(A.last(t.trailingTrivia))}function kt(t){return t.leadingTrivia.length===0?t.start:kt(t.leadingTrivia[0])}function an(t){return[h.SINGLE_LINE_COMMENT,h.MULTILINE_COMMENT].includes(t.kind)}class rn{constructor(){this.id=0}reset(){this.id=0}nextId(){return this.id++}}class O{constructor(e,n,s){this.id=e,this.kind=n;const i=s.find(r=>r!==void 0&&!Number.isNaN(r.start));i?(this.startPos=i.startPos,this.fullStart=i instanceof J?kt(i):i.fullStart):(this.startPos={offset:NaN,column:NaN,line:NaN},this.fullStart=NaN);const a=[...s].reverse().find(r=>r!==void 0&&!Number.isNaN(r.end));a?(this.endPos=a.endPos,this.fullEnd=a instanceof J?Pt(a):a.fullEnd):(this.endPos={offset:NaN,column:NaN,line:NaN},this.fullEnd=NaN),this.start=this.startPos.offset,this.end=this.endPos.offset}}var Ie=(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.PARTIAL_INJECTION="<partial-injection>",t))(Ie||{});class Z extends O{constructor({body:e=[],eof:n},s){super(s,"<program>",[...e,n]),this.body=e,this.eof=n}}class y extends O{constructor({type:e,name:n,as:s,alias:i,attributeList:a,bodyColon:r,body:c},p){if(super(p,"<element-declaration>",[e,n,s,i,a,r,c]),c&&r&&!(c instanceof w||c instanceof y))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=a,this.bodyColon=r,this.body=c}}class te extends O{constructor({identifiers:e=[]},n){super(n,"<identifer-stream>",e||[]),this.identifiers=e}}class ne extends O{constructor({name:e,colon:n,value:s},i){super(i,"<attribute>",[e,n,s]),this.name=e,this.value=s,this.colon=n}}class oe extends O{constructor({op:e,expression:n},s){super(s,"<prefix-expression>",[e,n]),this.op=e,this.expression=n}}class le extends O{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 We extends O{constructor({op:e,expression:n},s){super(s,"<postfix-expression>",[n,e]),this.op=e,this.expression=n}}class ue extends O{constructor({value:e},n){super(n,"<function-expression>",[e]),this.value=e}}class w extends O{constructor({callee:e,args:n=[]},s){super(s,"<function-application>",[e,...n]),this.callee=e,this.args=n}}class ae extends O{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 Le extends O{constructor({op:e,partial:n},s){super(s,"<partial-injection>",[e,n]),this.partial=n}}class M extends O{constructor({listOpenBracket:e,elementList:n=[],commaList:s=[],listCloseBracket:i},a){super(a,"<list-expression>",[e,...St(n,s),i]),this.listOpenBracket=e,this.elementList=n,this.commaList=s,this.listCloseBracket=i}}class ce extends O{constructor({tupleOpenParen:e,elementList:n=[],commaList:s=[],tupleCloseParen:i},a){super(a,"<tuple-expression>",[e,...St(n,s),i]),this.tupleOpenParen=e,this.elementList=n,this.commaList=s,this.tupleCloseParen=i}}class et extends ce{constructor({groupOpenParen:e,expression:n,groupCloseParen:s},i){super({tupleOpenParen:e,elementList:n&&[n],commaList:[],tupleCloseParen:s},i),this.kind="<group-expression>"}}class z extends O{constructor({callee:e,argumentList:n},s){super(s,"<call-expression>",[e,n]),this.callee=e,this.argumentList=n}}class ye extends O{constructor({literal:e},n){super(n,"<literal>",[e]),this.literal=e}}class ie extends O{constructor({variable:e},n){super(n,"<variable>",[e]),this.variable=e}}class $ extends O{constructor({expression:e},n){super(n,"<primary-expression>",[e]),this.expression=e}}class Me extends O{constructor({pre:e},n){const s=J.create(h.SPACE,e.endPos,e.endPos," ",!1);super(n,"<dummy>",[s])}}class he extends O{constructor({expression:e,indexer:n},s){super(s,"<array>",[e,n]),this.array=e,this.indexer=n}}function St(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?A.flatten(A.zip(t,e)):A.flatten(A.zip(e,t))).filter(i=>i!==null)}function on(t,e=!1){return JSON.stringify(t,function(n,s){var i;return!(this instanceof Z)&&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(a=>a.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 U{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 U(e(this.value))}isOk(){return!0}}class S{unwrap(){throw new Error("Trying to unwrap a None value")}unwrap_or(e){return e}and_then(e){return new S}map(e){return new S}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.TablePartial="TablePartial",t.TablePartialInjection="TablePartialInjection",t))(m||{});function tt(t){return`Schema:${t}`}function Ve(t){return`Table:${t}`}function qe(t){return`Column:${t}`}function nt(t){return`Enum:${t}`}function st(t){return`Enum field:${t}`}function it(t){return`TableGroup:${t}`}function at(t){return`TableGroup field:${t}`}function ln(t){return`Note:${t}`}function rt(t){return`TablePartial:${t}`}function Dt(t){return`TablePartialInjection:${t}`}function Fe(t,e){switch(e){case"Column":return qe(t);case"Enum":return nt(t);case"Enum field":return st(t);case"Schema":return tt(t);case"Table":return Ve(t);case"TableGroup":return it(t);case"TableGroup field":return at(t);case"TablePartial":return rt(t);default:throw new Error("Unreachable")}}function re(t){const[e,n]=t.split(":");return Object.values(m).includes(e)?new U({name:n,kind:e}):new S}function cn(t){const e=re(t).unwrap_or(void 0);if(!e)return!1;const{kind:n,name:s}=e;return n==="Schema"&&s==="public"}function un(t){const e=re(t).unwrap_or(void 0);if(!e)return!1;const{kind:n}=e;return n==="TablePartialInjection"}function hn(t){const e=re(t).unwrap_or(void 0);if(!e)return null;const{kind:n,name:s}=e;return n==="TablePartialInjection"?Fe(s,"TablePartial"):null}class fn{constructor(){this.id=0}reset(){this.id=0}nextId(){return this.id++}}class Ot{constructor({symbolTable:e},n){this.references=[],this.id=n,this.symbolTable=e}}class pn{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class dn{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}class xt{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class ot{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}class En{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class Nn{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}class Tn{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class mn{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}class bn{constructor({injectorFieldSymbol:e,injectorDeclaration:n},s){this.references=[],this.id=s,this.injectorDeclaration=n,this.injectorFieldSymbol=e}}function In(t){return[tt,Ve,nt,it,qe,st,at,rt,Dt].map(e=>e(t))}function Ln(t){return t instanceof ot?bn:null}function Ye(t){return!!t.match(/(\p{L}|_|\p{M})/gu)}function Ge(t){const[e]=t;return e>="0"&&e<="9"}function An(t){const[e]=t;return Ge(e)||Ye(e)&&e.toLowerCase()>="a"&&e.toLowerCase()<="f"}function ve(t){return Ye(t)||Ge(t)}function Et(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 Se(t,e){return t>=e.start&&t<e.end}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.INVALID_TABLE_PARTIAL_CONTEXT=3060]="INVALID_TABLE_PARTIAL_CONTEXT",t[t.INVALID_TABLE_PARTIAL_ELEMENT_NAME=3061]="INVALID_TABLE_PARTIAL_ELEMENT_NAME",t[t.INVALID_TABLE_PARTIAL_SETTING=3062]="INVALID_TABLE_PARTIAL_SETTING",t[t.DUPLICATE_TABLE_PARTIAL_ELEMENT_NAME=3063]="DUPLICATE_TABLE_PARTIAL_ELEMENT_NAME",t[t.DUPLICATE_TABLE_PARTIAL_SETTING=3064]="DUPLICATE_TABLE_PARTIAL_SETTING",t[t.INVALID_TABLE_PARTIAL_INJECTION=3065]="INVALID_TABLE_PARTIAL_INJECTION",t[t.INVALID_TABLE_PARTIAL_INJECTION_OP=3066]="INVALID_TABLE_PARTIAL_INJECTION_OP",t[t.INVALID_TABLE_PARTIAL_INJECTION_NAME=3067]="INVALID_TABLE_PARTIAL_INJECTION_NAME",t[t.DUPLICATE_TABLE_PARTIAL_INJECTION_NAME=3068]="DUPLICATE_TABLE_PARTIAL_INJECTION_NAME",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 l 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,l.prototype)}}class K{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 K(n.value,s)}map(e){return new K(e(this.value),this.errors)}}function _n(t,e,n){if(!t||!fe(t)||e.length===0)return new S;const s=[...e],i=Ke(t).unwrap(),a=s.pop();if(!(a instanceof ae))return new S;const r=A.last(s)instanceof M?s.pop():void 0;return s.length===3&&Ke(s[1]).unwrap().value==="as"?new U(n.create(y,{type:i,name:s[0],as:Ke(s[1]).unwrap(),alias:s[2],attributeList:r,body:a})):s.length===1?new U(n.create(y,{type:i,name:s[0],attributeList:r,body:a})):s.length===0?new U(n.create(y,{type:i,attributeList:r,body:a})):new S}function Nt(t){return t.kind===h.IDENTIFIER&&t.value==="as"}function b(t){t&&(t instanceof J?gn(t):vn(t))}function gn(t){t.kind!==h.EOF&&(t.isInvalid=!0)}function vn(t){if(t instanceof y)b(t.type),b(t.name),b(t.as),b(t.alias),b(t.bodyColon),b(t.attributeList),b(t.body);else if(t instanceof te)t.identifiers.forEach(b);else if(t instanceof ne)b(t.name),b(t.colon),b(t.value);else if(t instanceof oe)b(t.op),b(t.expression);else if(t instanceof le)b(t.leftExpression),b(t.op),b(t.rightExpression);else if(t instanceof We)b(t.op),b(t.expression);else if(t instanceof ae)b(t.blockOpenBrace),t.body.forEach(b),b(t.blockCloseBrace);else if(t instanceof M)b(t.listOpenBracket),t.commaList.forEach(b),t.elementList.forEach(b),b(t.listCloseBracket);else if(t instanceof ce)b(t.tupleOpenParen),t.commaList.forEach(b),t.elementList.forEach(b),b(t.tupleCloseParen);else if(t instanceof z)b(t.callee),b(t.argumentList);else if(t instanceof w)b(t.callee),t.args.forEach(b);else if(t instanceof $)b(t.expression);else if(t instanceof ue)b(t.value);else if(t instanceof ie)b(t.variable);else if(t instanceof ye)b(t.literal);else throw t instanceof et?new Error("This case is handled by the TupleExpressionNode case"):new Error("Unreachable case in markInvalidNode")}function Rt(t){return!!(t!=null&&t.isInvalid)}function C(...t){return t.filter(e=>e!==void 0)}function wn(t){if(t instanceof Z)return C(...t.body,t.eof);if(t instanceof y)return C(t.type,t.name,t.as,t.alias,t.attributeList,t.bodyColon,t.body);if(t instanceof ne)return C(t.name,t.colon,t.value);if(t instanceof te)return t.identifiers;if(t instanceof ye)return t.literal?[t.literal]:[];if(t instanceof ie)return C(t.variable);if(t instanceof oe)return C(t.op,t.expression);if(t instanceof le)return C(t.leftExpression,t.op,t.rightExpression);if(t instanceof We)return C(t.expression,t.op);if(t instanceof ue)return C(t.value);if(t instanceof w)return C(t.callee,...t.args);if(t instanceof ae)return C(t.blockOpenBrace,...t.body,t.blockCloseBrace);if(t instanceof M)return C(t.listOpenBracket,...Et(t.elementList,t.commaList),t.listCloseBracket);if(t instanceof ce)return C(t.tupleOpenParen,...Et(t.elementList,t.commaList),t.tupleCloseParen);if(t instanceof z)return C(t.callee,t.argumentList);if(t instanceof $)return C(t.expression);if(t instanceof he)return C(t.array,t.indexer);if(t instanceof Le)return C(t.partial);throw t instanceof et?new Error("This case is already handled by TupleExpressionNode"):new Error("Unreachable - no other possible cases")}function Ke(t){return j(t)?new U(t.expression.variable):new S}function W(t){var e;return t instanceof $&&(t.expression instanceof ie&&t.expression.variable instanceof J&&t.expression.variable.kind===h.QUOTED_STRING||t.expression instanceof ye&&((e=t.expression.literal)==null?void 0:e.kind)===h.STRING_LITERAL)}function j(t){return t instanceof $&&t.expression instanceof ie&&t.expression.variable instanceof J}function fe(t){var e;return t instanceof $&&t.expression instanceof ie&&((e=t.expression.variable)==null?void 0:e.kind)===h.IDENTIFIER}function ze(t){var e;return t instanceof le&&t.leftExpression instanceof O&&t.rightExpression instanceof O&&((e=t.op)==null?void 0:e.value)==="."}function we(t){if(t===void 0)return new S;const e=t.identifiers.map(n=>n.value).join(" ");return e===""?new S:new U(e)}class yn{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 J.create(e,this.start,this.current,this.text.substring(this.start.offset,this.current.offset),n)}lex(){return this.scanTokens(),this.tokens.push(J.create(h.EOF,this.start,this.current,"",!1)),this.gatherTrivia(),this.gatherInvalid(),new K(this.tokens,this.errors)}scanTokens(){for(;!this.isAtEnd();){const e=this.advance();switch(e){case" ":this.addToken(h.SPACE);break;case"\r":break;case`
|
|
3
|
+
`:this.addToken(h.NEWLINE);break;case" ":this.addToken(h.TAB);break;case",":this.addToken(h.COMMA);break;case"(":this.addToken(h.LPAREN);break;case")":this.addToken(h.RPAREN);break;case"[":this.addToken(h.LBRACKET);break;case"]":this.addToken(h.RBRACKET);break;case"{":this.addToken(h.LBRACE);break;case"}":this.addToken(h.RBRACE);break;case";":this.addToken(h.SEMICOLON);break;case":":this.addToken(h.COLON);break;case"~":this.addToken(h.TILDE);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(ft(e)){this.operator();break}if(Ye(e)){this.identifier();break}if(Ge(e)){this.numericLiteralOrIdentifier();break}this.addToken(h.OP,!0),this.errors.push(new l(o.UNKNOWN_SYMBOL,`Unexpected token '${e}'`,this.createToken(h.OP,!0)));break}this.start={...this.current}}}gatherTrivia(){let e=!0,n=[],s;const i=[];for(const a of this.tokens)sn(a)?(n.push(a),a.kind===h.NEWLINE&&s&&(s.trailingTrivia=n,e=!0,s=void 0,n=[])):(e?a.leadingTrivia=n:s.trailingTrivia=n,i.push(a),n=[],s=a,e=!1);this.tokens=i}gatherInvalid(){let e;const n=[],s=[];for(e=0;e<this.tokens.length&&Rt(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 a=this.tokens[e];a.isInvalid?i.trailingInvalid.push(a):(i=a,n.push(a))}this.tokens=n}consumeUntil(e,n,{allowNewline:s,allowEof:i,raw:a,consumeStopSequence:r=!0}){let c="";for(;!this.isAtEnd()&&(s||!this.check(`
|
|
4
4
|
`))&&!this.check(n);)this.peek()==="\\"&&!a?(this.advance(),c+=this.escapedString()):c+=this.advance();if(this.isAtEnd()&&!i){const p=this.createToken(e,!0);this.tokens.push(p),this.errors.push(new l(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 l(o.UNEXPECTED_NEWLINE,"Invalid newline encountered while parsing",p));return}r&&this.match(n),this.tokens.push(
|
|
6
|
-
`,{allowNewline:!0,allowEof:!0,raw:!0,consumeStopSequence:!1})}multilineComment(){this.consumeUntil(h.MULTILINE_COMMENT,"*/",{allowNewline:!0,allowEof:!1,raw:!0})}identifier(){for(;!this.isAtEnd()&&ve(this.peek());)this.advance();this.addToken(h.IDENTIFIER)}operator(){for(;
|
|
5
|
+
`)&&!s){const p=this.createToken(e,!0);this.tokens.push(p),this.errors.push(new l(o.UNEXPECTED_NEWLINE,"Invalid newline encountered while parsing",p));return}r&&this.match(n),this.tokens.push(J.create(e,this.start,this.current,c,!1))}singleLineStringLiteral(){this.consumeUntil(h.STRING_LITERAL,"'",{allowNewline:!1,allowEof:!1,raw:!1})}multilineStringLiteral(){this.consumeUntil(h.STRING_LITERAL,"'''",{allowNewline:!0,allowEof:!1,raw:!1})}functionExpression(){this.consumeUntil(h.FUNCTION_EXPRESSION,"`",{allowNewline:!1,allowEof:!1,raw:!0})}quotedVariable(){this.consumeUntil(h.QUOTED_STRING,'"',{allowNewline:!1,allowEof:!1,raw:!1})}singleLineComment(){this.consumeUntil(h.SINGLE_LINE_COMMENT,`
|
|
6
|
+
`,{allowNewline:!0,allowEof:!0,raw:!0,consumeStopSequence:!1})}multilineComment(){this.consumeUntil(h.MULTILINE_COMMENT,"*/",{allowNewline:!0,allowEof:!1,raw:!0})}identifier(){for(;!this.isAtEnd()&&ve(this.peek());)this.advance();this.addToken(h.IDENTIFIER)}operator(){for(;ft(this.peek());)this.advance();this.addToken(h.OP)}numericLiteralOrIdentifier(){let e=0;if(this.isAtEnd())return this.addToken(h.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(h.NUMERIC_LITERAL);if(!n&&!ve(this.peek()))return this.addToken(h.NUMERIC_LITERAL);if(!n&&!Ge(this.peek()))break;this.advance()}if(e>0){for(;!this.isAtEnd()&&(this.check(".")||ve(this.peek()));)this.advance();const n=this.createToken(h.NUMERIC_LITERAL,!0);this.tokens.push(n),this.errors.push(new l(o.UNKNOWN_TOKEN,"Invalid number",n))}else{for(;!this.isAtEnd()&&ve(this.peek());)this.advance();const n=this.createToken(h.IDENTIFIER,!1);this.tokens.push(n)}}colorLiteral(){for(;!this.isAtEnd()&&ve(this.peek());)this.advance();this.addToken(h.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
7
|
`)&&this.advance(),"";case`
|
|
8
8
|
`:return"";case"t":return" ";case"n":return`
|
|
9
|
-
`;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" ":return"\\ ";case"u":{let n="";for(let s=0;s<=3;s+=1){if(this.isAtEnd()||!ve(this.peek()))return this.errors.push(new l(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`,K.create(h.STRING_LITERAL,e,this.current,`\\u${n}`,!0))),`\\u${n}`;n+=this.advance()}return String.fromCharCode(parseInt(n,16))}default:return this.text[this.current.offset-1]}}}var Be=(t=>(t[t.ListExpression=0]="ListExpression",t[t.GroupExpression=1]="GroupExpression",t[t.BlockExpression=2]="BlockExpression",t))(Be||{});class wn{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 A.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 h.COMMA:if(this.isWithinGroupExpressionContext()||this.isWithinListExpressionContext())return[...this.stack].reverse().find(a=>[1,0].includes(a));break;case h.RPAREN:if(this.isWithinGroupExpressionContext())return 1;break;case h.RBRACE:if(this.isWithinBlockExpressionContext())return 2;break;case h.RBRACKET:if(this.isWithinListExpressionContext())return 0;break}}}class yn{constructor(e){this.generator=e}create(e,n){return new e(n,this.generator.nextId())}}class N{constructor(e,n,s){this.token=e,this.partialNode=n,this.handlerContext=s}}class kn{constructor(e,n){this.current=0,this.errors=[],this.contextStack=new wn,this.synchronizeProgram=()=>{const s=this.peek();s.kind!==h.EOF?b(this.advance()):(b(this.peek()),this.logError(s,o.UNEXPECTED_EOF,"Unexpected EOF"))},this.synchronizeElementDeclarationName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(Tt(s)||this.check(h.COLON,h.LBRACE,h.LBRACKET))break;b(s),this.advance()}},this.synchronizeElementDeclarationAlias=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(h.COLON,h.LBRACE,h.LBRACKET))break;b(s),this.advance()}},this.blockExpression=this.contextStack.withContextDo(Be.BlockExpression,()=>{const s={body:[]},i=()=>this.nodeFactory.create(oe,s);try{this.consume("Expect an opening brace '{'",h.LBRACE),s.blockOpenBrace=this.previous()}catch(a){if(!(a instanceof N))throw a;if(s.blockOpenBrace=a.partialNode,!this.canHandle(a))throw new N(a.token,i(),a.handlerContext);this.synchronizeBlock()}for(;!this.isAtEnd()&&!this.check(h.RBRACE);)try{if(this.match(h.TILDE)){const a=this.previous(),r=this.variable(),c=this.nodeFactory.create(Ae,{op:a,partial:r});s.body.push(c)}else s.body.push(this.canBeField()?this.fieldDeclaration():this.expression())}catch(a){if(!(a instanceof N))throw a;if(s.body.push(a.partialNode),!this.canHandle(a))throw new N(a.token,i(),a.handlerContext);this.synchronizeBlock()}try{this.consume("Expect a closing brace '}'",h.RBRACE),s.blockCloseBrace=this.previous()}catch(a){if(!(a instanceof N))throw a;if(s.blockCloseBrace=a.partialNode,!this.canHandle(a))throw new N(a.token,i(),a.handlerContext);this.synchronizeBlock()}return i()}),this.synchronizeBlock=()=>{if(!this.check(h.RBRACE))for(b(this.advance());!this.isAtEnd();){const s=this.peek();if(this.check(h.RBRACE)||Et(this.previous(),s))break;b(s),this.advance()}},this.tupleExpression=this.contextStack.withContextDo(Be.GroupExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(et,{groupOpenParen:s.tupleOpenParen,groupCloseParen:s.tupleCloseParen,expression:s.elementList[0]}),a=()=>this.nodeFactory.create(pe,s);try{this.consume("Expect an opening parenthesis '('",h.LPAREN),s.tupleOpenParen=this.previous()}catch(r){if(!(r instanceof N))throw r;if(s.tupleOpenParen=r.partialNode,!this.canHandle(r))throw new N(r.token,a(),r.handlerContext);this.synchronizeTuple()}if(!this.isAtEnd()&&!this.check(h.RPAREN))try{s.elementList.push(this.normalExpression())}catch(r){if(!(r instanceof N))throw r;if(s.elementList.push(r.partialNode),!this.canHandle(r))throw new N(r.token,i(),r.handlerContext);this.synchronizeTuple()}for(;!this.isAtEnd()&&!this.check(h.RPAREN);)try{this.consume("Expect a comma ','",h.COMMA),s.commaList.push(this.previous()),s.elementList.push(this.normalExpression())}catch(r){if(!(r instanceof N))throw r;if(r.partialNode instanceof D&&s.elementList.push(r.partialNode),!this.canHandle(r))throw new N(r.token,a(),r.handlerContext);this.synchronizeTuple()}try{this.consume("Expect a closing parenthesis ')'",h.RPAREN),s.tupleCloseParen=this.previous()}catch(r){if(!(r instanceof N))throw r;if(s.tupleCloseParen=r.partialNode,!this.canHandle(r))throw new N(r.token,a(),r.handlerContext);this.synchronizeTuple()}return s.elementList.length===1?i():a()}),this.synchronizeTuple=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(h.RPAREN,h.COMMA))break;b(s),this.advance()}},this.listExpression=this.contextStack.withContextDo(Be.ListExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(M,s);try{this.consume("Expect an opening bracket '['",h.LBRACKET),s.listOpenBracket=this.previous()}catch(a){if(!(a instanceof N))throw a;if(s.listOpenBracket=a.partialNode,!this.canHandle(a))throw new N(a.token,i(),a.handlerContext);this.synchronizeList()}if(!this.isAtEnd()&&!this.check(h.RBRACKET))try{s.elementList.push(this.attribute())}catch(a){if(!(a instanceof N))throw a;if(s.elementList.push(a.partialNode),!this.canHandle(a))throw new N(a.token,i(),a.handlerContext);this.synchronizeList()}for(;!this.isAtEnd()&&!this.check(h.RBRACKET);)try{this.consume("Expect a comma ','",h.COMMA),s.commaList.push(this.previous()),s.elementList.push(this.attribute())}catch(a){if(!(a instanceof N))throw a;if(a.partialNode instanceof D&&s.elementList.push(a.partialNode),!this.canHandle(a))throw new N(a.token,i(),a.handlerContext);this.synchronizeList()}try{this.consume("Expect a closing bracket ']'",h.RBRACKET),s.listCloseBracket=this.previous()}catch(a){if(!(a instanceof N))throw a;if(s.listCloseBracket=a.partialNode,!this.canHandle(a))throw new N(a.token,i(),a.handlerContext);this.synchronizeList()}return i()}),this.synchronizeList=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(h.COMMA,h.RBRACKET))break;b(s),this.advance()}},this.synchronizeAttributeName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(h.COMMA,h.RBRACKET,h.COLON))break;b(s),this.advance()}},this.synchronizeAttributeValue=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(h.COMMA,h.RBRACKET))break;b(s),this.advance()}},this.tokens=e,this.nodeFactory=new yn(n)}isAtEnd(){return this.current>=this.tokens.length||this.tokens[this.current].kind===h.EOF}advance(){return this.isAtEnd()?A.last(this.tokens):this.tokens[this.current++]}peek(e=0){return e+this.current>=this.tokens.length?A.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 N(this.peek(),void 0,this.contextStack.findHandlerContext(this.tokens,this.current))}discardUntil(e,...n){if(this.isAtEnd()||!this.check(...n)){for(b(this.peek()),this.logError(this.advance(),o.UNEXPECTED_TOKEN,e);!this.isAtEnd()&&!this.check(...n);)b(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 a=this.tokens[i];a.isInvalid?s.trailingInvalid.push(a):(s=a,e.push(s))}this.tokens=e}parse(){const e=this.program(),n=this.advance(),s=this.nodeFactory.create(Z,{body:e,eof:n});return this.gatherInvalid(),new z({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 N))throw n;e.push(n.partialNode),this.synchronizeProgram()}return e}elementDeclaration(){const e={},n=()=>this.nodeFactory.create(y,e);try{this.consume("Expect an identifier",h.IDENTIFIER),e.type=this.previous()}catch(s){throw s instanceof N?(e.type=s.partialNode,new N(s.token,n(),s.handlerContext)):s}if(!this.check(h.COLON,h.LBRACE,h.LBRACKET))try{e.name=this.normalExpression()}catch(s){if(!(s instanceof N))throw s;if(e.name=s.partialNode,!this.canHandle(s))throw new N(s.token,n(),s.handlerContext);this.synchronizeElementDeclarationName()}if(Tt(this.peek()))if(e.as=this.advance(),this.check(h.COLON,h.LBRACE,h.LBRACKET))this.logError(this.peek(),o.UNEXPECTED_TOKEN,"Expect an alias");else try{e.alias=this.normalExpression()}catch(s){if(!(s instanceof N))throw s;if(e.alias=s.partialNode,!this.canHandle(s))throw new N(s.token,n(),s.handlerContext);this.synchronizeElementDeclarationAlias()}try{e.attributeList=this.check(h.LBRACKET)?this.listExpression():void 0}catch(s){throw s instanceof N?(e.attributeList=s.partialNode,new N(s.token,n(),s.handlerContext)):s}if(!this.discardUntil("Expect an opening brace '{' or a colon ':'",h.LBRACE,h.COLON))return n();try{if(this.match(h.COLON)){e.bodyColon=this.previous();const s=this.expression();s instanceof y?(b(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 N?(e.body=s.partialNode,new N(s.token,n(),s.handlerContext)):s}return this.nodeFactory.create(y,e)}fieldDeclaration(){const e={},n=()=>this.nodeFactory.create(y,e);try{this.consume("Expect an identifier",h.IDENTIFIER),e.type=this.previous()}catch(s){throw s instanceof N?(e.type=s.partialNode,new N(s.token,n(),s.handlerContext)):s}try{this.consume("Expect a colon ':'",h.COLON),e.bodyColon=this.previous()}catch(s){throw s instanceof N?(e.bodyColon=s.partialNode,new N(s.token,n(),s.handlerContext)):s}try{const s=this.expression();s instanceof y?this.errors.push(new l(o.INVALID_ELEMENT_IN_SIMPLE_BODY,"Simple body cannot be an element declaration",s)):e.body=s}catch(s){throw s instanceof N?(e.body=s.partialNode,new N(s.token,n(),s.handlerContext)):s}return this.nodeFactory.create(y,e)}expression(){const e={args:[]},n=()=>Ln(e.callee,e.args,this.nodeFactory).unwrap_or(this.nodeFactory.create(w,e));try{e.callee=this.normalExpression()}catch(i){throw i instanceof N?(e.callee=i.partialNode,new N(i.token,n(),i.handlerContext)):i}if(this.shouldStopExpression())return n();let s=e.callee;for(;!this.shouldStopExpression();){Ze(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 N?(s=i.partialNode,e.args.push(s),new N(i.token,n(),i.handlerContext)):i}}return n()}shouldStopExpression(){if(this.isAtEnd()||kt(this.previous()))return!0;const e=this.peek().kind;return e===h.RBRACE||e===h.RBRACKET||e===h.RPAREN||e===h.COMMA||e===h.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===h.LPAREN){const{left:i}=mt(s);if(i<e||Et(this.previous(),s)&&!this.contextStack.isWithinGroupExpressionContext()&&!this.contextStack.isWithinListExpressionContext())break;try{n=this.nodeFactory.create(Y,{callee:n,argumentList:this.tupleExpression()})}catch(a){throw a instanceof N?(n=this.nodeFactory.create(Y,{callee:n,argumentList:a.partialNode}),new N(a.token,n,a.handlerContext)):a}}else if(s.kind===h.LBRACKET){if(Ze(this.previous()))break;try{n=this.nodeFactory.create(he,{expression:n,indexer:this.listExpression()})}catch(i){throw i instanceof N?(n=this.nodeFactory.create(he,{expression:n,indexer:i.partialNode}),new N(i.token,n,i.handlerContext)):i}}else if(dt(s)){const i=s,a=mt(i);if(a.left!==null){if(a.left<=e)break;this.advance(),n=this.nodeFactory.create(We,{expression:n,op:i})}else{const r=Sn(i);if(r.left===null||r.left<=e)break;this.advance();try{n=this.nodeFactory.create(ce,{leftExpression:n,op:i,rightExpression:i.value==="."?this.extractOperand():this.expression_bp(r.right)})}catch(c){throw c instanceof N?(n=this.nodeFactory.create(ce,{leftExpression:n,op:i,rightExpression:c.partialNode}),new N(c.token,n,c.handlerContext)):c}}}else break}return n}leftExpression_bp(){let e;if(dt(this.peek())){const n={};n.op=this.peek();const s=Dn(n.op);if(s.right===null)throw this.logError(n.op,o.UNKNOWN_PREFIX_OP,`Unexpected '${n.op.value}' in an expression`),new N(n.op,this.nodeFactory.create(Me,{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 N?(n.expression=i.partialNode,new N(i.token,this.nodeFactory.create(ae,n),i.handlerContext)):i}e=this.nodeFactory.create(ae,n)}else if(e=this.extractOperand(),e instanceof Me)throw new N(this.peek(),this.nodeFactory.create(Me,{pre:this.peek()}),this.contextStack.findHandlerContext(this.tokens,this.current));return e}extractOperand(){return this.check(h.NUMERIC_LITERAL,h.STRING_LITERAL,h.COLOR_LITERAL,h.QUOTED_STRING,h.IDENTIFIER)?this.primaryExpression():this.check(h.FUNCTION_EXPRESSION)?this.functionExpression():this.check(h.LBRACKET)?this.listExpression():this.check(h.LBRACE)?this.blockExpression():this.check(h.LPAREN)?this.tupleExpression():(this.peek().kind===h.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(Me,{pre:this.previous()}))}functionExpression(){const e={};try{this.consume("Expect a function expression",h.FUNCTION_EXPRESSION),e.value=this.previous()}catch(n){throw n instanceof N?(e.value=n.partialNode,new N(n.token,this.nodeFactory.create(ue,e),n.handlerContext)):n}return this.nodeFactory.create(ue,e)}variable(){this.consume("Expect a variable",h.IDENTIFIER);const e=this.previous();return this.nodeFactory.create(re,{variable:e})}canBeField(){return this.peek().kind===h.IDENTIFIER&&this.peek(1).kind===h.COLON}primaryExpression(){if(this.match(h.COLOR_LITERAL,h.STRING_LITERAL,h.NUMERIC_LITERAL))return this.nodeFactory.create(j,{expression:this.nodeFactory.create(ye,{literal:this.previous()})});if(this.match(h.QUOTED_STRING,h.IDENTIFIER))return this.nodeFactory.create(j,{expression:this.nodeFactory.create(re,{variable:this.previous()})});throw this.logError(this.peek(),o.UNEXPECTED_TOKEN,"Expect a variable or literal"),new N(this.peek(),void 0,this.contextStack.findHandlerContext(this.tokens,this.current))}attribute(){const e={};if(this.check(h.COLON,h.RBRACKET,h.COMMA)){const n=this.peek();this.logError(n,o.EMPTY_ATTRIBUTE_NAME,"Expect a non-empty attribute name"),e.name=this.nodeFactory.create(ne,{identifiers:[]})}else try{e.name=this.attributeName()}catch(n){if(!(n instanceof N))throw n;if(e.name=n.partialNode,!this.canHandle(n))throw new N(n.token,this.nodeFactory.create(se,e),n.handlerContext);this.synchronizeAttributeName()}return this.match(h.COLON)&&(e.colon=this.previous(),e.value=this.attributeValue()),this.nodeFactory.create(se,e)}attributeValue(){let e;try{e=this.peek().kind===h.IDENTIFIER&&this.peek(1).kind===h.IDENTIFIER?this.attributeName():this.normalExpression()}catch(n){if(!(n instanceof N)||!this.canHandle(n))throw n;e=n.partialNode,this.synchronizeAttributeValue()}return e}attributeName(){const e=[];if(this.peek().kind!==h.IDENTIFIER)return this.primaryExpression();for(;!this.isAtEnd()&&!this.check(h.COLON,h.COMMA,h.RBRACKET);)try{this.consume("Expect an identifier",h.IDENTIFIER),e.push(this.previous())}catch(n){throw n instanceof N?new N(n.token,this.nodeFactory.create(ne,{identifiers:e}),n.handlerContext):n}return this.nodeFactory.create(ne,{identifiers:e})}logError(e,n,s){this.errors.push(new l(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 Sn(t){return Pn[t.value]||{left:null,right:null}}const xn={"+":{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 Dn(t){return xn[t.value]||{left:null,right:null}}const On={"(":{left:14,right:null}};function mt(t){return On[t.value]||{left:null,right:null}}var I=(t=>(t.Table="table",t.Enum="enum",t.Ref="ref",t.Note="note",t.Project="project",t.Indexes="indexes",t.TableGroup="tablegroup",t.TablePartial="tablepartial",t))(I||{}),T=(t=>(t.Color="color",t.HeaderColor="headercolor",t.Note="note",t.PK="pk",t.PKey="primary key",t.Unique="unique",t.Ref="ref",t.NotNull="not null",t.Null="null",t.Increment="increment",t.Default="default",t.Name="name",t.Type="type",t.Update="update",t.Delete="delete",t))(T||{});function _e(t){var n;const e=(n=t==null?void 0:t.type)==null?void 0:n.value.toLowerCase();switch(e){case I.Enum:case I.Table:case I.Indexes:case I.Note:case I.Project:case I.Ref:case I.TableGroup:case I.TablePartial:return new U(e);default:return new S}}function ge(t){if(!ze(t))return new U([t]);const e=ge(t.leftExpression).unwrap_or(void 0);return e?(e.push(t.rightExpression),new U(e)):new S}function H(t){if(t===void 0)return new S;const e=ge(t).unwrap_or(void 0);if(!e)return new S;const n=[];for(const s of e){const i=q(s).unwrap_or(void 0);if(!i)return new S;n.push(i)}return new U(n)}function xe(t){if(t===void 0)return new S;const e=ge(t).unwrap_or(void 0);if(!e||e.length===0)return new S;const n=[];let s;if(!W(A.last(e))){const i=e.pop();if(Gt(i))s=i.elementList.map(a=>$(a).unwrap());else return new S}for(const i of e){const a=q(i).unwrap_or(void 0);if(!a)return new S;n.push(a)}return new U({variables:n,tupleElements:s})}function q(t){return W(t)?new U(t.expression.variable.value):new S}function Ce(t){if(bt(t))return t instanceof ue?new U({functional:[t],nonFunctional:[]}):new U({functional:[],nonFunctional:[t]});if(t instanceof pe&&t.elementList.every(bt)){const e=t.elementList.filter(s=>s instanceof ue),n=t.elementList.filter(W);return new U({functional:e,nonFunctional:n})}return new S}function $(t){var n;const e=(n=t==null?void 0:t.expression.variable)==null?void 0:n.value;return e===void 0?new S:new U(e)}function Rn(t){var n,s;const e=(s=(n=t==null?void 0:t.partial)==null?void 0:n.variable)==null?void 0:s.value;return e===void 0?new S:new U(e)}function F(t){return C(t)?t.expression instanceof re?new U(t.expression.variable.value):new U(t.expression.literal.value):new S}function Un(t){var e;return!(t instanceof ce)||!Ft((e=t.op)==null?void 0:e.value)?!1:xe(t.leftExpression).and_then(()=>xe(t.rightExpression)).unwrap_or(void 0)!==void 0}function Mn(t){const e=xe(t.leftExpression),n=xe(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 bt(t){return t instanceof j&&t.expression instanceof re||t instanceof ue}function It(t,e){var i,a,r,c;let n=e;const s=on(t);for(;n;){if((a=(i=n.symbol)==null?void 0:i.symbolTable)!=null&&a.has(t))return(r=n.symbol.symbolTable)==null?void 0:r.get(t);if(((c=n.symbol)==null?void 0:c.declaration)instanceof Z&&s)return n.symbol;if(n instanceof Z)return;n=n.parent}}class Fn{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 Z||_e(this.declarationNode.parent).unwrap_or(void 0)!==I.Project?[new l(o.INVALID_CUSTOM_CONTEXT,"A custom element can only appear in a Project",this.declarationNode)]:[]}validateName(e){return e?[new l(o.UNEXPECTED_NAME,"A Custom element shouldn't have a name",e)]:[]}validateAlias(e){return e?[new l(o.UNEXPECTED_NAME,"A Custom element shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new l(o.UNEXPECTED_SETTINGS,"A Custom element shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof oe)return[new l(o.UNEXPECTED_COMPLEX_BODY,"A Custom element can only have an inline field",e)];const n=[];return C(e.callee)||n.push(new l(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 l(o.INVALID_CUSTOM_ELEMENT_VALUE,"A Custom element value can only be a string",s))),n}}class ke{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()}forEach(e){return this.table.forEach(e)}}class Bn{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 y?[new l(o.INVALID_PROJECT_CONTEXT,"An Enum can only appear top-level",this.declarationNode)]:[]}validateName(e){return e?Mt(e)?[]:[new l(o.INVALID_NAME,"An Enum name must be of the form <enum> or <schema>.<enum>",e)]:[new l(o.NAME_NOT_FOUND,"An Enum must have a name",this.declarationNode)]}validateAlias(e){return e?[new l(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}registerElement(){const e=[];this.declarationNode.symbol=this.symbolFactory.create(hn,{declaration:this.declarationNode,symbolTable:new ke});const{name:n}=this.declarationNode,s=H(n);if(s.isOk()){const i=s.unwrap(),a=i.pop(),r=He(i,this.publicSymbolTable,this.symbolFactory),c=nt(a);r.has(c)&&e.push(new l(o.DUPLICATE_NAME,`Enum name ${a} already exists in schema '${i.join(".")||"public"}'`,n)),r.set(c,this.declarationNode.symbol)}return e}validateSettingList(e){return e?[new l(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]=A.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.length===0?[new l(o.EMPTY_ENUM,"An Enum must have at least one element",this.declarationNode)]:e.flatMap(n=>{const s=[];n.callee&&!W(n.callee)&&s.push(new l(o.INVALID_ENUM_ELEMENT_NAME,"An enum field must be an identifier or a quoted identifier",n.callee));const i=[...n.args];return A.last(i)instanceof M?(s.push(...this.validateFieldSettings(A.last(i))),i.pop()):i[0]instanceof M&&(s.push(...this.validateFieldSettings(i[0])),i.shift()),i.length>0&&s.push(...i.map(a=>new l(o.INVALID_ENUM_ELEMENT,"An Enum must have only a field and optionally a setting list",a))),s.push(...this.registerField(n)),s})}validateFieldSettings(e){const n=B(e),s=n.getErrors(),i=n.getValue();for(const a in i){const r=i[a];switch(a){case"note":r.length>1&&r.forEach(c=>s.push(new l(o.DUPLICATE_ENUM_ELEMENT_SETTING,"'note' can only appear once",c))),r.forEach(c=>{C(c.value)||s.push(new l(o.INVALID_ENUM_ELEMENT_SETTING,"'note' must be a string",c))});break;default:r.forEach(c=>s.push(new l(o.UNKNOWN_ENUM_ELEMENT_SETTING,`Unknown enum field setting '${a}'`,c)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=de(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}registerField(e){if(e.callee&&W(e.callee)){const n=$(e.callee).unwrap(),s=st(n),i=this.symbolFactory.create(fn,{declaration:e});e.symbol=i;const a=this.declarationNode.symbol.symbolTable;if(a.has(s)){const r=a.get(s);return[new l(o.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,e),new l(o.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,r.declaration)]}a.set(s,i)}return[]}}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(){const e=new l(o.INVALID_INDEXES_CONTEXT,"An Indexes can only appear inside a Table or a TablePartial",this.declarationNode);if(this.declarationNode.parent instanceof Z)return[e];const n=_e(this.declarationNode.parent).unwrap_or(void 0);return n&&[I.Table,I.TablePartial].includes(n)?[]:[e]}validateName(e){return e?[new l(o.UNEXPECTED_NAME,"An Indexes shouldn't have a name",e)]:[]}validateAlias(e){return e?[new l(o.UNEXPECTED_ALIAS,"An Indexes shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new l(o.UNEXPECTED_SETTINGS,"An Indexes shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return[new l(o.UNEXPECTED_SIMPLE_BODY,"An Indexes must have a complex body",e)];const[n,s]=A.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 A.last(i)instanceof M&&s.push(...this.validateFieldSetting(i.pop())),i.forEach(a=>{for(;a instanceof Y;)a.argumentList&&!Ce(a.argumentList).isOk()&&s.push(new l(o.INVALID_INDEXES_FIELD,"An index field must be an identifier, a quoted identifier, a functional expression or a tuple of such",a.argumentList)),a=a.callee;Ce(a).isOk()||s.push(new l(o.INVALID_INDEXES_FIELD,"An index field must be an identifier, a quoted identifier, a functional expression or a tuple of such",a))}),s})}validateFieldSetting(e){const n=B(e),s=n.getErrors(),i=n.getValue();for(const a in i){const r=i[a];switch(a){case"note":case"name":r.length>1&&r.forEach(c=>s.push(new l(o.DUPLICATE_INDEX_SETTING,`'${a}' can only appear once`,c))),r.forEach(c=>{C(c.value)||s.push(new l(o.INVALID_INDEX_SETTING_VALUE,`'${a}' must be a string`,c))});break;case"unique":case"pk":r.length>1&&r.forEach(c=>s.push(new l(o.DUPLICATE_INDEX_SETTING,`'${a}' can only appear once`,c))),r.forEach(c=>{J(c.value)||s.push(new l(o.INVALID_INDEX_SETTING_VALUE,`'${a}' must not have a value`,c))});break;case"type":r.length>1&&r.forEach(c=>s.push(new l(o.DUPLICATE_INDEX_SETTING,"'type' can only appear once",c))),r.forEach(c=>{W(c.value)||s.push(new l(o.INVALID_INDEX_SETTING_VALUE,`'type' must be "btree" or "hash"`,c))});break;default:r.forEach(c=>s.push(new l(o.UNKNOWN_INDEX_SETTING,`Unknown index setting '${a}'`,c)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=de(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}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.validateBody(this.declarationNode.body)]}validateContext(){return!(this.declarationNode.parent instanceof Z)&&![I.Table,I.TableGroup,I.TablePartial,I.Project].includes(_e(this.declarationNode.parent).unwrap_or(void 0))?[new l(o.INVALID_NOTE_CONTEXT,"A Note can only appear inside a Table, a TableGroup, a TablePartial or a Project. Sticky note can only appear at the global scope.",this.declarationNode)]:[]}validateName(e){if(!(this.declarationNode.parent instanceof Z))return e?[new l(o.UNEXPECTED_NAME,"A Note shouldn't have a name",e)]:[];if(!e)return[new l(o.INVALID_NAME,"Sticky note must have a name",this.declarationNode)];const n=H(e);if(!n.isOk())return[new l(o.INVALID_NAME,"Invalid name for sticky note ",this.declarationNode)];const i=n.unwrap().join("."),a=rn(i);return this.publicSymbolTable.has(a)?[new l(o.DUPLICATE_NAME,`Sticky note "${i}" has already been defined`,e)]:(this.publicSymbolTable.set(a,this.declarationNode.symbol),[])}validateAlias(e){return e?[new l(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new l(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]=A.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){const n=[];return e.length===0?[new l(o.EMPTY_NOTE,"A Note must have a content",this.declarationNode)]:(e.length>1&&e.slice(1).forEach(s=>n.push(new l(o.NOTE_CONTENT_REDEFINED,"A Note can only contain one string",s))),C(e[0].callee)||n.push(new l(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 l(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=de(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class Cn{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 y?[new l(o.INVALID_PROJECT_CONTEXT,"A Project can only appear top-level",this.declarationNode)]:[]}validateName(e){return e?Pe(e)?[]:[new l(o.INVALID_NAME,"A Project's name is optional or must be an identifier or a quoted identifer",e)]:[]}validateAlias(e){return e?[new l(o.UNEXPECTED_ALIAS,"A Project shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new l(o.UNEXPECTED_SETTINGS,"A Project shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return[new l(o.UNEXPECTED_SIMPLE_BODY,"A Project's body must be a block",e)];const[n,s]=A.partition(e.body,i=>i instanceof w);return[...n.map(i=>new l(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=de(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class Xn{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 Z?[]:[new l(o.INVALID_REF_CONTEXT,"A Ref must appear top-level",this.declarationNode)]}validateName(e){return e?Pe(e)?[]:[new l(o.INVALID_NAME,"A Ref's name is optional or must be an identifier or a quoted identifer",e)]:[]}validateAlias(e){return e?[new l(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new l(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]=A.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){if(e.length===0)return[new l(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 l(o.REF_REDEFINED,"A Ref can only contain one binary relationship",s))),e.forEach(s=>{s.callee&&!Un(s.callee)&&n.push(new l(o.INVALID_REF_FIELD,"A Ref field must be a binary relationship",s.callee)),s.callee&&!Mn(s.callee)&&n.push(new l(o.UNEQUAL_FIELDS_BINARY_REF,"Unequal fields in ref endpoints",s.callee));const i=[...s.args];if(A.last(i)instanceof M){const a=this.validateFieldSettings(A.last(i));n.push(...a),i.pop()}else i[0]instanceof M&&(n.push(...this.validateFieldSettings(i[0])),i.shift());i.length>0&&n.push(...i.map(a=>new l(o.INVALID_REF_FIELD,"A Ref field should only have a single binary relationship",a)))}),n}validateFieldSettings(e){const n=B(e),s=n.getErrors(),i=n.getValue();for(const a in i){const r=i[a];switch(a){case"delete":case"update":r.length>1&&r.forEach(c=>s.push(new l(o.DUPLICATE_REF_SETTING,`'${a}' can only appear once`,c))),r.forEach(c=>{$n(c.value)||s.push(new l(o.INVALID_REF_SETTING_VALUE,`'${a}' can only have values "cascade", "no action", "set null", "set default" or "restrict"`,c))});break;case"color":r.length>1&&s.push(...r.map(c=>new l(o.DUPLICATE_REF_SETTING,"'color' can only appear once",c))),r.forEach(c=>{Qe(c.value)||s.push(new l(o.INVALID_REF_SETTING_VALUE,"'color' must be a color literal",c))});break;default:r.forEach(c=>s.push(new l(o.UNKNOWN_REF_SETTING,`Unknown ref setting '${a}'`,c)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=de(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}function $n(t){if(!(W(t)&&t.expression.variable.kind!==h.QUOTED_STRING)&&!(t instanceof ne))return!1;let e;if(t instanceof ne?e=we(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 jn{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 y?[new l(o.INVALID_TABLE_CONTEXT,"Table must appear top-level",this.declarationNode)]:[]}validateName(e){return e?e instanceof he?[new l(o.INVALID_NAME,"Invalid array as Table name, maybe you forget to add a space between the name and the setting list?",e)]:Mt(e)?[]:[new l(o.INVALID_NAME,"A Table name must be of the form <table> or <schema>.<table>",e)]:[new l(o.NAME_NOT_FOUND,"A Table must have a name",this.declarationNode)]}validateAlias(e){return e?Qn(e)?[]:[new l(o.INVALID_ALIAS,"Table aliases can only contains alphanumeric and underscore unless surrounded by double quotes",e)]:[]}validateSettingList(e){const n=B(e),s=n.getErrors(),i=n.getValue();for(const a in i){const r=i[a];switch(a){case"headercolor":r.length>1&&s.push(...r.map(c=>new l(o.DUPLICATE_TABLE_SETTING,"'headercolor' can only appear once",c))),r.forEach(c=>{Qe(c.value)||s.push(new l(o.INVALID_TABLE_SETTING,"'headercolor' must be a color literal",c.value||c.name))});break;case"note":r.length>1&&s.push(...r.map(c=>new l(o.DUPLICATE_TABLE_SETTING,"'note' can only appear once",c))),r.forEach(c=>{C(c.value)||s.push(new l(o.INVALID_TABLE_SETTING,"'note' must be a string literal",c.value||c.name))});break;default:s.push(...r.map(c=>new l(o.INVALID_TABLE_SETTING,`Unknown '${a}' setting`,c)))}}return s}registerElement(){const e=[];this.declarationNode.symbol=this.symbolFactory.create(Rt,{declaration:this.declarationNode,symbolTable:new ke});const{name:n,alias:s}=this.declarationNode,i=H(n);if(i.isOk()){const a=[...i.unwrap()],r=a.pop(),c=He(a,this.publicSymbolTable,this.symbolFactory),p=Ve(r);c.has(p)&&e.push(new l(o.DUPLICATE_NAME,`Table name '${r}' already exists in schema '${a.join(".")||"public"}'`,n)),c.set(p,this.declarationNode.symbol)}if(s&&Pe(s)&&!qn(s.expression.variable.value,i.unwrap_or([]))){const a=$(s).unwrap(),r=Ve(a);this.publicSymbolTable.has(r)&&e.push(new l(o.DUPLICATE_NAME,`Table name '${a}' already exists`,n)),this.publicSymbolTable.set(r,this.declarationNode.symbol)}return e}validateBody(e){if(!e)return[];if(e instanceof w)return[new l(o.UNEXPECTED_SIMPLE_BODY,"A Table's body must be a block",e)];const[n,s,i]=e.body.reduce((a,r)=>(r instanceof w?a[0].push(r):r instanceof Ae?a[1].push(r):r instanceof y&&a[2].push(r),a),[[],[],[]]);return[...this.validateFields(n),...this.validateInjections(s),...this.validateSubElements(i)]}validateInjections(e){return e.flatMap(n=>this.registerInjection(n))}registerInjection(e){var c,p,f;if(!((p=(c=e.partial)==null?void 0:c.variable)!=null&&p.value))return[];const n=(f=e.partial.variable)==null?void 0:f.value,s=Dt(n),i=this.symbolFactory.create(Nn,{declaration:e});e.symbol=i;const a=this.declarationNode.symbol.symbolTable,r=a.get(s);return r?[new l(o.DUPLICATE_TABLE_PARTIAL_INJECTION_NAME,`Duplicate injection ${n}`,e),new l(o.DUPLICATE_TABLE_PARTIAL_INJECTION_NAME,`Duplicate injection ${n}`,r.declaration)]:(a.set(s,i),[])}validateFields(e){return e.length===0?[new l(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 l(o.INVALID_COLUMN,"A column must have a type",n.callee)),W(n.callee)||s.push(new l(o.INVALID_COLUMN_NAME,"A column name must be an identifier or a quoted identifier",n.callee)),n.args[0]&&!Wn(n.args[0])&&s.push(new l(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&&W(e.callee)){const n=$(e.callee).unwrap(),s=qe(n),i=this.symbolFactory.create(ot,{declaration:e});e.symbol=i;const a=this.declarationNode.symbol.symbolTable;if(a.has(s)){const r=a.get(s);return[new l(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,e),new l(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,r.declaration)]}a.set(s,i)}return[]}validateFieldSetting(e){if(!e.slice(0,-1).every(fe)||!e.slice(-1).every(p=>fe(p)||p instanceof M))return[...e.map(p=>new l(o.INVALID_COLUMN,"These fields must be some inline settings optionally ended with a setting list",p))];if(e.length===0)return[];let n;A.last(e)instanceof M&&(n=e.pop());const s=B(n),i=s.getErrors(),a=s.getValue();for(const p of e){const f=$(p).unwrap_or("").toLowerCase();if(f!=="pk"&&f!=="unique"){i.push(new l(o.INVALID_SETTINGS,"Inline column settings can only be `pk` or `unique`",p));continue}a[f]===void 0?a[f]=[p]:a[f].push(p)}const r=a.pk||[],c=a["primary key"]||[];r.length>=1&&c.length>=1&&i.push(...[...r,...c].map(p=>new l(o.DUPLICATE_COLUMN_SETTING,"Either one of 'primary key' and 'pk' can appear",p)));for(const p in a){const f=a[p];switch(p){case"note":f.length>1&&i.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"note can only appear once",u))),f.forEach(u=>{C(u.value)||i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'note' must be a quoted string",u.value||u.name))});break;case"ref":f.forEach(u=>{Vt(u.value)||i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'ref' must be a valid unary relationship",u.value||u.name))});break;case"primary key":f.length>1&&i.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"primary key can only appear once",u))),f.forEach(u=>{J(u.value)||i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'primary key' must not have a value",u.value||u.name))});break;case"pk":f.length>1&&i.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"'pk' can only appear once",u))),f.forEach(u=>{u instanceof se&&!J(u.value)&&i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'pk' must not have a value",u.value||u.name))});break;case"not null":f.length>1&&i.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"'not null' can only appear once",u)));const d=a.null||[];f.length>=1&&d.length>=1&&i.push(...[...f,...d].map(u=>new l(o.CONFLICTING_SETTING,"'not null' and 'null' can not be set at the same time",u))),f.forEach(u=>{J(u.value)||i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'not null' must not have a value",u.value||u.name))});break;case"null":f.length>1&&i.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"'null' can only appear once",u))),f.forEach(u=>{J(u.value)||i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'null' must not have a value",u.value||u.name))});break;case"unique":f.length>1&&i.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"'unique' can only appear once",u))),f.forEach(u=>{u instanceof se&&!J(u.value)&&i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'unique' must not have a value",u.value||u.name))});break;case"increment":f.length>1&&i.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"'increment' can only appear once",u))),f.forEach(u=>{u instanceof se&&!J(u.value)&&i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'increment' must not have a value",u.value||u.name))});break;case"default":f.length>1&&i.push(...f.map(u=>new l(o.DUPLICATE_TABLE_SETTING,"'default' can only appear once",u))),f.forEach(u=>{Bt(u.value)||i.push(new l(o.INVALID_TABLE_SETTING,"'default' must be a string literal, number literal, function expression, true, false or null",u.value||u.name))});break;default:f.forEach(u=>i.push(new l(o.UNKNOWN_COLUMN_SETTING,`Unknown column setting '${p}'`,u)))}}return i}validateSubElements(e){const n=e.flatMap(i=>{if(i.parent=this.declarationNode,!i.type)return[];const a=de(i);return new a(i,this.publicSymbolTable,this.symbolFactory).validate()}),s=e.filter(i=>{var a;return((a=i.type)==null?void 0:a.value.toLowerCase())==="note"});return s.length>1&&n.push(...s.map(i=>new l(o.NOTE_REDEFINED,"Duplicate notes are defined",i))),n}}function Wn(t){if(!(t instanceof Y||ze(t)||t instanceof j||t instanceof he))return!1;if(t instanceof Y){if(t.callee===void 0||t.argumentList===void 0||!t.argumentList.elementList.every(n=>ee(n)||C(n)||fe(n)))return!1;t=t.callee}for(;t instanceof he;){if(t.array===void 0||t.indexer===void 0||!t.indexer.elementList.every(n=>!n.colon&&!n.value&&ee(n.name)))return!1;t=t.array}const e=H(t).unwrap_or(void 0);return e!==void 0&&e.length>0}function qn(t,e){return e.length===1&&t===e[0]}class Yn{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 y?[new l(o.INVALID_TABLEGROUP_CONTEXT,"TableGroup must appear top-level",this.declarationNode)]:[]}validateName(e){return e?Pe(e)?[]:[new l(o.INVALID_NAME,"A TableGroup name must be a single identifier",e)]:[new l(o.NAME_NOT_FOUND,"A TableGroup must have a name",this.declarationNode)]}validateAlias(e){return e?[new l(o.UNEXPECTED_ALIAS,"A TableGroup shouldn't have an alias",e)]:[]}registerElement(){const{name:e}=this.declarationNode;this.declarationNode.symbol=this.symbolFactory.create(pn,{declaration:this.declarationNode,symbolTable:new ke});const n=H(e);if(n.isOk()){const s=n.unwrap(),i=s.pop(),a=He(s,this.publicSymbolTable,this.symbolFactory),r=it(i);if(a.has(r))return[new l(o.DUPLICATE_NAME,`TableGroup name '${i}' already exists`,e)];a.set(r,this.declarationNode.symbol)}return[]}validateSettingList(e){const n=B(e),s=n.getErrors(),i=n.getValue();return A.forIn(i,(a,r)=>{switch(r){case"color":a.length>1&&s.push(...a.map(c=>new l(o.DUPLICATE_TABLE_SETTING,"'color' can only appear once",c))),a.forEach(c=>{Qe(c.value)||s.push(new l(o.INVALID_TABLE_SETTING,"'color' must be a color literal",c.value||c.name))});break;case"note":a.length>1&&s.push(...a.map(c=>new l(o.DUPLICATE_TABLE_SETTING,"'note' can only appear once",c))),a.filter(c=>!C(c.value)).forEach(c=>{s.push(new l(o.INVALID_TABLE_SETTING,"'note' must be a string literal",c.value||c.name))});break;default:s.push(...a.map(c=>new l(o.INVALID_TABLE_SETTING,`Unknown '${r}' setting`,c)));break}}),s}validateBody(e){if(!e)return[];if(e instanceof w)return[new l(o.UNEXPECTED_SIMPLE_BODY,"A TableGroup's body must be a block",e)];const[n,s]=A.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&&!H(n.callee).isOk()&&s.push(new l(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 l(o.INVALID_TABLEGROUP_FIELD,"A TableGroup field should only have a single Table name",i))),s})}validateSubElements(e){const n=e.flatMap(i=>{if(i.parent=this.declarationNode,!i.type)return[];const a=de(i);return new a(i,this.publicSymbolTable,this.symbolFactory).validate()}),s=e.filter(i=>{var a;return((a=i.type)==null?void 0:a.value.toLowerCase())==="note"});return s.length>1&&n.push(...s.map(i=>new l(o.NOTE_REDEFINED,"Duplicate notes are defined",i))),n}registerField(e){if(e.callee&&W(e.callee)){const n=$(e.callee).unwrap(),s=at(n),i=this.symbolFactory.create(dn,{declaration:e});e.symbol=i;const a=this.declarationNode.symbol.symbolTable;if(a.has(s)){const r=a.get(s);return[new l(o.DUPLICATE_TABLEGROUP_FIELD_NAME,`${n} already exists in the group`,e),new l(o.DUPLICATE_TABLEGROUP_FIELD_NAME,`${n} already exists in the group`,r.declaration)]}a.set(s,i)}return[]}}const lt=["-","+"];function zn(t){if(!(t instanceof Y||ze(t)||t instanceof j||t instanceof he))return!1;if(t instanceof Y){if(t.callee===void 0||t.argumentList===void 0||!t.argumentList.elementList.every(n=>ee(n)||C(n)||fe(n)))return!1;t=t.callee}for(;t instanceof he;){if(t.array===void 0||t.indexer===void 0||!t.indexer.elementList.every(n=>!n.colon&&!n.value&&ee(n.name)))return!1;t=t.array}const e=H(t).unwrap_or(void 0);return e!==void 0&&e.length>0}class Hn{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 y?[new l(o.INVALID_TABLE_PARTIAL_CONTEXT,"TablePartial must appear top-level",this.declarationNode)]:[]}validateName(e){return e?Pe(e)?[]:[new l(o.INVALID_NAME,"A TablePartial name must be an identifier or a quoted identifer",e)]:[new l(o.NAME_NOT_FOUND,"A TablePartial must have a name",this.declarationNode)]}validateAlias(e){return e?[new l(o.UNEXPECTED_ALIAS,"A TablePartial shouldn't have an alias",e)]:[]}validateSettingList(e){const n=B(e),s=n.getErrors(),i=n.getValue();return A.forIn(i,(a,r)=>{switch(r){case T.HeaderColor:a.length>1&&s.push(...a.map(c=>new l(o.DUPLICATE_TABLE_PARTIAL_SETTING,`'${r}' can only appear once`,c))),a.forEach(c=>{Qe(c.value)||s.push(new l(o.INVALID_TABLE_PARTIAL_SETTING,`'${r}' must be a color literal`,c.value||c.name))});break;case T.Note:a.length>1&&s.push(...a.map(c=>new l(o.DUPLICATE_TABLE_PARTIAL_SETTING,`'${r}' can only appear once`,c))),a.forEach(c=>{C(c.value)||s.push(new l(o.INVALID_TABLE_PARTIAL_SETTING,`'${r}' must be a string literal`,c.value||c.name))});break;default:s.push(...a.map(c=>new l(o.INVALID_TABLE_SETTING,`Unknown '${r}' setting`,c)))}}),s}registerElement(){const{name:e}=this.declarationNode;this.declarationNode.symbol=this.symbolFactory.create(En,{declaration:this.declarationNode,symbolTable:new ke});const n=H(e);if(!n.isOk())return[];const s=n.unwrap(),i=s.pop(),a=He(s,this.publicSymbolTable,this.symbolFactory),r=rt(i);return a.has(r)?[new l(o.DUPLICATE_NAME,`TablePartial name '${i}' already exists`,e)]:(a.set(r,this.declarationNode.symbol),[])}validateBody(e){if(!e)return[];if(e instanceof w)return[new l(o.UNEXPECTED_SIMPLE_BODY,"A TablePartial's body must be a block",e)];const[n,s]=A.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=[];n.args.length===0&&s.push(new l(o.INVALID_COLUMN,"A column must have a type",n.callee)),W(n.callee)||s.push(new l(o.INVALID_COLUMN_NAME,"A column name must be an identifier or a quoted identifier",n.callee)),n.args[0]&&!zn(n.args[0])&&s.push(new l(o.INVALID_COLUMN_TYPE,"Invalid column type",n.args[0]));const i=n.args.slice(1);return s.push(...this.validateFieldSetting(i),...this.registerField(n)),s})}registerField(e){if(!e.callee||!W(e.callee))return[];const n=$(e.callee).unwrap(),s=qe(n),i=this.symbolFactory.create(ot,{declaration:e});e.symbol=i;const a=this.declarationNode.symbol.symbolTable;if(a.has(s)){const r=a.get(s);return[new l(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,e),new l(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,r.declaration)]}return a.set(s,i),[]}validateFieldSetting(e){const n=A.last(e);if(!e.slice(0,-1).every(fe)||!(fe(n)||n instanceof M))return[...e.map(f=>new l(o.INVALID_COLUMN,"These fields must be some inline settings optionally ended with a setting list",f))];if(e.length===0)return[];let s;A.last(e)instanceof M&&(s=e.pop());const i=B(s),a=i.getErrors(),r=i.getValue();e.forEach(f=>{const d=$(f).unwrap_or("").toLowerCase();if(d!==T.PK&&d!==T.Unique){a.push(new l(o.INVALID_SETTINGS,"Inline column settings can only be `pk` or `unique`",f));return}r[d]===void 0?r[d]=[f]:r[d].push(f)});const c=r[T.PK]||[],p=r[T.PKey]||[];return c.length>=1&&p.length>=1&&a.push(...[...c,...p].map(f=>new l(o.DUPLICATE_COLUMN_SETTING,"Either one of 'primary key' and 'pk' can appear",f))),A.forIn(r,(f,d)=>{switch(d){case T.Note:f.length>1&&a.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,`'${d}' can only appear once`,u))),f.forEach(u=>{C(u.value)||a.push(new l(o.INVALID_COLUMN_SETTING_VALUE,`'${d}' must be a quoted string`,u.value||u.name))});break;case T.Ref:f.forEach(u=>{Vt(u.value)||a.push(new l(o.INVALID_COLUMN_SETTING_VALUE,`'${d}' must be a valid unary relationship`,u.value||u.name))});break;case T.PKey:f.length>1&&a.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,`'${d}' can only appear once`,u))),f.forEach(u=>{J(u.value)||a.push(new l(o.INVALID_COLUMN_SETTING_VALUE,`'${d}' must not have a value`,u.value||u.name))});break;case T.PK:f.length>1&&a.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,`'${d}' can only appear once`,u))),f.forEach(u=>{u instanceof se&&!J(u.value)&&a.push(new l(o.INVALID_COLUMN_SETTING_VALUE,`'${d}' must not have a value`,u.value||u.name))});break;case T.NotNull:{f.length>1&&a.push(...f.map(E=>new l(o.DUPLICATE_COLUMN_SETTING,`'${d}' can only appear once`,E)));const u=r[T.Null]||[];f.length>=1&&u.length>=1&&a.push(...[...f,...u].map(E=>new l(o.CONFLICTING_SETTING,"'not null' and 'null' can not be set at the same time",E))),f.forEach(E=>{J(E.value)||a.push(new l(o.INVALID_COLUMN_SETTING_VALUE,`'${d}' must not have a value`,E.value||E.name))});break}case T.Null:f.length>1&&a.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,`'${d}' can only appear once`,u))),f.forEach(u=>{J(u.value)||a.push(new l(o.INVALID_COLUMN_SETTING_VALUE,`'${d}' must not have a value`,u.value||u.name))});break;case T.Unique:f.length>1&&a.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,`'${d}' can only appear once`,u))),f.forEach(u=>{u instanceof se&&!J(u.value)&&a.push(new l(o.INVALID_COLUMN_SETTING_VALUE,`'${d}' must not have a value`,u.value||u.name))});break;case T.Increment:f.length>1&&a.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,`'${d}' can only appear once`,u))),f.forEach(u=>{u instanceof se&&!J(u.value)&&a.push(new l(o.INVALID_COLUMN_SETTING_VALUE,`'${d}' must not have a value`,u.value||u.name))});break;case T.Default:f.length>1&&a.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,`'${d}' can only appear once`,u))),f.forEach(u=>{Bt(u.value)||a.push(new l(o.INVALID_COLUMN_SETTING_VALUE,`'${d}' must be a string literal, number literal, function expression, true, false or null`,u.value||u.name))});break;default:f.forEach(u=>a.push(new l(o.UNKNOWN_COLUMN_SETTING,`Unknown column setting '${d}'`,u)))}}),a}validateSubElements(e){const n=e.flatMap(i=>{if(i.parent=this.declarationNode,!i.type)return[];const a=de(i);return new a(i,this.publicSymbolTable,this.symbolFactory).validate()}),s=e.filter(i=>{var a;return((a=i.type)==null?void 0:a.value.toLowerCase())===I.Note});return s.length>1&&n.push(...s.map(i=>new l(o.NOTE_REDEFINED,"Duplicate notes are defined",i))),n}}function de(t){switch(t.type.value.toLowerCase()){case I.Enum:return Bn;case I.Table:return jn;case I.TableGroup:return Yn;case I.Project:return Cn;case I.Ref:return Xn;case I.Note:return Gn;case I.Indexes:return Vn;case I.TablePartial:return Hn;default:return Fn}}function Mt(t){return!!H(t).unwrap_or(!1)}function Qn(t){return Pe(t)}function Pe(t){return t instanceof j&&t.expression instanceof re}function He(t,e,n){var i;t[0]==="public"&&(t=t.slice(1));let s=e;for(const a of t){let r;const c=tt(a);if(s.has(c)){if(r=(i=s.get(c))==null?void 0:i.symbolTable,!r)throw new Error("Expect a symbol table in a schema symbol")}else{r=new ke;const p=n.create(Ot,{symbolTable:r});s.set(c,p)}s=r}return s}function Ft(t){return t==="-"||t==="<>"||t===">"||t==="<"}function Qe(t){var n;if(!(t instanceof j)||!(t.expression instanceof ye)||((n=t.expression.literal)==null?void 0:n.kind)!==h.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(!In(e[s]))return!1;return!0}function J(t){return t===void 0}function Bt(t){var e;return!!(C(t)||ee(t)||fe(t)&&["true","false","null"].includes(t.expression.variable.value.toLowerCase())||t instanceof ae&<.includes((e=t.op)==null?void 0:e.value)&&ee(t.expression)||t instanceof ue)}function ee(t){var e;return t instanceof j&&t.expression instanceof ye&&((e=t.expression.literal)==null?void 0:e.kind)===h.NUMERIC_LITERAL}function Vt(t){var n;if(!(t instanceof ae)||!Ft((n=t.op)==null?void 0:n.value))return!1;const e=H(t.expression).unwrap_or(void 0);return e!==void 0&&e.length>0}function Gt(t){return t instanceof pe&&t.elementList.every(W)}function B(t){var s;const e={},n=[];if(!t)return new z({});for(const i of t.elementList){if(!i.name)continue;if(i.name instanceof j){n.push(new l(o.INVALID_SETTINGS,"A setting name must be a stream of identifiers",i.name));continue}const a=(s=we(i.name).unwrap_or(void 0))==null?void 0:s.toLowerCase();a&&(e[a]===void 0?e[a]=[i]:e[a].push(i))}return new z(e,n)}class Lt{constructor(e,n){this.ast=e,this.symbolFactory=n,this.publicSchemaSymbol=this.symbolFactory.create(Ot,{symbolTable:new ke}),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=de(s),a=new i(s,this.publicSchemaSymbol.symbolTable,this.symbolFactory);e.push(...a.validate())});const n=this.ast.body.filter(s=>_e(s).unwrap_or(void 0)===I.Project);return n.length>1&&n.forEach(s=>e.push(new l(o.PROJECT_REDEFINED,"Only one project can exist",s))),new z(this.ast,e)}}class Ee{constructor(e,n){this.declarationNode=e,this.errors=n}bind(){this.bindSettingList(this.declarationNode.attributeList,this.settingList),this.bindBody()}bindSettingList(e,n){e&&e.elementList.forEach(s=>{if(s.name instanceof j)return;const i=we(s.name).unwrap_or(void 0);if(!i)return;const a=n[i.toLowerCase()];a!=null&&a.shouldBind&&this.scanAndBind(s.value,a)})}bindBody(){const e=this.declarationNode;if(!e.body)return;const{body:n}=e;n instanceof oe?n.body.forEach(s=>{if(s instanceof y){if(!s.type||_e(this.declarationNode).unwrap_or(null)===I.TablePartial&&_e(s).unwrap_or(null)===I.Indexes)return;const i=Ct(s);new i(s,this.errors).bind()}else s instanceof w?this.bindSubfield(s):this.bindPartialInjection(s)}):this.bindSubfield(n)}bindSubfield(e){const n=[e.callee,...e.args],s=A.last(n);s instanceof M&&(n.pop(),this.bindSettingList(s,this.subfield.settingList));const{argBinderRules:i}=this.subfield.arg;for(let a=0;a<Math.min(n.length,i.length);a+=1)i[a].shouldBind&&this.scanAndBind(n[a],i[a])}bindPartialInjection(e){var n;(n=this.injectionBinderRule)!=null&&n.shouldBind&&this.scanAndBind(e,this.injectionBinderRule)}scanAndBind(e,n){var s,i;if(e)if(e instanceof j){if(e.expression instanceof re&&((i=n.keywords)!=null&&i.includes((s=e.expression.variable)==null?void 0:s.value.toLowerCase())))return;this.bindFragments([e],n)}else e instanceof ce?ze(e)?this.bindFragments(ge(e).unwrap_or([]),n):(this.scanAndBind(e.leftExpression,n),this.scanAndBind(e.rightExpression,n)):e instanceof ae?this.scanAndBind(e.expression,n):e instanceof We?this.scanAndBind(e.expression,n):e instanceof pe?e.elementList.forEach(a=>this.scanAndBind(a,n)):e instanceof Ae&&this.bindFragments([e],n)}bindFragments(e,n){if(e.length===0)return;const s=e.length===1&&e[0]instanceof Ae,i=[...n.topSubnamesSymbolKind],{remainingSubnamesSymbolKind:a}=n,r=s?-1:e.findIndex(E=>!W(E)),p=r!==-1&&Gt(e[r])?e[r]:void 0,f=r>=0?i.pop():void 0,d=e.slice(0,r===-1?void 0:r);if(d.length===0)return;const u=[];for(;i.length&&d.length;){const E=i.pop(),L=d.pop(),v=$(L).unwrap();u.unshift({index:Fe(v,E),referrer:L})}for(;d.length;){const E=d.pop(),L=s?Rn(E).unwrap():$(E).unwrap();u.unshift({index:Fe(L,a),referrer:E})}return p?p.elementList.forEach(E=>this.resolveIndexStack([...u,{index:Fe($(E).unwrap(),f),referrer:E}],n.ignoreNameNotFound)):this.resolveIndexStack(u,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,a=It(s.index,this.declarationNode);if(a===void 0){const{kind:f,name:d}=le(s.index).unwrap();this.logError(s.referrer,`Can not find ${f} '${d}'`,n);return}a.references.push(s.referrer),s.referrer.referee=a;let r=a.symbolTable,{kind:c,name:p}=le(s.index).unwrap();for(const f of i){const{kind:d,name:u}=le(f.index).unwrap(),E=r.get(f.index);if(!E){this.logError(f.referrer,`${c} '${p}' does not have ${d} '${u}'`,n);return}if(c=d,p=u,f.referrer.referee=E,E.references.push(f.referrer),!E.symbolTable)break;r=E.symbolTable}}logError(e,n,s){s||this.errors.push(new l(o.BINDING_ERROR,n,e))}resolveInjections(e){var i;const n=(i=this.declarationNode.symbol)==null?void 0:i.symbolTable;if(!n)return;const s=new Map;n.forEach((a,r)=>{var f,d;if(!ln(r))return;const c=It(cn(r),this.declarationNode),p=(d=(f=c==null?void 0:c.declaration)==null?void 0:f.symbol)==null?void 0:d.symbolTable;p&&p.forEach((u,E)=>{n.has(E)||s.set(E,{injectorFieldSymbol:u,injectorDeclaration:a.declaration})})}),s.forEach((a,r)=>{const c=bn(a.injectorFieldSymbol);if(!c)return;const p=e.create(c,a);n.set(r,p)})}}class Jn extends Ee{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Kn extends Ee{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Zn extends Ee{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 es extends Ee{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class ts extends Ee{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class ns extends Ee{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class ss extends Ee{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={},this.injectionBinderRule={shouldBind:!0,topSubnamesSymbolKind:[],remainingSubnamesSymbolKind:m.TablePartial,ignoreNameNotFound:!1}}}class is extends Ee{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class as extends Ee{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={}}}function Ct(t){switch(t.type.value.toLowerCase()){case I.Enum:return Kn;case I.Table:return ss;case I.TableGroup:return is;case I.Project:return ts;case I.Ref:return ns;case I.Note:return es;case I.Indexes:return Zn;case I.TablePartial:return as;default:return Jn}}class rs{constructor(e){this.ast=e,this.errors=[]}resolve(e){return this.ast.body.map(n=>{if(!n.type)return null;const s=Ct(n),i=new s(n,this.errors);return i.resolveInjections(e),i}).forEach(n=>n==null?void 0:n.bind()),new z(this.ast,this.errors)}}class os{constructor(e){this.generator=e}create(e,n){return new e(n,this.generator.nextId())}}class ls{constructor(e,n){this.ast=e,this.symbolFactory=new os(n)}analyze(){return new Lt(this.ast,this.symbolFactory).validate().chain(n=>new rs(n).resolve(this.symbolFactory))}validate(){return new Lt(this.ast,this.symbolFactory).validate().chain(n=>new z(n,[]))}}function At(t,e){const{variables:n,tupleElements:s}=xe(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 Xt(t){switch(t){case"<":return["1","*"];case"<>":return["*","*"];case">":return["*","1"];case"-":return["1","1"]}throw new Error("Invalid relation op")}function g(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 Xe(t){var n;const e=(n=ge(t).unwrap_or(void 0))==null?void 0:n.pop();return e instanceof pe?e.elementList.map(s=>s.referee):[e.referee]}function be(t){const e=H(t).unwrap();return{name:e.pop(),schemaName:e}}function Oe(t){return t.expression.literal.value}function $t(t,e){if(Array.isArray(t)){const i=t.map(({id:r})=>r).sort().join(","),a=e.map(({id:r})=>r).sort().join(",");return i<a?`${i}-${a}`:`${a}-${i}`}const n=t.id.toString(),s=e.id.toString();return n<s?`${n}-${s}`:`${s}-${n}`}function ct(t,e){if(Array.isArray(t)){const i=t.map(({id:r})=>r).sort(),a=e.map(({id:r})=>r).sort();return A.zip(i,a).every(([r,c])=>r===c)}const n=t.id,s=e.id;return n===s}function ie(t){const e=t.split(`
|
|
9
|
+
`;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" ":return"\\ ";case"u":{let n="";for(let s=0;s<=3;s+=1){if(this.isAtEnd()||!ve(this.peek()))return this.errors.push(new l(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`,J.create(h.STRING_LITERAL,e,this.current,`\\u${n}`,!0))),`\\u${n}`;n+=this.advance()}return String.fromCharCode(parseInt(n,16))}default:return this.text[this.current.offset-1]}}}var Be=(t=>(t[t.ListExpression=0]="ListExpression",t[t.GroupExpression=1]="GroupExpression",t[t.BlockExpression=2]="BlockExpression",t))(Be||{});class Pn{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 A.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 h.COMMA:if(this.isWithinGroupExpressionContext()||this.isWithinListExpressionContext())return[...this.stack].reverse().find(a=>[1,0].includes(a));break;case h.RPAREN:if(this.isWithinGroupExpressionContext())return 1;break;case h.RBRACE:if(this.isWithinBlockExpressionContext())return 2;break;case h.RBRACKET:if(this.isWithinListExpressionContext())return 0;break}}}class kn{constructor(e){this.generator=e}create(e,n){return new e(n,this.generator.nextId())}}class T{constructor(e,n,s){this.token=e,this.partialNode=n,this.handlerContext=s}}class Sn{constructor(e,n){this.current=0,this.errors=[],this.contextStack=new Pn,this.synchronizeProgram=()=>{const s=this.peek();s.kind!==h.EOF?b(this.advance()):(b(this.peek()),this.logError(s,o.UNEXPECTED_EOF,"Unexpected EOF"))},this.synchronizeElementDeclarationName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(Nt(s)||this.check(h.COLON,h.LBRACE,h.LBRACKET))break;b(s),this.advance()}},this.synchronizeElementDeclarationAlias=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(h.COLON,h.LBRACE,h.LBRACKET))break;b(s),this.advance()}},this.blockExpression=this.contextStack.withContextDo(Be.BlockExpression,()=>{const s={body:[]},i=()=>this.nodeFactory.create(ae,s);try{this.consume("Expect an opening brace '{'",h.LBRACE),s.blockOpenBrace=this.previous()}catch(a){if(!(a instanceof T))throw a;if(s.blockOpenBrace=a.partialNode,!this.canHandle(a))throw new T(a.token,i(),a.handlerContext);this.synchronizeBlock()}for(;!this.isAtEnd()&&!this.check(h.RBRACE);)try{if(this.match(h.TILDE)){const a=this.previous(),r=this.variable(),c=this.nodeFactory.create(Le,{op:a,partial:r});s.body.push(c)}else s.body.push(this.canBeField()?this.fieldDeclaration():this.expression())}catch(a){if(!(a instanceof T))throw a;if(s.body.push(a.partialNode),!this.canHandle(a))throw new T(a.token,i(),a.handlerContext);this.synchronizeBlock()}try{this.consume("Expect a closing brace '}'",h.RBRACE),s.blockCloseBrace=this.previous()}catch(a){if(!(a instanceof T))throw a;if(s.blockCloseBrace=a.partialNode,!this.canHandle(a))throw new T(a.token,i(),a.handlerContext);this.synchronizeBlock()}return i()}),this.synchronizeBlock=()=>{if(!this.check(h.RBRACE))for(b(this.advance());!this.isAtEnd();){const s=this.peek();if(this.check(h.RBRACE)||dt(this.previous(),s))break;b(s),this.advance()}},this.tupleExpression=this.contextStack.withContextDo(Be.GroupExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(et,{groupOpenParen:s.tupleOpenParen,groupCloseParen:s.tupleCloseParen,expression:s.elementList[0]}),a=()=>this.nodeFactory.create(ce,s);try{this.consume("Expect an opening parenthesis '('",h.LPAREN),s.tupleOpenParen=this.previous()}catch(r){if(!(r instanceof T))throw r;if(s.tupleOpenParen=r.partialNode,!this.canHandle(r))throw new T(r.token,a(),r.handlerContext);this.synchronizeTuple()}if(!this.isAtEnd()&&!this.check(h.RPAREN))try{s.elementList.push(this.normalExpression())}catch(r){if(!(r instanceof T))throw r;if(s.elementList.push(r.partialNode),!this.canHandle(r))throw new T(r.token,i(),r.handlerContext);this.synchronizeTuple()}for(;!this.isAtEnd()&&!this.check(h.RPAREN);)try{this.consume("Expect a comma ','",h.COMMA),s.commaList.push(this.previous()),s.elementList.push(this.normalExpression())}catch(r){if(!(r instanceof T))throw r;if(r.partialNode instanceof O&&s.elementList.push(r.partialNode),!this.canHandle(r))throw new T(r.token,a(),r.handlerContext);this.synchronizeTuple()}try{this.consume("Expect a closing parenthesis ')'",h.RPAREN),s.tupleCloseParen=this.previous()}catch(r){if(!(r instanceof T))throw r;if(s.tupleCloseParen=r.partialNode,!this.canHandle(r))throw new T(r.token,a(),r.handlerContext);this.synchronizeTuple()}return s.elementList.length===1?i():a()}),this.synchronizeTuple=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(h.RPAREN,h.COMMA))break;b(s),this.advance()}},this.listExpression=this.contextStack.withContextDo(Be.ListExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(M,s);try{this.consume("Expect an opening bracket '['",h.LBRACKET),s.listOpenBracket=this.previous()}catch(a){if(!(a instanceof T))throw a;if(s.listOpenBracket=a.partialNode,!this.canHandle(a))throw new T(a.token,i(),a.handlerContext);this.synchronizeList()}if(!this.isAtEnd()&&!this.check(h.RBRACKET))try{s.elementList.push(this.attribute())}catch(a){if(!(a instanceof T))throw a;if(s.elementList.push(a.partialNode),!this.canHandle(a))throw new T(a.token,i(),a.handlerContext);this.synchronizeList()}for(;!this.isAtEnd()&&!this.check(h.RBRACKET);)try{this.consume("Expect a comma ','",h.COMMA),s.commaList.push(this.previous()),s.elementList.push(this.attribute())}catch(a){if(!(a instanceof T))throw a;if(a.partialNode instanceof O&&s.elementList.push(a.partialNode),!this.canHandle(a))throw new T(a.token,i(),a.handlerContext);this.synchronizeList()}try{this.consume("Expect a closing bracket ']'",h.RBRACKET),s.listCloseBracket=this.previous()}catch(a){if(!(a instanceof T))throw a;if(s.listCloseBracket=a.partialNode,!this.canHandle(a))throw new T(a.token,i(),a.handlerContext);this.synchronizeList()}return i()}),this.synchronizeList=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(h.COMMA,h.RBRACKET))break;b(s),this.advance()}},this.synchronizeAttributeName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(h.COMMA,h.RBRACKET,h.COLON))break;b(s),this.advance()}},this.synchronizeAttributeValue=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(h.COMMA,h.RBRACKET))break;b(s),this.advance()}},this.tokens=e,this.nodeFactory=new kn(n)}isAtEnd(){return this.current>=this.tokens.length||this.tokens[this.current].kind===h.EOF}advance(){return this.isAtEnd()?A.last(this.tokens):this.tokens[this.current++]}peek(e=0){return e+this.current>=this.tokens.length?A.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 T(this.peek(),void 0,this.contextStack.findHandlerContext(this.tokens,this.current))}discardUntil(e,...n){if(this.isAtEnd()||!this.check(...n)){for(b(this.peek()),this.logError(this.advance(),o.UNEXPECTED_TOKEN,e);!this.isAtEnd()&&!this.check(...n);)b(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 a=this.tokens[i];a.isInvalid?s.trailingInvalid.push(a):(s=a,e.push(s))}this.tokens=e}parse(){const e=this.program(),n=this.advance(),s=this.nodeFactory.create(Z,{body:e,eof:n});return this.gatherInvalid(),new K({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 T))throw n;e.push(n.partialNode),this.synchronizeProgram()}return e}elementDeclaration(){const e={},n=()=>this.nodeFactory.create(y,e);try{this.consume("Expect an identifier",h.IDENTIFIER),e.type=this.previous()}catch(s){throw s instanceof T?(e.type=s.partialNode,new T(s.token,n(),s.handlerContext)):s}if(!this.check(h.COLON,h.LBRACE,h.LBRACKET))try{e.name=this.normalExpression()}catch(s){if(!(s instanceof T))throw s;if(e.name=s.partialNode,!this.canHandle(s))throw new T(s.token,n(),s.handlerContext);this.synchronizeElementDeclarationName()}if(Nt(this.peek()))if(e.as=this.advance(),this.check(h.COLON,h.LBRACE,h.LBRACKET))this.logError(this.peek(),o.UNEXPECTED_TOKEN,"Expect an alias");else try{e.alias=this.normalExpression()}catch(s){if(!(s instanceof T))throw s;if(e.alias=s.partialNode,!this.canHandle(s))throw new T(s.token,n(),s.handlerContext);this.synchronizeElementDeclarationAlias()}try{e.attributeList=this.check(h.LBRACKET)?this.listExpression():void 0}catch(s){throw s instanceof T?(e.attributeList=s.partialNode,new T(s.token,n(),s.handlerContext)):s}if(!this.discardUntil("Expect an opening brace '{' or a colon ':'",h.LBRACE,h.COLON))return n();try{if(this.match(h.COLON)){e.bodyColon=this.previous();const s=this.expression();s instanceof y?(b(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 T?(e.body=s.partialNode,new T(s.token,n(),s.handlerContext)):s}return this.nodeFactory.create(y,e)}fieldDeclaration(){const e={},n=()=>this.nodeFactory.create(y,e);try{this.consume("Expect an identifier",h.IDENTIFIER),e.type=this.previous()}catch(s){throw s instanceof T?(e.type=s.partialNode,new T(s.token,n(),s.handlerContext)):s}try{this.consume("Expect a colon ':'",h.COLON),e.bodyColon=this.previous()}catch(s){throw s instanceof T?(e.bodyColon=s.partialNode,new T(s.token,n(),s.handlerContext)):s}try{const s=this.expression();s instanceof y?this.errors.push(new l(o.INVALID_ELEMENT_IN_SIMPLE_BODY,"Simple body cannot be an element declaration",s)):e.body=s}catch(s){throw s instanceof T?(e.body=s.partialNode,new T(s.token,n(),s.handlerContext)):s}return this.nodeFactory.create(y,e)}expression(){const e={args:[]},n=()=>_n(e.callee,e.args,this.nodeFactory).unwrap_or(this.nodeFactory.create(w,e));try{e.callee=this.normalExpression()}catch(i){throw i instanceof T?(e.callee=i.partialNode,new T(i.token,n(),i.handlerContext)):i}if(this.shouldStopExpression())return n();let s=e.callee;for(;!this.shouldStopExpression();){Ze(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 T?(s=i.partialNode,e.args.push(s),new T(i.token,n(),i.handlerContext)):i}}return n()}shouldStopExpression(){if(this.isAtEnd()||yt(this.previous()))return!0;const e=this.peek().kind;return e===h.RBRACE||e===h.RBRACKET||e===h.RPAREN||e===h.COMMA||e===h.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===h.LPAREN){const{left:i}=Tt(s);if(i<e||dt(this.previous(),s)&&!this.contextStack.isWithinGroupExpressionContext()&&!this.contextStack.isWithinListExpressionContext())break;try{n=this.nodeFactory.create(z,{callee:n,argumentList:this.tupleExpression()})}catch(a){throw a instanceof T?(n=this.nodeFactory.create(z,{callee:n,argumentList:a.partialNode}),new T(a.token,n,a.handlerContext)):a}}else if(s.kind===h.LBRACKET){if(Ze(this.previous()))break;try{n=this.nodeFactory.create(he,{expression:n,indexer:this.listExpression()})}catch(i){throw i instanceof T?(n=this.nodeFactory.create(he,{expression:n,indexer:i.partialNode}),new T(i.token,n,i.handlerContext)):i}}else if(pt(s)){const i=s,a=Tt(i);if(a.left!==null){if(a.left<=e)break;this.advance(),n=this.nodeFactory.create(We,{expression:n,op:i})}else{const r=On(i);if(r.left===null||r.left<=e)break;this.advance();try{n=this.nodeFactory.create(le,{leftExpression:n,op:i,rightExpression:i.value==="."?this.extractOperand():this.expression_bp(r.right)})}catch(c){throw c instanceof T?(n=this.nodeFactory.create(le,{leftExpression:n,op:i,rightExpression:c.partialNode}),new T(c.token,n,c.handlerContext)):c}}}else break}return n}leftExpression_bp(){let e;if(pt(this.peek())){const n={};n.op=this.peek();const s=Rn(n.op);if(s.right===null)throw this.logError(n.op,o.UNKNOWN_PREFIX_OP,`Unexpected '${n.op.value}' in an expression`),new T(n.op,this.nodeFactory.create(Me,{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 T?(n.expression=i.partialNode,new T(i.token,this.nodeFactory.create(oe,n),i.handlerContext)):i}e=this.nodeFactory.create(oe,n)}else if(e=this.extractOperand(),e instanceof Me)throw new T(this.peek(),this.nodeFactory.create(Me,{pre:this.peek()}),this.contextStack.findHandlerContext(this.tokens,this.current));return e}extractOperand(){return this.check(h.NUMERIC_LITERAL,h.STRING_LITERAL,h.COLOR_LITERAL,h.QUOTED_STRING,h.IDENTIFIER)?this.primaryExpression():this.check(h.FUNCTION_EXPRESSION)?this.functionExpression():this.check(h.LBRACKET)?this.listExpression():this.check(h.LBRACE)?this.blockExpression():this.check(h.LPAREN)?this.tupleExpression():(this.peek().kind===h.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(Me,{pre:this.previous()}))}functionExpression(){const e={};try{this.consume("Expect a function expression",h.FUNCTION_EXPRESSION),e.value=this.previous()}catch(n){throw n instanceof T?(e.value=n.partialNode,new T(n.token,this.nodeFactory.create(ue,e),n.handlerContext)):n}return this.nodeFactory.create(ue,e)}variable(){this.consume("Expect a variable",h.IDENTIFIER);const e=this.previous();return this.nodeFactory.create(ie,{variable:e})}canBeField(){return this.peek().kind===h.IDENTIFIER&&this.peek(1).kind===h.COLON}primaryExpression(){if(this.match(h.COLOR_LITERAL,h.STRING_LITERAL,h.NUMERIC_LITERAL))return this.nodeFactory.create($,{expression:this.nodeFactory.create(ye,{literal:this.previous()})});if(this.match(h.QUOTED_STRING,h.IDENTIFIER))return this.nodeFactory.create($,{expression:this.nodeFactory.create(ie,{variable:this.previous()})});throw this.logError(this.peek(),o.UNEXPECTED_TOKEN,"Expect a variable or literal"),new T(this.peek(),void 0,this.contextStack.findHandlerContext(this.tokens,this.current))}attribute(){const e={};if(this.check(h.COLON,h.RBRACKET,h.COMMA)){const n=this.peek();this.logError(n,o.EMPTY_ATTRIBUTE_NAME,"Expect a non-empty attribute name"),e.name=this.nodeFactory.create(te,{identifiers:[]})}else try{e.name=this.attributeName()}catch(n){if(!(n instanceof T))throw n;if(e.name=n.partialNode,!this.canHandle(n))throw new T(n.token,this.nodeFactory.create(ne,e),n.handlerContext);this.synchronizeAttributeName()}return this.match(h.COLON)&&(e.colon=this.previous(),e.value=this.attributeValue()),this.nodeFactory.create(ne,e)}attributeValue(){let e;try{e=this.peek().kind===h.IDENTIFIER&&this.peek(1).kind===h.IDENTIFIER?this.attributeName():this.normalExpression()}catch(n){if(!(n instanceof T)||!this.canHandle(n))throw n;e=n.partialNode,this.synchronizeAttributeValue()}return e}attributeName(){const e=[];if(this.peek().kind!==h.IDENTIFIER)return this.primaryExpression();for(;!this.isAtEnd()&&!this.check(h.COLON,h.COMMA,h.RBRACKET);)try{this.consume("Expect an identifier",h.IDENTIFIER),e.push(this.previous())}catch(n){throw n instanceof T?new T(n.token,this.nodeFactory.create(te,{identifiers:e}),n.handlerContext):n}return this.nodeFactory.create(te,{identifiers:e})}logError(e,n,s){this.errors.push(new l(n,s,e))}}const Dn={"+":{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 On(t){return Dn[t.value]||{left:null,right:null}}const xn={"+":{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 Rn(t){return xn[t.value]||{left:null,right:null}}const Un={"(":{left:14,right:null}};function Tt(t){return Un[t.value]||{left:null,right:null}}var I=(t=>(t.Table="table",t.Enum="enum",t.Ref="ref",t.Note="note",t.Project="project",t.Indexes="indexes",t.TableGroup="tablegroup",t.TablePartial="tablepartial",t))(I||{}),N=(t=>(t.Color="color",t.HeaderColor="headercolor",t.Note="note",t.PK="pk",t.PKey="primary key",t.Unique="unique",t.Ref="ref",t.NotNull="not null",t.Null="null",t.Increment="increment",t.Default="default",t.Name="name",t.Type="type",t.Update="update",t.Delete="delete",t))(N||{});function Ae(t){var n;const e=(n=t==null?void 0:t.type)==null?void 0:n.value.toLowerCase();switch(e){case I.Enum:case I.Table:case I.Indexes:case I.Note:case I.Project:case I.Ref:case I.TableGroup:case I.TablePartial:return new U(e);default:return new S}}function _e(t){if(!ze(t))return new U([t]);const e=_e(t.leftExpression).unwrap_or(void 0);return e?(e.push(t.rightExpression),new U(e)):new S}function q(t){if(t===void 0)return new S;const e=_e(t).unwrap_or(void 0);if(!e)return new S;const n=[];for(const s of e){const i=Y(s).unwrap_or(void 0);if(!i)return new S;n.push(i)}return new U(n)}function De(t){if(t===void 0)return new S;const e=_e(t).unwrap_or(void 0);if(!e||e.length===0)return new S;const n=[];let s;if(!j(A.last(e))){const i=e.pop();if(Gt(i))s=i.elementList.map(a=>X(a).unwrap());else return new S}for(const i of e){const a=Y(i).unwrap_or(void 0);if(!a)return new S;n.push(a)}return new U({variables:n,tupleElements:s})}function Y(t){return j(t)?new U(t.expression.variable.value):new S}function Ce(t){if(mt(t))return t instanceof ue?new U({functional:[t],nonFunctional:[]}):new U({functional:[],nonFunctional:[t]});if(t instanceof ce&&t.elementList.every(mt)){const e=t.elementList.filter(s=>s instanceof ue),n=t.elementList.filter(j);return new U({functional:e,nonFunctional:n})}return new S}function X(t){var n;const e=(n=t==null?void 0:t.expression.variable)==null?void 0:n.value;return e===void 0?new S:new U(e)}function Mn(t){var n,s;const e=(s=(n=t==null?void 0:t.partial)==null?void 0:n.variable)==null?void 0:s.value;return e===void 0?new S:new U(e)}function V(t){return W(t)?t.expression instanceof ie?new U(t.expression.variable.value):new U(t.expression.literal.value):new S}function Fn(t){var e;return!(t instanceof le)||!Ft((e=t.op)==null?void 0:e.value)?!1:De(t.leftExpression).and_then(()=>De(t.rightExpression)).unwrap_or(void 0)!==void 0}function Bn(t){const e=De(t.leftExpression),n=De(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 mt(t){return t instanceof $&&t.expression instanceof ie||t instanceof ue}function bt(t,e){var i,a,r,c;let n=e;const s=cn(t);for(;n;){if((a=(i=n.symbol)==null?void 0:i.symbolTable)!=null&&a.has(t))return(r=n.symbol.symbolTable)==null?void 0:r.get(t);if(((c=n.symbol)==null?void 0:c.declaration)instanceof Z&&s)return n.symbol;if(n instanceof Z)return;n=n.parent}}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 Z||Ae(this.declarationNode.parent).unwrap_or(void 0)!==I.Project?[new l(o.INVALID_CUSTOM_CONTEXT,"A custom element can only appear in a Project",this.declarationNode)]:[]}validateName(e){return e?[new l(o.UNEXPECTED_NAME,"A Custom element shouldn't have a name",e)]:[]}validateAlias(e){return e?[new l(o.UNEXPECTED_NAME,"A Custom element shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new l(o.UNEXPECTED_SETTINGS,"A Custom element shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof ae)return[new l(o.UNEXPECTED_COMPLEX_BODY,"A Custom element can only have an inline field",e)];const n=[];return W(e.callee)||n.push(new l(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 l(o.INVALID_CUSTOM_ELEMENT_VALUE,"A Custom element value can only be a string",s))),n}}class Pe{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()}forEach(e){return this.table.forEach(e)}}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 y?[new l(o.INVALID_PROJECT_CONTEXT,"An Enum can only appear top-level",this.declarationNode)]:[]}validateName(e){return e?Mt(e)?[]:[new l(o.INVALID_NAME,"An Enum name must be of the form <enum> or <schema>.<enum>",e)]:[new l(o.NAME_NOT_FOUND,"An Enum must have a name",this.declarationNode)]}validateAlias(e){return e?[new l(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}registerElement(){const e=[];this.declarationNode.symbol=this.symbolFactory.create(pn,{declaration:this.declarationNode,symbolTable:new Pe});const{name:n}=this.declarationNode,s=q(n);if(s.isOk()){const i=s.unwrap(),a=i.pop(),r=He(i,this.publicSymbolTable,this.symbolFactory),c=nt(a);r.has(c)&&e.push(new l(o.DUPLICATE_NAME,`Enum name ${a} already exists in schema '${i.join(".")||"public"}'`,n)),r.set(c,this.declarationNode.symbol)}return e}validateSettingList(e){return e?[new l(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]=A.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.length===0?[new l(o.EMPTY_ENUM,"An Enum must have at least one element",this.declarationNode)]:e.flatMap(n=>{const s=[];n.callee&&!j(n.callee)&&s.push(new l(o.INVALID_ENUM_ELEMENT_NAME,"An enum field must be an identifier or a quoted identifier",n.callee));const i=[...n.args];return A.last(i)instanceof M?(s.push(...this.validateFieldSettings(A.last(i))),i.pop()):i[0]instanceof M&&(s.push(...this.validateFieldSettings(i[0])),i.shift()),i.length>0&&s.push(...i.map(a=>new l(o.INVALID_ENUM_ELEMENT,"An Enum must have only a field and optionally a setting list",a))),s.push(...this.registerField(n)),s})}validateFieldSettings(e){const n=F(e),s=n.getErrors(),i=n.getValue();for(const a in i){const r=i[a];switch(a){case"note":r.length>1&&r.forEach(c=>s.push(new l(o.DUPLICATE_ENUM_ELEMENT_SETTING,"'note' can only appear once",c))),r.forEach(c=>{W(c.value)||s.push(new l(o.INVALID_ENUM_ELEMENT_SETTING,"'note' must be a string",c))});break;default:r.forEach(c=>s.push(new l(o.UNKNOWN_ENUM_ELEMENT_SETTING,`Unknown enum field setting '${a}'`,c)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=de(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}registerField(e){if(e.callee&&j(e.callee)){const n=X(e.callee).unwrap(),s=st(n),i=this.symbolFactory.create(dn,{declaration:e});e.symbol=i;const a=this.declarationNode.symbol.symbolTable;if(a.has(s)){const r=a.get(s);return[new l(o.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,e),new l(o.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,r.declaration)]}a.set(s,i)}return[]}}class Cn{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(){const e=new l(o.INVALID_INDEXES_CONTEXT,"An Indexes can only appear inside a Table or a TablePartial",this.declarationNode);if(this.declarationNode.parent instanceof Z)return[e];const n=Ae(this.declarationNode.parent).unwrap_or(void 0);return n&&[I.Table,I.TablePartial].includes(n)?[]:[e]}validateName(e){return e?[new l(o.UNEXPECTED_NAME,"An Indexes shouldn't have a name",e)]:[]}validateAlias(e){return e?[new l(o.UNEXPECTED_ALIAS,"An Indexes shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new l(o.UNEXPECTED_SETTINGS,"An Indexes shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return[new l(o.UNEXPECTED_SIMPLE_BODY,"An Indexes must have a complex body",e)];const[n,s]=A.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 A.last(i)instanceof M&&s.push(...this.validateFieldSetting(i.pop())),i.forEach(a=>{for(;a instanceof z;)a.argumentList&&!Ce(a.argumentList).isOk()&&s.push(new l(o.INVALID_INDEXES_FIELD,"An index field must be an identifier, a quoted identifier, a functional expression or a tuple of such",a.argumentList)),a=a.callee;Ce(a).isOk()||s.push(new l(o.INVALID_INDEXES_FIELD,"An index field must be an identifier, a quoted identifier, a functional expression or a tuple of such",a))}),s})}validateFieldSetting(e){const n=F(e),s=n.getErrors(),i=n.getValue();for(const a in i){const r=i[a];switch(a){case"note":case"name":r.length>1&&r.forEach(c=>s.push(new l(o.DUPLICATE_INDEX_SETTING,`'${a}' can only appear once`,c))),r.forEach(c=>{W(c.value)||s.push(new l(o.INVALID_INDEX_SETTING_VALUE,`'${a}' must be a string`,c))});break;case"unique":case"pk":r.length>1&&r.forEach(c=>s.push(new l(o.DUPLICATE_INDEX_SETTING,`'${a}' can only appear once`,c))),r.forEach(c=>{Q(c.value)||s.push(new l(o.INVALID_INDEX_SETTING_VALUE,`'${a}' must not have a value`,c))});break;case"type":r.length>1&&r.forEach(c=>s.push(new l(o.DUPLICATE_INDEX_SETTING,"'type' can only appear once",c))),r.forEach(c=>{j(c.value)||s.push(new l(o.INVALID_INDEX_SETTING_VALUE,`'type' must be "btree" or "hash"`,c))});break;default:r.forEach(c=>s.push(new l(o.UNKNOWN_INDEX_SETTING,`Unknown index setting '${a}'`,c)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=de(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class Xn{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 Z)&&![I.Table,I.TableGroup,I.TablePartial,I.Project].includes(Ae(this.declarationNode.parent).unwrap_or(void 0))?[new l(o.INVALID_NOTE_CONTEXT,"A Note can only appear inside a Table, a TableGroup, a TablePartial or a Project. Sticky note can only appear at the global scope.",this.declarationNode)]:[]}validateName(e){if(!(this.declarationNode.parent instanceof Z))return e?[new l(o.UNEXPECTED_NAME,"A Note shouldn't have a name",e)]:[];if(!e)return[new l(o.INVALID_NAME,"Sticky note must have a name",this.declarationNode)];const n=q(e);if(!n.isOk())return[new l(o.INVALID_NAME,"Invalid name for sticky note ",this.declarationNode)];const i=n.unwrap().join("."),a=ln(i);return this.publicSymbolTable.has(a)?[new l(o.DUPLICATE_NAME,`Sticky note "${i}" has already been defined`,e)]:(this.publicSymbolTable.set(a,this.declarationNode.symbol),[])}validateAlias(e){return e?[new l(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new l(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]=A.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){const n=[];return e.length===0?[new l(o.EMPTY_NOTE,"A Note must have a content",this.declarationNode)]:(e.length>1&&e.slice(1).forEach(s=>n.push(new l(o.NOTE_CONTENT_REDEFINED,"A Note can only contain one string",s))),W(e[0].callee)||n.push(new l(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 l(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=de(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}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 y?[new l(o.INVALID_PROJECT_CONTEXT,"A Project can only appear top-level",this.declarationNode)]:[]}validateName(e){return e?ke(e)?[]:[new l(o.INVALID_NAME,"A Project's name is optional or must be an identifier or a quoted identifer",e)]:[]}validateAlias(e){return e?[new l(o.UNEXPECTED_ALIAS,"A Project shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new l(o.UNEXPECTED_SETTINGS,"A Project shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return[new l(o.UNEXPECTED_SIMPLE_BODY,"A Project's body must be a block",e)];const[n,s]=A.partition(e.body,i=>i instanceof w);return[...n.map(i=>new l(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=de(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class jn{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 Z?[]:[new l(o.INVALID_REF_CONTEXT,"A Ref must appear top-level",this.declarationNode)]}validateName(e){return e?ke(e)?[]:[new l(o.INVALID_NAME,"A Ref's name is optional or must be an identifier or a quoted identifer",e)]:[]}validateAlias(e){return e?[new l(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new l(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]=A.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){if(e.length===0)return[new l(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 l(o.REF_REDEFINED,"A Ref can only contain one binary relationship",s))),e.forEach(s=>{s.callee&&!Fn(s.callee)&&n.push(new l(o.INVALID_REF_FIELD,"A Ref field must be a binary relationship",s.callee)),s.callee&&!Bn(s.callee)&&n.push(new l(o.UNEQUAL_FIELDS_BINARY_REF,"Unequal fields in ref endpoints",s.callee));const i=[...s.args];if(A.last(i)instanceof M){const a=this.validateFieldSettings(A.last(i));n.push(...a),i.pop()}else i[0]instanceof M&&(n.push(...this.validateFieldSettings(i[0])),i.shift());i.length>0&&n.push(...i.map(a=>new l(o.INVALID_REF_FIELD,"A Ref field should only have a single binary relationship",a)))}),n}validateFieldSettings(e){const n=F(e),s=n.getErrors(),i=n.getValue();for(const a in i){const r=i[a];switch(a){case"delete":case"update":r.length>1&&r.forEach(c=>s.push(new l(o.DUPLICATE_REF_SETTING,`'${a}' can only appear once`,c))),r.forEach(c=>{Wn(c.value)||s.push(new l(o.INVALID_REF_SETTING_VALUE,`'${a}' can only have values "cascade", "no action", "set null", "set default" or "restrict"`,c))});break;case"color":r.length>1&&s.push(...r.map(c=>new l(o.DUPLICATE_REF_SETTING,"'color' can only appear once",c))),r.forEach(c=>{Qe(c.value)||s.push(new l(o.INVALID_REF_SETTING_VALUE,"'color' must be a color literal",c))});break;default:r.forEach(c=>s.push(new l(o.UNKNOWN_REF_SETTING,`Unknown ref setting '${a}'`,c)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=de(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}function Wn(t){if(!(j(t)&&t.expression.variable.kind!==h.QUOTED_STRING)&&!(t instanceof te))return!1;let e;if(t instanceof te?e=we(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 qn{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 y?[new l(o.INVALID_TABLE_CONTEXT,"Table must appear top-level",this.declarationNode)]:[]}validateName(e){return e?e instanceof he?[new l(o.INVALID_NAME,"Invalid array as Table name, maybe you forget to add a space between the name and the setting list?",e)]:Mt(e)?[]:[new l(o.INVALID_NAME,"A Table name must be of the form <table> or <schema>.<table>",e)]:[new l(o.NAME_NOT_FOUND,"A Table must have a name",this.declarationNode)]}validateAlias(e){return e?Kn(e)?[]:[new l(o.INVALID_ALIAS,"Table aliases can only contains alphanumeric and underscore unless surrounded by double quotes",e)]:[]}validateSettingList(e){const n=F(e),s=n.getErrors(),i=n.getValue();for(const a in i){const r=i[a];switch(a){case"headercolor":r.length>1&&s.push(...r.map(c=>new l(o.DUPLICATE_TABLE_SETTING,"'headercolor' can only appear once",c))),r.forEach(c=>{Qe(c.value)||s.push(new l(o.INVALID_TABLE_SETTING,"'headercolor' must be a color literal",c.value||c.name))});break;case"note":r.length>1&&s.push(...r.map(c=>new l(o.DUPLICATE_TABLE_SETTING,"'note' can only appear once",c))),r.forEach(c=>{W(c.value)||s.push(new l(o.INVALID_TABLE_SETTING,"'note' must be a string literal",c.value||c.name))});break;default:s.push(...r.map(c=>new l(o.INVALID_TABLE_SETTING,`Unknown '${a}' setting`,c)))}}return s}registerElement(){const e=[];this.declarationNode.symbol=this.symbolFactory.create(xt,{declaration:this.declarationNode,symbolTable:new Pe});const{name:n,alias:s}=this.declarationNode,i=q(n);if(i.isOk()){const a=[...i.unwrap()],r=a.pop(),c=He(a,this.publicSymbolTable,this.symbolFactory),p=Ve(r);c.has(p)&&e.push(new l(o.DUPLICATE_NAME,`Table name '${r}' already exists in schema '${a.join(".")||"public"}'`,n)),c.set(p,this.declarationNode.symbol)}if(s&&ke(s)&&!zn(s.expression.variable.value,i.unwrap_or([]))){const a=X(s).unwrap(),r=Ve(a);this.publicSymbolTable.has(r)&&e.push(new l(o.DUPLICATE_NAME,`Table name '${a}' already exists`,n)),this.publicSymbolTable.set(r,this.declarationNode.symbol)}return e}validateBody(e){if(!e)return[];if(e instanceof w)return[new l(o.UNEXPECTED_SIMPLE_BODY,"A Table's body must be a block",e)];const[n,s,i]=e.body.reduce((a,r)=>(r instanceof w?a[0].push(r):r instanceof Le?a[1].push(r):r instanceof y&&a[2].push(r),a),[[],[],[]]);return[...this.validateFields(n),...this.validateInjections(s),...this.validateSubElements(i)]}validateInjections(e){return e.flatMap(n=>this.registerInjection(n))}registerInjection(e){var c,p,f;if(!((p=(c=e.partial)==null?void 0:c.variable)!=null&&p.value))return[];const n=(f=e.partial.variable)==null?void 0:f.value,s=Dt(n),i=this.symbolFactory.create(mn,{declaration:e});e.symbol=i;const a=this.declarationNode.symbol.symbolTable,r=a.get(s);return r?[new l(o.DUPLICATE_TABLE_PARTIAL_INJECTION_NAME,`Duplicate injection ${n}`,e),new l(o.DUPLICATE_TABLE_PARTIAL_INJECTION_NAME,`Duplicate injection ${n}`,r.declaration)]:(a.set(s,i),[])}validateFields(e){return e.length===0?[new l(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 l(o.INVALID_COLUMN,"A column must have a type",n.callee)),j(n.callee)||s.push(new l(o.INVALID_COLUMN_NAME,"A column name must be an identifier or a quoted identifier",n.callee)),n.args[0]&&!Yn(n.args[0])&&s.push(new l(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&&j(e.callee)){const n=X(e.callee).unwrap(),s=qe(n),i=this.symbolFactory.create(ot,{declaration:e});e.symbol=i;const a=this.declarationNode.symbol.symbolTable;if(a.has(s)){const r=a.get(s);return[new l(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,e),new l(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,r.declaration)]}a.set(s,i)}return[]}validateFieldSetting(e){if(!e.slice(0,-1).every(fe)||!e.slice(-1).every(p=>fe(p)||p instanceof M))return[...e.map(p=>new l(o.INVALID_COLUMN,"These fields must be some inline settings optionally ended with a setting list",p))];if(e.length===0)return[];let n;A.last(e)instanceof M&&(n=e.pop());const s=F(n),i=s.getErrors(),a=s.getValue();for(const p of e){const f=X(p).unwrap_or("").toLowerCase();if(f!=="pk"&&f!=="unique"){i.push(new l(o.INVALID_SETTINGS,"Inline column settings can only be `pk` or `unique`",p));continue}a[f]===void 0?a[f]=[p]:a[f].push(p)}const r=a.pk||[],c=a["primary key"]||[];r.length>=1&&c.length>=1&&i.push(...[...r,...c].map(p=>new l(o.DUPLICATE_COLUMN_SETTING,"Either one of 'primary key' and 'pk' can appear",p)));for(const p in a){const f=a[p];switch(p){case"note":f.length>1&&i.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"note can only appear once",u))),f.forEach(u=>{W(u.value)||i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'note' must be a quoted string",u.value||u.name))});break;case"ref":f.forEach(u=>{Vt(u.value)||i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'ref' must be a valid unary relationship",u.value||u.name))});break;case"primary key":f.length>1&&i.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"primary key can only appear once",u))),f.forEach(u=>{Q(u.value)||i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'primary key' must not have a value",u.value||u.name))});break;case"pk":f.length>1&&i.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"'pk' can only appear once",u))),f.forEach(u=>{u instanceof ne&&!Q(u.value)&&i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'pk' must not have a value",u.value||u.name))});break;case"not null":f.length>1&&i.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"'not null' can only appear once",u)));const d=a.null||[];f.length>=1&&d.length>=1&&i.push(...[...f,...d].map(u=>new l(o.CONFLICTING_SETTING,"'not null' and 'null' can not be set at the same time",u))),f.forEach(u=>{Q(u.value)||i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'not null' must not have a value",u.value||u.name))});break;case"null":f.length>1&&i.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"'null' can only appear once",u))),f.forEach(u=>{Q(u.value)||i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'null' must not have a value",u.value||u.name))});break;case"unique":f.length>1&&i.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"'unique' can only appear once",u))),f.forEach(u=>{u instanceof ne&&!Q(u.value)&&i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'unique' must not have a value",u.value||u.name))});break;case"increment":f.length>1&&i.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"'increment' can only appear once",u))),f.forEach(u=>{u instanceof ne&&!Q(u.value)&&i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'increment' must not have a value",u.value||u.name))});break;case"default":f.length>1&&i.push(...f.map(u=>new l(o.DUPLICATE_TABLE_SETTING,"'default' can only appear once",u))),f.forEach(u=>{Bt(u.value)||i.push(new l(o.INVALID_TABLE_SETTING,"'default' must be a string literal, number literal, function expression, true, false or null",u.value||u.name))});break;default:f.forEach(u=>i.push(new l(o.UNKNOWN_COLUMN_SETTING,`Unknown column setting '${p}'`,u)))}}return i}validateSubElements(e){const n=e.flatMap(i=>{if(i.parent=this.declarationNode,!i.type)return[];const a=de(i);return new a(i,this.publicSymbolTable,this.symbolFactory).validate()}),s=e.filter(i=>{var a;return((a=i.type)==null?void 0:a.value.toLowerCase())==="note"});return s.length>1&&n.push(...s.map(i=>new l(o.NOTE_REDEFINED,"Duplicate notes are defined",i))),n}}function Yn(t){if(!(t instanceof z||ze(t)||t instanceof $||t instanceof he))return!1;if(t instanceof z){if(t.callee===void 0||t.argumentList===void 0||!t.argumentList.elementList.every(n=>pe(n)||W(n)||fe(n)))return!1;t=t.callee}for(;t instanceof he;){if(t.array===void 0||t.indexer===void 0||!t.indexer.elementList.every(n=>!n.colon&&!n.value&&pe(n.name)))return!1;t=t.array}const e=q(t).unwrap_or(void 0);return e!==void 0&&e.length>0}function zn(t,e){return e.length===1&&t===e[0]}class Hn{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 y?[new l(o.INVALID_TABLEGROUP_CONTEXT,"TableGroup must appear top-level",this.declarationNode)]:[]}validateName(e){return e?ke(e)?[]:[new l(o.INVALID_NAME,"A TableGroup name must be a single identifier",e)]:[new l(o.NAME_NOT_FOUND,"A TableGroup must have a name",this.declarationNode)]}validateAlias(e){return e?[new l(o.UNEXPECTED_ALIAS,"A TableGroup shouldn't have an alias",e)]:[]}registerElement(){const{name:e}=this.declarationNode;this.declarationNode.symbol=this.symbolFactory.create(En,{declaration:this.declarationNode,symbolTable:new Pe});const n=q(e);if(n.isOk()){const s=n.unwrap(),i=s.pop(),a=He(s,this.publicSymbolTable,this.symbolFactory),r=it(i);if(a.has(r))return[new l(o.DUPLICATE_NAME,`TableGroup name '${i}' already exists`,e)];a.set(r,this.declarationNode.symbol)}return[]}validateSettingList(e){const n=F(e),s=n.getErrors(),i=n.getValue();return A.forIn(i,(a,r)=>{switch(r){case"color":a.length>1&&s.push(...a.map(c=>new l(o.DUPLICATE_TABLE_SETTING,"'color' can only appear once",c))),a.forEach(c=>{Qe(c.value)||s.push(new l(o.INVALID_TABLE_SETTING,"'color' must be a color literal",c.value||c.name))});break;case"note":a.length>1&&s.push(...a.map(c=>new l(o.DUPLICATE_TABLE_SETTING,"'note' can only appear once",c))),a.filter(c=>!W(c.value)).forEach(c=>{s.push(new l(o.INVALID_TABLE_SETTING,"'note' must be a string literal",c.value||c.name))});break;default:s.push(...a.map(c=>new l(o.INVALID_TABLE_SETTING,`Unknown '${r}' setting`,c)));break}}),s}validateBody(e){if(!e)return[];if(e instanceof w)return[new l(o.UNEXPECTED_SIMPLE_BODY,"A TableGroup's body must be a block",e)];const[n,s]=A.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&&!q(n.callee).isOk()&&s.push(new l(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 l(o.INVALID_TABLEGROUP_FIELD,"A TableGroup field should only have a single Table name",i))),s})}validateSubElements(e){const n=e.flatMap(i=>{if(i.parent=this.declarationNode,!i.type)return[];const a=de(i);return new a(i,this.publicSymbolTable,this.symbolFactory).validate()}),s=e.filter(i=>{var a;return((a=i.type)==null?void 0:a.value.toLowerCase())==="note"});return s.length>1&&n.push(...s.map(i=>new l(o.NOTE_REDEFINED,"Duplicate notes are defined",i))),n}registerField(e){if(e.callee&&j(e.callee)){const n=X(e.callee).unwrap(),s=at(n),i=this.symbolFactory.create(Nn,{declaration:e});e.symbol=i;const a=this.declarationNode.symbol.symbolTable;if(a.has(s)){const r=a.get(s);return[new l(o.DUPLICATE_TABLEGROUP_FIELD_NAME,`${n} already exists in the group`,e),new l(o.DUPLICATE_TABLEGROUP_FIELD_NAME,`${n} already exists in the group`,r.declaration)]}a.set(s,i)}return[]}}const Ut=["-","+"];function Qn(t){if(!(t instanceof z||ze(t)||t instanceof $||t instanceof he))return!1;if(t instanceof z){if(t.callee===void 0||t.argumentList===void 0||!t.argumentList.elementList.every(n=>pe(n)||W(n)||fe(n)))return!1;t=t.callee}for(;t instanceof he;){if(t.array===void 0||t.indexer===void 0||!t.indexer.elementList.every(n=>!n.colon&&!n.value&&pe(n.name)))return!1;t=t.array}const e=q(t).unwrap_or(void 0);return e!==void 0&&e.length>0}class Jn{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 y?[new l(o.INVALID_TABLE_PARTIAL_CONTEXT,"TablePartial must appear top-level",this.declarationNode)]:[]}validateName(e){return e?ke(e)?[]:[new l(o.INVALID_NAME,"A TablePartial name must be an identifier or a quoted identifer",e)]:[new l(o.NAME_NOT_FOUND,"A TablePartial must have a name",this.declarationNode)]}validateAlias(e){return e?[new l(o.UNEXPECTED_ALIAS,"A TablePartial shouldn't have an alias",e)]:[]}validateSettingList(e){const n=F(e),s=n.getErrors(),i=n.getValue();return A.forIn(i,(a,r)=>{switch(r){case N.HeaderColor:a.length>1&&s.push(...a.map(c=>new l(o.DUPLICATE_TABLE_PARTIAL_SETTING,`'${r}' can only appear once`,c))),a.forEach(c=>{Qe(c.value)||s.push(new l(o.INVALID_TABLE_PARTIAL_SETTING,`'${r}' must be a color literal`,c.value||c.name))});break;case N.Note:a.length>1&&s.push(...a.map(c=>new l(o.DUPLICATE_TABLE_PARTIAL_SETTING,`'${r}' can only appear once`,c))),a.forEach(c=>{W(c.value)||s.push(new l(o.INVALID_TABLE_PARTIAL_SETTING,`'${r}' must be a string literal`,c.value||c.name))});break;default:s.push(...a.map(c=>new l(o.INVALID_TABLE_SETTING,`Unknown '${r}' setting`,c)))}}),s}registerElement(){const{name:e}=this.declarationNode;this.declarationNode.symbol=this.symbolFactory.create(Tn,{declaration:this.declarationNode,symbolTable:new Pe});const n=q(e);if(!n.isOk())return[];const s=n.unwrap(),i=s.pop(),a=He(s,this.publicSymbolTable,this.symbolFactory),r=rt(i);return a.has(r)?[new l(o.DUPLICATE_NAME,`TablePartial name '${i}' already exists`,e)]:(a.set(r,this.declarationNode.symbol),[])}validateBody(e){if(!e)return[];if(e instanceof w)return[new l(o.UNEXPECTED_SIMPLE_BODY,"A TablePartial's body must be a block",e)];const[n,s]=A.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=[];n.args.length===0&&s.push(new l(o.INVALID_COLUMN,"A column must have a type",n.callee)),j(n.callee)||s.push(new l(o.INVALID_COLUMN_NAME,"A column name must be an identifier or a quoted identifier",n.callee)),n.args[0]&&!Qn(n.args[0])&&s.push(new l(o.INVALID_COLUMN_TYPE,"Invalid column type",n.args[0]));const i=n.args.slice(1);return s.push(...this.validateFieldSetting(i),...this.registerField(n)),s})}registerField(e){if(!e.callee||!j(e.callee))return[];const n=X(e.callee).unwrap(),s=qe(n),i=this.symbolFactory.create(ot,{declaration:e});e.symbol=i;const a=this.declarationNode.symbol.symbolTable;if(a.has(s)){const r=a.get(s);return[new l(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,e),new l(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,r.declaration)]}return a.set(s,i),[]}validateFieldSetting(e){const n=A.last(e);if(!e.slice(0,-1).every(fe)||!(fe(n)||n instanceof M))return[...e.map(f=>new l(o.INVALID_COLUMN,"These fields must be some inline settings optionally ended with a setting list",f))];if(e.length===0)return[];let s;A.last(e)instanceof M&&(s=e.pop());const i=F(s),a=i.getErrors(),r=i.getValue();e.forEach(f=>{const d=X(f).unwrap_or("").toLowerCase();if(d!==N.PK&&d!==N.Unique){a.push(new l(o.INVALID_SETTINGS,"Inline column settings can only be `pk` or `unique`",f));return}r[d]===void 0?r[d]=[f]:r[d].push(f)});const c=r[N.PK]||[],p=r[N.PKey]||[];return c.length>=1&&p.length>=1&&a.push(...[...c,...p].map(f=>new l(o.DUPLICATE_COLUMN_SETTING,"Either one of 'primary key' and 'pk' can appear",f))),A.forIn(r,(f,d)=>{switch(d){case N.Note:f.length>1&&a.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,`'${d}' can only appear once`,u))),f.forEach(u=>{W(u.value)||a.push(new l(o.INVALID_COLUMN_SETTING_VALUE,`'${d}' must be a quoted string`,u.value||u.name))});break;case N.Ref:f.forEach(u=>{Vt(u.value)||a.push(new l(o.INVALID_COLUMN_SETTING_VALUE,`'${d}' must be a valid unary relationship`,u.value||u.name))});break;case N.PKey:f.length>1&&a.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,`'${d}' can only appear once`,u))),f.forEach(u=>{Q(u.value)||a.push(new l(o.INVALID_COLUMN_SETTING_VALUE,`'${d}' must not have a value`,u.value||u.name))});break;case N.PK:f.length>1&&a.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,`'${d}' can only appear once`,u))),f.forEach(u=>{u instanceof ne&&!Q(u.value)&&a.push(new l(o.INVALID_COLUMN_SETTING_VALUE,`'${d}' must not have a value`,u.value||u.name))});break;case N.NotNull:{f.length>1&&a.push(...f.map(E=>new l(o.DUPLICATE_COLUMN_SETTING,`'${d}' can only appear once`,E)));const u=r[N.Null]||[];f.length>=1&&u.length>=1&&a.push(...[...f,...u].map(E=>new l(o.CONFLICTING_SETTING,"'not null' and 'null' can not be set at the same time",E))),f.forEach(E=>{Q(E.value)||a.push(new l(o.INVALID_COLUMN_SETTING_VALUE,`'${d}' must not have a value`,E.value||E.name))});break}case N.Null:f.length>1&&a.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,`'${d}' can only appear once`,u))),f.forEach(u=>{Q(u.value)||a.push(new l(o.INVALID_COLUMN_SETTING_VALUE,`'${d}' must not have a value`,u.value||u.name))});break;case N.Unique:f.length>1&&a.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,`'${d}' can only appear once`,u))),f.forEach(u=>{u instanceof ne&&!Q(u.value)&&a.push(new l(o.INVALID_COLUMN_SETTING_VALUE,`'${d}' must not have a value`,u.value||u.name))});break;case N.Increment:f.length>1&&a.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,`'${d}' can only appear once`,u))),f.forEach(u=>{u instanceof ne&&!Q(u.value)&&a.push(new l(o.INVALID_COLUMN_SETTING_VALUE,`'${d}' must not have a value`,u.value||u.name))});break;case N.Default:f.length>1&&a.push(...f.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,`'${d}' can only appear once`,u))),f.forEach(u=>{Bt(u.value)||a.push(new l(o.INVALID_COLUMN_SETTING_VALUE,`'${d}' must be a string literal, number literal, function expression, true, false or null`,u.value||u.name))});break;default:f.forEach(u=>a.push(new l(o.UNKNOWN_COLUMN_SETTING,`Unknown column setting '${d}'`,u)))}}),a}validateSubElements(e){const n=e.flatMap(i=>{if(i.parent=this.declarationNode,!i.type)return[];const a=de(i);return new a(i,this.publicSymbolTable,this.symbolFactory).validate()}),s=e.filter(i=>{var a;return((a=i.type)==null?void 0:a.value.toLowerCase())===I.Note});return s.length>1&&n.push(...s.map(i=>new l(o.NOTE_REDEFINED,"Duplicate notes are defined",i))),n}}function de(t){switch(t.type.value.toLowerCase()){case I.Enum:return Gn;case I.Table:return qn;case I.TableGroup:return Hn;case I.Project:return $n;case I.Ref:return jn;case I.Note:return Xn;case I.Indexes:return Cn;case I.TablePartial:return Jn;default:return Vn}}function Mt(t){return!!q(t).unwrap_or(!1)}function Kn(t){return ke(t)}function ke(t){return t instanceof $&&t.expression instanceof ie}function He(t,e,n){var i;t[0]==="public"&&(t=t.slice(1));let s=e;for(const a of t){let r;const c=tt(a);if(s.has(c)){if(r=(i=s.get(c))==null?void 0:i.symbolTable,!r)throw new Error("Expect a symbol table in a schema symbol")}else{r=new Pe;const p=n.create(Ot,{symbolTable:r});s.set(c,p)}s=r}return s}function Ft(t){return t==="-"||t==="<>"||t===">"||t==="<"}function Qe(t){var n;if(!(t instanceof $)||!(t.expression instanceof ye)||((n=t.expression.literal)==null?void 0:n.kind)!==h.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(!An(e[s]))return!1;return!0}function Q(t){return t===void 0}function Bt(t){var e;return!!(W(t)||pe(t)||fe(t)&&["true","false","null"].includes(t.expression.variable.value.toLowerCase())||t instanceof oe&&Ut.includes((e=t.op)==null?void 0:e.value)&&pe(t.expression)||t instanceof ue)}function pe(t){var e;return t instanceof $&&t.expression instanceof ye&&((e=t.expression.literal)==null?void 0:e.kind)===h.NUMERIC_LITERAL}function Vt(t){var n;if(!(t instanceof oe)||!Ft((n=t.op)==null?void 0:n.value))return!1;const e=q(t.expression).unwrap_or(void 0);return e!==void 0&&e.length>0}function Gt(t){return t instanceof ce&&t.elementList.every(j)}function F(t){var s;const e={},n=[];if(!t)return new K({});for(const i of t.elementList){if(!i.name)continue;if(i.name instanceof $){n.push(new l(o.INVALID_SETTINGS,"A setting name must be a stream of identifiers",i.name));continue}const a=(s=we(i.name).unwrap_or(void 0))==null?void 0:s.toLowerCase();a&&(e[a]===void 0?e[a]=[i]:e[a].push(i))}return new K(e,n)}class It{constructor(e,n){this.ast=e,this.symbolFactory=n,this.publicSchemaSymbol=this.symbolFactory.create(Ot,{symbolTable:new Pe}),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=de(s),a=new i(s,this.publicSchemaSymbol.symbolTable,this.symbolFactory);e.push(...a.validate())});const n=this.ast.body.filter(s=>Ae(s).unwrap_or(void 0)===I.Project);return n.length>1&&n.forEach(s=>e.push(new l(o.PROJECT_REDEFINED,"Only one project can exist",s))),new K(this.ast,e)}}class Ee{constructor(e,n){this.declarationNode=e,this.errors=n}bind(){this.bindSettingList(this.declarationNode.attributeList,this.settingList),this.bindBody()}bindSettingList(e,n){e&&e.elementList.forEach(s=>{if(s.name instanceof $)return;const i=we(s.name).unwrap_or(void 0);if(!i)return;const a=n[i.toLowerCase()];a!=null&&a.shouldBind&&this.scanAndBind(s.value,a)})}bindBody(){const e=this.declarationNode;if(!e.body)return;const{body:n}=e;n instanceof ae?n.body.forEach(s=>{if(s instanceof y){if(!s.type||Ae(this.declarationNode).unwrap_or(null)===I.TablePartial&&Ae(s).unwrap_or(null)===I.Indexes)return;const i=Ct(s);new i(s,this.errors).bind()}else s instanceof w?this.bindSubfield(s):this.bindPartialInjection(s)}):this.bindSubfield(n)}bindSubfield(e){const n=[e.callee,...e.args],s=A.last(n);s instanceof M&&(n.pop(),this.bindSettingList(s,this.subfield.settingList));const{argBinderRules:i}=this.subfield.arg;for(let a=0;a<Math.min(n.length,i.length);a+=1)i[a].shouldBind&&this.scanAndBind(n[a],i[a])}bindPartialInjection(e){var n;(n=this.injectionBinderRule)!=null&&n.shouldBind&&this.scanAndBind(e,this.injectionBinderRule)}scanAndBind(e,n){var s,i;if(e)if(e instanceof $){if(e.expression instanceof ie&&((i=n.keywords)!=null&&i.includes((s=e.expression.variable)==null?void 0:s.value.toLowerCase())))return;this.bindFragments([e],n)}else e instanceof le?ze(e)?this.bindFragments(_e(e).unwrap_or([]),n):(this.scanAndBind(e.leftExpression,n),this.scanAndBind(e.rightExpression,n)):e instanceof oe?this.scanAndBind(e.expression,n):e instanceof We?this.scanAndBind(e.expression,n):e instanceof ce?e.elementList.forEach(a=>this.scanAndBind(a,n)):e instanceof Le&&this.bindFragments([e],n)}bindFragments(e,n){if(e.length===0)return;const s=e.length===1&&e[0]instanceof Le,i=[...n.topSubnamesSymbolKind],{remainingSubnamesSymbolKind:a}=n,r=s?-1:e.findIndex(E=>!j(E)),p=r!==-1&&Gt(e[r])?e[r]:void 0,f=r>=0?i.pop():void 0,d=e.slice(0,r===-1?void 0:r);if(d.length===0)return;const u=[];for(;i.length&&d.length;){const E=i.pop(),L=d.pop(),v=X(L).unwrap();u.unshift({index:Fe(v,E),referrer:L})}for(;d.length;){const E=d.pop(),L=s?Mn(E).unwrap():X(E).unwrap();u.unshift({index:Fe(L,a),referrer:E})}return p?p.elementList.forEach(E=>this.resolveIndexStack([...u,{index:Fe(X(E).unwrap(),f),referrer:E}],n.ignoreNameNotFound)):this.resolveIndexStack(u,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,a=bt(s.index,this.declarationNode);if(a===void 0){const{kind:f,name:d}=re(s.index).unwrap();this.logError(s.referrer,`Can not find ${f} '${d}'`,n);return}a.references.push(s.referrer),s.referrer.referee=a;let r=a.symbolTable,{kind:c,name:p}=re(s.index).unwrap();for(const f of i){const{kind:d,name:u}=re(f.index).unwrap(),E=r.get(f.index);if(!E){this.logError(f.referrer,`${c} '${p}' does not have ${d} '${u}'`,n);return}if(c=d,p=u,f.referrer.referee=E,E.references.push(f.referrer),!E.symbolTable)break;r=E.symbolTable}}logError(e,n,s){s||this.errors.push(new l(o.BINDING_ERROR,n,e))}resolveInjections(e){var i;const n=(i=this.declarationNode.symbol)==null?void 0:i.symbolTable;if(!n)return;const s=new Map;n.forEach((a,r)=>{var f,d;if(!un(r))return;const c=bt(hn(r),this.declarationNode),p=(d=(f=c==null?void 0:c.declaration)==null?void 0:f.symbol)==null?void 0:d.symbolTable;p&&p.forEach((u,E)=>{n.has(E)||s.set(E,{injectorFieldSymbol:u,injectorDeclaration:a.declaration})})}),s.forEach((a,r)=>{const c=Ln(a.injectorFieldSymbol);if(!c)return;const p=e.create(c,a);n.set(r,p)})}}class Zn extends Ee{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class es extends Ee{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class ts extends Ee{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 ns extends Ee{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class ss extends Ee{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class is extends Ee{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class as extends Ee{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={},this.injectionBinderRule={shouldBind:!0,topSubnamesSymbolKind:[],remainingSubnamesSymbolKind:m.TablePartial,ignoreNameNotFound:!1}}}class rs extends Ee{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class os extends Ee{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={}}}function Ct(t){switch(t.type.value.toLowerCase()){case I.Enum:return es;case I.Table:return as;case I.TableGroup:return rs;case I.Project:return ss;case I.Ref:return is;case I.Note:return ns;case I.Indexes:return ts;case I.TablePartial:return os;default:return Zn}}class ls{constructor(e){this.ast=e,this.errors=[]}resolve(e){return this.ast.body.map(n=>{if(!n.type)return null;const s=Ct(n),i=new s(n,this.errors);return i.resolveInjections(e),i}).forEach(n=>n==null?void 0:n.bind()),new K(this.ast,this.errors)}}class cs{constructor(e){this.generator=e}create(e,n){return new e(n,this.generator.nextId())}}class us{constructor(e,n){this.ast=e,this.symbolFactory=new cs(n)}analyze(){return new It(this.ast,this.symbolFactory).validate().chain(n=>new ls(n).resolve(this.symbolFactory))}validate(){return new It(this.ast,this.symbolFactory).validate().chain(n=>new K(n,[]))}}function Lt(t,e){const{variables:n,tupleElements:s}=De(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 Xt(t){switch(t){case"<":return["1","*"];case"<>":return["*","*"];case">":return["*","1"];case"-":return["1","1"];default:throw new Error("Invalid relation op")}}function g(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 Xe(t){var n;const e=(n=_e(t).unwrap_or(void 0))==null?void 0:n.pop();return e instanceof ce?e.elementList.map(s=>s.referee):[e.referee]}function ge(t){const e=q(t).unwrap();return{name:e.pop(),schemaName:e}}function xe(t){return t.expression.literal.value}function $t(t,e){if(Array.isArray(t)){const i=t.map(({id:r})=>r).sort().join(","),a=e.map(({id:r})=>r).sort().join(",");return i<a?`${i}-${a}`:`${a}-${i}`}const n=t.id.toString(),s=e.id.toString();return n<s?`${n}-${s}`:`${s}-${n}`}function lt(t,e){if(Array.isArray(t)){const i=t.map(({id:r})=>r).sort(),a=e.map(({id:r})=>r).sort();return A.zip(i,a).every(([r,c])=>r===c)}const n=t.id,s=e.id;return n===s}function se(t){const e=t.split(`
|
|
10
10
|
`),n=e.slice(e.findIndex(a=>a.trimStart()!=="")),s=n.filter(a=>a.trimStart()),i=Math.min(...s.map(a=>a.length-a.trimStart().length));return n.map(a=>a.slice(i)).join(`
|
|
11
|
-
`)}class jt{constructor(e,n){this.declarationNode=e,this.env=n,this.table={name:void 0,schemaName:void 0,alias:null,fields:[],token:void 0,indexes:[],partials:[]},this.pkColumns=[]}interpret(){this.table.token=g(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,token:s})=>({value:n,type:"column",token:s})),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 l(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=$(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,a,r;const n=B(e).getValue();this.table.headerColor=(i=n.headercolor)!=null&&i.length?Oe((r=(a=n.headercolor)==null?void 0:a.at(0))==null?void 0:r.value):void 0;const[s]=n.note||[];return this.table.note=s&&{value:F(s==null?void 0:s.value).map(ie).unwrap(),token:g(s)},[]}interpretBody(e){const[n,s]=A.partition(e.body,i=>i instanceof w||i instanceof Ae);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 I.Note:return this.table.note={value:F(n.body instanceof oe?n.body.body[0].callee:n.body.callee).map(ie).unwrap(),token:g(n)},[];case I.Indexes:return this.interpretIndexes(n);default:return[]}})}interpretInjection(e,n){const s={order:n,token:g(e)};return s.name=e.partial.variable.value,this.table.partials.push(s),[]}interpretFields(e){return e.flatMap((n,s)=>n instanceof w?this.interpretColumn(n):this.interpretInjection(n,s))}interpretColumn(e){var r,c,p,f,d,u,E,L,v;const n=[],s={};s.name=$(e.callee).unwrap();const i=cs(e.args[0]);s.type=i.getValue(),n.push(...i.getErrors()),s.token=g(e),s.inline_refs=[];const a=e.args.slice(1);if(A.last(a)instanceof M){const _=B(a.pop()).getValue();s.pk=!!((r=_.pk)!=null&&r.length)||!!((c=_["primary key"])!=null&&c.length),s.increment=!!((p=_.increment)!=null&&p.length),s.unique=!!((f=_.unique)!=null&&f.length),s.not_null=(d=_["not null"])!=null&&d.length?!0:(u=_.null)!=null&&u.length?!1:void 0,s.dbdefault=us((L=(E=_.default)==null?void 0:E.at(0))==null?void 0:L.value);const P=(v=_.note)==null?void 0:v.at(0);s.note=P&&{value:F(P.value).map(ie).unwrap(),token:g(P)};const Ie=_.ref||[];s.inline_refs=Ie.flatMap(x=>{const[Ue]=Xe(x.value.expression);if(ct(Ue,e.symbol))return n.push(new l(o.SAME_ENDPOINT,"Two endpoints are the same",x)),[];const Ne=x.value.op,V=H(x.value.expression).unwrap();let te;if(V.length===1){const[Q]=V;te={schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[Q],relation:Ne.value,token:g(x)}}else if(V.length===2){const[Q,me]=V;te={schemaName:null,tableName:Q,fieldNames:[me],relation:Ne.value,token:g(x)}}else if(V.length===3){const[Q,me,ft]=V;te={schemaName:Q,tableName:me,fieldNames:[ft],relation:Ne.value,token:g(x)}}else{n.push(new l(o.UNSUPPORTED,"Nested schema is not supported",x));const Q=V.pop(),me=V.pop();te={schemaName:V.join("."),tableName:me,fieldNames:[Q],relation:Ne.value,token:g(x)}}const Te=this.registerInlineRefToEnv(e,Ue,te,x);return n.push(...Te),Te.length===0?te:[]})}return s.pk||(s.pk=a.some(_=>q(_).unwrap().toLowerCase()==="pk")),s.unique||(s.unique=a.some(_=>q(_).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 r,c,p,f,d,u,E;const s={columns:[]},i=n;s.token=g(i);const a=[i.callee,...i.args];if(A.last(a)instanceof M){const L=B(a.pop()).getValue();s.pk=!!((r=L.pk)!=null&&r.length),s.unique=!!((c=L.unique)!=null&&c.length),s.name=F((f=(p=L.name)==null?void 0:p.at(0))==null?void 0:f.value).unwrap_or(void 0);const v=(d=L.note)==null?void 0:d.at(0);s.note=v&&{value:F(v.value).unwrap(),token:g(v)},s.type=q((E=(u=L.type)==null?void 0:u.at(0))==null?void 0:E.value).unwrap_or(void 0)}return a.flatMap(L=>{if(!(L instanceof Y))return L;const v=[];for(;L instanceof Y;)v.push(L.argumentList),L=L.callee;return v.push(L),v}).forEach(L=>{const{functional:v,nonFunctional:_}=Ce(L).unwrap();s.columns.push(...v.map(P=>({value:P.value.value,type:"expression",token:g(P)})),..._.map(P=>({value:$(P).unwrap(),type:"column",token:g(P)})))}),s})),[]}registerInlineRefToEnv(e,n,s,i){const a=$t(e.symbol,n);if(this.env.refIds[a])return[new l(o.CIRCULAR_REF,"References with same endpoints exist",i),new l(o.CIRCULAR_REF,"References with same endpoints exist",this.env.refIds[a])];const r=Xt(s.relation);return this.env.refIds[a]=i,this.env.ref.set(i,{name:null,schemaName:null,token:s.token,endpoints:[{...s,relation:r[1]},{schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[q(e.callee).unwrap()],token:g(e),relation:r[0]}]}),[]}}function cs(t){let e=null;t instanceof Y&&(e=t.argumentList.elementList.map(a=>ee(a)?a.expression.literal.value:C(a)?F(a).unwrap():q(a).unwrap()).join(","),t=t.callee);let n="";for(;t instanceof he;)n=`[${t.indexer.elementList.map(a=>a.name.expression.literal.value).join(",")}]${n}`,t=t.array;const{name:s,schemaName:i}=be(t);return i.length>1?new z({schemaName:i.length===0?null:i[0],type_name:`${s}${n}${e?`(${e})`:""}`,args:e},[new l(o.UNSUPPORTED,"Nested schema is not supported",t)]):new z({schemaName:i.length===0?null:i[0],type_name:`${s}${n}${e?`(${e})`:""}`,args:e})}function us(t){var e,n,s;if(t){if(C(t))return{value:F(t).unwrap(),type:"string"};if(ee(t))return{type:"number",value:Number.parseFloat(t.expression.literal.value)};if(fe(t))return{value:t.expression.variable.value.toLowerCase(),type:"boolean"};if(t instanceof ae&<.includes((e=t.op)==null?void 0:e.value)&&ee(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 ue)return{value:(s=t.value)==null?void 0:s.value,type:"expression"};throw new Error("Unreachable")}}class hs{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=g(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,a;const n=B(e).getValue();return this.note.headerColor=(s=n.headercolor)!=null&&s.length?Oe((a=(i=n.headercolor)==null?void 0:i.at(0))==null?void 0:a.value):void 0,[]}interpretBody(e){const[n,s]=A.partition(e.body,i=>i instanceof w);return n.length!==1||s.length>0?[new l(o.INVALID_NOTE,"Invalid note syntax",e)]:[...this.interpretNote(n[0])]}interpretNote(e){const n=A.get(e,"callee.expression.literal.value","");return this.note.content=ie(n),[]}}class Wt{constructor(e,n){this.declarationNode=e,this.env=n,this.container=this.declarationNode.parent instanceof y?this.env.tables.get(this.declarationNode.parent):void 0,this.ref={}}interpret(){return this.ref.token=g(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=H(this.declarationNode.name).unwrap_or([]);return this.ref.name=s.pop()||null,s.length>1&&n.push(new l(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 f,d,u,E,L,v,_;const n=e.callee.op.value,{leftExpression:s,rightExpression:i}=e.callee,a=Xe(s),r=Xe(i);if(ct(a,r))return[new l(o.SAME_ENDPOINT,"Two endpoints are the same",e)];const c=$t(a,r);if(this.env.refIds[c])return[new l(o.CIRCULAR_REF,"References with same endpoints exist",this.declarationNode),new l(o.CIRCULAR_REF,"References with same endpoints exist",this.env.refIds[c])];if(e.args[0]){const P=B(e.args[0]).getValue(),Ie=(d=(f=P.delete)==null?void 0:f.at(0))==null?void 0:d.value;this.ref.onDelete=Ie instanceof ne?we(Ie).unwrap_or(void 0):q(Ie).unwrap_or(void 0);const x=(E=(u=P.update)==null?void 0:u.at(0))==null?void 0:E.value;this.ref.onUpdate=x instanceof ne?we(x).unwrap_or(void 0):q(x).unwrap_or(void 0),this.ref.color=(L=P.color)!=null&&L.length?Oe((_=(v=P.color)==null?void 0:v.at(0))==null?void 0:_.value):void 0}const p=Xt(n);return this.ref.endpoints=[{...At(s,this.container),relation:p[0],token:g(s)},{...At(i,this.container),relation:p[1],token:g(i)}],this.env.refIds[c]=this.declarationNode,[]}}class qt{constructor(e,n){this.declarationNode=e,this.env=n,this.tableGroup={tables:[]}}interpret(){const e=[];return this.tableGroup.token=g(this.declarationNode),this.env.tableGroups.set(this.declarationNode,this.tableGroup),e.push(...this.interpretName(this.declarationNode.name),...this.interpretSettingList(this.declarationNode.attributeList),...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 l(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,s]=A.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":this.tableGroup.note={value:F(n.body instanceof oe?n.body.body[0].callee:n.body.callee).map(ie).unwrap(),token:g(n)};break}return[]})}interpretFields(e){const n=[];return this.tableGroup.tables=e.map(s=>{const i=H(s.callee).unwrap();i.length>2&&n.push(new l(o.UNSUPPORTED,"Nested schema is not supported",s));const a=ge(s.callee).unwrap().pop().referee.id;if(this.env.groupOfTable[a]){const r=this.env.groupOfTable[a],{schemaName:c,name:p}=this.env.tableGroups.get(r),f=c?`${c}.${p}`:p;n.push(new l(o.TABLE_REAPPEAR_IN_TABLEGROUP,`Table "${i.join(".")}" already appears in group "${f}"`,s))}else this.env.groupOfTable[a]=this.declarationNode;return{name:i.pop(),schemaName:i.join(".")}}),n}interpretSettingList(e){var i,a,r;const n=B(e).getValue();this.tableGroup.color=(i=n.color)!=null&&i.length?Oe((r=(a=n.color)==null?void 0:a.at(0))==null?void 0:r.value):void 0;const[s]=n.note||[];return this.tableGroup.note=s&&{value:F(s==null?void 0:s.value).map(ie).unwrap(),token:g(s)},[]}}class Yt{constructor(e,n){this.declarationNode=e,this.env=n,this.enum={values:[]}}interpret(){return this.enum.token=g(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 l(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 c;const s=n,i={};i.token=g(s),i.name=q(s.callee).unwrap();const r=(c=B(s.args[0]).getValue().note)==null?void 0:c.at(0);return i.note=r&&{value:F(r.value).map(ie).unwrap(),token:g(r)},this.enum.values.push(i),[]})}}function fs(t){let e=null,n=t;n instanceof Y&&(e=n.argumentList.elementList.map(r=>ee(r)?r.expression.literal.value:C(r)?F(r).unwrap():q(r).unwrap()).join(","),n=n.callee);let s="";for(;n instanceof he;)s=`[${n.indexer.elementList.map(r=>r.name.expression.literal.value).join(",")}]${s}`,n=n.array;const{name:i,schemaName:a}=be(t);return a.length>1?new z({schemaName:a.length===0?null:a[0],type_name:`${i}${s}${e?`(${e})`:""}`,args:e},[new l(o.UNSUPPORTED,"Nested schema is not supported",t)]):new z({schemaName:a.length===0?null:a[0],type_name:`${i}${s}${e?`(${e})`:""}`,args:e})}function ps(t){var e,n;if(t){if(C(t))return{value:F(t).unwrap(),type:"string"};if(ee(t))return{type:"number",value:Number.parseFloat(t.expression.literal.value)};if(fe(t))return{value:t.expression.variable.value.toLowerCase(),type:"boolean"};if(t instanceof ae&<.includes((e=t.op)==null?void 0:e.value)&&ee(t.expression)){const s=Number.parseFloat(t.expression.expression.literal.value);return{value:((n=t.op)==null?void 0:n.value)==="-"?0-s:s,type:"number"}}if(t instanceof ue&&t.value)return{value:t.value.value,type:"expression"};throw new Error("Unreachable")}}class zt{constructor(e,n){this.declarationNode=e,this.env=n,this.tablePartial={name:void 0,fields:[],token:void 0,indexes:[]},this.pkColumns=[]}interpret(){this.tablePartial.token=g(this.declarationNode),this.env.tablePartials.set(this.declarationNode,this.tablePartial);const e=[...this.interpretName(this.declarationNode.name),...this.interpretSettingList(this.declarationNode.attributeList),...this.interpretBody(this.declarationNode.body)];return this.pkColumns.length>=2&&(this.tablePartial.indexes.push({columns:this.pkColumns.map(({name:n,token:s})=>({value:n,type:"column",token:s})),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}=be(e);return this.tablePartial.name=n,[]}interpretSettingList(e){const n=B(e).getValue(),s=A.head(n[T.HeaderColor]);this.tablePartial.headerColor=s?Oe(s.value):void 0;const[i]=n[T.Note]||[];return this.tablePartial.note=i&&{value:F(i==null?void 0:i.value).map(ie).unwrap(),token:g(i)},[]}interpretBody(e){const[n,s]=A.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 I.Note:return this.tablePartial.note={value:F(n.body instanceof oe?n.body.body[0].callee:n.body.callee).map(ie).unwrap(),token:g(n)},[];case I.Indexes:return this.interpretIndexes(n);default:return[]}})}interpretFields(e){return e.flatMap(n=>this.interpretColumn(n))}interpretColumn(e){var r,c,p,f,d,u,E,L,v;const n=[],s={};s.name=$(e.callee).unwrap();const i=fs(e.args[0]);s.type=i.getValue(),n.push(...i.getErrors()),s.token=g(e),s.inline_refs=[];const a=e.args.slice(1);if(A.last(a)instanceof M){const _=B(a.pop()).getValue();s.pk=!!((r=_[T.PK])!=null&&r.length)||!!((c=_[T.PKey])!=null&&c.length),s.increment=!!((p=_[T.Increment])!=null&&p.length),s.unique=!!((f=_[T.Unique])!=null&&f.length),s.not_null=(d=_[T.NotNull])!=null&&d.length?!0:(u=_[T.Null])!=null&&u.length?!1:void 0,s.dbdefault=ps((L=(E=_[T.Default])==null?void 0:E.at(0))==null?void 0:L.value);const P=(v=_[T.Note])==null?void 0:v.at(0);s.note=P&&{value:F(P.value).map(ie).unwrap(),token:g(P)};const Ie=_[T.Ref]||[];s.inline_refs=Ie.flatMap(x=>{const[Ue]=Xe(x.value.expression);if(ct(Ue,e.symbol))return n.push(new l(o.SAME_ENDPOINT,"Two endpoints are the same",x)),[];const Ne=x.value.op,V=H(x.value.expression).unwrap();let te;if(V.length===2){const[Te,Q]=V;te={schemaName:null,tableName:Te,fieldNames:[Q],relation:Ne.value,token:g(x)}}else if(V.length===3){const[Te,Q,me]=V;te={schemaName:Te,tableName:Q,fieldNames:[me],relation:Ne.value,token:g(x)}}else{n.push(new l(o.UNSUPPORTED,"Unsupported",x));const Te=V.pop(),Q=V.pop();te={schemaName:V.join("."),tableName:Q,fieldNames:[Te],relation:Ne.value,token:g(x)}}return te})}return s.pk||(s.pk=a.some(_=>q(_).unwrap().toLowerCase()==="pk")),s.unique||(s.unique=a.some(_=>q(_).unwrap().toLowerCase()==="unique")),this.tablePartial.fields.push(s),s.pk&&this.pkColumns.push(s),n}interpretIndexes(e){return this.tablePartial.indexes.push(...e.body.body.map(n=>{var r,c,p,f,d,u,E;const s={columns:[]},i=n;s.token=g(i);const a=[i.callee,...i.args];if(A.last(a)instanceof M){const L=B(a.pop()).getValue();s.pk=!!((r=L[T.PK])!=null&&r.length),s.unique=!!((c=L[T.Unique])!=null&&c.length),s.name=F((f=(p=L[T.Name])==null?void 0:p.at(0))==null?void 0:f.value).unwrap_or(void 0);const v=(d=L[T.Note])==null?void 0:d.at(0);s.note=v&&{value:F(v.value).unwrap(),token:g(v)},s.type=q((E=(u=L[T.Type])==null?void 0:u.at(0))==null?void 0:E.value).unwrap_or(void 0)}return a.flatMap(L=>{if(!(L instanceof Y))return L;const v=[];let _=L;for(;_ instanceof Y;)v.push(_.argumentList),_=_.callee;return v.push(_),v}).forEach(L=>{const{functional:v,nonFunctional:_}=Ce(L).unwrap();s.columns.push(...v.map(P=>({value:P.value.value,type:"expression",token:g(P)})),..._.map(P=>({value:$(P).unwrap(),type:"column",token:g(P)})))}),s})),[]}}class ds{constructor(e,n){this.declarationNode=e,this.env=n,this.project={enums:[],refs:[],tableGroups:[],tables:[],tablePartials:[]}}interpret(){return this.env.project.set(this.declarationNode,this.project),this.project.token=g(this.declarationNode),[...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 a=new jt(s,this.env).interpret();return this.project.tables.push(this.env.tables.get(s)),a}case"ref":{const a=new Wt(s,this.env).interpret();return this.project.refs.push(this.env.ref.get(s)),a}case"tablegroup":{const a=new qt(s,this.env).interpret();return this.project.tableGroups.push(this.env.tableGroups.get(s)),a}case"enum":{const a=new Yt(s,this.env).interpret();return this.project.enums.push(this.env.enums.get(s)),a}case"note":return this.project.note={value:F(s.body instanceof oe?s.body.body[0].callee:s.body.callee).map(ie).unwrap(),token:g(s)},[];case"tablepartial":{const a=new zt(s,this.env).interpret();return this.project.tablePartials.push(this.env.tablePartials.get(s)),a}default:return this.project[s.type.value.toLowerCase()]=F(s.body.callee).unwrap(),[]}})}}function Es(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]||{},tablePartials:Array.from(t.tablePartials.values())}}class Ns{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,tablePartials:new Map}}interpret(){const e=this.ast.body.flatMap(n=>{switch(_e(n).unwrap_or(void 0)){case I.Table:return new jt(n,this.env).interpret();case I.Note:return new hs(n,this.env).interpret();case I.Ref:return new Wt(n,this.env).interpret();case I.TableGroup:return new qt(n,this.env).interpret();case I.TablePartial:return new zt(n,this.env).interpret();case I.Enum:return new Yt(n,this.env).interpret();case I.Project:return new ds(n,this.env).interpret();default:return[]}});return new z(Es(this.env),e)}}var k=(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))(k||{}),R=(t=>(t[t.None=0]="None",t[t.KeepWhitespace=1]="KeepWhitespace",t[t.InsertAsSnippet=4]="InsertAsSnippet",t))(R||{});function De(t){switch(t){case m.Schema:return k.Module;case m.Table:case m.TablePartial:return k.Class;case m.Column:case m.TableGroupField:return k.Field;case m.Enum:return k.Enum;case m.EnumField:return k.EnumMember;case m.TableGroup:return k.Struct;default:return k.Text}}function $e(t,e){if(!t||Ze(t))return!1;for(const n of t.trailingTrivia){if(n.start>e)break;if(n.kind===h.NEWLINE&&n.end<=e)return!1}return!0}function G(){return{suggestions:[]}}function je(t){return{...t,suggestions:t.suggestions.map(e=>({...e,insertText:` ${e.insertText}`}))}}function Je(t){return{...t,suggestions:t.suggestions.map(e=>({...e,insertText:e.insertText.split("").every(Ye)?e.insertText:`"${e.insertText}"`}))}}function ut(t,e){return t.getOffsetAt(e)}class Ht{constructor(e,n=[]){this.compiler=e,this.triggerCharacters=n}provideCompletionItems(e,n){var d,u;const s=ut(e,n),i=this.compiler.token.flatStream(),{token:a,index:r}=this.compiler.container.token(s),c=r===void 0?i[0]:i[r+1];if([...(a==null?void 0:a.trailingTrivia)||[],...(a==null?void 0:a.leadingTrivia)||[],...(c==null?void 0:c.leadingTrivia)||[]].find(E=>nn(E)&&Se(s,E)))return G();if(r===void 0)return yt();if([h.STRING_LITERAL,h.QUOTED_STRING].includes(a.kind)&&Se(s,a))return G();const p=this.compiler.container.element(s);if(this.compiler.container.scopeKind(s)===O.TOPLEVEL||p instanceof y&&p.type&&p.type.start<=s&&p.type.end>=s)return yt();const f=[...this.compiler.container.stack(s)].reverse();for(const E of f)if(E instanceof ae)switch((d=E.op)==null?void 0:d.value){case">":case"<":case"<>":case"-":return _t(this.compiler,s,E)}else if(E instanceof ce)switch((u=E.op)==null?void 0:u.value){case">":case"<":case"<>":case"-":return _t(this.compiler,s,E);case".":return Qt(this.compiler,s,E)}else{if(E instanceof se)return gt(this.compiler,s,E);if(E instanceof M)return gt(this.compiler,s,E);if(E instanceof pe)return ms(this.compiler,s);if(E instanceof Ae)return Ts(this.compiler,s);if(E instanceof w)return wt(this.compiler,s,E);if(E instanceof y&&(E.bodyColon&&s>=E.bodyColon.end||E.body&&Se(s,E.body)))return wt(this.compiler,s,void 0)}return G()}}function Ts(t,e){const n=t.container.element(e);return Re(t,e,n,[m.TablePartial])}function _t(t,e,n){const s=t.container.scopeKind(e);if([O.REF,O.TABLE,O.TABLEPARTIAL].includes(s)){const i=Re(t,e,t.container.element(e),[m.Table,m.Schema,m.Column]);return $e(n.op,e)?je(i):i}return G()}function Re(t,e,n,s){var r;if(n===void 0)return G();let i=n;const a={suggestions:[]};for(;i;){if((r=i==null?void 0:i.symbol)!=null&&r.symbolTable){const{symbol:c}=i;a.suggestions.push(...t.symbol.members(c).filter(({kind:p})=>s.includes(p)).map(({name:p,kind:f})=>({label:p,insertText:p,insertTextRules:R.KeepWhitespace,kind:De(f),sortText:De(f).toString().padStart(2,"0"),range:void 0})))}i=i instanceof y?i.parent:void 0}return Je(a)}function ms(t,e){var s;switch(t.container.scopeKind(e)){case O.INDEXES:return Kt(t,e);case O.REF:{const i=[...t.container.stack(e)];for(;i.length>0;){const a=i.pop();if(a instanceof ce&&((s=a.op)==null?void 0:s.value)===".")return Qt(t,e,a)}}return Jt(t,e)}return G()}function gt(t,e,n){const{token:s}=t.container.token(e);if([h.COMMA,h.LBRACKET].includes(s==null?void 0:s.kind)){const i=vt(t,e);return(s==null?void 0:s.kind)===h.COMMA&&$e(s,e)?je(i):i}if(n.name&&n.name.start<=e&&n.name.end>=e)return vt(t,e);if(n.name instanceof ne){const i=bs(t,e,we(n.name).unwrap_or(""));return(s==null?void 0:s.kind)===h.COLON&&$e(s,e)?je(i):i}return G()}function vt(t,e){const n=t.container.element(e);if(n instanceof Z)return G();const s=t.container.scopeKind(e);if(n.body&&!Se(e,n.body)){let i;switch(s){case O.TABLE:case O.TABLEPARTIAL:i=[T.HeaderColor,T.Note];break;case O.TABLEGROUP:i=[T.Color,T.Note];break;default:i=[]}return{suggestions:i.map(a=>({label:a,insertText:`${a}: `,kind:k.Field,insertTextRules:R.KeepWhitespace,range:void 0}))}}switch(s){case O.TABLE:case O.TABLEPARTIAL:return{suggestions:[...[T.PK,T.PKey,T.Null,T.NotNull,T.Increment,T.Unique].map(i=>({label:i,insertText:i,kind:k.Property,insertTextRules:R.KeepWhitespace,range:void 0})),...[T.Ref,T.Default,T.Note].map(i=>({label:i,insertText:`${i}: `,kind:k.Property,insertTextRules:R.KeepWhitespace,range:void 0}))]};case O.ENUM:return{suggestions:[...[T.Note].map(i=>({label:i,insertText:`${i}: `,kind:k.Property,insertTextRules:R.KeepWhitespace,range:void 0}))]};case O.INDEXES:return{suggestions:[...[T.Unique,T.PK].map(i=>({label:i,insertText:i,insertTextRules:R.KeepWhitespace,kind:k.Property,range:void 0})),...[T.Note,T.Name,T.Type].map(i=>({label:i,insertText:`${i}: `,kind:k.Property,insertTextRules:R.KeepWhitespace,range:void 0}))]};case O.REF:return{suggestions:[T.Update,T.Delete].map(i=>({label:i,insertText:`${i}: `,kind:k.Property,insertTextRules:R.KeepWhitespace,range:void 0}))}}return G()}function bs(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:k.Value,insertTextRules:R.KeepWhitespace,range:void 0}))};case"type":return{suggestions:["btree","hash"].map(s=>({label:s,insertText:`${s}`,kind:k.Value,insertTextRules:R.KeepWhitespace,range:void 0}))}}return G()}function Qt(t,e,n){const s=ge(n).unwrap_or([]);if(s.pop(),s.some(a=>!W(a)))return G();const i=s.map(a=>q(a).unwrap());return Je({suggestions:t.symbol.ofName({nameStack:i,owner:t.container.element(e)}).flatMap(({symbol:a})=>t.symbol.members(a)).map(({kind:a,name:r})=>({label:r,insertText:r,kind:De(a),range:void 0}))})}function wt(t,e,n){var i;switch(t.container.scopeKind(e)){case O.TABLE:case O.TABLEPARTIAL:return Ls(t,e,n);case O.PROJECT:return As(t,e,n);case O.INDEXES:return gs(t,e);case O.ENUM:return Is(t,e,n);case O.REF:{const a=Jt(t,e);return((i=t.container.token(e).token)==null?void 0:i.kind)===h.COLON&&$e(t.container.token(e).token,e)?je(a):a}case O.TABLEGROUP:return _s(t);default:return G()}}function yt(){return{suggestions:["Table","TableGroup","Enum","Project","Ref","TablePartial"].map(t=>({label:t,insertText:t,insertTextRules:R.KeepWhitespace,kind:k.Keyword,range:void 0}))}}function Is(t,e,n){return n!=null&&n.callee&&ht(e,n)===1?Re(t,e,t.container.element(e),[m.Schema,m.Table,m.Column]):G()}function Ls(t,e,n){const s=["Note","indexes"];if(!(n!=null&&n.callee))return{suggestions:s.map(a=>({label:a,insertText:a,insertTextRules:R.KeepWhitespace,kind:k.Keyword,range:void 0}))};const i=ht(e,n);return i===0?{suggestions:s.map(a=>({label:a,insertText:a,insertTextRules:R.KeepWhitespace,kind:k.Keyword,range:void 0}))}:i===1?vs(t,e):G()}function As(t,e,n){const s=["Table","TableGroup","Enum","Note","Ref","TablePartial"];return n!=null&&n.callee?ht(e,n)===0?{suggestions:s.map(a=>({label:a,insertText:a,insertTextRules:R.KeepWhitespace,kind:k.Keyword,range:void 0}))}:G():{suggestions:s.map(a=>({label:a,insertText:a,insertTextRules:R.KeepWhitespace,kind:k.Keyword,range:void 0}))}}function Jt(t,e){return Re(t,e,t.container.element(e),[m.Schema,m.Table,m.Column])}function _s(t){return{suggestions:[...Je({suggestions:[...t.parse.publicSymbolTable().entries()].flatMap(([e])=>{const n=le(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:R.KeepWhitespace,kind:De(s),range:void 0}})}).suggestions,...["Note"].map(e=>({label:e,insertText:e,insertTextRules:R.KeepWhitespace,kind:k.Keyword,range:void 0}))]}}function gs(t,e){return Kt(t,e)}function vs(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:R.KeepWhitespace,kind:k.TypeParameter,sortText:k.TypeParameter.toString().padStart(2,"0"),range:void 0})),...Re(t,e,t.container.element(e),[m.Enum,m.Schema]).suggestions]}}function Kt(t,e){const n=t.container.element(e),s=n==null?void 0:n.parent;if(!((s==null?void 0:s.symbol)instanceof Rt))return G();const{symbolTable:i}=s.symbol;return Je({suggestions:[...i.entries()].flatMap(([a])=>{const r=le(a).unwrap_or(void 0);if(r===void 0)return[];const{name:c}=r;return{label:c,insertText:c,insertTextRules:R.KeepWhitespace,kind:De(m.Column),range:void 0}})})}function ht(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 Zt{constructor(e){this.compiler=e}provideDefinition(e,n){var r,c;const{uri:s}=e,i=ut(e,n),a=[...this.compiler.container.stack(i)];for(;a.length!==0;){const p=a.pop();if(!(p!=null&&p.referee))continue;let f;if((r=p.referee)!=null&&r.declaration&&[Le.PRIMARY_EXPRESSION,Le.VARIABLE,Le.PARTIAL_INJECTION].includes(p==null?void 0:p.kind)?{declaration:f}=p.referee:(c=p.referee)!=null&&c.injectorDeclaration&&(f=p.referee.injectorDeclaration),f){const{startPos:d,endPos:u}=f;return[{range:{startColumn:d.column+1,startLineNumber:d.line+1,endColumn:u.column+1,endLineNumber:u.line+1},uri:s}]}}return[]}}class en{constructor(e){this.compiler=e}provideReferences(e,n){const{uri:s}=e,i=ut(e,n),a=[...this.compiler.container.stack(i)];for(;a.length!==0;){const r=a.pop();if(r&&[Le.ELEMENT_DECLARATION,Le.FUNCTION_APPLICATION,Le.PRIMARY_EXPRESSION].includes(r==null?void 0:r.kind)){const{symbol:c}=r;if(c!=null&&c.references.length)return c.references.map(({startPos:p,endPos:f})=>({range:{startColumn:p.column+1,startLineNumber:p.line+1,endColumn:f.column+1,endLineNumber:f.line+1},uri:s}))}}return[]}}const ws=Object.freeze(Object.defineProperty({__proto__:null,CompletionItemInsertTextRule:R,CompletionItemKind:k,DBMLCompletionItemProvider:Ht,DBMLDefinitionProvider:Zt,DBMLReferencesProvider:en},Symbol.toStringTag,{value:"Module"}));var O=(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[t.TABLEPARTIAL=9]="TABLEPARTIAL",t))(O||{});class ys{constructor(){this.source="",this.cache=new Array(16).fill(null),this.nodeIdGenerator=new sn,this.symbolIdGenerator=new un,this.token={invalidStream:this.createQuery(6,()=>this.parse.tokens().filter(Ut)),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 vn(this.source).lex().chain(n=>new kn(n,this.nodeIdGenerator).parse()).chain(({ast:n,tokens:s})=>new ls(n,this.symbolIdGenerator).analyze().map(()=>({ast:n,tokens:s})));return e.getErrors().length>0?e:e.chain(({ast:n,tokens:s})=>new Ns(n).interpret().map(a=>({ast:n,tokens:s,rawDb:a})))}),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.token.flatStream(),{index:s,token:i}=this.container.token(e),a=s===void 0?-1:A.findLastIndex(n,f=>!f.isInvalid,s);if(a===-1)return[this.parse.ast()];const r=n[a].start;let c=this.parse.ast();const p=[c];for(;;){const d=gn(c).find(u=>Se(r,u));if(d===void 0||d instanceof K)break;p.push(d),c=d}if((i==null?void 0:i.kind)===h.COLON)return p;for(;p.length>0;){let f=!1;const d=A.last(p);if(d instanceof w){const u=this.parse.source();for(let E=d.end;E<e;E+=1)u[E]===`
|
|
12
|
-
`&&(p.pop(),f=!0)}else d instanceof
|
|
11
|
+
`)}function jt(t){var e,n;if(t){if(W(t))return{value:V(t).unwrap(),type:"string"};if(pe(t))return{type:"number",value:Number.parseFloat(t.expression.literal.value)};if(fe(t))return{value:t.expression.variable.value.toLowerCase(),type:"boolean"};if(t instanceof oe&&Ut.includes((e=t.op)==null?void 0:e.value)&&pe(t.expression)){const s=Number.parseFloat(t.expression.expression.literal.value);return{value:((n=t.op)==null?void 0:n.value)==="-"?0-s:s,type:"number"}}if(t instanceof ue&&t.value)return{value:t.value.value,type:"expression"};throw new Error("Unreachable")}}function Wt(t){let e=null;t instanceof z&&(e=t.argumentList.elementList.map(a=>pe(a)?a.expression.literal.value:W(a)?V(a).unwrap():Y(a).unwrap()).join(","),t=t.callee);let n="";for(;t instanceof he;)n=`[${t.indexer.elementList.map(a=>a.name.expression.literal.value).join(",")}]${n}`,t=t.array;const{name:s,schemaName:i}=ge(t);return i.length>1?new K({schemaName:i.length===0?null:i[0],type_name:`${s}${n}${e?`(${e})`:""}`,args:e},[new l(o.UNSUPPORTED,"Nested schema is not supported",t)]):new K({schemaName:i.length===0?null:i[0],type_name:`${s}${n}${e?`(${e})`:""}`,args:e})}class qt{constructor(e,n){this.declarationNode=e,this.env=n,this.table={name:void 0,schemaName:void 0,alias:null,fields:[],token:void 0,indexes:[],partials:[]},this.pkColumns=[]}interpret(){this.table.token=g(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,token:s})=>({value:n,type:"column",token:s})),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}=ge(e);return s.length>1?(this.table.name=n,this.table.schemaName=s.join("."),[new l(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=X(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,a,r;const n=F(e).getValue();this.table.headerColor=(i=n[N.HeaderColor])!=null&&i.length?xe((r=(a=n[N.HeaderColor])==null?void 0:a.at(0))==null?void 0:r.value):void 0;const[s]=n[N.Note]||[];return this.table.note=s&&{value:V(s==null?void 0:s.value).map(se).unwrap(),token:g(s)},[]}interpretBody(e){const[n,s]=A.partition(e.body,i=>i instanceof w||i instanceof Le);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 I.Note:return this.table.note={value:V(n.body instanceof ae?n.body.body[0].callee:n.body.callee).map(se).unwrap(),token:g(n)},[];case I.Indexes:return this.interpretIndexes(n);default:return[]}})}interpretInjection(e,n){const s={order:n,token:g(e)};return s.name=e.partial.variable.value,this.table.partials.push(s),[]}interpretFields(e){return e.flatMap((n,s)=>n instanceof w?this.interpretColumn(n):this.interpretInjection(n,s))}interpretColumn(e){var r,c,p,f,d,u,E,L,v;const n=[],s={};s.name=X(e.callee).unwrap();const i=Wt(e.args[0]);s.type=i.getValue(),n.push(...i.getErrors()),s.token=g(e),s.inline_refs=[];const a=e.args.slice(1);if(A.last(a)instanceof M){const _=F(a.pop()).getValue();s.pk=!!((r=_[N.PK])!=null&&r.length)||!!((c=_[N.PKey])!=null&&c.length),s.increment=!!((p=_[N.Increment])!=null&&p.length),s.unique=!!((f=_[N.Unique])!=null&&f.length),s.not_null=(d=_[N.NotNull])!=null&&d.length?!0:(u=_[N.Null])!=null&&u.length?!1:void 0,s.dbdefault=jt((L=(E=_[N.Default])==null?void 0:E.at(0))==null?void 0:L.value);const k=(v=_[N.Note])==null?void 0:v.at(0);s.note=k&&{value:V(k.value).map(se).unwrap(),token:g(k)};const be=_[N.Ref]||[];s.inline_refs=be.flatMap(D=>{const[Ue]=Xe(D.value.expression);if(lt(Ue,e.symbol))return n.push(new l(o.SAME_ENDPOINT,"Two endpoints are the same",D)),[];const Ne=D.value.op,B=q(D.value.expression).unwrap();let ee;if(B.length===1){const[H]=B;ee={schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[H],relation:Ne.value,token:g(D)}}else if(B.length===2){const[H,me]=B;ee={schemaName:null,tableName:H,fieldNames:[me],relation:Ne.value,token:g(D)}}else if(B.length===3){const[H,me,ht]=B;ee={schemaName:H,tableName:me,fieldNames:[ht],relation:Ne.value,token:g(D)}}else{n.push(new l(o.UNSUPPORTED,"Nested schema is not supported",D));const H=B.pop(),me=B.pop();ee={schemaName:B.join("."),tableName:me,fieldNames:[H],relation:Ne.value,token:g(D)}}const Te=this.registerInlineRefToEnv(e,Ue,ee,D);return n.push(...Te),Te.length===0?ee:[]})}return s.pk||(s.pk=a.some(_=>Y(_).unwrap().toLowerCase()==="pk")),s.unique||(s.unique=a.some(_=>Y(_).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 r,c,p,f,d,u,E;const s={columns:[]},i=n;s.token=g(i);const a=[i.callee,...i.args];if(A.last(a)instanceof M){const L=F(a.pop()).getValue();s.pk=!!((r=L[N.PK])!=null&&r.length),s.unique=!!((c=L[N.Unique])!=null&&c.length),s.name=V((f=(p=L[N.Name])==null?void 0:p.at(0))==null?void 0:f.value).unwrap_or(void 0);const v=(d=L[N.Note])==null?void 0:d.at(0);s.note=v&&{value:V(v.value).unwrap(),token:g(v)},s.type=Y((E=(u=L[N.Type])==null?void 0:u.at(0))==null?void 0:E.value).unwrap_or(void 0)}return a.flatMap(L=>{if(!(L instanceof z))return L;const v=[];for(;L instanceof z;)v.push(L.argumentList),L=L.callee;return v.push(L),v}).forEach(L=>{const{functional:v,nonFunctional:_}=Ce(L).unwrap();s.columns.push(...v.map(k=>({value:k.value.value,type:"expression",token:g(k)})),..._.map(k=>({value:X(k).unwrap(),type:"column",token:g(k)})))}),s})),[]}registerInlineRefToEnv(e,n,s,i){const a=$t(e.symbol,n);if(this.env.refIds[a])return[new l(o.CIRCULAR_REF,"References with same endpoints exist",i),new l(o.CIRCULAR_REF,"References with same endpoints exist",this.env.refIds[a])];const r=Xt(s.relation);return this.env.refIds[a]=i,this.env.ref.set(i,{name:null,schemaName:null,token:s.token,endpoints:[{...s,relation:r[1]},{schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[Y(e.callee).unwrap()],token:g(e),relation:r[0]}]}),[]}}class hs{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=g(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}=ge(e);return this.note.name=n,[]}interpretSettingList(e){var s,i,a;const n=F(e).getValue();return this.note.headerColor=(s=n.headercolor)!=null&&s.length?xe((a=(i=n.headercolor)==null?void 0:i.at(0))==null?void 0:a.value):void 0,[]}interpretBody(e){const[n,s]=A.partition(e.body,i=>i instanceof w);return n.length!==1||s.length>0?[new l(o.INVALID_NOTE,"Invalid note syntax",e)]:[...this.interpretNote(n[0])]}interpretNote(e){const n=A.get(e,"callee.expression.literal.value","");return this.note.content=se(n),[]}}class Yt{constructor(e,n){this.declarationNode=e,this.env=n,this.container=this.declarationNode.parent instanceof y?this.env.tables.get(this.declarationNode.parent):void 0,this.ref={}}interpret(){return this.ref.token=g(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=q(this.declarationNode.name).unwrap_or([]);return this.ref.name=s.pop()||null,s.length>1&&n.push(new l(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 f,d,u,E,L,v,_;const n=e.callee.op.value,{leftExpression:s,rightExpression:i}=e.callee,a=Xe(s),r=Xe(i);if(lt(a,r))return[new l(o.SAME_ENDPOINT,"Two endpoints are the same",e)];const c=$t(a,r);if(this.env.refIds[c])return[new l(o.CIRCULAR_REF,"References with same endpoints exist",this.declarationNode),new l(o.CIRCULAR_REF,"References with same endpoints exist",this.env.refIds[c])];if(e.args[0]){const k=F(e.args[0]).getValue(),be=(d=(f=k.delete)==null?void 0:f.at(0))==null?void 0:d.value;this.ref.onDelete=be instanceof te?we(be).unwrap_or(void 0):Y(be).unwrap_or(void 0);const D=(E=(u=k.update)==null?void 0:u.at(0))==null?void 0:E.value;this.ref.onUpdate=D instanceof te?we(D).unwrap_or(void 0):Y(D).unwrap_or(void 0),this.ref.color=(L=k.color)!=null&&L.length?xe((_=(v=k.color)==null?void 0:v.at(0))==null?void 0:_.value):void 0}const p=Xt(n);return this.ref.endpoints=[{...Lt(s,this.container),relation:p[0],token:g(s)},{...Lt(i,this.container),relation:p[1],token:g(i)}],this.env.refIds[c]=this.declarationNode,[]}}class zt{constructor(e,n){this.declarationNode=e,this.env=n,this.tableGroup={tables:[]}}interpret(){const e=[];return this.tableGroup.token=g(this.declarationNode),this.env.tableGroups.set(this.declarationNode,this.tableGroup),e.push(...this.interpretName(this.declarationNode.name),...this.interpretSettingList(this.declarationNode.attributeList),...this.interpretBody(this.declarationNode.body)),e}interpretName(e){const n=[],{name:s,schemaName:i}=ge(e);return i.length>=2&&(this.tableGroup.name=s,this.tableGroup.schemaName=i.join("."),n.push(new l(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,s]=A.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":this.tableGroup.note={value:V(n.body instanceof ae?n.body.body[0].callee:n.body.callee).map(se).unwrap(),token:g(n)};break}return[]})}interpretFields(e){const n=[];return this.tableGroup.tables=e.map(s=>{const i=q(s.callee).unwrap();i.length>2&&n.push(new l(o.UNSUPPORTED,"Nested schema is not supported",s));const a=_e(s.callee).unwrap().pop().referee.id;if(this.env.groupOfTable[a]){const r=this.env.groupOfTable[a],{schemaName:c,name:p}=this.env.tableGroups.get(r),f=c?`${c}.${p}`:p;n.push(new l(o.TABLE_REAPPEAR_IN_TABLEGROUP,`Table "${i.join(".")}" already appears in group "${f}"`,s))}else this.env.groupOfTable[a]=this.declarationNode;return{name:i.pop(),schemaName:i.join(".")}}),n}interpretSettingList(e){var i,a,r;const n=F(e).getValue();this.tableGroup.color=(i=n.color)!=null&&i.length?xe((r=(a=n.color)==null?void 0:a.at(0))==null?void 0:r.value):void 0;const[s]=n.note||[];return this.tableGroup.note=s&&{value:V(s==null?void 0:s.value).map(se).unwrap(),token:g(s)},[]}}class Ht{constructor(e,n){this.declarationNode=e,this.env=n,this.enum={values:[]}}interpret(){return this.enum.token=g(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}=ge(e);return s.length>1?(this.enum.name=n,this.enum.schemaName=s.join("."),[new l(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 c;const s=n,i={};i.token=g(s),i.name=Y(s.callee).unwrap();const r=(c=F(s.args[0]).getValue().note)==null?void 0:c.at(0);return i.note=r&&{value:V(r.value).map(se).unwrap(),token:g(r)},this.enum.values.push(i),[]})}}class Qt{constructor(e,n){this.declarationNode=e,this.env=n,this.tablePartial={name:void 0,fields:[],token:void 0,indexes:[]},this.pkColumns=[]}interpret(){this.tablePartial.token=g(this.declarationNode),this.env.tablePartials.set(this.declarationNode,this.tablePartial);const e=[...this.interpretName(this.declarationNode.name),...this.interpretSettingList(this.declarationNode.attributeList),...this.interpretBody(this.declarationNode.body)];return this.pkColumns.length>=2&&(this.tablePartial.indexes.push({columns:this.pkColumns.map(({name:n,token:s})=>({value:n,type:"column",token:s})),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}=ge(e);return this.tablePartial.name=n,[]}interpretSettingList(e){const n=F(e).getValue(),s=A.head(n[N.HeaderColor]);this.tablePartial.headerColor=s?xe(s.value):void 0;const[i]=n[N.Note]||[];return this.tablePartial.note=i&&{value:V(i==null?void 0:i.value).map(se).unwrap(),token:g(i)},[]}interpretBody(e){const[n,s]=A.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 I.Note:return this.tablePartial.note={value:V(n.body instanceof ae?n.body.body[0].callee:n.body.callee).map(se).unwrap(),token:g(n)},[];case I.Indexes:return this.interpretIndexes(n);default:return[]}})}interpretFields(e){return e.flatMap(n=>this.interpretColumn(n))}interpretColumn(e){var r,c,p,f,d,u,E,L,v;const n=[],s={};s.name=X(e.callee).unwrap();const i=Wt(e.args[0]);s.type=i.getValue(),n.push(...i.getErrors()),s.token=g(e),s.inline_refs=[];const a=e.args.slice(1);if(A.last(a)instanceof M){const _=F(a.pop()).getValue();s.pk=!!((r=_[N.PK])!=null&&r.length)||!!((c=_[N.PKey])!=null&&c.length),s.increment=!!((p=_[N.Increment])!=null&&p.length),s.unique=!!((f=_[N.Unique])!=null&&f.length),s.not_null=(d=_[N.NotNull])!=null&&d.length?!0:(u=_[N.Null])!=null&&u.length?!1:void 0,s.dbdefault=jt((L=(E=_[N.Default])==null?void 0:E.at(0))==null?void 0:L.value);const k=(v=_[N.Note])==null?void 0:v.at(0);s.note=k&&{value:V(k.value).map(se).unwrap(),token:g(k)};const be=_[N.Ref]||[];s.inline_refs=be.flatMap(D=>{const[Ue]=Xe(D.value.expression);if(lt(Ue,e.symbol))return n.push(new l(o.SAME_ENDPOINT,"Two endpoints are the same",D)),[];const Ne=D.value.op,B=q(D.value.expression).unwrap();let ee;if(B.length===2){const[Te,H]=B;ee={schemaName:null,tableName:Te,fieldNames:[H],relation:Ne.value,token:g(D)}}else if(B.length===3){const[Te,H,me]=B;ee={schemaName:Te,tableName:H,fieldNames:[me],relation:Ne.value,token:g(D)}}else{n.push(new l(o.UNSUPPORTED,"Unsupported",D));const Te=B.pop(),H=B.pop();ee={schemaName:B.join("."),tableName:H,fieldNames:[Te],relation:Ne.value,token:g(D)}}return ee})}return s.pk||(s.pk=a.some(_=>Y(_).unwrap().toLowerCase()==="pk")),s.unique||(s.unique=a.some(_=>Y(_).unwrap().toLowerCase()==="unique")),this.tablePartial.fields.push(s),s.pk&&this.pkColumns.push(s),n}interpretIndexes(e){return this.tablePartial.indexes.push(...e.body.body.map(n=>{var r,c,p,f,d,u,E;const s={columns:[]},i=n;s.token=g(i);const a=[i.callee,...i.args];if(A.last(a)instanceof M){const L=F(a.pop()).getValue();s.pk=!!((r=L[N.PK])!=null&&r.length),s.unique=!!((c=L[N.Unique])!=null&&c.length),s.name=V((f=(p=L[N.Name])==null?void 0:p.at(0))==null?void 0:f.value).unwrap_or(void 0);const v=(d=L[N.Note])==null?void 0:d.at(0);s.note=v&&{value:V(v.value).unwrap(),token:g(v)},s.type=Y((E=(u=L[N.Type])==null?void 0:u.at(0))==null?void 0:E.value).unwrap_or(void 0)}return a.flatMap(L=>{if(!(L instanceof z))return L;const v=[];let _=L;for(;_ instanceof z;)v.push(_.argumentList),_=_.callee;return v.push(_),v}).forEach(L=>{const{functional:v,nonFunctional:_}=Ce(L).unwrap();s.columns.push(...v.map(k=>({value:k.value.value,type:"expression",token:g(k)})),..._.map(k=>({value:X(k).unwrap(),type:"column",token:g(k)})))}),s})),[]}}class fs{constructor(e,n){this.declarationNode=e,this.env=n,this.project={enums:[],refs:[],tableGroups:[],tables:[],tablePartials:[]}}interpret(){return this.env.project.set(this.declarationNode,this.project),this.project.token=g(this.declarationNode),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(e){if(!e)return this.project.name=null,[];const{name:n}=ge(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 a=new qt(s,this.env).interpret();return this.project.tables.push(this.env.tables.get(s)),a}case"ref":{const a=new Yt(s,this.env).interpret();return this.project.refs.push(this.env.ref.get(s)),a}case"tablegroup":{const a=new zt(s,this.env).interpret();return this.project.tableGroups.push(this.env.tableGroups.get(s)),a}case"enum":{const a=new Ht(s,this.env).interpret();return this.project.enums.push(this.env.enums.get(s)),a}case"note":return this.project.note={value:V(s.body instanceof ae?s.body.body[0].callee:s.body.callee).map(se).unwrap(),token:g(s)},[];case"tablepartial":{const a=new Qt(s,this.env).interpret();return this.project.tablePartials.push(this.env.tablePartials.get(s)),a}default:return this.project[s.type.value.toLowerCase()]=V(s.body.callee).unwrap(),[]}})}}function ps(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]||{},tablePartials:Array.from(t.tablePartials.values())}}class ds{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,tablePartials:new Map}}interpret(){const e=this.ast.body.flatMap(n=>{switch(Ae(n).unwrap_or(void 0)){case I.Table:return new qt(n,this.env).interpret();case I.Note:return new hs(n,this.env).interpret();case I.Ref:return new Yt(n,this.env).interpret();case I.TableGroup:return new zt(n,this.env).interpret();case I.TablePartial:return new Qt(n,this.env).interpret();case I.Enum:return new Ht(n,this.env).interpret();case I.Project:return new fs(n,this.env).interpret();default:return[]}});return new K(ps(this.env),e)}}var P=(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))(P||{}),R=(t=>(t[t.None=0]="None",t[t.KeepWhitespace=1]="KeepWhitespace",t[t.InsertAsSnippet=4]="InsertAsSnippet",t))(R||{});function Oe(t){switch(t){case m.Schema:return P.Module;case m.Table:case m.TablePartial:return P.Class;case m.Column:case m.TableGroupField:return P.Field;case m.Enum:return P.Enum;case m.EnumField:return P.EnumMember;case m.TableGroup:return P.Struct;default:return P.Text}}function $e(t,e){if(!t||Ze(t))return!1;for(const n of t.trailingTrivia){if(n.start>e)break;if(n.kind===h.NEWLINE&&n.end<=e)return!1}return!0}function G(){return{suggestions:[]}}function je(t){return{...t,suggestions:t.suggestions.map(e=>({...e,insertText:` ${e.insertText}`}))}}function Je(t){return{...t,suggestions:t.suggestions.map(e=>({...e,insertText:e.insertText.split("").every(Ye)?e.insertText:`"${e.insertText}"`}))}}function ct(t,e){return t.getOffsetAt(e)}class Jt{constructor(e,n=[]){this.compiler=e,this.triggerCharacters=n}provideCompletionItems(e,n){var d,u;const s=ct(e,n),i=this.compiler.token.flatStream(),{token:a,index:r}=this.compiler.container.token(s),c=r===void 0?i[0]:i[r+1];if([...(a==null?void 0:a.trailingTrivia)||[],...(a==null?void 0:a.leadingTrivia)||[],...(c==null?void 0:c.leadingTrivia)||[]].find(E=>an(E)&&Se(s,E)))return G();if(r===void 0)return wt();if([h.STRING_LITERAL,h.QUOTED_STRING].includes(a.kind)&&Se(s,a))return G();const p=this.compiler.container.element(s);if(this.compiler.container.scopeKind(s)===x.TOPLEVEL||p instanceof y&&p.type&&p.type.start<=s&&p.type.end>=s)return wt();const f=[...this.compiler.container.stack(s)].reverse();for(const E of f)if(E instanceof oe)switch((d=E.op)==null?void 0:d.value){case">":case"<":case"<>":case"-":return At(this.compiler,s,E)}else if(E instanceof le)switch((u=E.op)==null?void 0:u.value){case">":case"<":case"<>":case"-":return At(this.compiler,s,E);case".":return Kt(this.compiler,s,E)}else{if(E instanceof ne)return _t(this.compiler,s,E);if(E instanceof M)return _t(this.compiler,s,E);if(E instanceof ce)return Ns(this.compiler,s);if(E instanceof Le)return Es(this.compiler,s);if(E instanceof w)return vt(this.compiler,s,E);if(E instanceof y&&(E.bodyColon&&s>=E.bodyColon.end||E.body&&Se(s,E.body)))return vt(this.compiler,s,void 0)}return G()}}function Es(t,e){const n=t.container.element(e);return Re(t,e,n,[m.TablePartial])}function At(t,e,n){const s=t.container.scopeKind(e);if([x.REF,x.TABLE,x.TABLEPARTIAL].includes(s)){const i=Re(t,e,t.container.element(e),[m.Table,m.Schema,m.Column]);return $e(n.op,e)?je(i):i}return G()}function Re(t,e,n,s){var r;if(n===void 0)return G();let i=n;const a={suggestions:[]};for(;i;){if((r=i==null?void 0:i.symbol)!=null&&r.symbolTable){const{symbol:c}=i;a.suggestions.push(...t.symbol.members(c).filter(({kind:p})=>s.includes(p)).map(({name:p,kind:f})=>({label:p,insertText:p,insertTextRules:R.KeepWhitespace,kind:Oe(f),sortText:Oe(f).toString().padStart(2,"0"),range:void 0})))}i=i instanceof y?i.parent:void 0}return Je(a)}function Ns(t,e){var s;switch(t.container.scopeKind(e)){case x.INDEXES:return en(t,e);case x.REF:{const i=[...t.container.stack(e)];for(;i.length>0;){const a=i.pop();if(a instanceof le&&((s=a.op)==null?void 0:s.value)===".")return Kt(t,e,a)}}return Zt(t,e)}return G()}function _t(t,e,n){const{token:s}=t.container.token(e);if([h.COMMA,h.LBRACKET].includes(s==null?void 0:s.kind)){const i=gt(t,e);return(s==null?void 0:s.kind)===h.COMMA&&$e(s,e)?je(i):i}if(n.name&&n.name.start<=e&&n.name.end>=e)return gt(t,e);if(n.name instanceof te){const i=Ts(t,e,we(n.name).unwrap_or(""));return(s==null?void 0:s.kind)===h.COLON&&$e(s,e)?je(i):i}return G()}function gt(t,e){const n=t.container.element(e);if(n instanceof Z)return G();const s=t.container.scopeKind(e);if(n.body&&!Se(e,n.body)){let i;switch(s){case x.TABLE:case x.TABLEPARTIAL:i=[N.HeaderColor,N.Note];break;case x.TABLEGROUP:i=[N.Color,N.Note];break;default:i=[]}return{suggestions:i.map(a=>({label:a,insertText:`${a}: `,kind:P.Field,insertTextRules:R.KeepWhitespace,range:void 0}))}}switch(s){case x.TABLE:case x.TABLEPARTIAL:return{suggestions:[...[N.PK,N.PKey,N.Null,N.NotNull,N.Increment,N.Unique].map(i=>({label:i,insertText:i,kind:P.Property,insertTextRules:R.KeepWhitespace,range:void 0})),...[N.Ref,N.Default,N.Note].map(i=>({label:i,insertText:`${i}: `,kind:P.Property,insertTextRules:R.KeepWhitespace,range:void 0}))]};case x.ENUM:return{suggestions:[...[N.Note].map(i=>({label:i,insertText:`${i}: `,kind:P.Property,insertTextRules:R.KeepWhitespace,range:void 0}))]};case x.INDEXES:return{suggestions:[...[N.Unique,N.PK].map(i=>({label:i,insertText:i,insertTextRules:R.KeepWhitespace,kind:P.Property,range:void 0})),...[N.Note,N.Name,N.Type].map(i=>({label:i,insertText:`${i}: `,kind:P.Property,insertTextRules:R.KeepWhitespace,range:void 0}))]};case x.REF:return{suggestions:[N.Update,N.Delete].map(i=>({label:i,insertText:`${i}: `,kind:P.Property,insertTextRules:R.KeepWhitespace,range:void 0}))}}return G()}function Ts(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:P.Value,insertTextRules:R.KeepWhitespace,range:void 0}))};case"type":return{suggestions:["btree","hash"].map(s=>({label:s,insertText:`${s}`,kind:P.Value,insertTextRules:R.KeepWhitespace,range:void 0}))}}return G()}function Kt(t,e,n){const s=_e(n).unwrap_or([]);if(s.pop(),s.some(a=>!j(a)))return G();const i=s.map(a=>Y(a).unwrap());return Je({suggestions:t.symbol.ofName({nameStack:i,owner:t.container.element(e)}).flatMap(({symbol:a})=>t.symbol.members(a)).map(({kind:a,name:r})=>({label:r,insertText:r,kind:Oe(a),range:void 0}))})}function vt(t,e,n){var i;switch(t.container.scopeKind(e)){case x.TABLE:case x.TABLEPARTIAL:return bs(t,e,n);case x.PROJECT:return Is(t,e,n);case x.INDEXES:return As(t,e);case x.ENUM:return ms(t,e,n);case x.REF:{const a=Zt(t,e);return((i=t.container.token(e).token)==null?void 0:i.kind)===h.COLON&&$e(t.container.token(e).token,e)?je(a):a}case x.TABLEGROUP:return Ls(t);default:return G()}}function wt(){return{suggestions:["Table","TableGroup","Enum","Project","Ref","TablePartial"].map(t=>({label:t,insertText:t,insertTextRules:R.KeepWhitespace,kind:P.Keyword,range:void 0}))}}function ms(t,e,n){return n!=null&&n.callee&&ut(e,n)===1?Re(t,e,t.container.element(e),[m.Schema,m.Table,m.Column]):G()}function bs(t,e,n){const s=["Note","indexes"];if(!(n!=null&&n.callee))return{suggestions:s.map(a=>({label:a,insertText:a,insertTextRules:R.KeepWhitespace,kind:P.Keyword,range:void 0}))};const i=ut(e,n);return i===0?{suggestions:s.map(a=>({label:a,insertText:a,insertTextRules:R.KeepWhitespace,kind:P.Keyword,range:void 0}))}:i===1?_s(t,e):G()}function Is(t,e,n){const s=["Table","TableGroup","Enum","Note","Ref","TablePartial"];return n!=null&&n.callee?ut(e,n)===0?{suggestions:s.map(a=>({label:a,insertText:a,insertTextRules:R.KeepWhitespace,kind:P.Keyword,range:void 0}))}:G():{suggestions:s.map(a=>({label:a,insertText:a,insertTextRules:R.KeepWhitespace,kind:P.Keyword,range:void 0}))}}function Zt(t,e){return Re(t,e,t.container.element(e),[m.Schema,m.Table,m.Column])}function Ls(t){return{suggestions:[...Je({suggestions:[...t.parse.publicSymbolTable().entries()].flatMap(([e])=>{const n=re(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:R.KeepWhitespace,kind:Oe(s),range:void 0}})}).suggestions,...["Note"].map(e=>({label:e,insertText:e,insertTextRules:R.KeepWhitespace,kind:P.Keyword,range:void 0}))]}}function As(t,e){return en(t,e)}function _s(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:R.KeepWhitespace,kind:P.TypeParameter,sortText:P.TypeParameter.toString().padStart(2,"0"),range:void 0})),...Re(t,e,t.container.element(e),[m.Enum,m.Schema]).suggestions]}}function en(t,e){const n=t.container.element(e),s=n==null?void 0:n.parent;if(!((s==null?void 0:s.symbol)instanceof xt))return G();const{symbolTable:i}=s.symbol;return Je({suggestions:[...i.entries()].flatMap(([a])=>{const r=re(a).unwrap_or(void 0);if(r===void 0)return[];const{name:c}=r;return{label:c,insertText:c,insertTextRules:R.KeepWhitespace,kind:Oe(m.Column),range:void 0}})})}function ut(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 tn{constructor(e){this.compiler=e}provideDefinition(e,n){var r,c;const{uri:s}=e,i=ct(e,n),a=[...this.compiler.container.stack(i)];for(;a.length!==0;){const p=a.pop();if(!(p!=null&&p.referee))continue;let f;if((r=p.referee)!=null&&r.declaration&&[Ie.PRIMARY_EXPRESSION,Ie.VARIABLE,Ie.PARTIAL_INJECTION].includes(p==null?void 0:p.kind)?{declaration:f}=p.referee:(c=p.referee)!=null&&c.injectorDeclaration&&(f=p.referee.injectorDeclaration),f){const{startPos:d,endPos:u}=f;return[{range:{startColumn:d.column+1,startLineNumber:d.line+1,endColumn:u.column+1,endLineNumber:u.line+1},uri:s}]}}return[]}}class nn{constructor(e){this.compiler=e}provideReferences(e,n){const{uri:s}=e,i=ct(e,n),a=[...this.compiler.container.stack(i)];for(;a.length!==0;){const r=a.pop();if(r&&[Ie.ELEMENT_DECLARATION,Ie.FUNCTION_APPLICATION,Ie.PRIMARY_EXPRESSION].includes(r==null?void 0:r.kind)){const{symbol:c}=r;if(c!=null&&c.references.length)return c.references.map(({startPos:p,endPos:f})=>({range:{startColumn:p.column+1,startLineNumber:p.line+1,endColumn:f.column+1,endLineNumber:f.line+1},uri:s}))}}return[]}}const gs=Object.freeze(Object.defineProperty({__proto__:null,CompletionItemInsertTextRule:R,CompletionItemKind:P,DBMLCompletionItemProvider:Jt,DBMLDefinitionProvider:tn,DBMLReferencesProvider:nn},Symbol.toStringTag,{value:"Module"}));var x=(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[t.TABLEPARTIAL=9]="TABLEPARTIAL",t))(x||{});class vs{constructor(){this.source="",this.cache=new Array(16).fill(null),this.nodeIdGenerator=new rn,this.symbolIdGenerator=new fn,this.token={invalidStream:this.createQuery(6,()=>this.parse.tokens().filter(Rt)),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 yn(this.source).lex().chain(n=>new Sn(n,this.nodeIdGenerator).parse()).chain(({ast:n,tokens:s})=>new us(n,this.symbolIdGenerator).analyze().map(()=>({ast:n,tokens:s})));return e.getErrors().length>0?e:e.chain(({ast:n,tokens:s})=>new ds(n).interpret().map(a=>({ast:n,tokens:s,rawDb:a})))}),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.token.flatStream(),{index:s,token:i}=this.container.token(e),a=s===void 0?-1:A.findLastIndex(n,f=>!f.isInvalid,s);if(a===-1)return[this.parse.ast()];const r=n[a].start;let c=this.parse.ast();const p=[c];for(;;){const d=wn(c).find(u=>Se(r,u));if(d===void 0||d instanceof J)break;p.push(d),c=d}if((i==null?void 0:i.kind)===h.COLON)return p;for(;p.length>0;){let f=!1;const d=A.last(p);if(d instanceof w){const u=this.parse.source();for(let E=d.end;E<e;E+=1)u[E]===`
|
|
12
|
+
`&&(p.pop(),f=!0)}else d instanceof oe||d instanceof le?this.container.token(e).token!==d.op&&(p.pop(),f=!0):d instanceof M?d.listCloseBracket&&d.end<=e&&(p.pop(),f=!0):d instanceof ce?d.tupleCloseParen&&d.end<=e&&(p.pop(),f=!0):d instanceof ae?d.blockCloseBrace&&d.end<=e&&(p.pop(),f=!0):d instanceof te||d.end<e&&(p.pop(),f=!0);if(f){const u=A.last(p);u instanceof y&&u.end<=e&&p.pop()}if(!f)break}return p}),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 y)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 Z)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;case"tablepartial":return 9;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 a=n;a;a=a instanceof y?a.parent:void 0){if(!((i=a.symbol)!=null&&i.symbolTable))continue;const{symbolTable:r}=a.symbol;let c=[r],p=[];for(const f of e)p=c.flatMap(d=>In(f).flatMap(u=>{const E=d.get(u),L=re(u).unwrap_or(void 0);return!E||!L?[]:{...L,symbol:E}})),c=p.flatMap(d=>d.symbol.symbolTable?d.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])=>({...re(n).unwrap(),symbol:s})):[])}}createQuery(e,n,s){return i=>{const a=this.cache[e],r=i&&s?s(i):i;if(a!==null){if(!(a instanceof Map))return a;if(a.has(r))return a.get(r)}const c=n(i);return i!==void 0?a instanceof Map?a.set(r,c):(this.cache[e]=new Map,this.cache[e].set(r,c)):this.cache[e]=c,c}}setSource(e){this.source=e,this.cache=new Array(16).fill(null),this.nodeIdGenerator.reset(),this.symbolIdGenerator.reset()}initMonacoServices(){return{definitionProvider:new tn(this),referenceProvider:new nn(this),autocompletionProvider:new Jt(this)}}}exports.Compiler=vs;exports.serialize=on;exports.services=gs;
|