@dbml/parse 3.13.0-alpha.0 → 3.13.0-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/compiler.d.ts +2 -1
- package/dist/dbml-parse.js +6 -6
- package/dist/dbml-parse.mjs +587 -571
- package/dist/lib/parser/nodes.d.ts +2 -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 I=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 Zt(t){switch(t.kind){case"<newline>":case"<space>":case"<tab>":case"<single-line-comment>":case"<multiline-comment>":return!0;default:return!1}}function ht(t){if(!t)return!1;switch(t){case"+":case"-":case"*":case"/":case"%":case"<":case">":case"=":case"!":case".":case"&":case"|":case"~":return!0;default:return!1}}function ft(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 wt(t){return t.trailingTrivia.find(({kind:e})=>e===h.NEWLINE)!==void 0}function pt(t,e){return e.leadingTrivia.find(({kind:s})=>s===h.NEWLINE)!==void 0||wt(t)}function Ke(t){return t.trailingTrivia.find(({kind:e})=>[h.SPACE,h.TAB].includes(e))!==void 0}function yt(t){return t.trailingTrivia.length===0?t.end:yt(I.last(t.trailingTrivia))}function kt(t){return t.leadingTrivia.length===0?t.start:kt(t.leadingTrivia[0])}function en(t){return[h.SINGLE_LINE_COMMENT,h.MULTILINE_COMMENT].includes(t.kind)}class tn{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 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?yt(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 _e=(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))(_e||{});class K 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},f){if(super(f,"<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 Z extends D{constructor({op:e,expression:n},s){super(s,"<prefix-expression>",[e,n]),this.op=e,this.expression=n}}class le 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 $e extends D{constructor({op:e,expression:n},s){super(s,"<postfix-expression>",[n,e]),this.op=e,this.expression=n}}class ce 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 re 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 ke extends D{constructor({partial:e},n){super(n,"<partial-injection>",[e]),this.partial=e}}class R extends D{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 fe extends D{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 fe{constructor({groupOpenParen:e,expression:n,groupCloseParen:s},i){super({tupleOpenParen:e,elementList:n&&[n],commaList:[],tupleCloseParen:s},i),this.kind="<group-expression>"}}class q extends D{constructor({callee:e,argumentList:n},s){super(s,"<call-expression>",[e,n]),this.callee=e,this.argumentList=n}}class ge extends D{constructor({literal:e},n){super(n,"<literal>",[e]),this.literal=e}}class ae extends D{constructor({variable:e},n){super(n,"<variable>",[e]),this.variable=e}}class G extends D{constructor({expression:e},n){super(n,"<primary-expression>",[e]),this.expression=e}}class Re extends D{constructor({pre:e},n){const s=J.create(h.SPACE,e.endPos,e.endPos," ",!1);super(n,"<dummy>",[s])}}class ue extends D{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?I.flatten(I.zip(t,e)):I.flatten(I.zip(e,t))).filter(i=>i!==null)}function nn(t,e=!1){return JSON.stringify(t,function(n,s){var i;return!(this instanceof K)&&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 O{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 O(e(this.value))}isOk(){return!0}}class x{unwrap(){throw new Error("Trying to unwrap a None value")}unwrap_or(e){return e}and_then(e){return new x}map(e){return new x}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 Fe(t){return`Table:${t}`}function je(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 sn(t){return`Note:${t}`}function Pt(t){return`TablePartial:${t}`}function an(t){return`TablePartialInjection:${t}`}function Ue(t,e){switch(e){case"Column":return je(t);case"Enum":return nt(t);case"Enum field":return st(t);case"Schema":return tt(t);case"Table":return Fe(t);case"TableGroup":return it(t);case"TableGroup field":return at(t);case"TablePartial":return Pt(t);default:throw new Error("Unreachable")}}function oe(t){const[e,n]=t.split(":");return Object.values(m).includes(e)?new O({name:n,kind:e}):new x}function rn(t){const e=oe(t).unwrap_or(void 0);if(!e)return!1;const{kind:n,name:s}=e;return n==="Schema"&&s==="public"}function on(t){const e=oe(t).unwrap_or(void 0);if(!e)return!1;const{kind:n}=e;return n==="TablePartialInjection"}function ln(t){const e=oe(t).unwrap_or(void 0);if(!e)return null;const{kind:n,name:s}=e;return n==="TablePartialInjection"?Ue(s,"TablePartial"):null}function cn(t){return[tt,Fe,nt,it,je,st,at].map(e=>e(t))}function We(t){return!!t.match(/(\p{L}|_|\p{M})/gu)}function Be(t){const[e]=t;return e>="0"&&e<="9"}function un(t){const[e]=t;return Be(e)||We(e)&&e.toLowerCase()>="a"&&e.toLowerCase()<="f"}function Le(t){return We(t)||Be(t)}function dt(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 ye(t,e){return t>=e.start&&t<e.end}class hn{constructor(){this.id=0}reset(){this.id=0}nextId(){return this.id++}}class xt{constructor({symbolTable:e},n){this.references=[],this.id=n,this.symbolTable=e}}class fn{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class pn{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}class Dt{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 dn{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class En{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}class Nn{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 Tn{constructor({injectorId:e},n){this.references=[],this.id=n,this.injectorId=e}}var o=(t=>(t[t.UNKNOWN_SYMBOL=1e3]="UNKNOWN_SYMBOL",t[t.UNEXPECTED_SYMBOL=1001]="UNEXPECTED_SYMBOL",t[t.UNEXPECTED_EOF=1002]="UNEXPECTED_EOF",t[t.UNEXPECTED_NEWLINE=1003]="UNEXPECTED_NEWLINE",t[t.UNKNOWN_TOKEN=1004]="UNKNOWN_TOKEN",t[t.UNEXPECTED_TOKEN=1005]="UNEXPECTED_TOKEN",t[t.UNEXPECTED_ELEMENT_DECLARATION=1006]="UNEXPECTED_ELEMENT_DECLARATION",t[t.MISSING_SPACES=1007]="MISSING_SPACES",t[t.UNKNOWN_PREFIX_OP=1008]="UNKNOWN_PREFIX_OP",t[t.INVALID_OPERAND=1009]="INVALID_OPERAND",t[t.EMPTY_ATTRIBUTE_NAME=1010]="EMPTY_ATTRIBUTE_NAME",t[t.INVALID_ESCAPE_SEQUENCE=1011]="INVALID_ESCAPE_SEQUENCE",t[t.INVALID_NAME=3e3]="INVALID_NAME",t[t.UNEXPECTED_NAME=3001]="UNEXPECTED_NAME",t[t.NAME_NOT_FOUND=3002]="NAME_NOT_FOUND",t[t.DUPLICATE_NAME=3003]="DUPLICATE_NAME",t[t.INVALID_ALIAS=3004]="INVALID_ALIAS",t[t.UNEXPECTED_ALIAS=3005]="UNEXPECTED_ALIAS",t[t.UNEXPECTED_SETTINGS=3006]="UNEXPECTED_SETTINGS",t[t.INVALID_SETTINGS=3007]="INVALID_SETTINGS",t[t.UNEXPECTED_SIMPLE_BODY=3008]="UNEXPECTED_SIMPLE_BODY",t[t.UNEXPECTED_COMPLEX_BODY=3009]="UNEXPECTED_COMPLEX_BODY",t[t.INVALID_TABLE_CONTEXT=3010]="INVALID_TABLE_CONTEXT",t[t.INVALID_TABLE_SETTING=3011]="INVALID_TABLE_SETTING",t[t.DUPLICATE_TABLE_SETTING=3012]="DUPLICATE_TABLE_SETTING",t[t.INVALID_TABLE_FIELD=3013]="INVALID_TABLE_FIELD",t[t.INVALID_TABLEGROUP_CONTEXT=3014]="INVALID_TABLEGROUP_CONTEXT",t[t.INVALID_TABLEGROUP_ELEMENT_NAME=3015]="INVALID_TABLEGROUP_ELEMENT_NAME",t[t.DUPLICATE_TABLEGROUP_ELEMENT_NAME=3016]="DUPLICATE_TABLEGROUP_ELEMENT_NAME",t[t.DUPLICATE_TABLEGROUP_FIELD_NAME=3017]="DUPLICATE_TABLEGROUP_FIELD_NAME",t[t.INVALID_TABLEGROUP_FIELD=3018]="INVALID_TABLEGROUP_FIELD",t[t.INVALID_TABLE_PARTIAL_CONTEXT=3019]="INVALID_TABLE_PARTIAL_CONTEXT",t[t.INVALID_TABLE_PARTIAL_ELEMENT_NAME=3020]="INVALID_TABLE_PARTIAL_ELEMENT_NAME",t[t.INVALID_TABLE_PARTIAL_SETTING=3021]="INVALID_TABLE_PARTIAL_SETTING",t[t.DUPLICATE_TABLE_PARTIAL_ELEMENT_NAME=3022]="DUPLICATE_TABLE_PARTIAL_ELEMENT_NAME",t[t.DUPLICATE_TABLE_PARTIAL_SETTING=3023]="DUPLICATE_TABLE_PARTIAL_SETTING",t[t.INVALID_TABLE_PARTIAL_INJECTION=3024]="INVALID_TABLE_PARTIAL_INJECTION",t[t.INVALID_TABLE_PARTIAL_INJECTION_OP=3025]="INVALID_TABLE_PARTIAL_INJECTION_OP",t[t.INVALID_TABLE_PARTIAL_INJECTION_NAME=3026]="INVALID_TABLE_PARTIAL_INJECTION_NAME",t[t.DUPLICATE_TABLE_PARTIAL_INJECTION_NAME=3027]="DUPLICATE_TABLE_PARTIAL_INJECTION_NAME",t[t.EMPTY_TABLE=3028]="EMPTY_TABLE",t[t.INVALID_COLUMN=3029]="INVALID_COLUMN",t[t.INVALID_COLUMN_NAME=3030]="INVALID_COLUMN_NAME",t[t.UNKNOWN_COLUMN_SETTING=3031]="UNKNOWN_COLUMN_SETTING",t[t.INVALID_COLUMN_TYPE=3032]="INVALID_COLUMN_TYPE",t[t.DUPLICATE_COLUMN_NAME=3033]="DUPLICATE_COLUMN_NAME",t[t.DUPLICATE_COLUMN_SETTING=3034]="DUPLICATE_COLUMN_SETTING",t[t.INVALID_COLUMN_SETTING_VALUE=3035]="INVALID_COLUMN_SETTING_VALUE",t[t.INVALID_ENUM_CONTEXT=3036]="INVALID_ENUM_CONTEXT",t[t.INVALID_ENUM_ELEMENT_NAME=3037]="INVALID_ENUM_ELEMENT_NAME",t[t.INVALID_ENUM_ELEMENT=3038]="INVALID_ENUM_ELEMENT",t[t.DUPLICATE_ENUM_ELEMENT_NAME=3039]="DUPLICATE_ENUM_ELEMENT_NAME",t[t.UNKNOWN_ENUM_ELEMENT_SETTING=3040]="UNKNOWN_ENUM_ELEMENT_SETTING",t[t.DUPLICATE_ENUM_ELEMENT_SETTING=3041]="DUPLICATE_ENUM_ELEMENT_SETTING",t[t.INVALID_ENUM_ELEMENT_SETTING=3042]="INVALID_ENUM_ELEMENT_SETTING",t[t.EMPTY_ENUM=3043]="EMPTY_ENUM",t[t.INVALID_REF_CONTEXT=3044]="INVALID_REF_CONTEXT",t[t.UNKNOWN_REF_SETTING=3045]="UNKNOWN_REF_SETTING",t[t.DUPLICATE_REF_SETTING=3046]="DUPLICATE_REF_SETTING",t[t.INVALID_REF_SETTING_VALUE=3047]="INVALID_REF_SETTING_VALUE",t[t.INVALID_REF_RELATIONSHIP=3048]="INVALID_REF_RELATIONSHIP",t[t.INVALID_REF_FIELD=3049]="INVALID_REF_FIELD",t[t.EMPTY_REF=3050]="EMPTY_REF",t[t.REF_REDEFINED=3051]="REF_REDEFINED",t[t.INVALID_NOTE_CONTEXT=3052]="INVALID_NOTE_CONTEXT",t[t.INVALID_NOTE=3053]="INVALID_NOTE",t[t.NOTE_REDEFINED=3054]="NOTE_REDEFINED",t[t.NOTE_CONTENT_REDEFINED=3055]="NOTE_CONTENT_REDEFINED",t[t.EMPTY_NOTE=3056]="EMPTY_NOTE",t[t.INVALID_INDEXES_CONTEXT=3057]="INVALID_INDEXES_CONTEXT",t[t.INVALID_INDEXES_FIELD=3058]="INVALID_INDEXES_FIELD",t[t.INVALID_INDEX=3059]="INVALID_INDEX",t[t.UNKNOWN_INDEX_SETTING=3060]="UNKNOWN_INDEX_SETTING",t[t.DUPLICATE_INDEX_SETTING=3061]="DUPLICATE_INDEX_SETTING",t[t.UNEXPECTED_INDEX_SETTING_VALUE=3062]="UNEXPECTED_INDEX_SETTING_VALUE",t[t.INVALID_INDEX_SETTING_VALUE=3063]="INVALID_INDEX_SETTING_VALUE",t[t.INVALID_PROJECT_CONTEXT=3064]="INVALID_PROJECT_CONTEXT",t[t.PROJECT_REDEFINED=3065]="PROJECT_REDEFINED",t[t.INVALID_PROJECT_FIELD=3066]="INVALID_PROJECT_FIELD",t[t.INVALID_CUSTOM_CONTEXT=3067]="INVALID_CUSTOM_CONTEXT",t[t.INVALID_CUSTOM_ELEMENT_VALUE=3068]="INVALID_CUSTOM_ELEMENT_VALUE",t[t.INVALID_ELEMENT_IN_SIMPLE_BODY=3069]="INVALID_ELEMENT_IN_SIMPLE_BODY",t[t.BINDING_ERROR=4e3]="BINDING_ERROR",t[t.UNSUPPORTED=5e3]="UNSUPPORTED",t[t.CIRCULAR_REF=5001]="CIRCULAR_REF",t[t.SAME_ENDPOINT=5002]="SAME_ENDPOINT",t[t.UNEQUAL_FIELDS_BINARY_REF=5003]="UNEQUAL_FIELDS_BINARY_REF",t[t.CONFLICTING_SETTING=5004]="CONFLICTING_SETTING",t[t.TABLE_REAPPEAR_IN_TABLEGROUP=5005]="TABLE_REAPPEAR_IN_TABLEGROUP",t))(o||{});class 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 Y{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 Y(n.value,s)}map(e){return new Y(e(this.value),this.errors)}}function bn(t,e,n){if(!t||!he(t)||e.length===0)return new x;const s=[...e],i=Je(t).unwrap(),a=s.pop();if(!(a instanceof re))return new x;const r=I.last(s)instanceof R?s.pop():void 0;return s.length===3&&Je(s[1]).unwrap().value==="as"?new O(n.create(y,{type:i,name:s[0],as:Je(s[1]).unwrap(),alias:s[2],attributeList:r,body:a})):s.length===1?new O(n.create(y,{type:i,name:s[0],attributeList:r,body:a})):s.length===0?new O(n.create(y,{type:i,attributeList:r,body:a})):new x}function Et(t){return t.kind===h.IDENTIFIER&&t.value==="as"}function T(t){t&&(t instanceof J?In(t):Ln(t))}function In(t){t.kind!==h.EOF&&(t.isInvalid=!0)}function Ln(t){if(t instanceof y)T(t.type),T(t.name),T(t.as),T(t.alias),T(t.bodyColon),T(t.attributeList),T(t.body);else if(t instanceof ne)t.identifiers.forEach(T);else if(t instanceof se)T(t.name),T(t.colon),T(t.value);else if(t instanceof Z)T(t.op),T(t.expression);else if(t instanceof le)T(t.leftExpression),T(t.op),T(t.rightExpression);else if(t instanceof $e)T(t.op),T(t.expression);else if(t instanceof re)T(t.blockOpenBrace),t.body.forEach(T),T(t.blockCloseBrace);else if(t instanceof R)T(t.listOpenBracket),t.commaList.forEach(T),t.elementList.forEach(T),T(t.listCloseBracket);else if(t instanceof fe)T(t.tupleOpenParen),t.commaList.forEach(T),t.elementList.forEach(T),T(t.tupleCloseParen);else if(t instanceof q)T(t.callee),T(t.argumentList);else if(t instanceof w)T(t.callee),t.args.forEach(T);else if(t instanceof G)T(t.expression);else if(t instanceof ce)T(t.value);else if(t instanceof ae)T(t.variable);else if(t instanceof ge)T(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 j(...t){return t.filter(e=>e!==void 0)}function _n(t){if(t instanceof K)return j(...t.body,t.eof);if(t instanceof y)return j(t.type,t.name,t.as,t.alias,t.attributeList,t.bodyColon,t.body);if(t instanceof se)return j(t.name,t.colon,t.value);if(t instanceof ne)return t.identifiers;if(t instanceof ge)return t.literal?[t.literal]:[];if(t instanceof ae)return j(t.variable);if(t instanceof Z)return j(t.op,t.expression);if(t instanceof le)return j(t.leftExpression,t.op,t.rightExpression);if(t instanceof $e)return j(t.expression,t.op);if(t instanceof ce)return j(t.value);if(t instanceof w)return j(t.callee,...t.args);if(t instanceof re)return j(t.blockOpenBrace,...t.body,t.blockCloseBrace);if(t instanceof R)return j(t.listOpenBracket,...dt(t.elementList,t.commaList),t.listCloseBracket);if(t instanceof fe)return j(t.tupleOpenParen,...dt(t.elementList,t.commaList),t.tupleCloseParen);if(t instanceof q)return j(t.callee,t.argumentList);if(t instanceof G)return j(t.expression);if(t instanceof ue)return j(t.array,t.indexer);throw t instanceof et?new Error("This case is already handled by TupleExpressionNode"):new Error("Unreachable - no other possible cases")}function Je(t){return $(t)?new O(t.expression.variable):new x}function C(t){var e;return t instanceof G&&(t.expression instanceof ae&&t.expression.variable instanceof J&&t.expression.variable.kind===h.QUOTED_STRING||t.expression instanceof ge&&((e=t.expression.literal)==null?void 0:e.kind)===h.STRING_LITERAL)}function $(t){return t instanceof G&&t.expression instanceof ae&&t.expression.variable instanceof J}function he(t){var e;return t instanceof G&&t.expression instanceof ae&&((e=t.expression.variable)==null?void 0:e.kind)===h.IDENTIFIER}function qe(t){var e;return t instanceof le&&t.leftExpression instanceof D&&t.rightExpression instanceof D&&((e=t.op)==null?void 0:e.value)==="."}function Ae(t){if(t===void 0)return new x;const e=t.identifiers.map(n=>n.value).join(" ");return e===""?new x:new O(e)}class An{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===`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I=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 en(t){switch(t.kind){case"<newline>":case"<space>":case"<tab>":case"<single-line-comment>":case"<multiline-comment>":return!0;default:return!1}}function ht(t){if(!t)return!1;switch(t){case"+":case"-":case"*":case"/":case"%":case"<":case">":case"=":case"!":case".":case"&":case"|":case"~":return!0;default:return!1}}function ft(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 pt(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 kt(t){return t.trailingTrivia.length===0?t.end:kt(I.last(t.trailingTrivia))}function St(t){return t.leadingTrivia.length===0?t.start:St(t.leadingTrivia[0])}function tn(t){return[h.SINGLE_LINE_COMMENT,h.MULTILINE_COMMENT].includes(t.kind)}class nn{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 J?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 J?kt(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 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},f){if(super(f,"<element-declaration>",[e,n,s,i,a,r,c]),c&&r&&!(c instanceof v||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 K extends D{constructor({op:e,expression:n},s){super(s,"<prefix-expression>",[e,n]),this.op=e,this.expression=n}}class le 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 je extends D{constructor({op:e,expression:n},s){super(s,"<postfix-expression>",[n,e]),this.op=e,this.expression=n}}class ce extends D{constructor({value:e},n){super(n,"<function-expression>",[e]),this.value=e}}class v extends D{constructor({callee:e,args:n=[]},s){super(s,"<function-application>",[e,...n]),this.callee=e,this.args=n}}class re 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 Le extends D{constructor({op:e,partial:n},s){super(s,"<partial-injection>",[e,n]),this.partial=n}}class R extends D{constructor({listOpenBracket:e,elementList:n=[],commaList:s=[],listCloseBracket:i},a){super(a,"<list-expression>",[e,...Pt(n,s),i]),this.listOpenBracket=e,this.elementList=n,this.commaList=s,this.listCloseBracket=i}}class fe extends D{constructor({tupleOpenParen:e,elementList:n=[],commaList:s=[],tupleCloseParen:i},a){super(a,"<tuple-expression>",[e,...Pt(n,s),i]),this.tupleOpenParen=e,this.elementList=n,this.commaList=s,this.tupleCloseParen=i}}class et extends fe{constructor({groupOpenParen:e,expression:n,groupCloseParen:s},i){super({tupleOpenParen:e,elementList:n&&[n],commaList:[],tupleCloseParen:s},i),this.kind="<group-expression>"}}class q extends D{constructor({callee:e,argumentList:n},s){super(s,"<call-expression>",[e,n]),this.callee=e,this.argumentList=n}}class ve extends D{constructor({literal:e},n){super(n,"<literal>",[e]),this.literal=e}}class ae extends D{constructor({variable:e},n){super(n,"<variable>",[e]),this.variable=e}}class G extends D{constructor({expression:e},n){super(n,"<primary-expression>",[e]),this.expression=e}}class Ue extends D{constructor({pre:e},n){const s=J.create(h.SPACE,e.endPos,e.endPos," ",!1);super(n,"<dummy>",[s])}}class ue extends D{constructor({expression:e,indexer:n},s){super(s,"<array>",[e,n]),this.array=e,this.indexer=n}}function Pt(t,e){if(!t||t.length===0)return e||[];if(!e||e.length===0)return t||[];const[n]=t,[s]=e;return(n.start<s.start?I.flatten(I.zip(t,e)):I.flatten(I.zip(e,t))).filter(i=>i!==null)}function sn(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 O{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 O(e(this.value))}isOk(){return!0}}class x{unwrap(){throw new Error("Trying to unwrap a None value")}unwrap_or(e){return e}and_then(e){return new x}map(e){return new x}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 Be(t){return`Table:${t}`}function We(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 an(t){return`Note:${t}`}function xt(t){return`TablePartial:${t}`}function rn(t){return`TablePartialInjection:${t}`}function Me(t,e){switch(e){case"Column":return We(t);case"Enum":return nt(t);case"Enum field":return st(t);case"Schema":return tt(t);case"Table":return Be(t);case"TableGroup":return it(t);case"TableGroup field":return at(t);case"TablePartial":return xt(t);default:throw new Error("Unreachable")}}function oe(t){const[e,n]=t.split(":");return Object.values(m).includes(e)?new O({name:n,kind:e}):new x}function on(t){const e=oe(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=oe(t).unwrap_or(void 0);if(!e)return!1;const{kind:n}=e;return n==="TablePartialInjection"}function cn(t){const e=oe(t).unwrap_or(void 0);if(!e)return null;const{kind:n,name:s}=e;return n==="TablePartialInjection"?Me(s,"TablePartial"):null}function un(t){return[tt,Be,nt,it,We,st,at].map(e=>e(t))}function qe(t){return!!t.match(/(\p{L}|_|\p{M})/gu)}function Ve(t){const[e]=t;return e>="0"&&e<="9"}function hn(t){const[e]=t;return Ve(e)||qe(e)&&e.toLowerCase()>="a"&&e.toLowerCase()<="f"}function Ae(t){return qe(t)||Ve(t)}function dt(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 ke(t,e){return t>=e.start&&t<e.end}class fn{constructor(){this.id=0}reset(){this.id=0}nextId(){return this.id++}}class Dt{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 Ot{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class Rt{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 mn{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class Tn{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}class bn{constructor({injectorId:e},n){this.references=[],this.id=n,this.injectorId=e}}var o=(t=>(t[t.UNKNOWN_SYMBOL=1e3]="UNKNOWN_SYMBOL",t[t.UNEXPECTED_SYMBOL=1001]="UNEXPECTED_SYMBOL",t[t.UNEXPECTED_EOF=1002]="UNEXPECTED_EOF",t[t.UNEXPECTED_NEWLINE=1003]="UNEXPECTED_NEWLINE",t[t.UNKNOWN_TOKEN=1004]="UNKNOWN_TOKEN",t[t.UNEXPECTED_TOKEN=1005]="UNEXPECTED_TOKEN",t[t.UNEXPECTED_ELEMENT_DECLARATION=1006]="UNEXPECTED_ELEMENT_DECLARATION",t[t.MISSING_SPACES=1007]="MISSING_SPACES",t[t.UNKNOWN_PREFIX_OP=1008]="UNKNOWN_PREFIX_OP",t[t.INVALID_OPERAND=1009]="INVALID_OPERAND",t[t.EMPTY_ATTRIBUTE_NAME=1010]="EMPTY_ATTRIBUTE_NAME",t[t.INVALID_ESCAPE_SEQUENCE=1011]="INVALID_ESCAPE_SEQUENCE",t[t.INVALID_NAME=3e3]="INVALID_NAME",t[t.UNEXPECTED_NAME=3001]="UNEXPECTED_NAME",t[t.NAME_NOT_FOUND=3002]="NAME_NOT_FOUND",t[t.DUPLICATE_NAME=3003]="DUPLICATE_NAME",t[t.INVALID_ALIAS=3004]="INVALID_ALIAS",t[t.UNEXPECTED_ALIAS=3005]="UNEXPECTED_ALIAS",t[t.UNEXPECTED_SETTINGS=3006]="UNEXPECTED_SETTINGS",t[t.INVALID_SETTINGS=3007]="INVALID_SETTINGS",t[t.UNEXPECTED_SIMPLE_BODY=3008]="UNEXPECTED_SIMPLE_BODY",t[t.UNEXPECTED_COMPLEX_BODY=3009]="UNEXPECTED_COMPLEX_BODY",t[t.INVALID_TABLE_CONTEXT=3010]="INVALID_TABLE_CONTEXT",t[t.INVALID_TABLE_SETTING=3011]="INVALID_TABLE_SETTING",t[t.DUPLICATE_TABLE_SETTING=3012]="DUPLICATE_TABLE_SETTING",t[t.INVALID_TABLE_FIELD=3013]="INVALID_TABLE_FIELD",t[t.INVALID_TABLEGROUP_CONTEXT=3014]="INVALID_TABLEGROUP_CONTEXT",t[t.INVALID_TABLEGROUP_ELEMENT_NAME=3015]="INVALID_TABLEGROUP_ELEMENT_NAME",t[t.DUPLICATE_TABLEGROUP_ELEMENT_NAME=3016]="DUPLICATE_TABLEGROUP_ELEMENT_NAME",t[t.DUPLICATE_TABLEGROUP_FIELD_NAME=3017]="DUPLICATE_TABLEGROUP_FIELD_NAME",t[t.INVALID_TABLEGROUP_FIELD=3018]="INVALID_TABLEGROUP_FIELD",t[t.INVALID_TABLE_PARTIAL_CONTEXT=3019]="INVALID_TABLE_PARTIAL_CONTEXT",t[t.INVALID_TABLE_PARTIAL_ELEMENT_NAME=3020]="INVALID_TABLE_PARTIAL_ELEMENT_NAME",t[t.INVALID_TABLE_PARTIAL_SETTING=3021]="INVALID_TABLE_PARTIAL_SETTING",t[t.DUPLICATE_TABLE_PARTIAL_ELEMENT_NAME=3022]="DUPLICATE_TABLE_PARTIAL_ELEMENT_NAME",t[t.DUPLICATE_TABLE_PARTIAL_SETTING=3023]="DUPLICATE_TABLE_PARTIAL_SETTING",t[t.INVALID_TABLE_PARTIAL_INJECTION=3024]="INVALID_TABLE_PARTIAL_INJECTION",t[t.INVALID_TABLE_PARTIAL_INJECTION_OP=3025]="INVALID_TABLE_PARTIAL_INJECTION_OP",t[t.INVALID_TABLE_PARTIAL_INJECTION_NAME=3026]="INVALID_TABLE_PARTIAL_INJECTION_NAME",t[t.DUPLICATE_TABLE_PARTIAL_INJECTION_NAME=3027]="DUPLICATE_TABLE_PARTIAL_INJECTION_NAME",t[t.EMPTY_TABLE=3028]="EMPTY_TABLE",t[t.INVALID_COLUMN=3029]="INVALID_COLUMN",t[t.INVALID_COLUMN_NAME=3030]="INVALID_COLUMN_NAME",t[t.UNKNOWN_COLUMN_SETTING=3031]="UNKNOWN_COLUMN_SETTING",t[t.INVALID_COLUMN_TYPE=3032]="INVALID_COLUMN_TYPE",t[t.DUPLICATE_COLUMN_NAME=3033]="DUPLICATE_COLUMN_NAME",t[t.DUPLICATE_COLUMN_SETTING=3034]="DUPLICATE_COLUMN_SETTING",t[t.INVALID_COLUMN_SETTING_VALUE=3035]="INVALID_COLUMN_SETTING_VALUE",t[t.INVALID_ENUM_CONTEXT=3036]="INVALID_ENUM_CONTEXT",t[t.INVALID_ENUM_ELEMENT_NAME=3037]="INVALID_ENUM_ELEMENT_NAME",t[t.INVALID_ENUM_ELEMENT=3038]="INVALID_ENUM_ELEMENT",t[t.DUPLICATE_ENUM_ELEMENT_NAME=3039]="DUPLICATE_ENUM_ELEMENT_NAME",t[t.UNKNOWN_ENUM_ELEMENT_SETTING=3040]="UNKNOWN_ENUM_ELEMENT_SETTING",t[t.DUPLICATE_ENUM_ELEMENT_SETTING=3041]="DUPLICATE_ENUM_ELEMENT_SETTING",t[t.INVALID_ENUM_ELEMENT_SETTING=3042]="INVALID_ENUM_ELEMENT_SETTING",t[t.EMPTY_ENUM=3043]="EMPTY_ENUM",t[t.INVALID_REF_CONTEXT=3044]="INVALID_REF_CONTEXT",t[t.UNKNOWN_REF_SETTING=3045]="UNKNOWN_REF_SETTING",t[t.DUPLICATE_REF_SETTING=3046]="DUPLICATE_REF_SETTING",t[t.INVALID_REF_SETTING_VALUE=3047]="INVALID_REF_SETTING_VALUE",t[t.INVALID_REF_RELATIONSHIP=3048]="INVALID_REF_RELATIONSHIP",t[t.INVALID_REF_FIELD=3049]="INVALID_REF_FIELD",t[t.EMPTY_REF=3050]="EMPTY_REF",t[t.REF_REDEFINED=3051]="REF_REDEFINED",t[t.INVALID_NOTE_CONTEXT=3052]="INVALID_NOTE_CONTEXT",t[t.INVALID_NOTE=3053]="INVALID_NOTE",t[t.NOTE_REDEFINED=3054]="NOTE_REDEFINED",t[t.NOTE_CONTENT_REDEFINED=3055]="NOTE_CONTENT_REDEFINED",t[t.EMPTY_NOTE=3056]="EMPTY_NOTE",t[t.INVALID_INDEXES_CONTEXT=3057]="INVALID_INDEXES_CONTEXT",t[t.INVALID_INDEXES_FIELD=3058]="INVALID_INDEXES_FIELD",t[t.INVALID_INDEX=3059]="INVALID_INDEX",t[t.UNKNOWN_INDEX_SETTING=3060]="UNKNOWN_INDEX_SETTING",t[t.DUPLICATE_INDEX_SETTING=3061]="DUPLICATE_INDEX_SETTING",t[t.UNEXPECTED_INDEX_SETTING_VALUE=3062]="UNEXPECTED_INDEX_SETTING_VALUE",t[t.INVALID_INDEX_SETTING_VALUE=3063]="INVALID_INDEX_SETTING_VALUE",t[t.INVALID_PROJECT_CONTEXT=3064]="INVALID_PROJECT_CONTEXT",t[t.PROJECT_REDEFINED=3065]="PROJECT_REDEFINED",t[t.INVALID_PROJECT_FIELD=3066]="INVALID_PROJECT_FIELD",t[t.INVALID_CUSTOM_CONTEXT=3067]="INVALID_CUSTOM_CONTEXT",t[t.INVALID_CUSTOM_ELEMENT_VALUE=3068]="INVALID_CUSTOM_ELEMENT_VALUE",t[t.INVALID_ELEMENT_IN_SIMPLE_BODY=3069]="INVALID_ELEMENT_IN_SIMPLE_BODY",t[t.BINDING_ERROR=4e3]="BINDING_ERROR",t[t.UNSUPPORTED=5e3]="UNSUPPORTED",t[t.CIRCULAR_REF=5001]="CIRCULAR_REF",t[t.SAME_ENDPOINT=5002]="SAME_ENDPOINT",t[t.UNEQUAL_FIELDS_BINARY_REF=5003]="UNEQUAL_FIELDS_BINARY_REF",t[t.CONFLICTING_SETTING=5004]="CONFLICTING_SETTING",t[t.TABLE_REAPPEAR_IN_TABLEGROUP=5005]="TABLE_REAPPEAR_IN_TABLEGROUP",t))(o||{});class 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 Y{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 Y(n.value,s)}map(e){return new Y(e(this.value),this.errors)}}function In(t,e,n){if(!t||!he(t)||e.length===0)return new x;const s=[...e],i=Je(t).unwrap(),a=s.pop();if(!(a instanceof re))return new x;const r=I.last(s)instanceof R?s.pop():void 0;return s.length===3&&Je(s[1]).unwrap().value==="as"?new O(n.create(y,{type:i,name:s[0],as:Je(s[1]).unwrap(),alias:s[2],attributeList:r,body:a})):s.length===1?new O(n.create(y,{type:i,name:s[0],attributeList:r,body:a})):s.length===0?new O(n.create(y,{type:i,attributeList:r,body:a})):new x}function Et(t){return t.kind===h.IDENTIFIER&&t.value==="as"}function T(t){t&&(t instanceof J?Ln(t):_n(t))}function Ln(t){t.kind!==h.EOF&&(t.isInvalid=!0)}function _n(t){if(t instanceof y)T(t.type),T(t.name),T(t.as),T(t.alias),T(t.bodyColon),T(t.attributeList),T(t.body);else if(t instanceof ne)t.identifiers.forEach(T);else if(t instanceof se)T(t.name),T(t.colon),T(t.value);else if(t instanceof K)T(t.op),T(t.expression);else if(t instanceof le)T(t.leftExpression),T(t.op),T(t.rightExpression);else if(t instanceof je)T(t.op),T(t.expression);else if(t instanceof re)T(t.blockOpenBrace),t.body.forEach(T),T(t.blockCloseBrace);else if(t instanceof R)T(t.listOpenBracket),t.commaList.forEach(T),t.elementList.forEach(T),T(t.listCloseBracket);else if(t instanceof fe)T(t.tupleOpenParen),t.commaList.forEach(T),t.elementList.forEach(T),T(t.tupleCloseParen);else if(t instanceof q)T(t.callee),T(t.argumentList);else if(t instanceof v)T(t.callee),t.args.forEach(T);else if(t instanceof G)T(t.expression);else if(t instanceof ce)T(t.value);else if(t instanceof ae)T(t.variable);else if(t instanceof ve)T(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 An(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 ve)return t.literal?[t.literal]:[];if(t instanceof ae)return X(t.variable);if(t instanceof K)return X(t.op,t.expression);if(t instanceof le)return X(t.leftExpression,t.op,t.rightExpression);if(t instanceof je)return X(t.expression,t.op);if(t instanceof ce)return X(t.value);if(t instanceof v)return X(t.callee,...t.args);if(t instanceof re)return X(t.blockOpenBrace,...t.body,t.blockCloseBrace);if(t instanceof R)return X(t.listOpenBracket,...dt(t.elementList,t.commaList),t.listCloseBracket);if(t instanceof fe)return X(t.tupleOpenParen,...dt(t.elementList,t.commaList),t.tupleCloseParen);if(t instanceof q)return X(t.callee,t.argumentList);if(t instanceof G)return X(t.expression);if(t instanceof ue)return X(t.array,t.indexer);if(t instanceof Le)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 Je(t){return j(t)?new O(t.expression.variable):new x}function C(t){var e;return t instanceof G&&(t.expression instanceof ae&&t.expression.variable instanceof J&&t.expression.variable.kind===h.QUOTED_STRING||t.expression instanceof ve&&((e=t.expression.literal)==null?void 0:e.kind)===h.STRING_LITERAL)}function j(t){return t instanceof G&&t.expression instanceof ae&&t.expression.variable instanceof J}function he(t){var e;return t instanceof G&&t.expression instanceof ae&&((e=t.expression.variable)==null?void 0:e.kind)===h.IDENTIFIER}function Ye(t){var e;return t instanceof le&&t.leftExpression instanceof D&&t.rightExpression instanceof D&&((e=t.op)==null?void 0:e.value)==="."}function ge(t){if(t===void 0)return new x;const e=t.identifiers.map(n=>n.value).join(" ");return e===""?new x:new O(e)}class gn{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
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 Y(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(ht(e)){this.operator();break}if(
|
|
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(ht(e)){this.operator();break}if(qe(e)){this.identifier();break}if(Ve(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)en(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&&Ut(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 f=this.createToken(e,!0);this.tokens.push(f),this.errors.push(new l(o.UNEXPECTED_EOF,"EOF reached while parsing",f));return}if(this.check(`
|
|
5
5
|
`)&&!s){const f=this.createToken(e,!0);this.tokens.push(f),this.errors.push(new l(o.UNEXPECTED_NEWLINE,"Invalid newline encountered while parsing",f));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()&&
|
|
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()&&Ae(this.peek());)this.advance();this.addToken(h.IDENTIFIER)}operator(){for(;ht(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&&!Ae(this.peek()))return this.addToken(h.NUMERIC_LITERAL);if(!n&&!Ve(this.peek()))break;this.advance()}if(e>0){for(;!this.isAtEnd()&&(this.check(".")||Ae(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()&&Ae(this.peek());)this.advance();const n=this.createToken(h.IDENTIFIER,!1);this.tokens.push(n)}}colorLiteral(){for(;!this.isAtEnd()&&Ae(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()||!Le(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 Me=(t=>(t[t.ListExpression=0]="ListExpression",t[t.GroupExpression=1]="GroupExpression",t[t.BlockExpression=2]="BlockExpression",t))(Me||{});class gn{constructor(){this.stack=[],this.numberOfNestedLParens=0,this.numberOfNestedLBrackets=0,this.numberOfNestedLBraces=0}push(e){this.stack.push(e),e===0&&(this.numberOfNestedLBrackets+=1),e===1&&(this.numberOfNestedLParens+=1),e===2&&(this.numberOfNestedLBraces+=1)}pop(){const e=this.stack.pop();return e===0&&(this.numberOfNestedLBrackets-=1),e===1&&(this.numberOfNestedLParens-=1),e===2&&(this.numberOfNestedLBraces-=1),e}top(){return I.last(this.stack)}isWithinGroupExpressionContext(){return this.numberOfNestedLParens>0}isWithinListExpressionContext(){return this.numberOfNestedLBrackets>0}isWithinBlockExpressionContext(){return this.numberOfNestedLBraces>0}withContextDo(e,n){return()=>{this.push(e);try{return n()}finally{this.pop()}}}findHandlerContext(e,n){if(!(this.numberOfNestedLBraces<=0&&this.numberOfNestedLBrackets<=0&&this.numberOfNestedLParens<=0))for(let s=n;s<e.length-1;s+=1)switch(e[s].kind){case 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 vn{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 wn{constructor(e,n){this.current=0,this.errors=[],this.contextStack=new gn,this.synchronizeProgram=()=>{const s=this.peek();s.kind!==h.EOF?T(this.advance()):(T(this.peek()),this.logError(s,o.UNEXPECTED_EOF,"Unexpected EOF"))},this.synchronizeElementDeclarationName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(Et(s)||this.check(h.COLON,h.LBRACE,h.LBRACKET))break;T(s),this.advance()}},this.synchronizeElementDeclarationAlias=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(h.COLON,h.LBRACE,h.LBRACKET))break;T(s),this.advance()}},this.blockExpression=this.contextStack.withContextDo(Me.BlockExpression,()=>{const s={body:[]},i=()=>this.nodeFactory.create(re,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(ke,{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(T(this.advance());!this.isAtEnd();){const s=this.peek();if(this.check(h.RBRACE)||pt(this.previous(),s))break;T(s),this.advance()}},this.tupleExpression=this.contextStack.withContextDo(Me.GroupExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(et,{groupOpenParen:s.tupleOpenParen,groupCloseParen:s.tupleCloseParen,expression:s.elementList[0]}),a=()=>this.nodeFactory.create(fe,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;T(s),this.advance()}},this.listExpression=this.contextStack.withContextDo(Me.ListExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(R,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;T(s),this.advance()}},this.synchronizeAttributeName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(h.COMMA,h.RBRACKET,h.COLON))break;T(s),this.advance()}},this.synchronizeAttributeValue=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(h.COMMA,h.RBRACKET))break;T(s),this.advance()}},this.tokens=e,this.nodeFactory=new vn(n)}isAtEnd(){return this.current>=this.tokens.length||this.tokens[this.current].kind===h.EOF}advance(){return this.isAtEnd()?I.last(this.tokens):this.tokens[this.current++]}peek(e=0){return e+this.current>=this.tokens.length?I.last(this.tokens):this.tokens[this.current+e]}match(...e){const n=this.check(...e);return n&&this.advance(),n}check(...e){const n=this.peek();return e.includes(n.kind)}previous(){return this.tokens[this.current-1]}canHandle(e){return e.handlerContext===void 0||e.handlerContext===this.contextStack.top()}consume(e,...n){if(!this.match(...n))throw this.logError(this.peek(),o.UNEXPECTED_TOKEN,e),new N(this.peek(),void 0,this.contextStack.findHandlerContext(this.tokens,this.current))}discardUntil(e,...n){if(this.isAtEnd()||!this.check(...n)){for(T(this.peek()),this.logError(this.advance(),o.UNEXPECTED_TOKEN,e);!this.isAtEnd()&&!this.check(...n);)T(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(K,{body:e,eof:n});return this.gatherInvalid(),new Y({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(Et(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?(T(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=()=>bn(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();){Ke(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()||wt(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}=Nt(s);if(i<e||pt(this.previous(),s)&&!this.contextStack.isWithinGroupExpressionContext()&&!this.contextStack.isWithinListExpressionContext())break;try{n=this.nodeFactory.create(q,{callee:n,argumentList:this.tupleExpression()})}catch(a){throw a instanceof N?(n=this.nodeFactory.create(q,{callee:n,argumentList:a.partialNode}),new N(a.token,n,a.handlerContext)):a}}else if(s.kind===h.LBRACKET){if(Ke(this.previous()))break;try{n=this.nodeFactory.create(ue,{expression:n,indexer:this.listExpression()})}catch(i){throw i instanceof N?(n=this.nodeFactory.create(ue,{expression:n,indexer:i.partialNode}),new N(i.token,n,i.handlerContext)):i}}else if(ft(s)){const i=s,a=Nt(i);if(a.left!==null){if(a.left<=e)break;this.advance(),n=this.nodeFactory.create($e,{expression:n,op:i})}else{const r=kn(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 N?(n=this.nodeFactory.create(le,{leftExpression:n,op:i,rightExpression:c.partialNode}),new N(c.token,n,c.handlerContext)):c}}}else break}return n}leftExpression_bp(){let e;if(ft(this.peek())){const n={};n.op=this.peek();const s=Pn(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(Re,{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(Z,n),i.handlerContext)):i}e=this.nodeFactory.create(Z,n)}else if(e=this.extractOperand(),e instanceof Re)throw new N(this.peek(),this.nodeFactory.create(Re,{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(Re,{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(ce,e),n.handlerContext)):n}return this.nodeFactory.create(ce,e)}variable(){this.consume("Expect a variable",h.IDENTIFIER);const e=this.previous();return this.nodeFactory.create(ae,{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(G,{expression:this.nodeFactory.create(ge,{literal:this.previous()})});if(this.match(h.QUOTED_STRING,h.IDENTIFIER))return this.nodeFactory.create(G,{expression:this.nodeFactory.create(ae,{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 yn={"+":{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 kn(t){return yn[t.value]||{left:null,right:null}}const Sn={"+":{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 Pn(t){return Sn[t.value]||{left:null,right:null}}const xn={"(":{left:14,right:null}};function Nt(t){return xn[t.value]||{left:null,right:null}}var L=(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))(L||{});function xe(t){var n;const e=(n=t==null?void 0:t.type)==null?void 0:n.value.toLowerCase();switch(e){case L.Enum:case L.Table:case L.Indexes:case L.Note:case L.Project:case L.Ref:case L.TableGroup:case L.TablePartial:return new O(e);default:return new x}}function Ie(t){if(!qe(t))return new O([t]);const e=Ie(t.leftExpression).unwrap_or(void 0);return e?(e.push(t.rightExpression),new O(e)):new x}function z(t){if(t===void 0)return new x;const e=Ie(t).unwrap_or(void 0);if(!e)return new x;const n=[];for(const s of e){const i=W(s).unwrap_or(void 0);if(!i)return new x;n.push(i)}return new O(n)}function Se(t){if(t===void 0)return new x;const e=Ie(t).unwrap_or(void 0);if(!e||e.length===0)return new x;const n=[];let s;if(!$(I.last(e))){const i=e.pop();if(Vt(i))s=i.elementList.map(a=>X(a).unwrap());else return new x}for(const i of e){const a=W(i).unwrap_or(void 0);if(!a)return new x;n.push(a)}return new O({variables:n,tupleElements:s})}function W(t){return $(t)?new O(t.expression.variable.value):new x}function Ve(t){if(mt(t))return t instanceof ce?new O({functional:[t],nonFunctional:[]}):new O({functional:[],nonFunctional:[t]});if(t instanceof fe&&t.elementList.every(mt)){const e=t.elementList.filter(s=>s instanceof ce),n=t.elementList.filter($);return new O({functional:e,nonFunctional:n})}return new x}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 x:new O(e)}function U(t){return C(t)?t.expression instanceof ae?new O(t.expression.variable.value):new O(t.expression.literal.value):new x}function Dn(t){var e;return!(t instanceof le)||!Mt((e=t.op)==null?void 0:e.value)?!1:Se(t.leftExpression).and_then(()=>Se(t.rightExpression)).unwrap_or(void 0)!==void 0}function On(t){const e=Se(t.leftExpression),n=Se(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 G&&t.expression instanceof ae||t instanceof ce}function Tt(t,e){var i,a,r,c;let n=e;const s=rn(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 K&&s)return n.symbol;if(n instanceof K)return;n=n.parent}}class Rn{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 K||xe(this.declarationNode.parent).unwrap_or(void 0)!==L.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 re)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 ve{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 Un{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?Ut(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(fn,{declaration:this.declarationNode,symbolTable:new ve});const{name:n}=this.declarationNode,s=z(n);if(s.isOk()){const i=s.unwrap(),a=i.pop(),r=Ye(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]=I.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&&!$(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 I.last(i)instanceof R?(s.push(...this.validateFieldSettings(I.last(i))),i.pop()):i[0]instanceof R&&(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=>{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=pe(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}registerField(e){if(e.callee&&$(e.callee)){const n=X(e.callee).unwrap(),s=st(n),i=this.symbolFactory.create(pn,{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 Mn{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(){if(this.declarationNode.parent instanceof K)return[new l(o.INVALID_NOTE_CONTEXT,"An Indexes can only appear inside a Table or a TablePartial",this.declarationNode)];const e=xe(this.declarationNode.parent).unwrap_or(void 0);return e&&[L.Table,L.TablePartial].includes(e)?[]:[new l(o.INVALID_NOTE_CONTEXT,"An Indexes can only appear inside a Table or a TablePartial",this.declarationNode)]}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]=I.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.flatMap(n=>{if(!n.callee)return[];const s=[],i=[n.callee,...n.args];return I.last(i)instanceof R&&s.push(...this.validateFieldSetting(i.pop())),i.forEach(a=>{for(;a instanceof q;)a.argumentList&&!Ve(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;Ve(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=>{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=>{H(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=>{$(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=pe(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}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 K)&&![L.Table,L.TableGroup,L.TablePartial,L.Project].includes(xe(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 K))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=z(e);if(!n.isOk())return[new l(o.INVALID_NAME,"Invalid name for sticky note ",this.declarationNode)];const i=n.unwrap().join("."),a=sn(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]=I.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=pe(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}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.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?we(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]=I.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=pe(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class Vn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof K?[]:[new l(o.INVALID_REF_CONTEXT,"A Ref must appear top-level",this.declarationNode)]}validateName(e){return e?we(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]=I.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&&!Dn(s.callee)&&n.push(new l(o.INVALID_REF_FIELD,"A Ref field must be a binary relationship",s.callee)),s.callee&&!On(s.callee)&&n.push(new l(o.UNEQUAL_FIELDS_BINARY_REF,"Unequal fields in ref endpoints",s.callee));const i=[...s.args];if(I.last(i)instanceof R){const a=this.validateFieldSettings(I.last(i));n.push(...a),i.pop()}else i[0]instanceof R&&(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=>{Gn(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=>{ze(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=pe(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}function Gn(t){if(!($(t)&&t.expression.variable.kind!==h.QUOTED_STRING)&&!(t instanceof ne))return!1;let e;if(t instanceof ne?e=Ae(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 Cn{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 ue?[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)]:Ut(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?Yn(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=>{ze(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(Dt,{declaration:this.declarationNode,symbolTable:new ve});const{name:n,alias:s}=this.declarationNode,i=z(n);if(i.isOk()){const a=[...i.unwrap()],r=a.pop(),c=Ye(a,this.publicSymbolTable,this.symbolFactory),f=Fe(r);c.has(f)&&e.push(new l(o.DUPLICATE_NAME,`Table name '${r}' already exists in schema '${a.join(".")||"public"}'`,n)),c.set(f,this.declarationNode.symbol)}if(s&&we(s)&&!$n(s.expression.variable.value,i.unwrap_or([]))){const a=X(s).unwrap(),r=Fe(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.partition(e.body,r=>r instanceof w),[i,a]=I.partition(s,r=>r instanceof ke);return[...this.validateFields(n),...this.validateInjections(i),...this.validateSubElements(a)]}validateFields(e){const[n,s,i]=e.reduce((a,r)=>(r.callee instanceof G?a[0].push(r):r.callee instanceof Z?a[1].push(r):a[2].push(new l(o.INVALID_TABLE_FIELD,"A Table field must be a column or a TablePartial injection",r)),a),[[],[],[]]);return[...i,...this.validateColumns(n),...this.validateInjections(s)]}validateInjections(e){return e.flatMap(n=>this.registerInjection(n))}registerInjection(e){var n,s;if(e.partial&&((n=e.partial.variable)!=null&&n.value)){const i=(s=e.partial.variable)==null?void 0:s.value,a=an(i),r=this.symbolFactory.create(mn,{declaration:e});e.symbol=r;const c=this.declarationNode.symbol.symbolTable,f=c.get(a);if(f)return[new l(o.DUPLICATE_TABLE_PARTIAL_INJECTION_NAME,`Duplicate injection ${i}`,e),new l(o.DUPLICATE_TABLE_PARTIAL_INJECTION_NAME,`Duplicate injection ${i}`,f.declaration)];c.set(a,r)}return[]}validateColumns(e){return e.length===0?[new l(o.EMPTY_TABLE,"A Table must have at least one column",this.declarationNode)]:e.flatMap(n=>{const s=[];n.args.length===0&&s.push(new l(o.INVALID_COLUMN,"A column must have a type",n.callee)),$(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]&&!Xn(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.validateColumnSetting(i)),s.push(...this.registerColumn(n)),s})}registerColumn(e){if(e.callee&&$(e.callee)){const n=X(e.callee).unwrap(),s=je(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[]}validateColumnSetting(e){if(!e.slice(0,-1).every(he)||!e.slice(-1).every(f=>he(f)||f instanceof R))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 n;I.last(e)instanceof R&&(n=e.pop());const s=F(n),i=s.getErrors(),a=s.getValue();for(const f of e){const p=X(f).unwrap_or("").toLowerCase();if(p!=="pk"&&p!=="unique"){i.push(new l(o.INVALID_SETTINGS,"Inline column settings can only be `pk` or `unique`",f));continue}a[p]===void 0?a[p]=[f]:a[p].push(f)}const r=a.pk||[],c=a["primary key"]||[];r.length>=1&&c.length>=1&&i.push(...[...r,...c].map(f=>new l(o.DUPLICATE_COLUMN_SETTING,"Either one of 'primary key' and 'pk' can appear",f)));for(const f in a){const p=a[f];switch(f){case"note":p.length>1&&i.push(...p.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"note can only appear once",u))),p.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":p.forEach(u=>{Bt(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":p.length>1&&i.push(...p.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"primary key can only appear once",u))),p.forEach(u=>{H(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":p.length>1&&i.push(...p.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"'pk' can only appear once",u))),p.forEach(u=>{u instanceof se&&!H(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":p.length>1&&i.push(...p.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"'not null' can only appear once",u)));const d=a.null||[];p.length>=1&&d.length>=1&&i.push(...[...p,...d].map(u=>new l(o.CONFLICTING_SETTING,"'not null' and 'null' can not be set at the same time",u))),p.forEach(u=>{H(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":p.length>1&&i.push(...p.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"'null' can only appear once",u))),p.forEach(u=>{H(u.value)||i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'null' must not have a value",u.value||u.name))});break;case"unique":p.length>1&&i.push(...p.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"'unique' can only appear once",u))),p.forEach(u=>{u instanceof se&&!H(u.value)&&i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'unique' must not have a value",u.value||u.name))});break;case"increment":p.length>1&&i.push(...p.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"'increment' can only appear once",u))),p.forEach(u=>{u instanceof se&&!H(u.value)&&i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'increment' must not have a value",u.value||u.name))});break;case"default":p.length>1&&i.push(...p.map(u=>new l(o.DUPLICATE_TABLE_SETTING,"'default' can only appear once",u))),p.forEach(u=>{Ft(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:p.forEach(u=>i.push(new l(o.UNKNOWN_COLUMN_SETTING,`Unknown column setting '${f}'`,u)))}}return i}validateSubElements(e){const n=e.flatMap(i=>{if(!i)return[];if(i.parent=this.declarationNode,!i.type)return[];const a=pe(i);return new a(i,this.publicSymbolTable,this.symbolFactory).validate()}),s=e.filter(i=>{var a;return((a=i==null?void 0: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 Xn(t){if(!(t instanceof q||qe(t)||t instanceof G||t instanceof ue))return!1;if(t instanceof q){if(t.callee===void 0||t.argumentList===void 0||!t.argumentList.elementList.every(n=>ee(n)||C(n)||he(n)))return!1;t=t.callee}for(;t instanceof ue;){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=z(t).unwrap_or(void 0);return e!==void 0&&e.length>0}function $n(t,e){return e.length===1&&t===e[0]}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.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?we(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(dn,{declaration:this.declarationNode,symbolTable:new ve});const n=z(e);if(n.isOk()){const s=n.unwrap(),i=s.pop(),a=Ye(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 I.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=>{ze(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]=I.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.flatMap(n=>{const s=[];return n.callee&&!z(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=pe(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&&$(e.callee)){const n=X(e.callee).unwrap(),s=at(n),i=this.symbolFactory.create(En,{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 rt=["-","+"];function Wn(t){if(!(t instanceof q||qe(t)||t instanceof G||t instanceof ue))return!1;if(t instanceof q){if(t.callee===void 0||t.argumentList===void 0||!t.argumentList.elementList.every(n=>ee(n)||C(n)||he(n)))return!1;t=t.callee}for(;t instanceof ue;){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=z(t).unwrap_or(void 0);return e!==void 0&&e.length>0}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_PARTIAL_CONTEXT,"TablePartial must appear top-level",this.declarationNode)]:[]}validateName(e){return e?we(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 I.forIn(i,(a,r)=>{switch(r){case"headercolor":a.length>1&&s.push(...a.map(c=>new l(o.DUPLICATE_TABLE_PARTIAL_SETTING,"'headercolor' can only appear once",c))),a.forEach(c=>{ze(c.value)||s.push(new l(o.INVALID_TABLE_PARTIAL_SETTING,"'headercolor' 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_PARTIAL_SETTING,"'note' can only appear once",c))),a.forEach(c=>{C(c.value)||s.push(new l(o.INVALID_TABLE_PARTIAL_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)))}}),s}registerElement(){const{name:e}=this.declarationNode;this.declarationNode.symbol=this.symbolFactory.create(Nn,{declaration:this.declarationNode,symbolTable:new ve});const n=z(e);if(n.isOk()){const s=n.unwrap(),i=s.pop(),a=Ye(s,this.publicSymbolTable,this.symbolFactory),r=Pt(i);if(a.has(r))return[new l(o.DUPLICATE_NAME,`TablePartial name '${i}' already exists`,e)];a.set(r,this.declarationNode.symbol)}return[]}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]=I.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.flatMap(n=>{if(!n.callee)return[];const s=[];n.args.length===0&&s.push(new l(o.INVALID_COLUMN,"A column must have a type",n.callee)),$(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&&$(e.callee)){const n=X(e.callee).unwrap(),s=je(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(he)||!e.slice(-1).every(f=>he(f)||f instanceof R))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 n;I.last(e)instanceof R&&(n=e.pop());const s=F(n),i=s.getErrors(),a=s.getValue();e.forEach(f=>{const p=X(f).unwrap_or("").toLowerCase();if(p!=="pk"&&p!=="unique"){i.push(new l(o.INVALID_SETTINGS,"Inline column settings can only be `pk` or `unique`",f));return}a[p]===void 0?a[p]=[f]:a[p].push(f)});const r=a.pk||[],c=a["primary key"]||[];return r.length>=1&&c.length>=1&&i.push(...[...r,...c].map(f=>new l(o.DUPLICATE_COLUMN_SETTING,"Either one of 'primary key' and 'pk' can appear",f))),I.forIn(a,(f,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=>{Bt(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=>{H(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&&!H(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=>{H(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=>{H(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&&!H(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&&!H(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_COLUMN_SETTING,"'default' can only appear once",u))),f.forEach(u=>{Ft(u.value)||i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'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)))}}),i}validateSubElements(e){const n=e.flatMap(i=>{if(i.parent=this.declarationNode,!i.type)return[];const a=pe(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 pe(t){switch(t.type.value.toLowerCase()){case L.Enum:return Un;case L.Table:return Cn;case L.TableGroup:return jn;case L.Project:return Bn;case L.Ref:return Vn;case L.Note:return Fn;case L.Indexes:return Mn;case L.TablePartial:return qn;default:return Rn}}function Ut(t){return!!z(t).unwrap_or(!1)}function Yn(t){return we(t)}function we(t){return t instanceof G&&t.expression instanceof ae}function Ye(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 ve;const f=n.create(xt,{symbolTable:r});s.set(c,f)}s=r}return s}function Mt(t){return t==="-"||t==="<>"||t===">"||t==="<"}function ze(t){var n;if(!(t instanceof G)||!(t.expression instanceof ge)||((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(!un(e[s]))return!1;return!0}function H(t){return t===void 0}function Ft(t){var e;return!!(C(t)||ee(t)||he(t)&&["true","false","null"].includes(t.expression.variable.value.toLowerCase())||t instanceof Z&&rt.includes((e=t.op)==null?void 0:e.value)&&ee(t.expression)||t instanceof ce)}function ee(t){var e;return t instanceof G&&t.expression instanceof ge&&((e=t.expression.literal)==null?void 0:e.kind)===h.NUMERIC_LITERAL}function Bt(t){var n;if(!(t instanceof Z)||!Mt((n=t.op)==null?void 0:n.value))return!1;const e=z(t.expression).unwrap_or(void 0);return e!==void 0&&e.length>0}function Vt(t){return t instanceof fe&&t.elementList.every($)}function F(t){var s;const e={},n=[];if(!t)return new Y({});for(const i of t.elementList){if(!i.name)continue;if(i.name instanceof G){n.push(new l(o.INVALID_SETTINGS,"A setting name must be a stream of identifiers",i.name));continue}const a=(s=Ae(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 Y(e,n)}class bt{constructor(e,n){this.ast=e,this.symbolFactory=n,this.publicSchemaSymbol=this.symbolFactory.create(xt,{symbolTable:new ve}),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=pe(s),a=new i(s,this.publicSchemaSymbol.symbolTable,this.symbolFactory);e.push(...a.validate())});const n=this.ast.body.filter(s=>xe(s).unwrap_or(void 0)===L.Project);return n.length>1&&n.forEach(s=>e.push(new l(o.PROJECT_REDEFINED,"Only one project can exist",s))),new Y(this.ast,e)}}class de{constructor(e,n){this.declarationNode=e,this.errors=n}bind(){this.bindSettingList(this.declarationNode.attributeList,this.settingList),this.bindBody()}bindSettingList(e,n){if(e)for(const s of e.elementList){if(s.name instanceof G)continue;const i=Ae(s.name).unwrap_or(void 0);if(!i)continue;const a=n[i.toLowerCase()];a!=null&&a.shouldBind&&this.scanAndBind(s.value,a)}}bindBody(){var s,i;const e=this.declarationNode;if(!e.body)return;const{body:n}=e;if(n instanceof re)for(const a of n.body)if(a instanceof y){if(((s=this.declarationNode.type)==null?void 0:s.value.toLowerCase())===L.TablePartial&&((i=a.type)==null?void 0:i.value.toLowerCase())===L.Indexes||!a.type)continue;const r=Ze(a);new r(a,this.errors).bind()}else a instanceof w?this.bindSubfield(a):this.bindPartialInjection(a);else this.bindSubfield(n)}bindSubfield(e){const n=[e.callee,...e.args],s=I.last(n);s instanceof R&&(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.subfield.injection)!=null&&n.injectionBinderRule.shouldBind&&this.scanAndBind(e,this.subfield.injection.injectionBinderRule)}scanAndBind(e,n){var s,i;if(e)if(e instanceof G){if(e.expression instanceof ae&&((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?qe(e)?this.bindFragments(Ie(e).unwrap_or([]),n):(this.scanAndBind(e.leftExpression,n),this.scanAndBind(e.rightExpression,n)):e instanceof Z?this.scanAndBind(e.expression,n):e instanceof $e?this.scanAndBind(e.expression,n):e instanceof fe?e.elementList.forEach(a=>this.scanAndBind(a,n)):e instanceof ke&&this.bindFragments([e],n)}bindFragments(e,n){if(e.length===0)return;const s=e[0]instanceof ke,i=[...n.topSubnamesSymbolKind],{remainingSubnamesSymbolKind:a}=n,r=s?-1:e.findIndex(E=>!$(E)),f=r!==-1&&Vt(e[r])?e[r]:void 0,p=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(),b=d.pop(),g=X(b).unwrap();u.unshift({index:Ue(g,E),referrer:b})}for(;d.length;){const E=d.pop(),b=s?E.partial.variable.value:X(E).unwrap();u.unshift({index:Ue(b,a),referrer:E})}return f?f.elementList.forEach(E=>this.resolveIndexStack([...u,{index:Ue(X(E).unwrap(),p),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=Tt(s.index,this.declarationNode);if(a===void 0){const{kind:p,name:d}=oe(s.index).unwrap();this.logError(s.referrer,`Can not find ${p} '${d}'`,n);return}a.references.push(s.referrer),s.referrer.referee=a;let r=a.symbolTable,{kind:c,name:f}=oe(s.index).unwrap();for(const p of i){const{kind:d,name:u}=oe(p.index).unwrap(),E=r.get(p.index);if(!E){this.logError(p.referrer,`${c} '${f}' does not have ${d} '${u}'`,n);return}if(c=d,f=u,p.referrer.referee=E,E.references.push(p.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 c,f,p;if(on(r)){const d=Tt(ln(r),this.declarationNode);(p=(f=(c=d==null?void 0:d.declaration)==null?void 0:c.symbol)==null?void 0:f.symbolTable)==null||p.forEach((u,E)=>{n.has(E)||s.set(E,u)})}}),s.forEach((a,r)=>{const c=e.create(Tn,{injectorId:a.id});n.set(r,c)})}}class zn extends de{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Qn extends de{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Hn extends de{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 Jn extends de{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Kn extends de{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Zn extends de{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class es extends de{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Enum],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!0}]},injection:{injectionBinderRule:{shouldBind:!0,topSubnamesSymbolKind:[],remainingSubnamesSymbolKind:m.TablePartial,ignoreNameNotFound:!1}},settingList:{ref:{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},default:{shouldBind:!1}}},this.settingList={}}}class ts extends de{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class ns extends de{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 Ze(t){switch(t.type.value.toLowerCase()){case L.Enum:return Qn;case L.Table:return es;case L.TableGroup:return ts;case L.Project:return Kn;case L.Ref:return Zn;case L.Note:return Jn;case L.Indexes:return Hn;case L.TablePartial:return ns;default:return zn}}class ss{constructor(e){this.ast=e,this.errors=[]}resolve(e){this.ast.body.forEach(n=>{if(n.type){const s=Ze(n);new s(n,this.errors).resolveInjections(e)}});for(const n of this.ast.body)if(n.type){const s=Ze(n);new s(n,this.errors).bind()}return new Y(this.ast,this.errors)}}class is{constructor(e){this.generator=e}create(e,n){return new e(n,this.generator.nextId())}}class as{constructor(e,n){this.ast=e,this.symbolFactory=new is(n)}analyze(){return new bt(this.ast,this.symbolFactory).validate().chain(n=>new ss(n).resolve(this.symbolFactory))}validate(){return new bt(this.ast,this.symbolFactory).validate().chain(n=>new Y(n,[]))}}function It(t,e){const{variables:n,tupleElements:s}=Se(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 Gt(t){switch(t){case"<":return["1","*"];case"<>":return["*","*"];case">":return["*","1"];case"-":return["1","1"]}throw new Error("Invalid relation op")}function _(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 Ge(t){var n;const e=(n=Ie(t).unwrap_or(void 0))==null?void 0:n.pop();return e instanceof fe?e.elementList.map(s=>s.referee):[e.referee]}function Te(t){const e=z(t).unwrap();return{name:e.pop(),schemaName:e}}function De(t){return t.expression.literal.value}function Ct(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 ot(t,e){if(Array.isArray(t)){const i=t.map(({id:r})=>r).sort(),a=e.map(({id:r})=>r).sort();return I.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()||!Ae(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 Fe=(t=>(t[t.ListExpression=0]="ListExpression",t[t.GroupExpression=1]="GroupExpression",t[t.BlockExpression=2]="BlockExpression",t))(Fe||{});class vn{constructor(){this.stack=[],this.numberOfNestedLParens=0,this.numberOfNestedLBrackets=0,this.numberOfNestedLBraces=0}push(e){this.stack.push(e),e===0&&(this.numberOfNestedLBrackets+=1),e===1&&(this.numberOfNestedLParens+=1),e===2&&(this.numberOfNestedLBraces+=1)}pop(){const e=this.stack.pop();return e===0&&(this.numberOfNestedLBrackets-=1),e===1&&(this.numberOfNestedLParens-=1),e===2&&(this.numberOfNestedLBraces-=1),e}top(){return I.last(this.stack)}isWithinGroupExpressionContext(){return this.numberOfNestedLParens>0}isWithinListExpressionContext(){return this.numberOfNestedLBrackets>0}isWithinBlockExpressionContext(){return this.numberOfNestedLBraces>0}withContextDo(e,n){return()=>{this.push(e);try{return n()}finally{this.pop()}}}findHandlerContext(e,n){if(!(this.numberOfNestedLBraces<=0&&this.numberOfNestedLBrackets<=0&&this.numberOfNestedLParens<=0))for(let s=n;s<e.length-1;s+=1)switch(e[s].kind){case 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 wn{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 yn{constructor(e,n){this.current=0,this.errors=[],this.contextStack=new vn,this.synchronizeProgram=()=>{const s=this.peek();s.kind!==h.EOF?T(this.advance()):(T(this.peek()),this.logError(s,o.UNEXPECTED_EOF,"Unexpected EOF"))},this.synchronizeElementDeclarationName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(Et(s)||this.check(h.COLON,h.LBRACE,h.LBRACKET))break;T(s),this.advance()}},this.synchronizeElementDeclarationAlias=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(h.COLON,h.LBRACE,h.LBRACKET))break;T(s),this.advance()}},this.blockExpression=this.contextStack.withContextDo(Fe.BlockExpression,()=>{const s={body:[]},i=()=>this.nodeFactory.create(re,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(Le,{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(T(this.advance());!this.isAtEnd();){const s=this.peek();if(this.check(h.RBRACE)||pt(this.previous(),s))break;T(s),this.advance()}},this.tupleExpression=this.contextStack.withContextDo(Fe.GroupExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(et,{groupOpenParen:s.tupleOpenParen,groupCloseParen:s.tupleCloseParen,expression:s.elementList[0]}),a=()=>this.nodeFactory.create(fe,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;T(s),this.advance()}},this.listExpression=this.contextStack.withContextDo(Fe.ListExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(R,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;T(s),this.advance()}},this.synchronizeAttributeName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(h.COMMA,h.RBRACKET,h.COLON))break;T(s),this.advance()}},this.synchronizeAttributeValue=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(h.COMMA,h.RBRACKET))break;T(s),this.advance()}},this.tokens=e,this.nodeFactory=new wn(n)}isAtEnd(){return this.current>=this.tokens.length||this.tokens[this.current].kind===h.EOF}advance(){return this.isAtEnd()?I.last(this.tokens):this.tokens[this.current++]}peek(e=0){return e+this.current>=this.tokens.length?I.last(this.tokens):this.tokens[this.current+e]}match(...e){const n=this.check(...e);return n&&this.advance(),n}check(...e){const n=this.peek();return e.includes(n.kind)}previous(){return this.tokens[this.current-1]}canHandle(e){return e.handlerContext===void 0||e.handlerContext===this.contextStack.top()}consume(e,...n){if(!this.match(...n))throw this.logError(this.peek(),o.UNEXPECTED_TOKEN,e),new N(this.peek(),void 0,this.contextStack.findHandlerContext(this.tokens,this.current))}discardUntil(e,...n){if(this.isAtEnd()||!this.check(...n)){for(T(this.peek()),this.logError(this.advance(),o.UNEXPECTED_TOKEN,e);!this.isAtEnd()&&!this.check(...n);)T(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 Y({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(Et(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?(T(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=()=>In(e.callee,e.args,this.nodeFactory).unwrap_or(this.nodeFactory.create(v,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()||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}=Nt(s);if(i<e||pt(this.previous(),s)&&!this.contextStack.isWithinGroupExpressionContext()&&!this.contextStack.isWithinListExpressionContext())break;try{n=this.nodeFactory.create(q,{callee:n,argumentList:this.tupleExpression()})}catch(a){throw a instanceof N?(n=this.nodeFactory.create(q,{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(ue,{expression:n,indexer:this.listExpression()})}catch(i){throw i instanceof N?(n=this.nodeFactory.create(ue,{expression:n,indexer:i.partialNode}),new N(i.token,n,i.handlerContext)):i}}else if(ft(s)){const i=s,a=Nt(i);if(a.left!==null){if(a.left<=e)break;this.advance(),n=this.nodeFactory.create(je,{expression:n,op:i})}else{const r=Sn(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 N?(n=this.nodeFactory.create(le,{leftExpression:n,op:i,rightExpression:c.partialNode}),new N(c.token,n,c.handlerContext)):c}}}else break}return n}leftExpression_bp(){let e;if(ft(this.peek())){const n={};n.op=this.peek();const s=xn(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(Ue,{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(K,n),i.handlerContext)):i}e=this.nodeFactory.create(K,n)}else if(e=this.extractOperand(),e instanceof Ue)throw new N(this.peek(),this.nodeFactory.create(Ue,{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(Ue,{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(ce,e),n.handlerContext)):n}return this.nodeFactory.create(ce,e)}variable(){this.consume("Expect a variable",h.IDENTIFIER);const e=this.previous();return this.nodeFactory.create(ae,{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(G,{expression:this.nodeFactory.create(ve,{literal:this.previous()})});if(this.match(h.QUOTED_STRING,h.IDENTIFIER))return this.nodeFactory.create(G,{expression:this.nodeFactory.create(ae,{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 kn={"+":{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 kn[t.value]||{left:null,right:null}}const Pn={"+":{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 xn(t){return Pn[t.value]||{left:null,right:null}}const Dn={"(":{left:14,right:null}};function Nt(t){return Dn[t.value]||{left:null,right:null}}var L=(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))(L||{});function xe(t){var n;const e=(n=t==null?void 0:t.type)==null?void 0:n.value.toLowerCase();switch(e){case L.Enum:case L.Table:case L.Indexes:case L.Note:case L.Project:case L.Ref:case L.TableGroup:case L.TablePartial:return new O(e);default:return new x}}function _e(t){if(!Ye(t))return new O([t]);const e=_e(t.leftExpression).unwrap_or(void 0);return e?(e.push(t.rightExpression),new O(e)):new x}function z(t){if(t===void 0)return new x;const e=_e(t).unwrap_or(void 0);if(!e)return new x;const n=[];for(const s of e){const i=W(s).unwrap_or(void 0);if(!i)return new x;n.push(i)}return new O(n)}function Se(t){if(t===void 0)return new x;const e=_e(t).unwrap_or(void 0);if(!e||e.length===0)return new x;const n=[];let s;if(!j(I.last(e))){const i=e.pop();if(Gt(i))s=i.elementList.map(a=>$(a).unwrap());else return new x}for(const i of e){const a=W(i).unwrap_or(void 0);if(!a)return new x;n.push(a)}return new O({variables:n,tupleElements:s})}function W(t){return j(t)?new O(t.expression.variable.value):new x}function Ge(t){if(mt(t))return t instanceof ce?new O({functional:[t],nonFunctional:[]}):new O({functional:[],nonFunctional:[t]});if(t instanceof fe&&t.elementList.every(mt)){const e=t.elementList.filter(s=>s instanceof ce),n=t.elementList.filter(j);return new O({functional:e,nonFunctional:n})}return new x}function $(t){var n;const e=(n=t==null?void 0:t.expression.variable)==null?void 0:n.value;return e===void 0?new x:new O(e)}function M(t){return C(t)?t.expression instanceof ae?new O(t.expression.variable.value):new O(t.expression.literal.value):new x}function On(t){var e;return!(t instanceof le)||!Ft((e=t.op)==null?void 0:e.value)?!1:Se(t.leftExpression).and_then(()=>Se(t.rightExpression)).unwrap_or(void 0)!==void 0}function Rn(t){const e=Se(t.leftExpression),n=Se(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 G&&t.expression instanceof ae||t instanceof ce}function Tt(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 Un{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||xe(this.declarationNode.parent).unwrap_or(void 0)!==L.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 re)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 we{constructor(){this.table=new Map}has(e){return this.table.has(e)}set(e,n){this.table.set(e,n)}get(e,n){return this.table.get(e)||n!==void 0&&this.set(e,n)||n}entries(){return this.table.entries()}forEach(e){return this.table.forEach(e)}}class Mn{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 we});const{name:n}=this.declarationNode,s=z(n);if(s.isOk()){const i=s.unwrap(),a=i.pop(),r=ze(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 v)return this.validateFields([e]);const[n,s]=I.partition(e.body,i=>i instanceof v);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 I.last(i)instanceof R?(s.push(...this.validateFieldSettings(I.last(i))),i.pop()):i[0]instanceof R&&(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=>{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=pe(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}registerField(e){if(e.callee&&j(e.callee)){const n=$(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 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(){if(this.declarationNode.parent instanceof Z)return[new l(o.INVALID_NOTE_CONTEXT,"An Indexes can only appear inside a Table or a TablePartial",this.declarationNode)];const e=xe(this.declarationNode.parent).unwrap_or(void 0);return e&&[L.Table,L.TablePartial].includes(e)?[]:[new l(o.INVALID_NOTE_CONTEXT,"An Indexes can only appear inside a Table or a TablePartial",this.declarationNode)]}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 v)return[new l(o.UNEXPECTED_SIMPLE_BODY,"An Indexes must have a complex body",e)];const[n,s]=I.partition(e.body,i=>i instanceof v);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.flatMap(n=>{if(!n.callee)return[];const s=[],i=[n.callee,...n.args];return I.last(i)instanceof R&&s.push(...this.validateFieldSetting(i.pop())),i.forEach(a=>{for(;a instanceof q;)a.argumentList&&!Ge(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;Ge(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=>{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=>{H(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=pe(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}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.validateBody(this.declarationNode.body)]}validateContext(){return!(this.declarationNode.parent instanceof Z)&&![L.Table,L.TableGroup,L.TablePartial,L.Project].includes(xe(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=z(e);if(!n.isOk())return[new l(o.INVALID_NAME,"Invalid name for sticky note ",this.declarationNode)];const i=n.unwrap().join("."),a=an(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 v)return this.validateFields([e]);const[n,s]=I.partition(e.body,i=>i instanceof v);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=pe(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class Vn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof y?[new l(o.INVALID_PROJECT_CONTEXT,"A Project can only appear top-level",this.declarationNode)]:[]}validateName(e){return e?ye(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 v)return[new l(o.UNEXPECTED_SIMPLE_BODY,"A Project's body must be a block",e)];const[n,s]=I.partition(e.body,i=>i instanceof v);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=pe(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?[]:[new l(o.INVALID_REF_CONTEXT,"A Ref must appear top-level",this.declarationNode)]}validateName(e){return e?ye(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 v)return this.validateFields([e]);const[n,s]=I.partition(e.body,i=>i instanceof v);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&&!On(s.callee)&&n.push(new l(o.INVALID_REF_FIELD,"A Ref field must be a binary relationship",s.callee)),s.callee&&!Rn(s.callee)&&n.push(new l(o.UNEQUAL_FIELDS_BINARY_REF,"Unequal fields in ref endpoints",s.callee));const i=[...s.args];if(I.last(i)instanceof R){const a=this.validateFieldSettings(I.last(i));n.push(...a),i.pop()}else i[0]instanceof R&&(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=>{Cn(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=pe(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}function Cn(t){if(!(j(t)&&t.expression.variable.kind!==h.QUOTED_STRING)&&!(t instanceof ne))return!1;let e;if(t instanceof ne?e=ge(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 Xn{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 ue?[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?zn(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=>{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(Ot,{declaration:this.declarationNode,symbolTable:new we});const{name:n,alias:s}=this.declarationNode,i=z(n);if(i.isOk()){const a=[...i.unwrap()],r=a.pop(),c=ze(a,this.publicSymbolTable,this.symbolFactory),f=Be(r);c.has(f)&&e.push(new l(o.DUPLICATE_NAME,`Table name '${r}' already exists in schema '${a.join(".")||"public"}'`,n)),c.set(f,this.declarationNode.symbol)}if(s&&ye(s)&&!jn(s.expression.variable.value,i.unwrap_or([]))){const a=$(s).unwrap(),r=Be(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 v)return[new l(o.UNEXPECTED_SIMPLE_BODY,"A Table's body must be a block",e)];const[n,s]=I.partition(e.body,r=>r instanceof v),[i,a]=I.partition(s,r=>r instanceof Le);return[...this.validateFields(n),...this.validateInjections(i),...this.validateSubElements(a)]}validateFields(e){const[n,s,i]=e.reduce((a,r)=>(r.callee instanceof G?a[0].push(r):r.callee instanceof K?a[1].push(r):a[2].push(new l(o.INVALID_TABLE_FIELD,"A Table field must be a column or a TablePartial injection",r)),a),[[],[],[]]);return[...i,...this.validateColumns(n),...this.validateInjections(s)]}validateInjections(e){return e.flatMap(n=>this.registerInjection(n))}registerInjection(e){var n,s;if(e.partial&&((n=e.partial.variable)!=null&&n.value)){const i=(s=e.partial.variable)==null?void 0:s.value,a=rn(i),r=this.symbolFactory.create(Tn,{declaration:e});e.symbol=r;const c=this.declarationNode.symbol.symbolTable,f=c.get(a);if(f)return[new l(o.DUPLICATE_TABLE_PARTIAL_INJECTION_NAME,`Duplicate injection ${i}`,e),new l(o.DUPLICATE_TABLE_PARTIAL_INJECTION_NAME,`Duplicate injection ${i}`,f.declaration)];c.set(a,r)}return[]}validateColumns(e){return e.length===0?[new l(o.EMPTY_TABLE,"A Table must have at least one column",this.declarationNode)]:e.flatMap(n=>{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]&&!$n(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.validateColumnSetting(i)),s.push(...this.registerColumn(n)),s})}registerColumn(e){if(e.callee&&j(e.callee)){const n=$(e.callee).unwrap(),s=We(n),i=this.symbolFactory.create(Rt,{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[]}validateColumnSetting(e){if(!e.slice(0,-1).every(he)||!e.slice(-1).every(f=>he(f)||f instanceof R))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 n;I.last(e)instanceof R&&(n=e.pop());const s=F(n),i=s.getErrors(),a=s.getValue();for(const f of e){const p=$(f).unwrap_or("").toLowerCase();if(p!=="pk"&&p!=="unique"){i.push(new l(o.INVALID_SETTINGS,"Inline column settings can only be `pk` or `unique`",f));continue}a[p]===void 0?a[p]=[f]:a[p].push(f)}const r=a.pk||[],c=a["primary key"]||[];r.length>=1&&c.length>=1&&i.push(...[...r,...c].map(f=>new l(o.DUPLICATE_COLUMN_SETTING,"Either one of 'primary key' and 'pk' can appear",f)));for(const f in a){const p=a[f];switch(f){case"note":p.length>1&&i.push(...p.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"note can only appear once",u))),p.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":p.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":p.length>1&&i.push(...p.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"primary key can only appear once",u))),p.forEach(u=>{H(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":p.length>1&&i.push(...p.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"'pk' can only appear once",u))),p.forEach(u=>{u instanceof se&&!H(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":p.length>1&&i.push(...p.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"'not null' can only appear once",u)));const d=a.null||[];p.length>=1&&d.length>=1&&i.push(...[...p,...d].map(u=>new l(o.CONFLICTING_SETTING,"'not null' and 'null' can not be set at the same time",u))),p.forEach(u=>{H(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":p.length>1&&i.push(...p.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"'null' can only appear once",u))),p.forEach(u=>{H(u.value)||i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'null' must not have a value",u.value||u.name))});break;case"unique":p.length>1&&i.push(...p.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"'unique' can only appear once",u))),p.forEach(u=>{u instanceof se&&!H(u.value)&&i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'unique' must not have a value",u.value||u.name))});break;case"increment":p.length>1&&i.push(...p.map(u=>new l(o.DUPLICATE_COLUMN_SETTING,"'increment' can only appear once",u))),p.forEach(u=>{u instanceof se&&!H(u.value)&&i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'increment' must not have a value",u.value||u.name))});break;case"default":p.length>1&&i.push(...p.map(u=>new l(o.DUPLICATE_TABLE_SETTING,"'default' can only appear once",u))),p.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:p.forEach(u=>i.push(new l(o.UNKNOWN_COLUMN_SETTING,`Unknown column setting '${f}'`,u)))}}return i}validateSubElements(e){const n=e.flatMap(i=>{if(!i)return[];if(i.parent=this.declarationNode,!i.type)return[];const a=pe(i);return new a(i,this.publicSymbolTable,this.symbolFactory).validate()}),s=e.filter(i=>{var a;return((a=i==null?void 0: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 $n(t){if(!(t instanceof q||Ye(t)||t instanceof G||t instanceof ue))return!1;if(t instanceof q){if(t.callee===void 0||t.argumentList===void 0||!t.argumentList.elementList.every(n=>ee(n)||C(n)||he(n)))return!1;t=t.callee}for(;t instanceof ue;){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=z(t).unwrap_or(void 0);return e!==void 0&&e.length>0}function jn(t,e){return e.length===1&&t===e[0]}class Wn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.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?ye(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 we});const n=z(e);if(n.isOk()){const s=n.unwrap(),i=s.pop(),a=ze(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 I.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 v)return[new l(o.UNEXPECTED_SIMPLE_BODY,"A TableGroup's body must be a block",e)];const[n,s]=I.partition(e.body,i=>i instanceof v);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.flatMap(n=>{const s=[];return n.callee&&!z(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=pe(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=$(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 rt=["-","+"];function qn(t){if(!(t instanceof q||Ye(t)||t instanceof G||t instanceof ue))return!1;if(t instanceof q){if(t.callee===void 0||t.argumentList===void 0||!t.argumentList.elementList.every(n=>ee(n)||C(n)||he(n)))return!1;t=t.callee}for(;t instanceof ue;){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=z(t).unwrap_or(void 0);return e!==void 0&&e.length>0}class Yn{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?ye(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 I.forIn(i,(a,r)=>{switch(r){case"headercolor":a.length>1&&s.push(...a.map(c=>new l(o.DUPLICATE_TABLE_PARTIAL_SETTING,"'headercolor' can only appear once",c))),a.forEach(c=>{Qe(c.value)||s.push(new l(o.INVALID_TABLE_PARTIAL_SETTING,"'headercolor' 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_PARTIAL_SETTING,"'note' can only appear once",c))),a.forEach(c=>{C(c.value)||s.push(new l(o.INVALID_TABLE_PARTIAL_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)))}}),s}registerElement(){const{name:e}=this.declarationNode;this.declarationNode.symbol=this.symbolFactory.create(mn,{declaration:this.declarationNode,symbolTable:new we});const n=z(e);if(n.isOk()){const s=n.unwrap(),i=s.pop(),a=ze(s,this.publicSymbolTable,this.symbolFactory),r=xt(i);if(a.has(r))return[new l(o.DUPLICATE_NAME,`TablePartial name '${i}' already exists`,e)];a.set(r,this.declarationNode.symbol)}return[]}validateBody(e){if(!e)return[];if(e instanceof v)return[new l(o.UNEXPECTED_SIMPLE_BODY,"A TablePartial's body must be a block",e)];const[n,s]=I.partition(e.body,i=>i instanceof v);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)),s.push(...this.registerField(n)),s})}registerField(e){if(e.callee&&j(e.callee)){const n=$(e.callee).unwrap(),s=We(n),i=this.symbolFactory.create(Rt,{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(he)||!e.slice(-1).every(f=>he(f)||f instanceof R))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 n;I.last(e)instanceof R&&(n=e.pop());const s=F(n),i=s.getErrors(),a=s.getValue();e.forEach(f=>{const p=$(f).unwrap_or("").toLowerCase();if(p!=="pk"&&p!=="unique"){i.push(new l(o.INVALID_SETTINGS,"Inline column settings can only be `pk` or `unique`",f));return}a[p]===void 0?a[p]=[f]:a[p].push(f)});const r=a.pk||[],c=a["primary key"]||[];return r.length>=1&&c.length>=1&&i.push(...[...r,...c].map(f=>new l(o.DUPLICATE_COLUMN_SETTING,"Either one of 'primary key' and 'pk' can appear",f))),I.forIn(a,(f,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=>{H(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&&!H(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=>{H(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=>{H(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&&!H(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&&!H(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_COLUMN_SETTING,"'default' can only appear once",u))),f.forEach(u=>{Bt(u.value)||i.push(new l(o.INVALID_COLUMN_SETTING_VALUE,"'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)))}}),i}validateSubElements(e){const n=e.flatMap(i=>{if(i.parent=this.declarationNode,!i.type)return[];const a=pe(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 pe(t){switch(t.type.value.toLowerCase()){case L.Enum:return Mn;case L.Table:return Xn;case L.TableGroup:return Wn;case L.Project:return Vn;case L.Ref:return Gn;case L.Note:return Bn;case L.Indexes:return Fn;case L.TablePartial:return Yn;default:return Un}}function Mt(t){return!!z(t).unwrap_or(!1)}function zn(t){return ye(t)}function ye(t){return t instanceof G&&t.expression instanceof ae}function ze(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 we;const f=n.create(Dt,{symbolTable:r});s.set(c,f)}s=r}return s}function Ft(t){return t==="-"||t==="<>"||t===">"||t==="<"}function Qe(t){var n;if(!(t instanceof G)||!(t.expression instanceof ve)||((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(!hn(e[s]))return!1;return!0}function H(t){return t===void 0}function Bt(t){var e;return!!(C(t)||ee(t)||he(t)&&["true","false","null"].includes(t.expression.variable.value.toLowerCase())||t instanceof K&&rt.includes((e=t.op)==null?void 0:e.value)&&ee(t.expression)||t instanceof ce)}function ee(t){var e;return t instanceof G&&t.expression instanceof ve&&((e=t.expression.literal)==null?void 0:e.kind)===h.NUMERIC_LITERAL}function Vt(t){var n;if(!(t instanceof K)||!Ft((n=t.op)==null?void 0:n.value))return!1;const e=z(t.expression).unwrap_or(void 0);return e!==void 0&&e.length>0}function Gt(t){return t instanceof fe&&t.elementList.every(j)}function F(t){var s;const e={},n=[];if(!t)return new Y({});for(const i of t.elementList){if(!i.name)continue;if(i.name instanceof G){n.push(new l(o.INVALID_SETTINGS,"A setting name must be a stream of identifiers",i.name));continue}const a=(s=ge(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 Y(e,n)}class bt{constructor(e,n){this.ast=e,this.symbolFactory=n,this.publicSchemaSymbol=this.symbolFactory.create(Dt,{symbolTable:new we}),this.ast.symbol=this.publicSchemaSymbol,this.ast.symbol.declaration=this.ast}validate(){const e=[];this.ast.body.forEach(s=>{if(s.parent=this.ast,s.type===void 0)return;const i=pe(s),a=new i(s,this.publicSchemaSymbol.symbolTable,this.symbolFactory);e.push(...a.validate())});const n=this.ast.body.filter(s=>xe(s).unwrap_or(void 0)===L.Project);return n.length>1&&n.forEach(s=>e.push(new l(o.PROJECT_REDEFINED,"Only one project can exist",s))),new Y(this.ast,e)}}class de{constructor(e,n){this.declarationNode=e,this.errors=n}bind(){this.bindSettingList(this.declarationNode.attributeList,this.settingList),this.bindBody()}bindSettingList(e,n){if(e)for(const s of e.elementList){if(s.name instanceof G)continue;const i=ge(s.name).unwrap_or(void 0);if(!i)continue;const a=n[i.toLowerCase()];a!=null&&a.shouldBind&&this.scanAndBind(s.value,a)}}bindBody(){var s,i;const e=this.declarationNode;if(!e.body)return;const{body:n}=e;if(n instanceof re)for(const a of n.body)if(a instanceof y){if(((s=this.declarationNode.type)==null?void 0:s.value.toLowerCase())===L.TablePartial&&((i=a.type)==null?void 0:i.value.toLowerCase())===L.Indexes||!a.type)continue;const r=Ke(a);new r(a,this.errors).bind()}else a instanceof v?this.bindSubfield(a):this.bindPartialInjection(a);else this.bindSubfield(n)}bindSubfield(e){const n=[e.callee,...e.args],s=I.last(n);s instanceof R&&(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.subfield.injection)!=null&&n.injectionBinderRule.shouldBind&&this.scanAndBind(e,this.subfield.injection.injectionBinderRule)}scanAndBind(e,n){var s,i;if(e)if(e instanceof G){if(e.expression instanceof ae&&((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?Ye(e)?this.bindFragments(_e(e).unwrap_or([]),n):(this.scanAndBind(e.leftExpression,n),this.scanAndBind(e.rightExpression,n)):e instanceof K?this.scanAndBind(e.expression,n):e instanceof je?this.scanAndBind(e.expression,n):e instanceof fe?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[0]instanceof Le,i=[...n.topSubnamesSymbolKind],{remainingSubnamesSymbolKind:a}=n,r=s?-1:e.findIndex(E=>!j(E)),f=r!==-1&&Gt(e[r])?e[r]:void 0,p=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(),b=d.pop(),g=$(b).unwrap();u.unshift({index:Me(g,E),referrer:b})}for(;d.length;){const E=d.pop(),b=s?E.partial.variable.value:$(E).unwrap();u.unshift({index:Me(b,a),referrer:E})}return f?f.elementList.forEach(E=>this.resolveIndexStack([...u,{index:Me($(E).unwrap(),p),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=Tt(s.index,this.declarationNode);if(a===void 0){const{kind:p,name:d}=oe(s.index).unwrap();this.logError(s.referrer,`Can not find ${p} '${d}'`,n);return}a.references.push(s.referrer),s.referrer.referee=a;let r=a.symbolTable,{kind:c,name:f}=oe(s.index).unwrap();for(const p of i){const{kind:d,name:u}=oe(p.index).unwrap(),E=r.get(p.index);if(!E){this.logError(p.referrer,`${c} '${f}' does not have ${d} '${u}'`,n);return}if(c=d,f=u,p.referrer.referee=E,E.references.push(p.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 c,f,p;if(ln(r)){const d=Tt(cn(r),this.declarationNode);(p=(f=(c=d==null?void 0:d.declaration)==null?void 0:c.symbol)==null?void 0:f.symbolTable)==null||p.forEach((u,E)=>{n.has(E)||s.set(E,u)})}}),s.forEach((a,r)=>{const c=e.create(bn,{injectorId:a.id});n.set(r,c)})}}class Qn extends de{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Hn extends de{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Jn extends de{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 Zn extends de{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Kn extends de{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class es extends de{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class ts extends de{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Enum],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!0}]},injection:{injectionBinderRule:{shouldBind:!0,topSubnamesSymbolKind:[],remainingSubnamesSymbolKind:m.TablePartial,ignoreNameNotFound:!1}},settingList:{ref:{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},default:{shouldBind:!1}}},this.settingList={}}}class ns extends de{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class ss extends de{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 Ke(t){switch(t.type.value.toLowerCase()){case L.Enum:return Hn;case L.Table:return ts;case L.TableGroup:return ns;case L.Project:return Kn;case L.Ref:return es;case L.Note:return Zn;case L.Indexes:return Jn;case L.TablePartial:return ss;default:return Qn}}class is{constructor(e){this.ast=e,this.errors=[]}resolve(e){this.ast.body.forEach(n=>{if(n.type){const s=Ke(n);new s(n,this.errors).resolveInjections(e)}});for(const n of this.ast.body)if(n.type){const s=Ke(n);new s(n,this.errors).bind()}return new Y(this.ast,this.errors)}}class as{constructor(e){this.generator=e}create(e,n){return new e(n,this.generator.nextId())}}class rs{constructor(e,n){this.ast=e,this.symbolFactory=new as(n)}analyze(){return new bt(this.ast,this.symbolFactory).validate().chain(n=>new is(n).resolve(this.symbolFactory))}validate(){return new bt(this.ast,this.symbolFactory).validate().chain(n=>new Y(n,[]))}}function It(t,e){const{variables:n,tupleElements:s}=Se(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 Ct(t){switch(t){case"<":return["1","*"];case"<>":return["*","*"];case">":return["*","1"];case"-":return["1","1"]}throw new Error("Invalid relation op")}function _(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 Ce(t){var n;const e=(n=_e(t).unwrap_or(void 0))==null?void 0:n.pop();return e instanceof fe?e.elementList.map(s=>s.referee):[e.referee]}function Te(t){const e=z(t).unwrap();return{name:e.pop(),schemaName:e}}function De(t){return t.expression.literal.value}function Xt(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 ot(t,e){if(Array.isArray(t)){const i=t.map(({id:r})=>r).sort(),a=e.map(({id:r})=>r).sort();return I.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(`
|
|
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 Xt{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=_(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}=Te(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.headercolor)!=null&&i.length?De((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:U(s==null?void 0:s.value).map(ie).unwrap(),token:_(s)},[]}interpretBody(e){const[n,s]=I.partition(e.body,i=>i instanceof w||i instanceof ke);return[...this.interpretFields(n),...this.interpretSubElements(s)]}interpretSubElements(e){return e.flatMap(n=>{var s;switch((s=n.type)==null?void 0:s.value.toLowerCase()){case"note":return this.table.note={value:U(n.body instanceof re?n.body.body[0].callee:n.body.callee).map(ie).unwrap(),token:_(n)},[];case"indexes":return this.interpretIndexes(n)}return[]})}interpretInjection(e,n){const s={order:n,token:_(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,f,p,d,u,E,b,g;const n=[],s={};s.name=X(e.callee).unwrap();const i=rs(e.args[0]);s.type=i.getValue(),n.push(...i.getErrors()),s.token=_(e),s.inline_refs=[];const a=e.args.slice(1);if(I.last(a)instanceof R){const A=F(a.pop()).getValue();s.pk=!!((r=A.pk)!=null&&r.length)||!!((c=A["primary key"])!=null&&c.length),s.increment=!!((f=A.increment)!=null&&f.length),s.unique=!!((p=A.unique)!=null&&p.length),s.not_null=(d=A["not null"])!=null&&d.length?!0:(u=A.null)!=null&&u.length?!1:void 0,s.dbdefault=os((b=(E=A.default)==null?void 0:E.at(0))==null?void 0:b.value);const k=(g=A.note)==null?void 0:g.at(0);s.note=k&&{value:U(k.value).map(ie).unwrap(),token:_(k)};const be=A.ref||[];s.inline_refs=be.flatMap(S=>{const[Oe]=Ge(S.value.expression);if(ot(Oe,e.symbol))return n.push(new l(o.SAME_ENDPOINT,"Two endpoints are the same",S)),[];const Ee=S.value.op,V=z(S.value.expression).unwrap();let te;if(V.length===1){const[Q]=V;te={schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[Q],relation:Ee.value,token:_(S)}}else if(V.length===2){const[Q,me]=V;te={schemaName:null,tableName:Q,fieldNames:[me],relation:Ee.value,token:_(S)}}else if(V.length===3){const[Q,me,ut]=V;te={schemaName:Q,tableName:me,fieldNames:[ut],relation:Ee.value,token:_(S)}}else{n.push(new l(o.UNSUPPORTED,"Nested schema is not supported",S));const Q=V.pop(),me=V.pop();te={schemaName:V.join("."),tableName:me,fieldNames:[Q],relation:Ee.value,token:_(S)}}const Ne=this.registerInlineRefToEnv(e,Oe,te,S);return n.push(...Ne),Ne.length===0?te:[]})}return s.pk||(s.pk=a.some(A=>W(A).unwrap().toLowerCase()==="pk")),s.unique||(s.unique=a.some(A=>W(A).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,f,p,d,u,E;const s={columns:[]},i=n;s.token=_(i);const a=[i.callee,...i.args];if(I.last(a)instanceof R){const b=F(a.pop()).getValue();s.pk=!!((r=b.pk)!=null&&r.length),s.unique=!!((c=b.unique)!=null&&c.length),s.name=U((p=(f=b.name)==null?void 0:f.at(0))==null?void 0:p.value).unwrap_or(void 0);const g=(d=b.note)==null?void 0:d.at(0);s.note=g&&{value:U(g.value).unwrap(),token:_(g)},s.type=W((E=(u=b.type)==null?void 0:u.at(0))==null?void 0:E.value).unwrap_or(void 0)}return a.flatMap(b=>{if(!(b instanceof q))return b;const g=[];for(;b instanceof q;)g.push(b.argumentList),b=b.callee;return g.push(b),g}).forEach(b=>{const{functional:g,nonFunctional:A}=Ve(b).unwrap();s.columns.push(...g.map(k=>({value:k.value.value,type:"expression",token:_(k)})),...A.map(k=>({value:X(k).unwrap(),type:"column",token:_(k)})))}),s})),[]}registerInlineRefToEnv(e,n,s,i){const a=Ct(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=Gt(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:[W(e.callee).unwrap()],token:_(e),relation:r[0]}]}),[]}}function rs(t){let e=null;t instanceof q&&(e=t.argumentList.elementList.map(a=>ee(a)?a.expression.literal.value:C(a)?U(a).unwrap():W(a).unwrap()).join(","),t=t.callee);let n="";for(;t instanceof ue;)n=`[${t.indexer.elementList.map(a=>a.name.expression.literal.value).join(",")}]${n}`,t=t.array;const{name:s,schemaName:i}=Te(t);return i.length>1?new Y({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 Y({schemaName:i.length===0?null:i[0],type_name:`${s}${n}${e?`(${e})`:""}`,args:e})}function os(t){var e,n,s;if(t){if(C(t))return{value:U(t).unwrap(),type:"string"};if(ee(t))return{type:"number",value:Number.parseFloat(t.expression.literal.value)};if(he(t))return{value:t.expression.variable.value.toLowerCase(),type:"boolean"};if(t instanceof Z&&rt.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 ce)return{value:(s=t.value)==null?void 0:s.value,type:"expression"};throw new Error("Unreachable")}}class ls{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=_(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}=Te(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?De((a=(i=n.headercolor)==null?void 0:i.at(0))==null?void 0:a.value):void 0,[]}interpretBody(e){const[n,s]=I.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=I.get(e,"callee.expression.literal.value","");return this.note.content=ie(n),[]}}class $t{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=_(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=z(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 p,d,u,E,b,g,A;const n=e.callee.op.value,{leftExpression:s,rightExpression:i}=e.callee,a=Ge(s),r=Ge(i);if(ot(a,r))return[new l(o.SAME_ENDPOINT,"Two endpoints are the same",e)];const c=Ct(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=(p=k.delete)==null?void 0:p.at(0))==null?void 0:d.value;this.ref.onDelete=be instanceof ne?Ae(be).unwrap_or(void 0):W(be).unwrap_or(void 0);const S=(E=(u=k.update)==null?void 0:u.at(0))==null?void 0:E.value;this.ref.onUpdate=S instanceof ne?Ae(S).unwrap_or(void 0):W(S).unwrap_or(void 0),this.ref.color=(b=k.color)!=null&&b.length?De((A=(g=k.color)==null?void 0:g.at(0))==null?void 0:A.value):void 0}const f=Gt(n);return this.ref.endpoints=[{...It(s,this.container),relation:f[0],token:_(s)},{...It(i,this.container),relation:f[1],token:_(i)}],this.env.refIds[c]=this.declarationNode,[]}}class jt{constructor(e,n){this.declarationNode=e,this.env=n,this.tableGroup={tables:[]}}interpret(){const e=[];return this.tableGroup.token=_(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}=Te(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]=I.partition(e.body,i=>i instanceof w);return[...this.interpretFields(n),...this.interpretSubElements(s)]}interpretSubElements(e){return e.flatMap(n=>{var s;switch((s=n.type)==null?void 0:s.value.toLowerCase()){case"note":this.tableGroup.note={value:U(n.body instanceof re?n.body.body[0].callee:n.body.callee).map(ie).unwrap(),token:_(n)};break}return[]})}interpretFields(e){const n=[];return this.tableGroup.tables=e.map(s=>{const i=z(s.callee).unwrap();i.length>2&&n.push(new l(o.UNSUPPORTED,"Nested schema is not supported",s));const a=Ie(s.callee).unwrap().pop().referee.id;if(this.env.groupOfTable[a]){const r=this.env.groupOfTable[a],{schemaName:c,name:f}=this.env.tableGroups.get(r),p=c?`${c}.${f}`:f;n.push(new l(o.TABLE_REAPPEAR_IN_TABLEGROUP,`Table "${i.join(".")}" already appears in group "${p}"`,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?De((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:U(s==null?void 0:s.value).map(ie).unwrap(),token:_(s)},[]}}class Wt{constructor(e,n){this.declarationNode=e,this.env=n,this.enum={values:[]}}interpret(){return this.enum.token=_(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}=Te(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=_(s),i.name=W(s.callee).unwrap();const r=(c=F(s.args[0]).getValue().note)==null?void 0:c.at(0);return i.note=r&&{value:U(r.value).map(ie).unwrap(),token:_(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=_(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}=Te(e);return this.tablePartial.name=n,[]}interpretSettingList(e){var i,a,r;const n=F(e).getValue();this.tablePartial.headerColor=(i=n.headercolor)!=null&&i.length?De((r=(a=n.headercolor)==null?void 0:a.at(0))==null?void 0:r.value):void 0;const[s]=n.note||[];return this.tablePartial.note=s&&{value:U(s==null?void 0:s.value).map(ie).unwrap(),token:_(s)},[]}interpretBody(e){const[n,s]=I.partition(e.body,i=>i instanceof w);return[...this.interpretFields(n),...this.interpretSubElements(s)]}interpretSubElements(e){return e.flatMap(n=>{var s;switch((s=n.type)==null?void 0:s.value.toLowerCase()){case"note":return this.tablePartial.note={value:U(n.body instanceof re?n.body.body[0].callee:n.body.callee).map(ie).unwrap(),token:_(n)},[];case"indexes":return this.interpretIndexes(n)}return[]})}interpretFields(e){return e.flatMap(n=>this.interpretColumn(n))}interpretColumn(e){var r,c,f,p,d,u,E,b,g;const n=[],s={};s.name=X(e.callee).unwrap();const i=cs(e.args[0]);s.type=i.getValue(),n.push(...i.getErrors()),s.token=_(e),s.inline_refs=[];const a=e.args.slice(1);if(I.last(a)instanceof R){const A=F(a.pop()).getValue();s.pk=!!((r=A.pk)!=null&&r.length)||!!((c=A["primary key"])!=null&&c.length),s.increment=!!((f=A.increment)!=null&&f.length),s.unique=!!((p=A.unique)!=null&&p.length),s.not_null=(d=A["not null"])!=null&&d.length?!0:(u=A.null)!=null&&u.length?!1:void 0,s.dbdefault=us((b=(E=A.default)==null?void 0:E.at(0))==null?void 0:b.value);const k=(g=A.note)==null?void 0:g.at(0);s.note=k&&{value:U(k.value).map(ie).unwrap(),token:_(k)};const be=A.ref||[];s.inline_refs=be.flatMap(S=>{const[Oe]=Ge(S.value.expression);if(ot(Oe,e.symbol))return n.push(new l(o.SAME_ENDPOINT,"Two endpoints are the same",S)),[];const Ee=S.value.op,V=z(S.value.expression).unwrap();let te;if(V.length===2){const[Ne,Q]=V;te={schemaName:null,tableName:Ne,fieldNames:[Q],relation:Ee.value,token:_(S)}}else if(V.length===3){const[Ne,Q,me]=V;te={schemaName:Ne,tableName:Q,fieldNames:[me],relation:Ee.value,token:_(S)}}else{n.push(new l(o.UNSUPPORTED,"Unsupported",S));const Ne=V.pop(),Q=V.pop();te={schemaName:V.join("."),tableName:Q,fieldNames:[Ne],relation:Ee.value,token:_(S)}}return te})}return s.pk||(s.pk=a.some(A=>W(A).unwrap().toLowerCase()==="pk")),s.unique||(s.unique=a.some(A=>W(A).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,f,p,d,u,E;const s={columns:[]},i=n;s.token=_(i);const a=[i.callee,...i.args];if(I.last(a)instanceof R){const b=F(a.pop()).getValue();s.pk=!!((r=b.pk)!=null&&r.length),s.unique=!!((c=b.unique)!=null&&c.length),s.name=U((p=(f=b.name)==null?void 0:f.at(0))==null?void 0:p.value).unwrap_or(void 0);const g=(d=b.note)==null?void 0:d.at(0);s.note=g&&{value:U(g.value).unwrap(),token:_(g)},s.type=W((E=(u=b.type)==null?void 0:u.at(0))==null?void 0:E.value).unwrap_or(void 0)}return a.flatMap(b=>{if(!(b instanceof q))return b;const g=[];for(;b instanceof q;)g.push(b.argumentList),b=b.callee;return g.push(b),g}).forEach(b=>{const{functional:g,nonFunctional:A}=Ve(b).unwrap();s.columns.push(...g.map(k=>({value:k.value.value,type:"expression",token:_(k)})),...A.map(k=>({value:X(k).unwrap(),type:"column",token:_(k)})))}),s})),[]}}function cs(t){let e=null;t instanceof q&&(e=t.argumentList.elementList.map(a=>ee(a)?a.expression.literal.value:C(a)?U(a).unwrap():W(a).unwrap()).join(","),t=t.callee);let n="";for(;t instanceof ue;)n=`[${t.indexer.elementList.map(a=>a.name.expression.literal.value).join(",")}]${n}`,t=t.array;const{name:s,schemaName:i}=Te(t);return i.length>1?new Y({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 Y({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:U(t).unwrap(),type:"string"};if(ee(t))return{type:"number",value:Number.parseFloat(t.expression.literal.value)};if(he(t))return{value:t.expression.variable.value.toLowerCase(),type:"boolean"};if(t instanceof Z&&rt.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 ce)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.project={enums:[],refs:[],tableGroups:[],tables:[],tablePartials:[]}}interpret(){return this.env.project.set(this.declarationNode,this.project),this.project.token=_(this.declarationNode),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(e){if(!e)return this.project.name=null,[];const{name:n}=Te(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 Xt(s,this.env).interpret();return this.project.tables.push(this.env.tables.get(s)),a}case"ref":{const a=new $t(s,this.env).interpret();return this.project.refs.push(this.env.ref.get(s)),a}case"tablegroup":{const a=new jt(s,this.env).interpret();return this.project.tableGroups.push(this.env.tableGroups.get(s)),a}case"enum":{const a=new Wt(s,this.env).interpret();return this.project.enums.push(this.env.enums.get(s)),a}case"note":return this.project.note={value:U(s.body instanceof re?s.body.body[0].callee:s.body.callee).map(ie).unwrap(),token:_(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()]=U(s.body.callee).unwrap(),[]}})}}class fs{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(xe(n).unwrap_or(void 0)){case L.Table:return new Xt(n,this.env).interpret();case L.Note:return new ls(n,this.env).interpret();case L.Ref:return new $t(n,this.env).interpret();case L.TableGroup:return new jt(n,this.env).interpret();case L.TablePartial:return new qt(n,this.env).interpret();case L.Enum:return new Wt(n,this.env).interpret();case L.Project:return new hs(n,this.env).interpret();default:return[]}});return new Y(ps(this.env),e)}}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())}}var v=(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))(v||{}),P=(t=>(t[t.None=0]="None",t[t.KeepWhitespace=1]="KeepWhitespace",t[t.InsertAsSnippet=4]="InsertAsSnippet",t))(P||{});function Pe(t){switch(t){case m.Schema:return v.Module;case m.Table:return v.Class;case m.Column:return v.Field;case m.Enum:return v.Enum;case m.EnumField:return v.EnumMember;case m.TableGroup:return v.Struct;case m.TableGroupField:return v.Field;default:return v.Text}}function Ce(t,e){if(!t||Ke(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 B(){return{suggestions:[]}}function Xe(t){return{...t,suggestions:t.suggestions.map(e=>({...e,insertText:` ${e.insertText}`}))}}function Qe(t){return{...t,suggestions:t.suggestions.map(e=>({...e,insertText:e.insertText.split("").every(We)?e.insertText:`"${e.insertText}"`}))}}function lt(t,e){return t.getOffsetAt(e)}class Yt{constructor(e,n=[]){this.compiler=e,this.triggerCharacters=n}provideCompletionItems(e,n){var d,u;const s=lt(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=>en(E)&&ye(s,E)))return B();if(r===void 0)return vt();if([h.STRING_LITERAL,h.QUOTED_STRING].includes(a.kind)&&ye(s,a))return B();const f=this.compiler.container.element(s);if(this.compiler.container.scopeKind(s)===M.TOPLEVEL||f instanceof y&&f.type&&f.type.start<=s&&f.type.end>=s)return vt();const p=[...this.compiler.container.stack(s)].reverse();for(const E of p)if(E instanceof Z)switch((d=E.op)==null?void 0:d.value){case">":case"<":case"<>":case"-":return Lt(this.compiler,s,E)}else if(E instanceof le)switch((u=E.op)==null?void 0:u.value){case">":case"<":case"<>":case"-":return Lt(this.compiler,s,E);case".":return zt(this.compiler,s,E)}else{if(E instanceof se)return _t(this.compiler,s,E);if(E instanceof R)return _t(this.compiler,s,E);if(E instanceof fe)return ds(this.compiler,s);if(E instanceof w)return gt(this.compiler,s,E);if(E instanceof y&&(E.bodyColon&&s>=E.bodyColon.end||E.body&&ye(s,E.body)))return gt(this.compiler,s,void 0)}return B()}}function Lt(t,e,n){const s=t.container.scopeKind(e);if([M.REF,M.TABLE].includes(s)){const i=He(t,e,t.container.element(e),[m.Table,m.Schema,m.Column]);return Ce(n.op,e)?Xe(i):i}return B()}function He(t,e,n,s){var r;if(n===void 0)return B();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:f})=>s.includes(f)).map(({name:f,kind:p})=>({label:f,insertText:f,insertTextRules:P.KeepWhitespace,kind:Pe(p),sortText:Pe(p).toString().padStart(2,"0"),range:void 0})))}i=i instanceof y?i.parent:void 0}return Qe(a)}function ds(t,e){var s;switch(t.container.scopeKind(e)){case M.INDEXES:return Ht(t,e);case M.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 zt(t,e,a)}}return Qt(t,e)}return B()}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=At(t,e);return(s==null?void 0:s.kind)===h.COMMA&&Ce(s,e)?Xe(i):i}if(n.name&&n.name.start<=e&&n.name.end>=e)return At(t,e);if(n.name instanceof ne){const i=Es(t,e,Ae(n.name).unwrap_or(""));return(s==null?void 0:s.kind)===h.COLON&&Ce(s,e)?Xe(i):i}return B()}function At(t,e){const n=t.container.element(e),s=t.container.scopeKind(e);if(n instanceof K)return B();if(n.body&&!ye(e,n.body))switch(s){case M.TABLE:return{suggestions:["headercolor","note"].map(i=>({label:i,insertText:`${i}: `,kind:v.Field,insertTextRules:P.KeepWhitespace,range:void 0}))};case M.TABLEGROUP:return{suggestions:["color","note"].map(i=>({label:i,insertText:`${i}: `,kind:v.Field,insertTextRules:P.KeepWhitespace,range:void 0}))};default:return B()}switch(s){case M.TABLE:return{suggestions:[...["primary key","null","not null","increment","pk","unique"].map(i=>({label:i,insertText:i,kind:v.Property,insertTextRules:P.KeepWhitespace,range:void 0})),...["ref","default"].map(i=>({label:i,insertText:`${i}: `,kind:v.Property,insertTextRules:P.KeepWhitespace,range:void 0})),{label:"note",insertText:"note: ",kind:v.Property,insertTextRules:P.KeepWhitespace,range:void 0}]};case M.ENUM:return{suggestions:[{label:"note",insertText:"note: ",kind:v.Property,insertTextRules:P.KeepWhitespace,range:void 0}]};case M.INDEXES:return{suggestions:[...["unique","pk"].map(i=>({label:i,insertText:i,insertTextRules:P.KeepWhitespace,kind:v.Property,range:void 0})),...["note","name","type"].map(i=>({label:i,insertText:`${i}: `,kind:v.Property,insertTextRules:P.KeepWhitespace,range:void 0}))]};case M.REF:return{suggestions:["update","delete"].map(i=>({label:i,insertText:`${i}: `,kind:v.Property,insertTextRules:P.KeepWhitespace,range:void 0}))}}return B()}function Es(t,e,n){switch(n==null?void 0:n.toLowerCase()){case"update":case"delete":return{suggestions:["cascade","set default","set null","restrict"].map(s=>({label:s,insertText:s,kind:v.Value,insertTextRules:P.KeepWhitespace,range:void 0}))};case"type":return{suggestions:["btree","hash"].map(s=>({label:s,insertText:`${s}`,kind:v.Value,insertTextRules:P.KeepWhitespace,range:void 0}))}}return B()}function zt(t,e,n){const s=Ie(n).unwrap_or([]);if(s.pop(),s.some(a=>!$(a)))return B();const i=s.map(a=>W(a).unwrap());return Qe({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:Pe(a),range:void 0}))})}function gt(t,e,n){var i;switch(t.container.scopeKind(e)){case M.TABLE:return ms(t,e,n);case M.PROJECT:return Ts(t,e,n);case M.INDEXES:return Is(t,e);case M.ENUM:return Ns(t,e,n);case M.REF:{const a=Qt(t,e);return((i=t.container.token(e).token)==null?void 0:i.kind)===h.COLON&&Ce(t.container.token(e).token,e)?Xe(a):a}case M.TABLEGROUP:return bs(t);default:return B()}}function vt(){return{suggestions:["Table","TableGroup","Enum","Project","Ref"].map(t=>({label:t,insertText:t,insertTextRules:P.KeepWhitespace,kind:v.Keyword,range:void 0}))}}function Ns(t,e,n){return n!=null&&n.callee&&ct(e,n)===1?He(t,e,t.container.element(e),[m.Schema,m.Table,m.Column]):B()}function ms(t,e,n){if(!(n!=null&&n.callee))return{suggestions:["Note","indexes"].map(i=>({label:i,insertText:i,insertTextRules:P.KeepWhitespace,kind:v.Keyword,range:void 0}))};const s=ct(e,n);return s===0?{suggestions:["Note","indexes"].map(i=>({label:i,insertText:i,insertTextRules:P.KeepWhitespace,kind:v.Keyword,range:void 0}))}:s===1?Ls(t,e):B()}function Ts(t,e,n){return n!=null&&n.callee?ct(e,n)===0?{suggestions:["Table","TableGroup","Enum","Note","Ref"].map(i=>({label:i,insertText:i,insertTextRules:P.KeepWhitespace,kind:v.Keyword,range:void 0}))}:B():{suggestions:["Table","TableGroup","Enum","Note","Ref"].map(i=>({label:i,insertText:i,insertTextRules:P.KeepWhitespace,kind:v.Keyword,range:void 0}))}}function Qt(t,e){return He(t,e,t.container.element(e),[m.Schema,m.Table,m.Column])}function bs(t){return{suggestions:[...Qe({suggestions:[...t.parse.publicSymbolTable().entries()].flatMap(([e])=>{const n=oe(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:P.KeepWhitespace,kind:Pe(s),range:void 0}})}).suggestions,...["Note"].map(e=>({label:e,insertText:e,insertTextRules:P.KeepWhitespace,kind:v.Keyword,range:void 0}))]}}function Is(t,e){return Ht(t,e)}function Ls(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:P.KeepWhitespace,kind:v.TypeParameter,sortText:v.TypeParameter.toString().padStart(2,"0"),range:void 0})),...He(t,e,t.container.element(e),[m.Enum,m.Schema]).suggestions]}}function Ht(t,e){const n=t.container.element(e),s=n==null?void 0:n.parent;if(!((s==null?void 0:s.symbol)instanceof Dt))return B();const{symbolTable:i}=s.symbol;return Qe({suggestions:[...i.entries()].flatMap(([a])=>{const r=oe(a).unwrap_or(void 0);if(r===void 0)return[];const{name:c}=r;return{label:c,insertText:c,insertTextRules:P.KeepWhitespace,kind:Pe(m.Column),range:void 0}})})}function ct(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 Jt{constructor(e){this.compiler=e}provideDefinition(e,n){var r;const{uri:s}=e,i=lt(e,n),a=[...this.compiler.container.stack(i)];for(;a.length!==0;){const c=a.pop();if((r=c==null?void 0:c.referee)!=null&&r.declaration&&[_e.PRIMARY_EXPRESSION,_e.VARIABLE].includes(c==null?void 0:c.kind)){const{startPos:f,endPos:p}=c.referee.declaration;return[{range:{startColumn:f.column+1,startLineNumber:f.line+1,endColumn:p.column+1,endLineNumber:p.line+1},uri:s}]}}return[]}}class Kt{constructor(e){this.compiler=e}provideReferences(e,n){const{uri:s}=e,i=lt(e,n),a=[...this.compiler.container.stack(i)];for(;a.length!==0;){const r=a.pop();if(r&&[_e.ELEMENT_DECLARATION,_e.FUNCTION_APPLICATION,_e.PRIMARY_EXPRESSION].includes(r==null?void 0:r.kind)){const{symbol:c}=r;if(c!=null&&c.references.length)return c.references.map(({startPos:f,endPos:p})=>({range:{startColumn:f.column+1,startLineNumber:f.line+1,endColumn:p.column+1,endLineNumber:p.line+1},uri:s}))}}return[]}}const _s=Object.freeze(Object.defineProperty({__proto__:null,CompletionItemInsertTextRule:P,CompletionItemKind:v,DBMLCompletionItemProvider:Yt,DBMLDefinitionProvider:Jt,DBMLReferencesProvider:Kt},Symbol.toStringTag,{value:"Module"}));var M=(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))(M||{});class As{constructor(){this.source="",this.cache=new Array(16).fill(null),this.nodeIdGenerator=new tn,this.symbolIdGenerator=new hn,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 An(this.source).lex().chain(n=>new wn(n,this.nodeIdGenerator).parse()).chain(({ast:n,tokens:s})=>new as(n,this.symbolIdGenerator).analyze().map(()=>({ast:n,tokens:s})));return e.getErrors().length>0?e:e.chain(({ast:n,tokens:s})=>new fs(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:I.findLastIndex(n,p=>!p.isInvalid,s);if(a===-1)return[this.parse.ast()];const r=n[a].start;let c=this.parse.ast();const f=[c];for(;;){const d=_n(c).find(u=>ye(r,u));if(d===void 0||d instanceof J)break;f.push(d),c=d}if((i==null?void 0:i.kind)===h.COLON)return f;for(;f.length>0;){let p=!1;const d=I.last(f);if(d instanceof w){const u=this.parse.source();for(let E=d.end;E<e;E+=1)u[E]===`
|
|
12
|
-
`&&(f.pop(),p=!0)}else d instanceof
|
|
11
|
+
`)}class $t{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=_(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}=Te(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=F(e).getValue();this.table.headerColor=(i=n.headercolor)!=null&&i.length?De((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:M(s==null?void 0:s.value).map(ie).unwrap(),token:_(s)},[]}interpretBody(e){const[n,s]=I.partition(e.body,i=>i instanceof v||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"note":return this.table.note={value:M(n.body instanceof re?n.body.body[0].callee:n.body.callee).map(ie).unwrap(),token:_(n)},[];case"indexes":return this.interpretIndexes(n)}return[]})}interpretInjection(e,n){const s={order:n,token:_(e)};return s.name=e.partial.variable.value,this.table.partials.push(s),[]}interpretFields(e){return e.flatMap((n,s)=>n instanceof v?this.interpretColumn(n):this.interpretInjection(n,s))}interpretColumn(e){var r,c,f,p,d,u,E,b,g;const n=[],s={};s.name=$(e.callee).unwrap();const i=os(e.args[0]);s.type=i.getValue(),n.push(...i.getErrors()),s.token=_(e),s.inline_refs=[];const a=e.args.slice(1);if(I.last(a)instanceof R){const A=F(a.pop()).getValue();s.pk=!!((r=A.pk)!=null&&r.length)||!!((c=A["primary key"])!=null&&c.length),s.increment=!!((f=A.increment)!=null&&f.length),s.unique=!!((p=A.unique)!=null&&p.length),s.not_null=(d=A["not null"])!=null&&d.length?!0:(u=A.null)!=null&&u.length?!1:void 0,s.dbdefault=ls((b=(E=A.default)==null?void 0:E.at(0))==null?void 0:b.value);const k=(g=A.note)==null?void 0:g.at(0);s.note=k&&{value:M(k.value).map(ie).unwrap(),token:_(k)};const be=A.ref||[];s.inline_refs=be.flatMap(S=>{const[Re]=Ce(S.value.expression);if(ot(Re,e.symbol))return n.push(new l(o.SAME_ENDPOINT,"Two endpoints are the same",S)),[];const Ee=S.value.op,V=z(S.value.expression).unwrap();let te;if(V.length===1){const[Q]=V;te={schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[Q],relation:Ee.value,token:_(S)}}else if(V.length===2){const[Q,me]=V;te={schemaName:null,tableName:Q,fieldNames:[me],relation:Ee.value,token:_(S)}}else if(V.length===3){const[Q,me,ut]=V;te={schemaName:Q,tableName:me,fieldNames:[ut],relation:Ee.value,token:_(S)}}else{n.push(new l(o.UNSUPPORTED,"Nested schema is not supported",S));const Q=V.pop(),me=V.pop();te={schemaName:V.join("."),tableName:me,fieldNames:[Q],relation:Ee.value,token:_(S)}}const Ne=this.registerInlineRefToEnv(e,Re,te,S);return n.push(...Ne),Ne.length===0?te:[]})}return s.pk||(s.pk=a.some(A=>W(A).unwrap().toLowerCase()==="pk")),s.unique||(s.unique=a.some(A=>W(A).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,f,p,d,u,E;const s={columns:[]},i=n;s.token=_(i);const a=[i.callee,...i.args];if(I.last(a)instanceof R){const b=F(a.pop()).getValue();s.pk=!!((r=b.pk)!=null&&r.length),s.unique=!!((c=b.unique)!=null&&c.length),s.name=M((p=(f=b.name)==null?void 0:f.at(0))==null?void 0:p.value).unwrap_or(void 0);const g=(d=b.note)==null?void 0:d.at(0);s.note=g&&{value:M(g.value).unwrap(),token:_(g)},s.type=W((E=(u=b.type)==null?void 0:u.at(0))==null?void 0:E.value).unwrap_or(void 0)}return a.flatMap(b=>{if(!(b instanceof q))return b;const g=[];for(;b instanceof q;)g.push(b.argumentList),b=b.callee;return g.push(b),g}).forEach(b=>{const{functional:g,nonFunctional:A}=Ge(b).unwrap();s.columns.push(...g.map(k=>({value:k.value.value,type:"expression",token:_(k)})),...A.map(k=>({value:$(k).unwrap(),type:"column",token:_(k)})))}),s})),[]}registerInlineRefToEnv(e,n,s,i){const a=Xt(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=Ct(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:[W(e.callee).unwrap()],token:_(e),relation:r[0]}]}),[]}}function os(t){let e=null;t instanceof q&&(e=t.argumentList.elementList.map(a=>ee(a)?a.expression.literal.value:C(a)?M(a).unwrap():W(a).unwrap()).join(","),t=t.callee);let n="";for(;t instanceof ue;)n=`[${t.indexer.elementList.map(a=>a.name.expression.literal.value).join(",")}]${n}`,t=t.array;const{name:s,schemaName:i}=Te(t);return i.length>1?new Y({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 Y({schemaName:i.length===0?null:i[0],type_name:`${s}${n}${e?`(${e})`:""}`,args:e})}function ls(t){var e,n,s;if(t){if(C(t))return{value:M(t).unwrap(),type:"string"};if(ee(t))return{type:"number",value:Number.parseFloat(t.expression.literal.value)};if(he(t))return{value:t.expression.variable.value.toLowerCase(),type:"boolean"};if(t instanceof K&&rt.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 ce)return{value:(s=t.value)==null?void 0:s.value,type:"expression"};throw new Error("Unreachable")}}class cs{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=_(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}=Te(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?De((a=(i=n.headercolor)==null?void 0:i.at(0))==null?void 0:a.value):void 0,[]}interpretBody(e){const[n,s]=I.partition(e.body,i=>i instanceof v);return n.length!==1||s.length>0?[new l(o.INVALID_NOTE,"Invalid note syntax",e)]:[...this.interpretNote(n[0])]}interpretNote(e){const n=I.get(e,"callee.expression.literal.value","");return this.note.content=ie(n),[]}}class jt{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=_(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=z(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 v?this.interpretField(e):this.interpretField(e.body[0])}interpretField(e){var p,d,u,E,b,g,A;const n=e.callee.op.value,{leftExpression:s,rightExpression:i}=e.callee,a=Ce(s),r=Ce(i);if(ot(a,r))return[new l(o.SAME_ENDPOINT,"Two endpoints are the same",e)];const c=Xt(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=(p=k.delete)==null?void 0:p.at(0))==null?void 0:d.value;this.ref.onDelete=be instanceof ne?ge(be).unwrap_or(void 0):W(be).unwrap_or(void 0);const S=(E=(u=k.update)==null?void 0:u.at(0))==null?void 0:E.value;this.ref.onUpdate=S instanceof ne?ge(S).unwrap_or(void 0):W(S).unwrap_or(void 0),this.ref.color=(b=k.color)!=null&&b.length?De((A=(g=k.color)==null?void 0:g.at(0))==null?void 0:A.value):void 0}const f=Ct(n);return this.ref.endpoints=[{...It(s,this.container),relation:f[0],token:_(s)},{...It(i,this.container),relation:f[1],token:_(i)}],this.env.refIds[c]=this.declarationNode,[]}}class Wt{constructor(e,n){this.declarationNode=e,this.env=n,this.tableGroup={tables:[]}}interpret(){const e=[];return this.tableGroup.token=_(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}=Te(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]=I.partition(e.body,i=>i instanceof v);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:M(n.body instanceof re?n.body.body[0].callee:n.body.callee).map(ie).unwrap(),token:_(n)};break}return[]})}interpretFields(e){const n=[];return this.tableGroup.tables=e.map(s=>{const i=z(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:f}=this.env.tableGroups.get(r),p=c?`${c}.${f}`:f;n.push(new l(o.TABLE_REAPPEAR_IN_TABLEGROUP,`Table "${i.join(".")}" already appears in group "${p}"`,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?De((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:M(s==null?void 0:s.value).map(ie).unwrap(),token:_(s)},[]}}class qt{constructor(e,n){this.declarationNode=e,this.env=n,this.enum={values:[]}}interpret(){return this.enum.token=_(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}=Te(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=_(s),i.name=W(s.callee).unwrap();const r=(c=F(s.args[0]).getValue().note)==null?void 0:c.at(0);return i.note=r&&{value:M(r.value).map(ie).unwrap(),token:_(r)},this.enum.values.push(i),[]})}}class Yt{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=_(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}=Te(e);return this.tablePartial.name=n,[]}interpretSettingList(e){var i,a,r;const n=F(e).getValue();this.tablePartial.headerColor=(i=n.headercolor)!=null&&i.length?De((r=(a=n.headercolor)==null?void 0:a.at(0))==null?void 0:r.value):void 0;const[s]=n.note||[];return this.tablePartial.note=s&&{value:M(s==null?void 0:s.value).map(ie).unwrap(),token:_(s)},[]}interpretBody(e){const[n,s]=I.partition(e.body,i=>i instanceof v);return[...this.interpretFields(n),...this.interpretSubElements(s)]}interpretSubElements(e){return e.flatMap(n=>{var s;switch((s=n.type)==null?void 0:s.value.toLowerCase()){case"note":return this.tablePartial.note={value:M(n.body instanceof re?n.body.body[0].callee:n.body.callee).map(ie).unwrap(),token:_(n)},[];case"indexes":return this.interpretIndexes(n)}return[]})}interpretFields(e){return e.flatMap(n=>this.interpretColumn(n))}interpretColumn(e){var r,c,f,p,d,u,E,b,g;const n=[],s={};s.name=$(e.callee).unwrap();const i=us(e.args[0]);s.type=i.getValue(),n.push(...i.getErrors()),s.token=_(e),s.inline_refs=[];const a=e.args.slice(1);if(I.last(a)instanceof R){const A=F(a.pop()).getValue();s.pk=!!((r=A.pk)!=null&&r.length)||!!((c=A["primary key"])!=null&&c.length),s.increment=!!((f=A.increment)!=null&&f.length),s.unique=!!((p=A.unique)!=null&&p.length),s.not_null=(d=A["not null"])!=null&&d.length?!0:(u=A.null)!=null&&u.length?!1:void 0,s.dbdefault=hs((b=(E=A.default)==null?void 0:E.at(0))==null?void 0:b.value);const k=(g=A.note)==null?void 0:g.at(0);s.note=k&&{value:M(k.value).map(ie).unwrap(),token:_(k)};const be=A.ref||[];s.inline_refs=be.flatMap(S=>{const[Re]=Ce(S.value.expression);if(ot(Re,e.symbol))return n.push(new l(o.SAME_ENDPOINT,"Two endpoints are the same",S)),[];const Ee=S.value.op,V=z(S.value.expression).unwrap();let te;if(V.length===2){const[Ne,Q]=V;te={schemaName:null,tableName:Ne,fieldNames:[Q],relation:Ee.value,token:_(S)}}else if(V.length===3){const[Ne,Q,me]=V;te={schemaName:Ne,tableName:Q,fieldNames:[me],relation:Ee.value,token:_(S)}}else{n.push(new l(o.UNSUPPORTED,"Unsupported",S));const Ne=V.pop(),Q=V.pop();te={schemaName:V.join("."),tableName:Q,fieldNames:[Ne],relation:Ee.value,token:_(S)}}return te})}return s.pk||(s.pk=a.some(A=>W(A).unwrap().toLowerCase()==="pk")),s.unique||(s.unique=a.some(A=>W(A).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,f,p,d,u,E;const s={columns:[]},i=n;s.token=_(i);const a=[i.callee,...i.args];if(I.last(a)instanceof R){const b=F(a.pop()).getValue();s.pk=!!((r=b.pk)!=null&&r.length),s.unique=!!((c=b.unique)!=null&&c.length),s.name=M((p=(f=b.name)==null?void 0:f.at(0))==null?void 0:p.value).unwrap_or(void 0);const g=(d=b.note)==null?void 0:d.at(0);s.note=g&&{value:M(g.value).unwrap(),token:_(g)},s.type=W((E=(u=b.type)==null?void 0:u.at(0))==null?void 0:E.value).unwrap_or(void 0)}return a.flatMap(b=>{if(!(b instanceof q))return b;const g=[];for(;b instanceof q;)g.push(b.argumentList),b=b.callee;return g.push(b),g}).forEach(b=>{const{functional:g,nonFunctional:A}=Ge(b).unwrap();s.columns.push(...g.map(k=>({value:k.value.value,type:"expression",token:_(k)})),...A.map(k=>({value:$(k).unwrap(),type:"column",token:_(k)})))}),s})),[]}}function us(t){let e=null;t instanceof q&&(e=t.argumentList.elementList.map(a=>ee(a)?a.expression.literal.value:C(a)?M(a).unwrap():W(a).unwrap()).join(","),t=t.callee);let n="";for(;t instanceof ue;)n=`[${t.indexer.elementList.map(a=>a.name.expression.literal.value).join(",")}]${n}`,t=t.array;const{name:s,schemaName:i}=Te(t);return i.length>1?new Y({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 Y({schemaName:i.length===0?null:i[0],type_name:`${s}${n}${e?`(${e})`:""}`,args:e})}function hs(t){var e,n,s;if(t){if(C(t))return{value:M(t).unwrap(),type:"string"};if(ee(t))return{type:"number",value:Number.parseFloat(t.expression.literal.value)};if(he(t))return{value:t.expression.variable.value.toLowerCase(),type:"boolean"};if(t instanceof K&&rt.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 ce)return{value:(s=t.value)==null?void 0:s.value,type:"expression"};throw new Error("Unreachable")}}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=_(this.declarationNode),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(e){if(!e)return this.project.name=null,[];const{name:n}=Te(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 $t(s,this.env).interpret();return this.project.tables.push(this.env.tables.get(s)),a}case"ref":{const a=new jt(s,this.env).interpret();return this.project.refs.push(this.env.ref.get(s)),a}case"tablegroup":{const a=new Wt(s,this.env).interpret();return this.project.tableGroups.push(this.env.tableGroups.get(s)),a}case"enum":{const a=new qt(s,this.env).interpret();return this.project.enums.push(this.env.enums.get(s)),a}case"note":return this.project.note={value:M(s.body instanceof re?s.body.body[0].callee:s.body.callee).map(ie).unwrap(),token:_(s)},[];case"tablepartial":{const a=new Yt(s,this.env).interpret();return this.project.tablePartials.push(this.env.tablePartials.get(s)),a}default:return this.project[s.type.value.toLowerCase()]=M(s.body.callee).unwrap(),[]}})}}class ps{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(xe(n).unwrap_or(void 0)){case L.Table:return new $t(n,this.env).interpret();case L.Note:return new cs(n,this.env).interpret();case L.Ref:return new jt(n,this.env).interpret();case L.TableGroup:return new Wt(n,this.env).interpret();case L.TablePartial:return new Yt(n,this.env).interpret();case L.Enum:return new qt(n,this.env).interpret();case L.Project:return new fs(n,this.env).interpret();default:return[]}});return new Y(ds(this.env),e)}}function ds(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())}}var w=(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))(w||{}),P=(t=>(t[t.None=0]="None",t[t.KeepWhitespace=1]="KeepWhitespace",t[t.InsertAsSnippet=4]="InsertAsSnippet",t))(P||{});function Pe(t){switch(t){case m.Schema:return w.Module;case m.Table:case m.TablePartial:return w.Class;case m.Column:case m.TableGroupField:return w.Field;case m.Enum:return w.Enum;case m.EnumField:return w.EnumMember;case m.TableGroup:return w.Struct;default:return w.Text}}function Xe(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 B(){return{suggestions:[]}}function $e(t){return{...t,suggestions:t.suggestions.map(e=>({...e,insertText:` ${e.insertText}`}))}}function He(t){return{...t,suggestions:t.suggestions.map(e=>({...e,insertText:e.insertText.split("").every(qe)?e.insertText:`"${e.insertText}"`}))}}function lt(t,e){return t.getOffsetAt(e)}class zt{constructor(e,n=[]){this.compiler=e,this.triggerCharacters=n}provideCompletionItems(e,n){var d,u;const s=lt(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=>tn(E)&&ke(s,E)))return B();if(r===void 0)return vt();if([h.STRING_LITERAL,h.QUOTED_STRING].includes(a.kind)&&ke(s,a))return B();const f=this.compiler.container.element(s);if(this.compiler.container.scopeKind(s)===U.TOPLEVEL||f instanceof y&&f.type&&f.type.start<=s&&f.type.end>=s)return vt();const p=[...this.compiler.container.stack(s)].reverse();for(const E of p)if(E instanceof K)switch((d=E.op)==null?void 0:d.value){case">":case"<":case"<>":case"-":return Lt(this.compiler,s,E)}else if(E instanceof le)switch((u=E.op)==null?void 0:u.value){case">":case"<":case"<>":case"-":return Lt(this.compiler,s,E);case".":return Qt(this.compiler,s,E)}else{if(E instanceof se)return _t(this.compiler,s,E);if(E instanceof R)return _t(this.compiler,s,E);if(E instanceof fe)return Ns(this.compiler,s);if(E instanceof Le)return Es(this.compiler,s);if(E instanceof v)return gt(this.compiler,s,E);if(E instanceof y&&(E.bodyColon&&s>=E.bodyColon.end||E.body&&ke(s,E.body)))return gt(this.compiler,s,void 0)}return B()}}function Es(t,e,n){const s=t.container.element(e);return Oe(t,e,s,[m.TablePartial])}function Lt(t,e,n){const s=t.container.scopeKind(e);if([U.REF,U.TABLE].includes(s)){const i=Oe(t,e,t.container.element(e),[m.Table,m.Schema,m.Column]);return Xe(n.op,e)?$e(i):i}return B()}function Oe(t,e,n,s){var r;if(n===void 0)return B();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:f})=>s.includes(f)).map(({name:f,kind:p})=>({label:f,insertText:f,insertTextRules:P.KeepWhitespace,kind:Pe(p),sortText:Pe(p).toString().padStart(2,"0"),range:void 0})))}i=i instanceof y?i.parent:void 0}return He(a)}function Ns(t,e){var s;switch(t.container.scopeKind(e)){case U.INDEXES:return Jt(t,e);case U.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 Qt(t,e,a)}}return Ht(t,e)}return B()}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=At(t,e);return(s==null?void 0:s.kind)===h.COMMA&&Xe(s,e)?$e(i):i}if(n.name&&n.name.start<=e&&n.name.end>=e)return At(t,e);if(n.name instanceof ne){const i=ms(t,e,ge(n.name).unwrap_or(""));return(s==null?void 0:s.kind)===h.COLON&&Xe(s,e)?$e(i):i}return B()}function At(t,e){const n=t.container.element(e),s=t.container.scopeKind(e);if(n instanceof Z)return B();if(n.body&&!ke(e,n.body))switch(s){case U.TABLE:return{suggestions:["headercolor","note"].map(i=>({label:i,insertText:`${i}: `,kind:w.Field,insertTextRules:P.KeepWhitespace,range:void 0}))};case U.TABLEGROUP:return{suggestions:["color","note"].map(i=>({label:i,insertText:`${i}: `,kind:w.Field,insertTextRules:P.KeepWhitespace,range:void 0}))};default:return B()}switch(s){case U.TABLE:return{suggestions:[...["primary key","null","not null","increment","pk","unique"].map(i=>({label:i,insertText:i,kind:w.Property,insertTextRules:P.KeepWhitespace,range:void 0})),...["ref","default"].map(i=>({label:i,insertText:`${i}: `,kind:w.Property,insertTextRules:P.KeepWhitespace,range:void 0})),{label:"note",insertText:"note: ",kind:w.Property,insertTextRules:P.KeepWhitespace,range:void 0}]};case U.ENUM:return{suggestions:[{label:"note",insertText:"note: ",kind:w.Property,insertTextRules:P.KeepWhitespace,range:void 0}]};case U.INDEXES:return{suggestions:[...["unique","pk"].map(i=>({label:i,insertText:i,insertTextRules:P.KeepWhitespace,kind:w.Property,range:void 0})),...["note","name","type"].map(i=>({label:i,insertText:`${i}: `,kind:w.Property,insertTextRules:P.KeepWhitespace,range:void 0}))]};case U.REF:return{suggestions:["update","delete"].map(i=>({label:i,insertText:`${i}: `,kind:w.Property,insertTextRules:P.KeepWhitespace,range:void 0}))}}return B()}function ms(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:w.Value,insertTextRules:P.KeepWhitespace,range:void 0}))};case"type":return{suggestions:["btree","hash"].map(s=>({label:s,insertText:`${s}`,kind:w.Value,insertTextRules:P.KeepWhitespace,range:void 0}))}}return B()}function Qt(t,e,n){const s=_e(n).unwrap_or([]);if(s.pop(),s.some(a=>!j(a)))return B();const i=s.map(a=>W(a).unwrap());return He({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:Pe(a),range:void 0}))})}function gt(t,e,n){var i;switch(t.container.scopeKind(e)){case U.TABLE:return wt(t,e,n);case U.TABLEPARTIAL:return wt(t,e,n);case U.PROJECT:return bs(t,e,n);case U.INDEXES:return Ls(t,e);case U.ENUM:return Ts(t,e,n);case U.REF:{const a=Ht(t,e);return((i=t.container.token(e).token)==null?void 0:i.kind)===h.COLON&&Xe(t.container.token(e).token,e)?$e(a):a}case U.TABLEGROUP:return Is(t);default:return B()}}function vt(){return{suggestions:["Table","TableGroup","Enum","Project","Ref","TablePartial"].map(t=>({label:t,insertText:t,insertTextRules:P.KeepWhitespace,kind:w.Keyword,range:void 0}))}}function Ts(t,e,n){return n!=null&&n.callee&&ct(e,n)===1?Oe(t,e,t.container.element(e),[m.Schema,m.Table,m.Column]):B()}function wt(t,e,n){if(!(n!=null&&n.callee))return{suggestions:["Note","indexes"].map(i=>({label:i,insertText:i,insertTextRules:P.KeepWhitespace,kind:w.Keyword,range:void 0}))};const s=ct(e,n);return s===0?{suggestions:["Note","indexes"].map(i=>({label:i,insertText:i,insertTextRules:P.KeepWhitespace,kind:w.Keyword,range:void 0}))}:s===1?_s(t,e):B()}function bs(t,e,n){return n!=null&&n.callee?ct(e,n)===0?{suggestions:["Table","TableGroup","Enum","Note","Ref"].map(i=>({label:i,insertText:i,insertTextRules:P.KeepWhitespace,kind:w.Keyword,range:void 0}))}:B():{suggestions:["Table","TableGroup","Enum","Note","Ref"].map(i=>({label:i,insertText:i,insertTextRules:P.KeepWhitespace,kind:w.Keyword,range:void 0}))}}function Ht(t,e){return Oe(t,e,t.container.element(e),[m.Schema,m.Table,m.Column])}function Is(t){return{suggestions:[...He({suggestions:[...t.parse.publicSymbolTable().entries()].flatMap(([e])=>{const n=oe(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:P.KeepWhitespace,kind:Pe(s),range:void 0}})}).suggestions,...["Note"].map(e=>({label:e,insertText:e,insertTextRules:P.KeepWhitespace,kind:w.Keyword,range:void 0}))]}}function Ls(t,e){return Jt(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:P.KeepWhitespace,kind:w.TypeParameter,sortText:w.TypeParameter.toString().padStart(2,"0"),range:void 0})),...Oe(t,e,t.container.element(e),[m.Enum,m.Schema]).suggestions]}}function Jt(t,e){const n=t.container.element(e),s=n==null?void 0:n.parent;if(!((s==null?void 0:s.symbol)instanceof Ot))return B();const{symbolTable:i}=s.symbol;return He({suggestions:[...i.entries()].flatMap(([a])=>{const r=oe(a).unwrap_or(void 0);if(r===void 0)return[];const{name:c}=r;return{label:c,insertText:c,insertTextRules:P.KeepWhitespace,kind:Pe(m.Column),range:void 0}})})}function ct(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;const{uri:s}=e,i=lt(e,n),a=[...this.compiler.container.stack(i)];for(;a.length!==0;){const c=a.pop();if((r=c==null?void 0:c.referee)!=null&&r.declaration&&[Ie.PRIMARY_EXPRESSION,Ie.VARIABLE,Ie.PARTIAL_INJECTION].includes(c==null?void 0:c.kind)){const{startPos:f,endPos:p}=c.referee.declaration;return[{range:{startColumn:f.column+1,startLineNumber:f.line+1,endColumn:p.column+1,endLineNumber:p.line+1},uri:s}]}}return[]}}class Kt{constructor(e){this.compiler=e}provideReferences(e,n){const{uri:s}=e,i=lt(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:f,endPos:p})=>({range:{startColumn:f.column+1,startLineNumber:f.line+1,endColumn:p.column+1,endLineNumber:p.line+1},uri:s}))}}return[]}}const As=Object.freeze(Object.defineProperty({__proto__:null,CompletionItemInsertTextRule:P,CompletionItemKind:w,DBMLCompletionItemProvider:zt,DBMLDefinitionProvider:Zt,DBMLReferencesProvider:Kt},Symbol.toStringTag,{value:"Module"}));var U=(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))(U||{});class gs{constructor(){this.source="",this.cache=new Array(16).fill(null),this.nodeIdGenerator=new nn,this.symbolIdGenerator=new fn,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 gn(this.source).lex().chain(n=>new yn(n,this.nodeIdGenerator).parse()).chain(({ast:n,tokens:s})=>new rs(n,this.symbolIdGenerator).analyze().map(()=>({ast:n,tokens:s})));return e.getErrors().length>0?e:e.chain(({ast:n,tokens:s})=>new ps(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:I.findLastIndex(n,p=>!p.isInvalid,s);if(a===-1)return[this.parse.ast()];const r=n[a].start;let c=this.parse.ast();const f=[c];for(;;){const d=An(c).find(u=>ke(r,u));if(d===void 0||d instanceof J)break;f.push(d),c=d}if((i==null?void 0:i.kind)===h.COLON)return f;for(;f.length>0;){let p=!1;const d=I.last(f);if(d instanceof v){const u=this.parse.source();for(let E=d.end;E<e;E+=1)u[E]===`
|
|
12
|
+
`&&(f.pop(),p=!0)}else d instanceof K||d instanceof le?this.container.token(e).token!==d.op&&(f.pop(),p=!0):d instanceof R?d.listCloseBracket&&d.end<=e&&(f.pop(),p=!0):d instanceof fe?d.tupleCloseParen&&d.end<=e&&(f.pop(),p=!0):d instanceof re?d.blockCloseBrace&&d.end<=e&&(f.pop(),p=!0):d instanceof ne||d.end<e&&(f.pop(),p=!0);if(p){const u=I.last(f);u instanceof y&&u.end<=e&&f.pop()}if(!p)break}return f}),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],f=[];for(const p of e)f=c.flatMap(d=>un(p).flatMap(u=>{const E=d.get(u),b=oe(u).unwrap_or(void 0);return!E||!b?[]:{...b,symbol:E}})),c=f.flatMap(d=>d.symbol.symbolTable?d.symbol.symbolTable:[]);s.push(...f)}return s},({nameStack:e,owner:n})=>`${e.join(".")}@${n.id}`),members:this.createQuery(9,e=>e.symbolTable?[...e.symbolTable.entries()].map(([n,s])=>({...oe(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 Zt(this),referenceProvider:new Kt(this),autocompletionProvider:new zt(this)}}}exports.Compiler=gs;exports.serialize=sn;exports.services=As;
|