@dbml/parse 3.1.3 → 3.1.4-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/dbml-parse.js +8 -8
- package/dist/dbml-parse.mjs +1353 -1307
- package/package.json +2 -2
package/dist/dbml-parse.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I=require("lodash");var c=(t=>(t.SPACE="<space>",t.TAB="<tab>",t.NEWLINE="<newline>",t.COMMA="<comma>",t.LPAREN="<lparen>",t.RPAREN="<rparen>",t.LBRACE="<lbrace>",t.RBRACE="<rbrace>",t.LBRACKET="<lbracket>",t.RBRACKET="<rbracket>",t.LANGLE="<langle>",t.RANGLE="<rangle>",t.OP="<op>",t.EOF="<eof>",t.NUMERIC_LITERAL="<number>",t.STRING_LITERAL="<string>",t.COLOR_LITERAL="<color>",t.FUNCTION_EXPRESSION="<function-expression>",t.QUOTED_STRING="<variable>",t.IDENTIFIER="<identifier>",t.SEMICOLON="<semicolon>",t.COLON="<colon>",t.SINGLE_LINE_COMMENT="<single-line-comment>",t.MULTILINE_COMMENT="<multiline-comment>",t))(c||{});function Xt(t){switch(t.kind){case"<newline>":case"<space>":case"<tab>":case"<single-line-comment>":case"<multiline-comment>":return!0;default:return!1}}function rt(t){if(!t)return!1;switch(t){case"+":case"-":case"*":case"/":case"%":case"<":case">":case"=":case"!":case".":case"&":case"|":return!0;default:return!1}}function at(t){return t!==void 0&&t.kind==="<op>"}class B{constructor(e,s,n,i,r){this.kind=e,this.startPos=s,this.endPos=n,this.value=i,this.leadingTrivia=[],this.trailingTrivia=[],this.leadingInvalid=[],this.trailingInvalid=[],this.isInvalid=r,this.start=s.offset,this.end=n.offset}static create(e,s,n,i,r){return new B(e,s,n,i,r)}}function bt(t){return t.trailingTrivia.find(({kind:e})=>e===c.NEWLINE)!==void 0}function ot(t,e){return e.leadingTrivia.find(({kind:n})=>n===c.NEWLINE)!==void 0||bt(t)}function Ve(t){return t.trailingTrivia.find(({kind:e})=>e===c.SPACE)!==void 0}function It(t){return t.trailingTrivia.length===0?t.end:It(I.last(t.trailingTrivia))}function Lt(t){return t.leadingTrivia.length===0?t.start:Lt(t.leadingTrivia[0])}function $t(t){return[c.SINGLE_LINE_COMMENT,c.MULTILINE_COMMENT].includes(t.kind)}class Wt{constructor(){this.id=0}reset(){this.id=0}nextId(){return this.id++}}class y{constructor(e,s,n){this.id=e,this.kind=s;const i=n.find(a=>a!==void 0&&!Number.isNaN(a.start));i?(this.startPos=i.startPos,this.fullStart=i instanceof B?Lt(i):i.fullStart):(this.startPos={offset:NaN,column:NaN,line:NaN},this.fullStart=NaN);const r=[...n].reverse().find(a=>a!==void 0&&!Number.isNaN(a.end));r?(this.endPos=r.endPos,this.fullEnd=r instanceof B?It(r):r.fullEnd):(this.endPos={offset:NaN,column:NaN,line:NaN},this.fullEnd=NaN),this.start=this.startPos.offset,this.end=this.endPos.offset}}var ue=(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))(ue||{});class C extends y{constructor({body:e=[],eof:s},n){super(n,"<program>",[...e,s]),this.body=e,this.eof=s}}class _ extends y{constructor({type:e,name:s,as:n,alias:i,attributeList:r,bodyColon:a,body:l},p){if(super(p,"<element-declaration>",[e,s,n,i,r,a,l]),l&&a&&!(l instanceof x||l instanceof _))throw new Error("If an element has a simple body, it must be a function application node");this.type=e,this.name=s,this.as=n,this.alias=i,this.attributeList=r,this.bodyColon=a,this.body=l}}class te extends y{constructor({identifiers:e=[]},s){super(s,"<identifer-stream>",e||[]),this.identifiers=e}}class ne extends y{constructor({name:e,colon:s,value:n},i){super(i,"<attribute>",[e,s,n]),this.name=e,this.value=n,this.colon=s}}class q extends y{constructor({op:e,expression:s},n){super(n,"<prefix-expression>",[e,s]),this.op=e,this.expression=s}}class Q extends y{constructor({op:e,leftExpression:s,rightExpression:n},i){super(i,"<infix-expression>",[s,e,n]),this.op=e,this.leftExpression=s,this.rightExpression=n}}class De extends y{constructor({op:e,expression:s},n){super(n,"<postfix-expression>",[s,e]),this.op=e,this.expression=s}}class K extends y{constructor({value:e},s){super(s,"<function-expression>",[e]),this.value=e}}class x extends y{constructor({callee:e,args:s=[]},n){super(n,"<function-application>",[e,...s]),this.callee=e,this.args=s}}class ee extends y{constructor({blockOpenBrace:e,body:s=[],blockCloseBrace:n},i){super(i,"<block-expression>",[e,...s,n]),this.blockOpenBrace=e,this.body=s,this.blockCloseBrace=n}}class U extends y{constructor({listOpenBracket:e,elementList:s=[],commaList:n=[],listCloseBracket:i},r){super(r,"<list-expression>",[e,...gt(s,n),i]),this.listOpenBracket=e,this.elementList=s,this.commaList=n,this.listCloseBracket=i}}class J extends y{constructor({tupleOpenParen:e,elementList:s=[],commaList:n=[],tupleCloseParen:i},r){super(r,"<tuple-expression>",[e,...gt(s,n),i]),this.tupleOpenParen=e,this.elementList=s,this.commaList=n,this.tupleCloseParen=i}}class Xe extends J{constructor({groupOpenParen:e,expression:s,groupCloseParen:n},i){super({tupleOpenParen:e,elementList:s&&[s],commaList:[],tupleCloseParen:n},i),this.kind="<group-expression>"}}class H extends y{constructor({callee:e,argumentList:s},n){super(n,"<call-expression>",[e,s]),this.callee=e,this.argumentList=s}}class pe extends y{constructor({literal:e},s){super(s,"<literal>",[e]),this.literal=e}}class X extends y{constructor({variable:e},s){super(s,"<variable>",[e]),this.variable=e}}class R extends y{constructor({expression:e},s){super(s,"<primary-expression>",[e]),this.expression=e}}class we extends y{constructor({pre:e},s){const n=B.create(c.SPACE,e.endPos,e.endPos," ",!1);super(s,"<dummy>",[n])}}class he extends y{constructor({expression:e,indexer:s},n){super(n,"<array>",[e,s]),this.array=e,this.indexer=s}}function gt(t,e){if(!t||t.length===0)return e||[];if(!e||e.length===0)return t||[];const[s]=t,[n]=e;return(s.start<n.start?I.flatten(I.zip(t,e)):I.flatten(I.zip(e,t))).filter(i=>i!==null)}function jt(t,e=!1){return JSON.stringify(t,function(s,n){var i;return!(this instanceof C)&&s==="symbol"?n==null?void 0:n.id:s==="symbol"?{symbolTable:n==null?void 0:n.symbolTable,id:n==null?void 0:n.id,references:n==null?void 0:n.references.map(r=>r.id),declaration:(i=n==null?void 0:n.declaration)==null?void 0:i.id}:s==="referee"||s==="parent"||s==="declaration"?n==null?void 0:n.id:s==="symbolTable"?Object.fromEntries(n.table):n},e?2:0)}class S{constructor(e){this.value=e}unwrap(){return this.value}unwrap_or(e){return this.value}and_then(e){return e(this.value)}map(e){return new S(e(this.value))}isOk(){return!0}}class A{unwrap(){throw new Error("Trying to unwrap a None value")}unwrap_or(e){return e}and_then(e){return new A}map(e){return new A}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))(m||{});function $e(t){return`Schema:${t}`}function xe(t){return`Table:${t}`}function We(t){return`Column:${t}`}function je(t){return`Enum:${t}`}function Ye(t){return`Enum field:${t}`}function ze(t){return`TableGroup:${t}`}function qe(t){return`TableGroup field:${t}`}function Fe(t,e){switch(e){case"Column":return We(t);case"Enum":return je(t);case"Enum field":return Ye(t);case"Schema":return $e(t);case"Table":return xe(t);case"TableGroup":return ze(t);case"TableGroup field":return qe(t);default:throw new Error("Unreachable")}}function se(t){const[e,s]=t.split(":");return Object.values(m).includes(e)?new S({name:s,kind:e}):new A}function Yt(t){const e=se(t).unwrap_or(void 0);if(!e)return!1;const{kind:s,name:n}=e;return s==="Schema"&&n==="public"}function zt(t){return[$e,xe,je,ze,We,Ye,qe].map(e=>e(t))}function Qe(t){const[e]=t;return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"}function ke(t){const[e]=t;return e>="0"&&e<="9"}function qt(t){const[e]=t;return ke(e)||Qe(e)&&e.toLowerCase()>="a"&&e.toLowerCase()<="f"}function be(t){return Qe(t)||ke(t)}function lt(t,e){const s=[],n=Math.min(t.length,e.length);for(let i=0;i<n;i+=1)s.push(t[i],e[i]);return s.push(...t.slice(n),...e.slice(n)),s}function Ie(t,e){return t>=e.start&&t<e.end}class Qt{constructor(){this.id=0}reset(){this.id=0}nextId(){return this.id++}}class _t{constructor({symbolTable:e},s){this.references=[],this.id=s,this.symbolTable=e}}class Ht{constructor({symbolTable:e,declaration:s},n){this.references=[],this.id=n,this.symbolTable=e,this.declaration=s}}class Jt{constructor({declaration:e},s){this.references=[],this.id=s,this.declaration=e}}class At{constructor({symbolTable:e,declaration:s},n){this.references=[],this.id=n,this.symbolTable=e,this.declaration=s}}class Zt{constructor({declaration:e},s){this.references=[],this.id=s,this.declaration=e}}class Kt{constructor({symbolTable:e,declaration:s},n){this.references=[],this.id=n,this.symbolTable=e,this.declaration=s}}class en{constructor({declaration:e},s){this.references=[],this.id=s,this.declaration=e}}var o=(t=>(t[t.UNKNOWN_SYMBOL=1e3]="UNKNOWN_SYMBOL",t[t.UNEXPECTED_SYMBOL=1001]="UNEXPECTED_SYMBOL",t[t.UNEXPECTED_EOF=1002]="UNEXPECTED_EOF",t[t.UNEXPECTED_NEWLINE=1003]="UNEXPECTED_NEWLINE",t[t.UNKNOWN_TOKEN=1004]="UNKNOWN_TOKEN",t[t.UNEXPECTED_TOKEN=1005]="UNEXPECTED_TOKEN",t[t.UNEXPECTED_ELEMENT_DECLARATION=1006]="UNEXPECTED_ELEMENT_DECLARATION",t[t.MISSING_SPACES=1007]="MISSING_SPACES",t[t.UNKNOWN_PREFIX_OP=1008]="UNKNOWN_PREFIX_OP",t[t.INVALID_OPERAND=1009]="INVALID_OPERAND",t[t.EMPTY_ATTRIBUTE_NAME=1010]="EMPTY_ATTRIBUTE_NAME",t[t.INVALID_NAME=3e3]="INVALID_NAME",t[t.UNEXPECTED_NAME=3001]="UNEXPECTED_NAME",t[t.NAME_NOT_FOUND=3002]="NAME_NOT_FOUND",t[t.DUPLICATE_NAME=3003]="DUPLICATE_NAME",t[t.INVALID_ALIAS=3004]="INVALID_ALIAS",t[t.UNEXPECTED_ALIAS=3005]="UNEXPECTED_ALIAS",t[t.UNEXPECTED_SETTINGS=3006]="UNEXPECTED_SETTINGS",t[t.INVALID_SETTINGS=3007]="INVALID_SETTINGS",t[t.UNEXPECTED_SIMPLE_BODY=3008]="UNEXPECTED_SIMPLE_BODY",t[t.UNEXPECTED_COMPLEX_BODY=3009]="UNEXPECTED_COMPLEX_BODY",t[t.INVALID_TABLE_CONTEXT=3010]="INVALID_TABLE_CONTEXT",t[t.INVALID_TABLE_SETTING=3011]="INVALID_TABLE_SETTING",t[t.DUPLICATE_TABLE_SETTING=3012]="DUPLICATE_TABLE_SETTING",t[t.INVALID_TABLEGROUP_CONTEXT=3013]="INVALID_TABLEGROUP_CONTEXT",t[t.INVALID_TABLEGROUP_ELEMENT_NAME=3014]="INVALID_TABLEGROUP_ELEMENT_NAME",t[t.DUPLICATE_TABLEGROUP_ELEMENT_NAME=3015]="DUPLICATE_TABLEGROUP_ELEMENT_NAME",t[t.DUPLICATE_TABLEGROUP_FIELD_NAME=3016]="DUPLICATE_TABLEGROUP_FIELD_NAME",t[t.INVALID_TABLEGROUP_FIELD=3017]="INVALID_TABLEGROUP_FIELD",t[t.EMPTY_TABLE=3018]="EMPTY_TABLE",t[t.INVALID_COLUMN=3019]="INVALID_COLUMN",t[t.INVALID_COLUMN_NAME=3020]="INVALID_COLUMN_NAME",t[t.UNKNOWN_COLUMN_SETTING=3021]="UNKNOWN_COLUMN_SETTING",t[t.INVALID_COLUMN_TYPE=3022]="INVALID_COLUMN_TYPE",t[t.DUPLICATE_COLUMN_NAME=3023]="DUPLICATE_COLUMN_NAME",t[t.DUPLICATE_COLUMN_SETTING=3024]="DUPLICATE_COLUMN_SETTING",t[t.INVALID_COLUMN_SETTING_VALUE=3025]="INVALID_COLUMN_SETTING_VALUE",t[t.INVALID_ENUM_CONTEXT=3026]="INVALID_ENUM_CONTEXT",t[t.INVALID_ENUM_ELEMENT_NAME=3027]="INVALID_ENUM_ELEMENT_NAME",t[t.INVALID_ENUM_ELEMENT=3028]="INVALID_ENUM_ELEMENT",t[t.DUPLICATE_ENUM_ELEMENT_NAME=3029]="DUPLICATE_ENUM_ELEMENT_NAME",t[t.UNKNOWN_ENUM_ELEMENT_SETTING=3030]="UNKNOWN_ENUM_ELEMENT_SETTING",t[t.DUPLICATE_ENUM_ELEMENT_SETTING=3031]="DUPLICATE_ENUM_ELEMENT_SETTING",t[t.INVALID_ENUM_ELEMENT_SETTING=3032]="INVALID_ENUM_ELEMENT_SETTING",t[t.EMPTY_ENUM=3033]="EMPTY_ENUM",t[t.INVALID_REF_CONTEXT=3034]="INVALID_REF_CONTEXT",t[t.UNKNOWN_REF_SETTING=3035]="UNKNOWN_REF_SETTING",t[t.DUPLICATE_REF_SETTING=3036]="DUPLICATE_REF_SETTING",t[t.INVALID_REF_SETTING_VALUE=3037]="INVALID_REF_SETTING_VALUE",t[t.INVALID_REF_RELATIONSHIP=3038]="INVALID_REF_RELATIONSHIP",t[t.INVALID_REF_FIELD=3039]="INVALID_REF_FIELD",t[t.EMPTY_REF=3040]="EMPTY_REF",t[t.REF_REDEFINED=3041]="REF_REDEFINED",t[t.INVALID_NOTE_CONTEXT=3042]="INVALID_NOTE_CONTEXT",t[t.INVALID_NOTE=3043]="INVALID_NOTE",t[t.NOTE_REDEFINED=3044]="NOTE_REDEFINED",t[t.NOTE_CONTENT_REDEFINED=3045]="NOTE_CONTENT_REDEFINED",t[t.EMPTY_NOTE=3046]="EMPTY_NOTE",t[t.INVALID_INDEXES_CONTEXT=3047]="INVALID_INDEXES_CONTEXT",t[t.INVALID_INDEXES_FIELD=3048]="INVALID_INDEXES_FIELD",t[t.INVALID_INDEX=3049]="INVALID_INDEX",t[t.UNKNOWN_INDEX_SETTING=3050]="UNKNOWN_INDEX_SETTING",t[t.DUPLICATE_INDEX_SETTING=3051]="DUPLICATE_INDEX_SETTING",t[t.UNEXPECTED_INDEX_SETTING_VALUE=3052]="UNEXPECTED_INDEX_SETTING_VALUE",t[t.INVALID_INDEX_SETTING_VALUE=3053]="INVALID_INDEX_SETTING_VALUE",t[t.INVALID_PROJECT_CONTEXT=3054]="INVALID_PROJECT_CONTEXT",t[t.PROJECT_REDEFINED=3055]="PROJECT_REDEFINED",t[t.INVALID_PROJECT_FIELD=3056]="INVALID_PROJECT_FIELD",t[t.INVALID_CUSTOM_CONTEXT=3057]="INVALID_CUSTOM_CONTEXT",t[t.INVALID_CUSTOM_ELEMENT_VALUE=3058]="INVALID_CUSTOM_ELEMENT_VALUE",t[t.INVALID_ELEMENT_IN_SIMPLE_BODY=3059]="INVALID_ELEMENT_IN_SIMPLE_BODY",t[t.BINDING_ERROR=4e3]="BINDING_ERROR",t[t.UNSUPPORTED=5e3]="UNSUPPORTED",t[t.CIRCULAR_REF=5001]="CIRCULAR_REF",t[t.SAME_ENDPOINT=5002]="SAME_ENDPOINT",t[t.UNEQUAL_FIELDS_BINARY_REF=5003]="UNEQUAL_FIELDS_BINARY_REF",t[t.CONFLICTING_SETTING=5004]="CONFLICTING_SETTING",t))(o||{});class u extends Error{constructor(e,s,n){super(s),this.code=e,this.diagnostic=s,this.nodeOrToken=n,this.start=n.start,this.end=n.end,this.name=this.constructor.name,Object.setPrototypeOf(this,u.prototype)}}class F{constructor(e,s){this.value=e,this.errors=s===void 0?[]:s}getValue(){return this.value}getErrors(){return this.errors}chain(e){const s=e(this.value),n=[...this.errors,...s.errors];return new F(s.value,n)}map(e){return new F(e(this.value),this.errors)}}function tn(t,e,s){if(!t||!fe(t)||e.length===0)return new A;const n=[...e],i=Be(t).unwrap(),r=n.pop();if(!(r instanceof ee))return new A;const a=I.last(n)instanceof U?n.pop():void 0;return n.length===3&&Be(n[1]).unwrap().value==="as"?new S(s.create(_,{type:i,name:n[0],as:Be(n[1]).unwrap(),alias:n[2],attributeList:a,body:r})):n.length===1?new S(s.create(_,{type:i,name:n[0],attributeList:a,body:r})):n.length===0?new S(s.create(_,{type:i,attributeList:a,body:r})):new A}function ct(t){return t.kind===c.IDENTIFIER&&t.value==="as"}function E(t){t&&(t instanceof B?nn(t):sn(t))}function nn(t){t.kind!==c.EOF&&(t.isInvalid=!0)}function sn(t){if(t instanceof _)E(t.type),E(t.name),E(t.as),E(t.alias),E(t.bodyColon),E(t.attributeList),E(t.body);else if(t instanceof te)t.identifiers.forEach(E);else if(t instanceof ne)E(t.name),E(t.colon),E(t.value);else if(t instanceof q)E(t.op),E(t.expression);else if(t instanceof Q)E(t.leftExpression),E(t.op),E(t.rightExpression);else if(t instanceof De)E(t.op),E(t.expression);else if(t instanceof ee)E(t.blockOpenBrace),t.body.forEach(E),E(t.blockCloseBrace);else if(t instanceof U)E(t.listOpenBracket),t.commaList.forEach(E),t.elementList.forEach(E),E(t.listCloseBracket);else if(t instanceof J)E(t.tupleOpenParen),t.commaList.forEach(E),t.elementList.forEach(E),E(t.tupleCloseParen);else if(t instanceof H)E(t.callee),E(t.argumentList);else if(t instanceof x)E(t.callee),t.args.forEach(E);else if(t instanceof R)E(t.expression);else if(t instanceof K)E(t.value);else if(t instanceof X)E(t.variable);else if(t instanceof pe)E(t.literal);else throw t instanceof Xe?new Error("This case is handled by the TupleExpressionNode case"):new Error("Unreachable case in markInvalidNode")}function vt(t){return!!(t!=null&&t.isInvalid)}function P(...t){return t.filter(e=>e!==void 0)}function rn(t){if(t instanceof C)return P(...t.body,t.eof);if(t instanceof _)return P(t.type,t.name,t.as,t.alias,t.attributeList,t.bodyColon,t.body);if(t instanceof ne)return P(t.name,t.colon,t.value);if(t instanceof te)return t.identifiers;if(t instanceof pe)return t.literal?[t.literal]:[];if(t instanceof X)return P(t.variable);if(t instanceof q)return P(t.op,t.expression);if(t instanceof Q)return P(t.leftExpression,t.op,t.rightExpression);if(t instanceof De)return P(t.expression,t.op);if(t instanceof K)return P(t.value);if(t instanceof x)return P(t.callee,...t.args);if(t instanceof ee)return P(t.blockOpenBrace,...t.body,t.blockCloseBrace);if(t instanceof U)return P(t.listOpenBracket,...lt(t.elementList,t.commaList),t.listCloseBracket);if(t instanceof J)return P(t.tupleOpenParen,...lt(t.elementList,t.commaList),t.tupleCloseParen);if(t instanceof H)return P(t.callee,t.argumentList);if(t instanceof R)return P(t.expression);throw t instanceof Xe?new Error("This case is already handled by TupleExpressionNode"):new Error("Unreachable - no other possible cases")}function Be(t){return M(t)?new S(t.expression.variable):new A}function $(t){var e;return t instanceof R&&(t.expression instanceof X&&t.expression.variable instanceof B&&t.expression.variable.kind===c.QUOTED_STRING||t.expression instanceof pe&&((e=t.expression.literal)==null?void 0:e.kind)===c.STRING_LITERAL)}function M(t){return t instanceof R&&t.expression instanceof X&&t.expression.variable instanceof B}function fe(t){var e;return t instanceof R&&t.expression instanceof X&&((e=t.expression.variable)==null?void 0:e.kind)===c.IDENTIFIER}function He(t){var e;return t instanceof Q&&t.leftExpression instanceof y&&t.rightExpression instanceof y&&((e=t.op)==null?void 0:e.value)==="."}function Re(t){if(t===void 0)return new A;const e=t.identifiers.map(s=>s.value).join(" ");return e===""?new A:new S(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===`
|
|
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
|
|
3
|
-
`:this.addToken(
|
|
4
|
-
`))&&!this.check(
|
|
5
|
-
`)&&!
|
|
6
|
-
`,{allowNewline:!0,allowEof:!0,raw:!0,consumeStopSequence:!1})}multilineComment(){this.consumeUntil(
|
|
7
|
-
`;case"\\":return"\\";case"r":return"\r";case"'":return"'";case'"':return'"';case"0":return"\0";case"b":return"\b";case"v":return"\v";case"f":return"\f";case"u":{let e="";for(let s=0;s<=3;s+=1){if(this.isAtEnd()||!be(this.peek()))return`\\u${e}`;e+=this.advance()}return String.fromCharCode(parseInt(e,16))}default:return`\\${this.tokens[this.current.offset-1]}`}}}var ye=(t=>(t[t.ListExpression=0]="ListExpression",t[t.GroupExpression=1]="GroupExpression",t[t.BlockExpression=2]="BlockExpression",t))(ye||{});class on{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,s){return()=>{this.push(e);try{return s()}finally{this.pop()}}}findHandlerContext(e,s){if(!(this.numberOfNestedLBraces<=0&&this.numberOfNestedLBrackets<=0&&this.numberOfNestedLParens<=0))for(let n=s;n<e.length-1;n+=1)switch(e[n].kind){case c.COMMA:if(this.isWithinGroupExpressionContext()||this.isWithinListExpressionContext())return[...this.stack].reverse().find(r=>[1,0].includes(r));break;case c.RPAREN:if(this.isWithinGroupExpressionContext())return 1;break;case c.RBRACE:if(this.isWithinBlockExpressionContext())return 2;break;case c.RBRACKET:if(this.isWithinListExpressionContext())return 0;break}}}class ln{constructor(e){this.generator=e}create(e,s){return new e(s,this.generator.nextId())}}class d{constructor(e,s,n){this.token=e,this.partialNode=s,this.handlerContext=n}}class cn{constructor(e,s){this.current=0,this.errors=[],this.contextStack=new on,this.synchronizeProgram=()=>{const n=this.peek();n.kind!==c.EOF?E(this.advance()):(E(this.peek()),this.logError(n,o.UNEXPECTED_EOF,"Unexpected EOF"))},this.synchronizeElementDeclarationName=()=>{for(;!this.isAtEnd();){const n=this.peek();if(ct(n)||this.check(c.COLON,c.LBRACE,c.LBRACKET))break;E(n),this.advance()}},this.synchronizeElementDeclarationAlias=()=>{for(;!this.isAtEnd();){const n=this.peek();if(this.check(c.COLON,c.LBRACE,c.LBRACKET))break;E(n),this.advance()}},this.blockExpression=this.contextStack.withContextDo(ye.BlockExpression,()=>{const n={body:[]},i=()=>this.nodeFactory.create(ee,n);try{this.consume("Expect an opening brace '{'",c.LBRACE),n.blockOpenBrace=this.previous()}catch(r){if(!(r instanceof d))throw r;if(n.blockOpenBrace=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}for(;!this.isAtEnd()&&!this.check(c.RBRACE);)try{n.body.push(this.canBeField()?this.fieldDeclaration():this.expression())}catch(r){if(!(r instanceof d))throw r;if(n.body.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}try{this.consume("Expect a closing brace '}'",c.RBRACE),n.blockCloseBrace=this.previous()}catch(r){if(!(r instanceof d))throw r;if(n.blockCloseBrace=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}return i()}),this.synchronizeBlock=()=>{if(!this.check(c.RBRACE))for(E(this.advance());!this.isAtEnd();){const n=this.peek();if(this.check(c.RBRACE)||ot(this.previous(),n))break;E(n),this.advance()}},this.tupleExpression=this.contextStack.withContextDo(ye.GroupExpression,()=>{const n={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(Xe,{groupOpenParen:n.tupleOpenParen,groupCloseParen:n.tupleCloseParen,expression:n.elementList[0]}),r=()=>this.nodeFactory.create(J,n);try{this.consume("Expect an opening parenthesis '('",c.LPAREN),n.tupleOpenParen=this.previous()}catch(a){if(!(a instanceof d))throw a;if(n.tupleOpenParen=a.partialNode,!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}if(!this.isAtEnd()&&!this.check(c.RPAREN))try{n.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof d))throw a;if(n.elementList.push(a.partialNode),!this.canHandle(a))throw new d(a.token,i(),a.handlerContext);this.synchronizeTuple()}for(;!this.isAtEnd()&&!this.check(c.RPAREN);)try{this.consume("Expect a comma ','",c.COMMA),n.commaList.push(this.previous()),n.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof d))throw a;if(a.partialNode instanceof y&&n.elementList.push(a.partialNode),!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}try{this.consume("Expect a closing parenthesis ')'",c.RPAREN),n.tupleCloseParen=this.previous()}catch(a){if(!(a instanceof d))throw a;if(n.tupleCloseParen=a.partialNode,!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}return n.elementList.length===1?i():r()}),this.synchronizeTuple=()=>{for(;!this.isAtEnd();){const n=this.peek();if(this.check(c.RPAREN,c.COMMA))break;E(n),this.advance()}},this.listExpression=this.contextStack.withContextDo(ye.ListExpression,()=>{const n={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(U,n);try{this.consume("Expect an opening bracket '['",c.LBRACKET),n.listOpenBracket=this.previous()}catch(r){if(!(r instanceof d))throw r;if(n.listOpenBracket=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}if(!this.isAtEnd()&&!this.check(c.RBRACKET))try{n.elementList.push(this.attribute())}catch(r){if(!(r instanceof d))throw r;if(n.elementList.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}for(;!this.isAtEnd()&&!this.check(c.RBRACKET);)try{this.consume("Expect a comma ','",c.COMMA),n.commaList.push(this.previous()),n.elementList.push(this.attribute())}catch(r){if(!(r instanceof d))throw r;if(r.partialNode instanceof y&&n.elementList.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}try{this.consume("Expect a closing bracket ']'",c.RBRACKET),n.listCloseBracket=this.previous()}catch(r){if(!(r instanceof d))throw r;if(n.listCloseBracket=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}return i()}),this.synchronizeList=()=>{for(;!this.isAtEnd();){const n=this.peek();if(this.check(c.COMMA,c.RBRACKET))break;E(n),this.advance()}},this.synchronizeAttributeName=()=>{for(;!this.isAtEnd();){const n=this.peek();if(this.check(c.COMMA,c.RBRACKET,c.COLON))break;E(n),this.advance()}},this.synchronizeAttributeValue=()=>{for(;!this.isAtEnd();){const n=this.peek();if(this.check(c.COMMA,c.RBRACKET))break;E(n),this.advance()}},this.tokens=e,this.nodeFactory=new ln(s)}isAtEnd(){return this.current>=this.tokens.length||this.tokens[this.current].kind===c.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 s=this.check(...e);return s&&this.advance(),s}check(...e){const s=this.peek();return e.includes(s.kind)}previous(){return this.tokens[this.current-1]}canHandle(e){return e.handlerContext===void 0||e.handlerContext===this.contextStack.top()}consume(e,...s){if(!this.match(...s))throw this.logError(this.peek(),o.UNEXPECTED_TOKEN,e),new d(this.peek(),void 0,this.contextStack.findHandlerContext(this.tokens,this.current))}discardUntil(e,...s){if(this.isAtEnd()||!this.check(...s)){for(E(this.peek()),this.logError(this.advance(),o.UNEXPECTED_TOKEN,e);!this.isAtEnd()&&!this.check(...s);)E(this.advance());return!this.isAtEnd()}return!0}gatherInvalid(){const e=[],s=[];let n,i=0;for(;i<this.tokens.length&&this.tokens[i].isInvalid;i+=1)s.push(this.tokens[i]);for(n=this.tokens[i],n.leadingInvalid=s,e.push(n),i+=1;i<this.tokens.length;i+=1){const r=this.tokens[i];r.isInvalid?n.trailingInvalid.push(r):(n=r,e.push(n))}this.tokens=e}parse(){const e=this.program(),s=this.advance(),n=this.nodeFactory.create(C,{body:e,eof:s});return this.gatherInvalid(),new F({ast:n,tokens:this.tokens},this.errors)}program(){const e=[];for(;!this.isAtEnd();)try{const s=this.elementDeclaration();e.push(s)}catch(s){if(!(s instanceof d))throw s;e.push(s.partialNode),this.synchronizeProgram()}return e}elementDeclaration(){const e={},s=()=>this.nodeFactory.create(_,e);try{this.consume("Expect an identifier",c.IDENTIFIER),e.type=this.previous()}catch(n){throw n instanceof d?(e.type=n.partialNode,new d(n.token,s(),n.handlerContext)):n}if(!this.check(c.COLON,c.LBRACE,c.LBRACKET))try{e.name=this.normalExpression()}catch(n){if(!(n instanceof d))throw n;if(e.name=n.partialNode,!this.canHandle(n))throw new d(n.token,s(),n.handlerContext);this.synchronizeElementDeclarationName()}if(ct(this.peek()))if(e.as=this.advance(),this.check(c.COLON,c.LBRACE,c.LBRACKET))this.logError(this.peek(),o.UNEXPECTED_TOKEN,"Expect an alias");else try{e.alias=this.normalExpression()}catch(n){if(!(n instanceof d))throw n;if(e.alias=n.partialNode,!this.canHandle(n))throw new d(n.token,s(),n.handlerContext);this.synchronizeElementDeclarationAlias()}try{e.attributeList=this.check(c.LBRACKET)?this.listExpression():void 0}catch(n){throw n instanceof d?(e.attributeList=n.partialNode,new d(n.token,s(),n.handlerContext)):n}if(!this.discardUntil("Expect an opening brace '{' or a colon ':'",c.LBRACE,c.COLON))return s();try{if(this.match(c.COLON)){e.bodyColon=this.previous();const n=this.expression();n instanceof _?(E(n),this.logError(n,o.UNEXPECTED_ELEMENT_DECLARATION,"An element's simple body must not be an element declaration")):e.body=n}else e.body=this.blockExpression()}catch(n){throw n instanceof d?(e.body=n.partialNode,new d(n.token,s(),n.handlerContext)):n}return this.nodeFactory.create(_,e)}fieldDeclaration(){const e={},s=()=>this.nodeFactory.create(_,e);try{this.consume("Expect an identifier",c.IDENTIFIER),e.type=this.previous()}catch(n){throw n instanceof d?(e.type=n.partialNode,new d(n.token,s(),n.handlerContext)):n}try{this.consume("Expect a colon ':'",c.COLON),e.bodyColon=this.previous()}catch(n){throw n instanceof d?(e.bodyColon=n.partialNode,new d(n.token,s(),n.handlerContext)):n}try{const n=this.expression();n instanceof _?this.errors.push(new u(o.INVALID_ELEMENT_IN_SIMPLE_BODY,"Simple body cannot be an element declaration",n)):e.body=n}catch(n){throw n instanceof d?(e.body=n.partialNode,new d(n.token,s(),n.handlerContext)):n}return this.nodeFactory.create(_,e)}expression(){const e={args:[]},s=()=>tn(e.callee,e.args,this.nodeFactory).unwrap_or(this.nodeFactory.create(x,e));try{e.callee=this.normalExpression()}catch(i){throw i instanceof d?(e.callee=i.partialNode,new d(i.token,s(),i.handlerContext)):i}if(this.shouldStopExpression())return s();let n=e.callee;for(;!this.shouldStopExpression();){Ve(this.previous())||this.logError(n,o.MISSING_SPACES,"Expect a following space");try{n=this.normalExpression(),e.args.push(n)}catch(i){throw i instanceof d?(n=i.partialNode,e.args.push(n),new d(i.token,s(),i.handlerContext)):i}}return s()}shouldStopExpression(){if(this.isAtEnd()||bt(this.previous()))return!0;const e=this.peek().kind;return e===c.RBRACE||e===c.RBRACKET||e===c.RPAREN||e===c.COMMA||e===c.COLON}normalExpression(){return this.expression_bp(0)}expression_bp(e){let s=this.leftExpression_bp();for(;!this.isAtEnd();){const n=this.peek();if(n.kind===c.LPAREN){const{left:i}=ut(n);if(i<e||ot(this.previous(),n)&&!this.contextStack.isWithinGroupExpressionContext()&&!this.contextStack.isWithinListExpressionContext())break;try{s=this.nodeFactory.create(H,{callee:s,argumentList:this.tupleExpression()})}catch(r){throw r instanceof d?(s=this.nodeFactory.create(H,{callee:s,argumentList:r.partialNode}),new d(r.token,s,r.handlerContext)):r}}else if(n.kind===c.LBRACKET){if(Ve(this.previous()))break;try{s=this.nodeFactory.create(he,{expression:s,indexer:this.listExpression()})}catch(i){throw i instanceof d?(s=this.nodeFactory.create(he,{expression:s,indexer:i.partialNode}),new d(i.token,s,i.handlerContext)):i}}else if(at(n)){const i=n,r=ut(i);if(r.left!==null){if(r.left<=e)break;this.advance(),s=this.nodeFactory.create(De,{expression:s,op:i})}else{const a=hn(i);if(a.left===null||a.left<=e)break;this.advance();try{s=this.nodeFactory.create(Q,{leftExpression:s,op:i,rightExpression:i.value==="."?this.extractOperand():this.expression_bp(a.right)})}catch(l){throw l instanceof d?(s=this.nodeFactory.create(Q,{leftExpression:s,op:i,rightExpression:l.partialNode}),new d(l.token,s,l.handlerContext)):l}}}else break}return s}leftExpression_bp(){let e;if(at(this.peek())){const s={};s.op=this.peek();const n=pn(s.op);if(n.right===null)throw this.logError(s.op,o.UNKNOWN_PREFIX_OP,`Unexpected '${s.op.value}' in an expression`),new d(s.op,this.nodeFactory.create(we,{pre:s.op}),this.contextStack.findHandlerContext(this.tokens,this.current));this.advance();try{s.expression=this.expression_bp(n.right)}catch(i){throw i instanceof d?(s.expression=i.partialNode,new d(i.token,this.nodeFactory.create(q,s),i.handlerContext)):i}e=this.nodeFactory.create(q,s)}else if(e=this.extractOperand(),e instanceof we)throw new d(this.peek(),this.nodeFactory.create(we,{pre:this.peek()}),this.contextStack.findHandlerContext(this.tokens,this.current));return e}extractOperand(){return this.check(c.NUMERIC_LITERAL,c.STRING_LITERAL,c.COLOR_LITERAL,c.QUOTED_STRING,c.IDENTIFIER)?this.primaryExpression():this.check(c.FUNCTION_EXPRESSION)?this.functionExpression():this.check(c.LBRACKET)?this.listExpression():this.check(c.LBRACE)?this.blockExpression():this.check(c.LPAREN)?this.tupleExpression():(this.peek().kind===c.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(we,{pre:this.previous()}))}functionExpression(){const e={};try{this.consume("Expect a function expression",c.FUNCTION_EXPRESSION),e.value=this.previous()}catch(s){throw s instanceof d?(e.value=s.partialNode,new d(s.token,this.nodeFactory.create(K,e),s.handlerContext)):s}return this.nodeFactory.create(K,e)}canBeField(){return this.peek().kind===c.IDENTIFIER&&this.peek(1).kind===c.COLON}primaryExpression(){if(this.match(c.COLOR_LITERAL,c.STRING_LITERAL,c.NUMERIC_LITERAL))return this.nodeFactory.create(R,{expression:this.nodeFactory.create(pe,{literal:this.previous()})});if(this.match(c.QUOTED_STRING,c.IDENTIFIER))return this.nodeFactory.create(R,{expression:this.nodeFactory.create(X,{variable:this.previous()})});throw this.logError(this.peek(),o.UNEXPECTED_TOKEN,"Expect a variable or literal"),new d(this.peek(),this.nodeFactory.create(R,{expression:this.nodeFactory.create(X,{})}),this.contextStack.findHandlerContext(this.tokens,this.current))}attribute(){const e={};if(this.check(c.COLON,c.RBRACKET,c.COMMA)){const s=this.peek();this.logError(s,o.EMPTY_ATTRIBUTE_NAME,"Expect a non-empty attribute name"),e.name=this.nodeFactory.create(te,{identifiers:[]})}else try{e.name=this.attributeName()}catch(s){if(!(s instanceof d))throw s;if(e.name=s.partialNode,!this.canHandle(s))throw new d(s.token,this.nodeFactory.create(ne,e),s.handlerContext);this.synchronizeAttributeName()}return this.match(c.COLON)&&(e.colon=this.previous(),e.value=this.attributeValue()),this.nodeFactory.create(ne,e)}attributeValue(){let e;try{e=this.peek().kind===c.IDENTIFIER&&this.peek(1).kind===c.IDENTIFIER?this.attributeName():this.normalExpression()}catch(s){if(!(s instanceof d)||!this.canHandle(s))throw s;e=s.partialNode,this.synchronizeAttributeValue()}return e}attributeName(){const e=[];if(this.peek().kind!==c.IDENTIFIER)return this.primaryExpression();for(;!this.isAtEnd()&&!this.check(c.COLON,c.COMMA,c.RBRACKET);)try{this.consume("Expect an identifier",c.IDENTIFIER),e.push(this.previous())}catch(s){throw s instanceof d?new d(s.token,this.nodeFactory.create(te,{identifiers:e}),s.handlerContext):s}return this.nodeFactory.create(te,{identifiers:e})}logError(e,s,n){this.errors.push(new u(s,n,e))}}const un={"+":{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 hn(t){return un[t.value]||{left:null,right:null}}const fn={"+":{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 fn[t.value]||{left:null,right:null}}const dn={"(":{left:14,right:null}};function ut(t){return dn[t.value]||{left:null,right:null}}var b=(t=>(t.Table="table",t.Enum="enum",t.Ref="ref",t.Note="note",t.Project="project",t.Indexes="indexes",t.TableGroup="tablegroup",t))(b||{});function de(t){var s;const e=(s=t==null?void 0:t.type)==null?void 0:s.value.toLowerCase();switch(e){case b.Enum:case b.Table:case b.Indexes:case b.Note:case b.Project:case b.Ref:case b.TableGroup:return new S(e);default:return new A}}function Ee(t){if(!He(t))return new S([t]);const e=Ee(t.leftExpression).unwrap_or(void 0);return e?(e.push(t.rightExpression),new S(e)):new A}function W(t){if(t===void 0)return new A;const e=Ee(t).unwrap_or(void 0);if(!e)return new A;const s=[];for(const n of e){const i=G(n).unwrap_or(void 0);if(!i)return new A;s.push(i)}return new S(s)}function Le(t){if(t===void 0)return new A;const e=Ee(t).unwrap_or(void 0);if(!e||e.length===0)return new A;const s=[];let n;if(!M(I.last(e))){const i=e.pop();if(xt(i))n=i.elementList.map(r=>V(r).unwrap());else return new A}for(const i of e){const r=G(i).unwrap_or(void 0);if(!r)return new A;s.push(r)}return new S({variables:s,tupleElements:n})}function G(t){return M(t)?new S(t.expression.variable.value):new A}function Ge(t){if(ht(t))return t instanceof K?new S({functional:[t],nonFunctional:[]}):new S({functional:[],nonFunctional:[t]});if(t instanceof J&&t.elementList.every(ht)){const e=t.elementList.filter(n=>n instanceof K),s=t.elementList.filter(M);return new S({functional:e,nonFunctional:s})}return new A}function V(t){var s;const e=(s=t==null?void 0:t.expression.variable)==null?void 0:s.value;return e===void 0?new A:new S(e)}function Y(t){return $(t)?t.expression instanceof X?new S(t.expression.variable.value):new S(t.expression.literal.value):new A}function En(t){var e;return!(t instanceof Q)||!yt((e=t.op)==null?void 0:e.value)?!1:Le(t.leftExpression).and_then(()=>Le(t.rightExpression)).unwrap_or(void 0)!==void 0}function Nn(t){const e=Le(t.leftExpression),s=Le(t.rightExpression);if(!e.isOk()||!s.isOk())return!1;const{tupleElements:n}=e.unwrap(),{tupleElements:i}=s.unwrap();return(n==null?void 0:n.length)===(i==null?void 0:i.length)}function ht(t){return t instanceof R&&t.expression instanceof X||t instanceof K}function mn(t,e){var i,r,a,l;let s=e;const n=Yt(t);for(;s;){if((r=(i=s.symbol)==null?void 0:i.symbolTable)!=null&&r.has(t))return(a=s.symbol.symbolTable)==null?void 0:a.get(t);if(((l=s.symbol)==null?void 0:l.declaration)instanceof C&&n)return s.symbol;if(s instanceof C)return;s=s.parent}}class Tn{constructor(e,s,n){this.declarationNode=e,this.publicSymbolTable=s,this.symbolFactory=n}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 C||de(this.declarationNode.parent).unwrap_or(void 0)!==b.Project?[new u(o.INVALID_CUSTOM_CONTEXT,"A custom element can only appear in a Project",this.declarationNode)]:[]}validateName(e){return e?[new u(o.UNEXPECTED_NAME,"A Custom element shouldn't have a name",e)]:[]}validateAlias(e){return e?[new u(o.UNEXPECTED_NAME,"A Custom element shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new u(o.UNEXPECTED_SETTINGS,"A Custom element shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof ee)return[new u(o.UNEXPECTED_COMPLEX_BODY,"A Custom element can only have an inline field",e)];const s=[];return $(e.callee)||s.push(new u(o.INVALID_CUSTOM_ELEMENT_VALUE,"A Custom element value can only be a string",e)),e.args.length>0&&s.push(...e.args.map(n=>new u(o.INVALID_CUSTOM_ELEMENT_VALUE,"A Custom element value can only be a string",n))),s}}class _e{constructor(){this.table=new Map}has(e){return this.table.has(e)}set(e,s){this.table.set(e,s)}get(e,s){return this.table.get(e)||s!==void 0&&this.set(e,s)||s}entries(){return this.table.entries()}}class bn{constructor(e,s,n){this.declarationNode=e,this.publicSymbolTable=s,this.symbolFactory=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 _?[new u(o.INVALID_PROJECT_CONTEXT,"An Enum can only appear top-level",this.declarationNode)]:[]}validateName(e){return e?Je(e)?[]:[new u(o.INVALID_NAME,"An Enum name must be of the form <enum> or <schema>.<enum>",e)]:[new u(o.NAME_NOT_FOUND,"An Enum must have a name",this.declarationNode)]}validateAlias(e){return e?[new u(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}registerElement(){const e=[];this.declarationNode.symbol=this.symbolFactory.create(Ht,{declaration:this.declarationNode,symbolTable:new _e});const{name:s}=this.declarationNode,n=W(s);if(n.isOk()){const i=n.unwrap(),r=i.pop(),a=Ze(i,this.publicSymbolTable,this.symbolFactory),l=je(r);a.has(l)&&e.push(new u(o.DUPLICATE_NAME,`Enum name ${r} already exists in schema '${i.join(".")||"public"}'`,s)),a.set(l,this.declarationNode.symbol)}return e}validateSettingList(e){return e?[new u(o.UNEXPECTED_SETTINGS,"An Enum shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof x)return this.validateFields([e]);const[s,n]=I.partition(e.body,i=>i instanceof x);return[...this.validateFields(s),...this.validateSubElements(n)]}validateFields(e){return e.length===0?[new u(o.EMPTY_ENUM,"An Enum must have at least one element",this.declarationNode)]:e.flatMap(s=>{const n=[];return s.callee&&!M(s.callee)&&n.push(new u(o.INVALID_COLUMN_NAME,"A column name must be an identifier or a quoted identifier",s.callee)),I.last(s.args)instanceof U&&n.push(...this.validateFieldSetting(I.last(s.args))),s.args.length>1&&n.push(...s.args.map(i=>new u(o.INVALID_ENUM_ELEMENT,"An Enum must have only a field and optionally a setting list",i))),n.push(...this.registerField(s)),n})}validateFieldSetting(e){const s=z(e),n=s.getErrors(),i=s.getValue();for(const r in i){const a=i[r];switch(r){case"note":a.length>1&&a.forEach(l=>n.push(new u(o.DUPLICATE_ENUM_ELEMENT_SETTING,"'note' can only appear once",l))),a.forEach(l=>{$(l.value)||n.push(new u(o.INVALID_ENUM_ELEMENT_SETTING,"'note' must be a string",l))});break;default:a.forEach(l=>n.push(new u(o.UNKNOWN_ENUM_ELEMENT_SETTING,`Unknown enum field setting '${r}'`,l)))}}return n}validateSubElements(e){return e.flatMap(s=>{if(s.parent=this.declarationNode,!s.type)return[];const n=ie(s);return new n(s,this.publicSymbolTable,this.symbolFactory).validate()})}registerField(e){if(e.callee&&M(e.callee)){const s=V(e.callee).unwrap(),n=Ye(s),i=this.symbolFactory.create(Jt,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(n)){const a=r.get(n);return[new u(o.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${s}`,e),new u(o.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${s}`,a.declaration)]}r.set(n,i)}return[]}}class In{constructor(e,s,n){this.declarationNode=e,this.publicSymbolTable=s,this.symbolFactory=n}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 C||de(this.declarationNode.parent).unwrap_or(void 0)!==b.Table?[new u(o.INVALID_NOTE_CONTEXT,"An Indexes can only appear inside a Table",this.declarationNode)]:[]}validateName(e){return e?[new u(o.UNEXPECTED_NAME,"An Indexes shouldn't have a name",e)]:[]}validateAlias(e){return e?[new u(o.UNEXPECTED_ALIAS,"An Indexes shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new u(o.UNEXPECTED_SETTINGS,"An Indexes shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof x)return[new u(o.UNEXPECTED_SIMPLE_BODY,"An Indexes must have a complex body",e)];const[s,n]=I.partition(e.body,i=>i instanceof x);return[...this.validateFields(s),...this.validateSubElements(n)]}validateFields(e){return e.flatMap(s=>{if(!s.callee)return[];const n=[],i=[s.callee,...s.args];return I.last(i)instanceof U&&n.push(...this.validateFieldSetting(i.pop())),i.forEach(r=>{for(;r instanceof H;)r.argumentList&&!Ge(r.argumentList).isOk()&&n.push(new u(o.INVALID_INDEXES_FIELD,"An index field must be an identifier, a quoted identifier, a functional expression or a tuple of such",r.argumentList)),r=r.callee;Ge(r).isOk()||n.push(new u(o.INVALID_INDEXES_FIELD,"An index field must be an identifier, a quoted identifier, a functional expression or a tuple of such",r))}),n})}validateFieldSetting(e){const s=z(e),n=s.getErrors(),i=s.getValue();for(const r in i){const a=i[r];switch(r){case"note":case"name":a.length>1&&a.forEach(l=>n.push(new u(o.DUPLICATE_INDEX_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{$(l.value)||n.push(new u(o.INVALID_INDEX_SETTING_VALUE,`'${r}' must be a string`,l))});break;case"unique":case"pk":a.length>1&&a.forEach(l=>n.push(new u(o.DUPLICATE_INDEX_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{oe(l.value)||n.push(new u(o.INVALID_INDEX_SETTING_VALUE,`'${r}' must not have a value`,l))});break;case"type":a.length>1&&a.forEach(l=>n.push(new u(o.DUPLICATE_INDEX_SETTING,"'type' can only appear once",l))),a.forEach(l=>{M(l.value)||n.push(new u(o.INVALID_INDEX_SETTING_VALUE,`'type' must be "btree" or "hash"`,l))});break;default:a.forEach(l=>n.push(new u(o.UNKNOWN_INDEX_SETTING,`Unknown index setting '${r}'`,l)))}}return n}validateSubElements(e){return e.flatMap(s=>{if(s.parent=this.declarationNode,!s.type)return[];const n=ie(s);return new n(s,this.publicSymbolTable,this.symbolFactory).validate()})}}class Ln{constructor(e,s,n){this.declarationNode=e,this.publicSymbolTable=s,this.symbolFactory=n}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 C||![b.Table,b.Project].includes(de(this.declarationNode.parent).unwrap_or(void 0))?[new u(o.INVALID_NOTE_CONTEXT,"A Note can only appear inside a Table or a Project",this.declarationNode)]:[]}validateName(e){return e?[new u(o.UNEXPECTED_NAME,"A Note shouldn't have a name",e)]:[]}validateAlias(e){return e?[new u(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new u(o.UNEXPECTED_SETTINGS,"A Note shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof x)return this.validateFields([e]);const[s,n]=I.partition(e.body,i=>i instanceof x);return[...this.validateFields(s),...this.validateSubElements(n)]}validateFields(e){const s=[];return e.length===0?[new u(o.EMPTY_NOTE,"A Note must have a content",this.declarationNode)]:(e.length>1&&e.slice(1).forEach(n=>s.push(new u(o.NOTE_CONTENT_REDEFINED,"A Note can only contain one string",n))),$(e[0].callee)||s.push(new u(o.INVALID_NOTE,"A Note content must be a quoted string",e[0])),e[0].args.length>0&&s.push(...e[0].args.map(n=>new u(o.INVALID_NOTE,"A Note can only contain one quoted string",n))),s)}validateSubElements(e){return e.flatMap(s=>{if(s.parent=this.declarationNode,!s.type)return[];const n=ie(s);return new n(s,this.publicSymbolTable,this.symbolFactory).validate()})}}class gn{constructor(e,s,n){this.declarationNode=e,this.publicSymbolTable=s,this.symbolFactory=n}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 _?[new u(o.INVALID_PROJECT_CONTEXT,"A Project can only appear top-level",this.declarationNode)]:[]}validateName(e){return e?Pe(e)?[]:[new u(o.INVALID_NAME,"A Project's name is optional or must be an identifier or a quoted identifer",e)]:[]}validateAlias(e){return e?[new u(o.UNEXPECTED_ALIAS,"A Project shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new u(o.UNEXPECTED_SETTINGS,"A Project shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof x)return[new u(o.UNEXPECTED_SIMPLE_BODY,"A Project's body must be a block",e)];const[s,n]=I.partition(e.body,i=>i instanceof x);return[...s.map(i=>new u(o.INVALID_PROJECT_FIELD,"A Project can not have inline fields",i)),...this.validateSubElements(n)]}validateSubElements(e){return e.flatMap(s=>{if(s.parent=this.declarationNode,!s.type)return[];const n=ie(s);return new n(s,this.publicSymbolTable,this.symbolFactory).validate()})}}class _n{constructor(e,s,n){this.declarationNode=e,this.publicSymbolTable=s,this.symbolFactory=n}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 C||de(this.declarationNode.parent).unwrap_or(void 0)===b.Table?[]:[new u(o.INVALID_REF_CONTEXT,"A Ref must appear top-level or inside a table",this.declarationNode)]}validateName(e){return e?Pe(e)?[]:[new u(o.INVALID_NAME,"A Ref's name is optional or must be an identifier or a quoted identifer",e)]:[]}validateAlias(e){return e?[new u(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new u(o.UNEXPECTED_SETTINGS,"A Ref shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof x)return this.validateFields([e]);const[s,n]=I.partition(e.body,i=>i instanceof x);return[...this.validateFields(s),...this.validateSubElements(n)]}validateFields(e){if(e.length===0)return[new u(o.EMPTY_REF,"A Ref must have at least one field",this.declarationNode)];const s=[];return e.length>1&&s.push(...e.slice(1).map(n=>new u(o.REF_REDEFINED,"A Ref can only contain one binary relationship",n))),e.forEach(n=>{n.callee&&!En(n.callee)&&s.push(new u(o.INVALID_REF_FIELD,"A Ref field must be a binary relationship",n.callee)),n.callee&&!Nn(n.callee)&&s.push(new u(o.UNEQUAL_FIELDS_BINARY_REF,"Unequal fields in ref endpoints",n.callee)),I.last(n.args)instanceof U&&this.validateFieldSettings(I.last(n.args)),n.args.length>1&&s.push(...n.args.map(i=>new u(o.INVALID_REF_FIELD,"A Ref field should only have a single binary relationship",i)))}),s}validateFieldSettings(e){const s=z(e),n=s.getErrors(),i=s.getValue();for(const r in i){const a=i[r];switch(r){case"delete":case"update":a.length>1&&a.forEach(l=>n.push(new u(o.DUPLICATE_REF_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{An(l.value)||n.push(new u(o.INVALID_REF_SETTING_VALUE,`'${r}' can only have values "cascade", "no action", "set null", "set default" or "restrict"`,l))});break;default:a.forEach(l=>n.push(new u(o.UNKNOWN_REF_SETTING,`Unknown ref setting '${r}'`,l)))}}return n}validateSubElements(e){return e.flatMap(s=>{if(s.parent=this.declarationNode,!s.type)return[];const n=ie(s);return new n(s,this.publicSymbolTable,this.symbolFactory).validate()})}}function An(t){if(!(M(t)&&t.expression.variable.kind!==c.QUOTED_STRING)&&!(t instanceof te))return!1;let e;if(t instanceof te?e=Re(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 vn{constructor(e,s,n){this.declarationNode=e,this.symbolFactory=n,this.publicSymbolTable=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 _?[new u(o.INVALID_TABLE_CONTEXT,"Table must appear top-level",this.declarationNode)]:[]}validateName(e){return e?e instanceof he?[new u(o.INVALID_NAME,"Invalid array as Table name, maybe you forget to add a space between the name and the setting list?",e)]:Je(e)?[]:[new u(o.INVALID_NAME,"A Table name must be of the form <table> or <schema>.<table>",e)]:[new u(o.NAME_NOT_FOUND,"A Table must have a name",this.declarationNode)]}validateAlias(e){return e?kn(e)?[]:[new u(o.INVALID_ALIAS,"Table aliases can only contains alphanumeric and underscore unless surrounded by double quotes",e)]:[]}validateSettingList(e){const s=z(e),n=s.getErrors(),i=s.getValue();for(const r in i){const a=i[r];switch(r){case"headercolor":a.length>1&&n.push(...a.map(l=>new u(o.DUPLICATE_TABLE_SETTING,"'headercolor' can only appear once",l))),a.forEach(l=>{Sn(l.value)||n.push(new u(o.INVALID_TABLE_SETTING,"'headercolor' must be a color literal",l.value||l.name))});break;case"note":a.length>1&&n.push(...a.map(l=>new u(o.DUPLICATE_TABLE_SETTING,"'note' can only appear once",l))),a.forEach(l=>{$(l.value)||n.push(new u(o.INVALID_TABLE_SETTING,"'note' must be a string literal",l.value||l.name))});break;default:n.push(...a.map(l=>new u(o.INVALID_TABLE_SETTING,`Unknown '${r}' setting`,l)))}}return n}registerElement(){const e=[];this.declarationNode.symbol=this.symbolFactory.create(At,{declaration:this.declarationNode,symbolTable:new _e});const{name:s,alias:n}=this.declarationNode,i=W(s);if(i.isOk()){const r=[...i.unwrap()],a=r.pop(),l=Ze(r,this.publicSymbolTable,this.symbolFactory),p=xe(a);l.has(p)&&e.push(new u(o.DUPLICATE_NAME,`Table name '${a}' already exists in schema '${r.join(".")||"public"}'`,s)),l.set(p,this.declarationNode.symbol)}if(n&&Pe(n)&&!yn(n.expression.variable.value,i.unwrap_or([]))){const r=V(n).unwrap(),a=xe(r);this.publicSymbolTable.has(a)&&e.push(new u(o.DUPLICATE_NAME,`Table name '${r}' already exists`,s)),this.publicSymbolTable.set(a,this.declarationNode.symbol)}return e}validateBody(e){if(!e)return[];if(e instanceof x)return[new u(o.UNEXPECTED_SIMPLE_BODY,"A Table's body must be a block",e)];const[s,n]=I.partition(e.body,i=>i instanceof x);return[...this.validateFields(s),...this.validateSubElements(n)]}validateFields(e){return e.length===0?[new u(o.EMPTY_TABLE,"A Table must have at least one column",this.declarationNode)]:e.flatMap(s=>{if(!s.callee)return[];const n=[];s.args.length===0&&n.push(new u(o.INVALID_COLUMN,"A column must have a type",s.callee)),M(s.callee)||n.push(new u(o.INVALID_COLUMN_NAME,"A column name must be an identifier or a quoted identifier",s.callee)),s.args[0]&&!wn(s.args[0])&&n.push(new u(o.INVALID_COLUMN_TYPE,"Invalid column type",s.args[0]));const i=s.args.slice(1);return n.push(...this.validateFieldSetting(i)),n.push(...this.registerField(s)),n})}registerField(e){if(e.callee&&M(e.callee)){const s=V(e.callee).unwrap(),n=We(s),i=this.symbolFactory.create(Zt,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(n)){const a=r.get(n);return[new u(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${s}`,e),new u(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${s}`,a.declaration)]}r.set(n,i)}return[]}validateFieldSetting(e){if(!e.slice(0,-1).every(fe)||!e.slice(-1).every(p=>fe(p)||p instanceof U))return[...e.map(p=>new u(o.INVALID_COLUMN,"These fields must be some inline settings optionally ended with a setting list",p))];if(e.length===0)return[];let s;I.last(e)instanceof U&&(s=e.pop());const n=z(s),i=n.getErrors(),r=n.getValue();for(const p of e){const h=V(p).unwrap_or("").toLowerCase();if(h!=="pk"&&h!=="unique"){i.push(new u(o.INVALID_SETTINGS,"Inline column settings can only be `pk` or `unique`",p));continue}r[h]===void 0?r[h]=[p]:r[h].push(p)}const a=r.pk||[],l=r["primary key"]||[];a.length>=1&&l.length>=1&&i.push(...[...a,...l].map(p=>new u(o.DUPLICATE_COLUMN_SETTING,"Either one of 'primary key' and 'pk' can appear",p)));for(const p in r){const h=r[p];switch(p){case"note":h.length>1&&i.push(...h.map(f=>new u(o.DUPLICATE_COLUMN_SETTING,"note can only appear once",f))),h.forEach(f=>{$(f.value)||i.push(new u(o.INVALID_COLUMN_SETTING_VALUE,"'note' must be a quoted string",f.value||f.name))});break;case"ref":h.forEach(f=>{Dn(f.value)||i.push(new u(o.INVALID_COLUMN_SETTING_VALUE,"'ref' must be a valid unary relationship",f.value||f.name))});break;case"primary key":h.length>1&&i.push(...h.map(f=>new u(o.DUPLICATE_COLUMN_SETTING,"primary key can only appear once",f))),h.forEach(f=>{oe(f.value)||i.push(new u(o.INVALID_COLUMN_SETTING_VALUE,"'primary key' must not have a value",f.value||f.name))});break;case"pk":h.length>1&&i.push(...h.map(f=>new u(o.DUPLICATE_COLUMN_SETTING,"'pk' can only appear once",f))),h.forEach(f=>{f instanceof ne&&!oe(f.value)&&i.push(new u(o.INVALID_COLUMN_SETTING_VALUE,"'pk' must not have a value",f.value||f.name))});break;case"not null":h.length>1&&i.push(...h.map(f=>new u(o.DUPLICATE_COLUMN_SETTING,"'not null' can only appear once",f)));const T=r.null||[];h.length>=1&&T.length>=1&&i.push(...[...h,...T].map(f=>new u(o.CONFLICTING_SETTING,"'not null' and 'null' can not be set at the same time",f))),h.forEach(f=>{oe(f.value)||i.push(new u(o.INVALID_COLUMN_SETTING_VALUE,"'not null' must not have a value",f.value||f.name))});break;case"null":h.length>1&&i.push(...h.map(f=>new u(o.DUPLICATE_COLUMN_SETTING,"'null' can only appear once",f))),h.forEach(f=>{oe(f.value)||i.push(new u(o.INVALID_COLUMN_SETTING_VALUE,"'null' must not have a value",f.value||f.name))});break;case"unique":h.length>1&&i.push(...h.map(f=>new u(o.DUPLICATE_COLUMN_SETTING,"'unique' can only appear once",f))),h.forEach(f=>{f instanceof ne&&!oe(f.value)&&i.push(new u(o.INVALID_COLUMN_SETTING_VALUE,"'unique' must not have a value",f.value||f.name))});break;case"increment":h.length>1&&i.push(...h.map(f=>new u(o.DUPLICATE_COLUMN_SETTING,"'increment' can only appear once",f))),h.forEach(f=>{f instanceof ne&&!oe(f.value)&&i.push(new u(o.INVALID_COLUMN_SETTING_VALUE,"'increment' must not have a value",f.value||f.name))});break;case"default":h.length>1&&i.push(...h.map(f=>new u(o.DUPLICATE_TABLE_SETTING,"'default' can only appear once",f))),h.forEach(f=>{On(f.value)||i.push(new u(o.INVALID_TABLE_SETTING,"'default' must be a string literal, number literal, function expression, true, false or null",f.value||f.name))});break;default:h.forEach(f=>i.push(new u(o.UNKNOWN_COLUMN_SETTING,`Unknown column setting '${p}'`,f)))}}return i}validateSubElements(e){const s=e.flatMap(i=>{if(i.parent=this.declarationNode,!i.type)return[];const r=ie(i);return new r(i,this.publicSymbolTable,this.symbolFactory).validate()}),n=e.filter(i=>{var r;return((r=i.type)==null?void 0:r.value.toLowerCase())==="note"});return n.length>1&&(s.push(...n.map(i=>new u(o.NOTE_REDEFINED,"Duplicate notes are defined",i))),s.push()),s}}function wn(t){if(!(t instanceof H||He(t)||t instanceof R||t instanceof he))return!1;if(t instanceof H){if(t.callee===void 0||t.argumentList===void 0||!t.argumentList.elementList.every(s=>le(s)||$(s)||fe(s)))return!1;t=t.callee}for(;t instanceof he;){if(t.array===void 0||t.indexer===void 0||!t.indexer.elementList.every(s=>!s.colon&&!s.value&&le(s.name)))return!1;t=t.array}const e=W(t).unwrap_or(void 0);return e!==void 0&&e.length>0}function yn(t,e){return e.length===1&&t===e[0]}class xn{constructor(e,s,n){this.declarationNode=e,this.publicSymbolTable=s,this.symbolFactory=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 _?[new u(o.INVALID_TABLEGROUP_CONTEXT,"TableGroup must appear top-level",this.declarationNode)]:[]}validateName(e){return e?Je(e)?[]:[new u(o.INVALID_NAME,"A TableGroup name must be of the form <tablegroup> or <schema>.<tablegroup>",e)]:[new u(o.NAME_NOT_FOUND,"A TableGroup must have a name",this.declarationNode)]}validateAlias(e){return e?[new u(o.UNEXPECTED_ALIAS,"A TableGroup shouldn't have an alias",e)]:[]}registerElement(){const{name:e}=this.declarationNode;this.declarationNode.symbol=this.symbolFactory.create(Kt,{declaration:this.declarationNode,symbolTable:new _e});const s=W(e);if(s.isOk()){const n=s.unwrap(),i=n.pop(),r=Ze(n,this.publicSymbolTable,this.symbolFactory),a=ze(i);if(r.has(a))return[new u(o.DUPLICATE_NAME,`TableGroup name '${i}' already exists in schema '${n.join(".")||"public"}'`,e)];r.set(a,this.declarationNode.symbol)}return[]}validateSettingList(e){return e?[new u(o.UNEXPECTED_SETTINGS,"A TableGroup shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof x)return[new u(o.UNEXPECTED_SIMPLE_BODY,"A TableGroup's body must be a block",e)];const[s,n]=I.partition(e.body,i=>i instanceof x);return[...this.validateFields(s),...this.validateSubElements(n)]}validateFields(e){return e.flatMap(s=>{const n=[];return s.callee&&!W(s.callee).isOk()&&n.push(new u(o.INVALID_TABLEGROUP_FIELD,"A TableGroup field must be of the form <table> or <schema>.<table>",s.callee)),this.registerField(s),s.args.length>0&&n.push(...s.args.map(i=>new u(o.INVALID_TABLEGROUP_FIELD,"A TableGroup field should only have a single Table name",i))),n})}validateSubElements(e){return e.flatMap(s=>{if(s.parent=this.declarationNode,!s.type)return[];const n=ie(s);return new n(s,this.publicSymbolTable,this.symbolFactory).validate()})}registerField(e){if(e.callee&&M(e.callee)){const s=V(e.callee).unwrap(),n=qe(s),i=this.symbolFactory.create(en,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(n)){const a=r.get(n);return[new u(o.DUPLICATE_TABLEGROUP_FIELD_NAME,`${s} already exists in the group`,e),new u(o.DUPLICATE_TABLEGROUP_FIELD_NAME,`${s} already exists in the group`,a.declaration)]}r.set(n,i)}return[]}}const wt=["-","+"];function ie(t){switch(t.type.value.toLowerCase()){case b.Enum:return bn;case b.Table:return vn;case b.TableGroup:return xn;case b.Project:return gn;case b.Ref:return _n;case b.Note:return Ln;case b.Indexes:return In;default:return Tn}}function Je(t){return!!W(t).unwrap_or(!1)}function kn(t){return Pe(t)}function Pe(t){return t instanceof R&&t.expression instanceof X}function Ze(t,e,s){var i;t[0]==="public"&&(t=t.slice(1));let n=e;for(const r of t){let a;const l=$e(r);if(n.has(l)){if(a=(i=n.get(l))==null?void 0:i.symbolTable,!a)throw new Error("Expect a symbol table in a schema symbol")}else{a=new _e;const p=s.create(_t,{symbolTable:a});n.set(l,p)}n=a}return n}function yt(t){return t==="-"||t==="<>"||t===">"||t==="<"}function Sn(t){var s;if(!(t instanceof R)||!(t.expression instanceof pe)||((s=t.expression.literal)==null?void 0:s.kind)!==c.COLOR_LITERAL)return!1;const e=t.expression.literal.value;if(e.length!==4&&e.length!==7||e[0]!=="#")return!1;for(let n=1;n<e.length;n+=1)if(!qt(e[n]))return!1;return!0}function oe(t){return t===void 0}function On(t){var e;return!!($(t)||le(t)||fe(t)&&["true","false","null"].includes(t.expression.variable.value.toLowerCase())||t instanceof q&&wt.includes((e=t.op)==null?void 0:e.value)&&le(t.expression)||t instanceof K)}function le(t){var e;return t instanceof R&&t.expression instanceof pe&&((e=t.expression.literal)==null?void 0:e.kind)===c.NUMERIC_LITERAL}function Dn(t){var s;if(!(t instanceof q)||!yt((s=t.op)==null?void 0:s.value))return!1;const e=W(t.expression).unwrap_or(void 0);return e!==void 0&&e.length>0}function xt(t){return t instanceof J&&t.elementList.every(M)}function z(t){var n;const e={},s=[];if(!t)return new F({});for(const i of t.elementList){if(!i.name)continue;if(i.name instanceof R){s.push(new u(o.INVALID_SETTINGS,"A setting name must be a stream of identifiers",i.name));continue}const r=(n=Re(i.name).unwrap_or(void 0))==null?void 0:n.toLowerCase();r&&(e[r]===void 0?e[r]=[i]:e[r].push(i))}return new F(e,s)}class ft{constructor(e,s){this.ast=e,this.symbolFactory=s,this.publicSchemaSymbol=this.symbolFactory.create(_t,{symbolTable:new _e}),this.ast.symbol=this.publicSchemaSymbol,this.ast.symbol.declaration=this.ast}validate(){const e=[];this.ast.body.forEach(n=>{if(n.parent=this.ast,n.type===void 0)return;const i=ie(n),r=new i(n,this.publicSchemaSymbol.symbolTable,this.symbolFactory);e.push(...r.validate())});const s=this.ast.body.filter(n=>de(n).unwrap_or(void 0)===b.Project);return s.length>1&&s.forEach(n=>e.push(new u(o.PROJECT_REDEFINED,"Only one project can exist",n))),new F(this.ast,e)}}class re{constructor(e,s){this.declarationNode=e,this.errors=s}bind(){this.bindSettingList(this.declarationNode.attributeList,this.settingList),this.bindBody()}bindSettingList(e,s){if(e)for(const n of e.elementList){if(n.name instanceof R)continue;const i=Re(n.name).unwrap_or(void 0);if(!i)continue;const r=s[i.toLowerCase()];r!=null&&r.shouldBind&&this.scanAndBind(n.value,r)}}bindBody(){const e=this.declarationNode;if(!e.body)return;const{body:s}=e;if(s instanceof ee)for(const n of s.body)if(n instanceof _){if(!n.type)continue;const i=kt(n);new i(n,this.errors).bind()}else this.bindSubfield(n);else this.bindSubfield(s)}bindSubfield(e){const s=[e.callee,...e.args],n=I.last(s);n instanceof U&&(s.pop(),this.bindSettingList(n,this.subfield.settingList));const{argBinderRules:i}=this.subfield.arg;for(let r=0;r<Math.min(s.length,i.length);r+=1)i[r].shouldBind&&this.scanAndBind(s[r],i[r])}scanAndBind(e,s){var n,i;if(e)if(e instanceof R){if(e.expression instanceof X&&((i=s.keywords)!=null&&i.includes((n=e.expression.variable)==null?void 0:n.value.toLowerCase())))return;this.bindFragments([e],s)}else e instanceof Q?He(e)?this.bindFragments(Ee(e).unwrap_or([]),s):(this.scanAndBind(e.leftExpression,s),this.scanAndBind(e.rightExpression,s)):e instanceof q?this.scanAndBind(e.expression,s):e instanceof De?this.scanAndBind(e.expression,s):e instanceof J&&e.elementList.forEach(r=>this.scanAndBind(r,s))}bindFragments(e,s){if(e.length===0)return;const n=[...s.topSubnamesSymbolKind],{remainingSubnamesSymbolKind:i}=s,r=e.findIndex(f=>!M(f)),l=r!==-1&&xt(e[r])?e[r]:void 0,p=r>=0?n.pop():void 0,h=e.slice(0,r===-1?void 0:r);if(h.length===0)return;const T=[];for(;n.length&&h.length;){const f=n.pop(),N=h.pop(),g=V(N).unwrap();T.unshift({index:Fe(g,f),referrer:N})}for(;h.length;){const f=h.pop(),N=V(f).unwrap();T.unshift({index:Fe(N,i),referrer:f})}return l?l.elementList.forEach(f=>this.resolveIndexStack([...T,{index:Fe(V(f).unwrap(),p),referrer:f}],s.ignoreNameNotFound)):this.resolveIndexStack(T,s.ignoreNameNotFound)}resolveIndexStack(e,s){if(e.length===0)throw new Error("Unreachable - An unresolved name must have at least one name component");const[n,...i]=e,r=mn(n.index,this.declarationNode);if(r===void 0){const{kind:h,name:T}=se(n.index).unwrap();this.logError(n.referrer,`Can not find ${h} '${T}'`,s);return}r.references.push(n.referrer),n.referrer.referee=r;let a=r.symbolTable,{kind:l,name:p}=se(n.index).unwrap();for(const h of i){const{kind:T,name:f}=se(h.index).unwrap(),N=a.get(h.index);if(!N){this.logError(h.referrer,`${l} '${p}' does not have ${T} '${f}'`,s);return}if(l=T,p=f,h.referrer.referee=N,N.references.push(h.referrer),!N.symbolTable)break;a=N.symbolTable}}logError(e,s,n){n||this.errors.push(new u(o.BINDING_ERROR,s,e))}}class Rn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Pn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Un extends re{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 Mn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Fn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Bn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class Vn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Enum],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!0}]},settingList:{ref:{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},default:{shouldBind:!1}}},this.settingList={}}}class Gn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}function kt(t){switch(t.type.value.toLowerCase()){case b.Enum:return Pn;case b.Table:return Vn;case b.TableGroup:return Gn;case b.Project:return Fn;case b.Ref:return Bn;case b.Note:return Mn;case b.Indexes:return Un;default:return Rn}}class Cn{constructor(e){this.ast=e,this.errors=[]}resolve(){for(const e of this.ast.body)if(e.type){const s=kt(e);new s(e,this.errors).bind()}return new F(this.ast,this.errors)}}class Xn{constructor(e){this.generator=e}create(e,s){return new e(s,this.generator.nextId())}}class $n{constructor(e,s){this.ast=e,this.symbolFactory=new Xn(s)}analyze(){return new ft(this.ast,this.symbolFactory).validate().chain(s=>new Cn(s).resolve())}validate(){return new ft(this.ast,this.symbolFactory).validate().chain(s=>new F(s,[]))}}function pt(t,e){const{variables:s,tupleElements:n}=Le(t).unwrap();return n?s.length===0?{schemaName:e.schemaName,tableName:e.name,fieldNames:n}:{tableName:s.pop(),schemaName:s.pop()||null,fieldNames:n}:s.length===1?{schemaName:e.schemaName,tableName:e.name,fieldNames:[s[0]]}:{fieldNames:[s.pop()],tableName:s.pop(),schemaName:s.pop()||null}}function St(t){switch(t){case"<":return["1","*"];case"<>":return["*","*"];case">":return["*","1"];case"-":return["1","1"]}throw new Error("Invalid relation op")}function k(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 s;const e=(s=Ee(t).unwrap_or(void 0))==null?void 0:s.pop();return e instanceof J?e.elementList.map(n=>n.referee):[e.referee]}function Ae(t){const e=W(t).unwrap();return{name:e.pop(),schemaName:e}}function Wn(t){return t.expression.literal.value}function Ot(t,e){if(Array.isArray(t)){const i=t.map(({id:a})=>a).sort().join(","),r=e.map(({id:a})=>a).sort().join(",");return i<r?`${i}-${r}`:`${i}-${r}`}const s=t.id,n=e.id;return s<n?`${s}-${n}`:`${n}-${s}`}function Dt(t,e){if(Array.isArray(t)){const i=t.map(({id:a})=>a).sort(),r=e.map(({id:a})=>a).sort();return I.zip(i,r).every(([a,l])=>a===l)}const s=t.id,n=e.id;return s===n}class Ke{constructor(e,s){this.declarationNode=e,this.env=s,this.container=this.declarationNode.parent instanceof _?this.env.tables.get(this.declarationNode.parent):void 0,this.ref={}}interpret(){return this.ref.token=k(this.declarationNode),this.env.ref.set(this.declarationNode,this.ref),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(e){const s=[],n=W(this.declarationNode.name).unwrap_or([]);return this.ref.name=n.pop()||null,n.length>1&&s.push(new u(o.UNSUPPORTED,"Nested schema is not supported",this.declarationNode.name)),this.ref.schemaName=n.join(".")||null,s}interpretBody(e){return e instanceof x?this.interpretField(e):this.interpretField(e.body[0])}interpretField(e){var h,T,f,N;const s=e.callee.op.value,{leftExpression:n,rightExpression:i}=e.callee,r=Ce(n),a=Ce(i);if(Dt(r,a))return[new u(o.SAME_ENDPOINT,"Two endpoints are the same",e)];const l=Ot(r,a);if(this.env.refIds[l])return[new u(o.CIRCULAR_REF,"References with same endpoints exist",this.declarationNode),new u(o.CIRCULAR_REF,"References with same endpoints exist",this.env.refIds[l])];if(e.args[0]){const g=z(e.args[0]).getValue();this.ref.onDelete=G((T=(h=g.delete)==null?void 0:h.at(0))==null?void 0:T.value).unwrap_or(void 0),this.ref.onDelete=G((N=(f=g.delete)==null?void 0:f.at(0))==null?void 0:N.value).unwrap_or(void 0)}const p=St(s);return this.ref.endpoints=[{...pt(n,this.container),relation:p[0],token:k(n)},{...pt(i,this.container),relation:p[1],token:k(i)}],this.env.refIds[l]=this.declarationNode,[]}}class Rt{constructor(e,s){this.declarationNode=e,this.env=s,this.table={name:void 0,schemaName:void 0,alias:null,fields:[],token:void 0,indexes:[]},this.pkColumns=[]}interpret(){this.table.token=k(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:s})=>({value:s,type:"column"})),token:{start:{offset:-1,line:-1,column:-1},end:{offset:-1,line:-1,column:-1}},pk:!0}),this.pkColumns.forEach(s=>s.pk=!1)),e}interpretName(e){const{name:s,schemaName:n}=Ae(e);return n.length>1?(this.table.name=s,this.table.schemaName=n.join("."),[new u(o.UNSUPPORTED,"Nested schema is not supported",e)]):(this.table.name=s,this.table.schemaName=n.length?n[0]:null,[])}interpretAlias(e){if(!e)return[];const s=V(e).unwrap_or(null);return s&&(this.env.aliases.push({name:s,kind:"table",value:{tableName:this.table.name,schemaName:this.table.schemaName}}),this.table.alias=s),[]}interpretSettingList(e){var r,a,l;const s=z(e).getValue();this.table.headerColor=(r=s.headercolor)!=null&&r.length?Wn((l=(a=s.headercolor)==null?void 0:a.at(0))==null?void 0:l.value):void 0;const[n]=s.note||[],i=Y(n==null?void 0:n.value).unwrap_or(void 0);return this.table.note=n&&{value:i,token:k(n)},[]}interpretBody(e){const[s,n]=I.partition(e.body,i=>i instanceof x);return[...this.interpretFields(s),...this.interpretSubElements(n)]}interpretSubElements(e){return e.flatMap(s=>{var n;switch((n=s.type)==null?void 0:n.value.toLowerCase()){case"note":return this.table.note={value:Y(s.body instanceof ee?s.body.body[0].callee:s.body.callee).unwrap(),token:k(s)},[];case"indexes":return this.interpretIndexes(s);case"ref":return new Ke(s,this.env).interpret()}return[]})}interpretFields(e){return e.flatMap(s=>this.interpretColumn(s))}interpretColumn(e){var a,l,p,h,T,f,N,g;const s=[],n={};n.name=V(e.callee).unwrap();const i=jn(e.args[0]);n.type=i.getValue(),s.push(...i.getErrors()),n.token=k(e),n.inline_refs=[];const r=e.args.slice(1);if(I.last(r)instanceof U){const v=z(r.pop()).getValue();n.pk=!!((a=v.pk)!=null&&a.length)||!!((l=v["primary key"])!=null&&l.length),n.increment=!!((p=v.increment)!=null&&p.length),n.unique=!!((h=v.unique)!=null&&h.length),n.not_null=!!((T=v["not null"])!=null&&T.length)&&!0,n.dbdefault=Yn((N=(f=v.default)==null?void 0:f.at(0))==null?void 0:N.value);const Ne=(g=v.note)==null?void 0:g.at(0);n.note=Ne&&{value:Y(Ne.value).unwrap(),token:k(Ne)};const me=v.ref||[];n.inline_refs=me.flatMap(j=>{const[nt]=Ce(j.value.expression);if(Dt(nt,e.symbol))return s.push(new u(o.SAME_ENDPOINT,"Two endpoints are the same",j)),[];const ve=j.value.op,Z=W(j.value.expression).unwrap();let ce;if(Z.length===1){const[ae]=Z;ce={schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[ae],relation:ve.value,token:k(j)}}else if(Z.length===2){const[ae,Te]=Z;ce={schemaName:null,tableName:ae,fieldNames:[Te],relation:ve.value,token:k(j)}}else if(Z.length===3){const[ae,Te,it]=Z;ce={schemaName:ae,tableName:Te,fieldNames:[it],relation:ve.value,token:k(j)}}else{s.push(new u(o.UNSUPPORTED,"Nested schema is not supported",j));const ae=Z.pop(),Te=Z.pop();ce={schemaName:Z.join("."),tableName:Te,fieldNames:[ae],relation:ve.value,token:k(j)}}const st=this.registerInlineRefToEnv(e,nt,ce,j);return s.push(...st),st.length===0?ce:[]})}return n.pk||(n.pk=r.some(v=>G(v).unwrap().toLowerCase()==="pk")),n.unique||(n.unique=r.some(v=>G(v).unwrap().toLowerCase()==="unique")),this.table.fields.push(n),n.pk&&this.pkColumns.push(n),s}interpretIndexes(e){return this.table.indexes.push(...e.body.body.map(s=>{var a,l,p,h,T,f,N;const n={columns:[]},i=s;n.token=k(e);const r=[i.callee,...i.args];if(I.last(r)instanceof U){const g=z(r.pop()).getValue();n.pk=!!((a=g.pk)!=null&&a.length),n.unique=!!((l=g.unique)!=null&&l.length),n.name=Y((h=(p=g.name)==null?void 0:p.at(0))==null?void 0:h.value).unwrap_or(void 0);const v=(T=g.note)==null?void 0:T.at(0);n.note=v&&{value:Y(v.value).unwrap(),token:k(v)},n.type=G((N=(f=g.type)==null?void 0:f.at(0))==null?void 0:N.value).unwrap_or(void 0)}return r.flatMap(g=>{if(!(g instanceof H))return g;const v=[];for(;g instanceof H;)v.push(g.argumentList),g=g.callee;return v.push(g),v}).forEach(g=>{const{functional:v,nonFunctional:Ne}=Ge(g).unwrap();n.columns.push(...v.map(me=>({value:me.value.value,type:"expression"})),...Ne.map(me=>({value:V(me).unwrap(),type:"column"})))}),n})),[]}registerInlineRefToEnv(e,s,n,i){const r=Ot(e.symbol,s);if(this.env.refIds[r])return[new u(o.CIRCULAR_REF,"References with same endpoints exist",i),new u(o.CIRCULAR_REF,"References with same endpoints exist",this.env.refIds[r])];const a=St(n.relation);return this.env.refIds[r]=i,this.env.ref.set(i,{name:null,schemaName:null,token:n.token,endpoints:[{schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[G(e.callee).unwrap()],token:k(e),relation:a[0]},{...n,relation:a[1]}]}),[]}}function jn(t){let e=null;t instanceof H&&(e=t.argumentList.elementList.map(r=>le(r)?r.expression.literal.value:$(r)?Y(r).unwrap():G(r).unwrap()).join(","),t=t.callee);let s="";for(;t instanceof he;)s=`[${t.indexer.elementList.map(r=>r.name.expression.literal.value).join(",")}]${s}`,t=t.array;const{name:n,schemaName:i}=Ae(t);return i.length>1&&new F({schemaName:i.length===0?null:i[0],type_name:`${n}${s}${e?`(${e})`:""}`,args:e},[new u(o.UNSUPPORTED,"Nested schema is not supported",t)]),new F({schemaName:i.length===0?null:i[0],type_name:`${n}${s}${e?`(${e})`:""}`,args:e})}function Yn(t){var e,s,n;if(t){if($(t))return{value:Y(t).unwrap(),type:"string"};if(le(t))return{type:"number",value:Number.parseFloat(t.expression.literal.value)};if(fe(t))return{value:t.expression.variable.value.toLowerCase(),type:"boolean"};if(t instanceof q&&wt.includes((e=t.op)==null?void 0:e.value)&&le(t.expression)){const i=Number.parseFloat(t.expression.expression.literal.value);return{value:((s=t.op)==null?void 0:s.value)==="-"?0-i:i,type:"number"}}if(t instanceof K)return{value:(n=t.value)==null?void 0:n.value,type:"expression"};throw new Error("Unreachable")}}class Pt{constructor(e,s){this.declarationNode=e,this.env=s,this.tableGroup={tables:[]}}interpret(){const e=[];this.tableGroup.token=k(this.declarationNode),this.env.tableGroups.set(this.declarationNode,this.tableGroup);const{name:s,schemaName:n}=Ae(this.declarationNode.name);return n.length>=2&&(this.tableGroup.name=s,this.tableGroup.schemaName=n.join("."),e.push(new u(o.UNSUPPORTED,"Nested schema is not supported",this.declarationNode.name))),this.tableGroup.name=s,this.tableGroup.schemaName=n[0]||null,this.tableGroup.tables=this.declarationNode.body.body.map(i=>{const r=W(i.callee).unwrap();return r.length>2&&e.push(new u(o.UNSUPPORTED,"Nested schema is not supported",i)),{name:r.pop(),schemaName:r.join(".")}}),e}}class Ut{constructor(e,s){this.declarationNode=e,this.env=s,this.enum={values:[]}}interpret(){return this.enum.token=k(this.declarationNode),this.env.enums.set(this.declarationNode,this.enum),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(e){const{name:s,schemaName:n}=Ae(e);return n.length>1?(this.enum.name=s,this.enum.schemaName=n.join("."),[new u(o.UNSUPPORTED,"Nested schema is not supported",e)]):(this.enum.name=s,this.enum.schemaName=n.length?n[0]:null,[])}interpretBody(e){return e.body.flatMap(s=>{var l;const n=s,i={};i.token=k(n),i.name=G(n.callee).unwrap();const a=(l=z(n.args[0]).getValue().note)==null?void 0:l.at(0);return i.note=a&&{value:Y(a.value).unwrap(),token:k(a)},this.enum.values.push(i),[]})}}class zn{constructor(e,s){this.declarationNode=e,this.env=s,this.project={enums:[],refs:[],tableGroups:[],tables:[]}}interpret(){return this.env.project.set(this.declarationNode,this.project),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(e){if(!e)return this.project.name=null,[];const{name:s}=Ae(e);return this.project.name=s,[]}interpretBody(e){return e.body.flatMap(s=>{var i;const n=s;switch((i=n.type)==null?void 0:i.value.toLowerCase()){case"table":{const r=new Rt(n,this.env).interpret();return this.project.tables.push(this.env.tables.get(n)),r}case"ref":{const r=new Ke(n,this.env).interpret();return this.project.refs.push(this.env.ref.get(n)),r}case"tablegroup":{const r=new Pt(n,this.env).interpret();return this.project.tableGroups.push(this.env.tableGroups.get(n)),r}case"enum":{const r=new Ut(n,this.env).interpret();return this.project.enums.push(this.env.enums.get(n)),r}case"note":return this.project.note={value:Y(n.body instanceof ee?n.body.body[0].callee:n.body.callee).unwrap(),token:k(n)},[];default:return this.project[n.type.value.toLowerCase()]=Y(n.body.callee).unwrap(),[]}})}}class qn{constructor(e){this.ast=e,this.env={schema:[],tables:new Map,refIds:{},ref:new Map,enums:new Map,tableGroups:new Map,aliases:[],project:new Map}}interpret(){const e=this.ast.body.flatMap(s=>{switch(de(s).unwrap_or(void 0)){case b.Table:return new Rt(s,this.env).interpret();case b.Ref:return new Ke(s,this.env).interpret();case b.TableGroup:return new Pt(s,this.env).interpret();case b.Enum:return new Ut(s,this.env).interpret();case b.Project:return new zn(s,this.env).interpret();default:return[]}});return new F(Qn(this.env),e)}}function Qn(t){return{schemas:[],tables:Array.from(t.tables.values()),refs:Array.from(t.ref.values()),enums:Array.from(t.enums.values()),tableGroups:Array.from(t.tableGroups.values()),aliases:t.aliases,project:Array.from(t.project.values())[0]||{}}}var L=(t=>(t[t.Function=1]="Function",t[t.Constructor=2]="Constructor",t[t.Field=3]="Field",t[t.Variable=4]="Variable",t[t.Class=5]="Class",t[t.Struct=6]="Struct",t[t.Interface=7]="Interface",t[t.Module=8]="Module",t[t.Property=9]="Property",t[t.Event=10]="Event",t[t.Operator=11]="Operator",t[t.Unit=12]="Unit",t[t.Value=13]="Value",t[t.Constant=14]="Constant",t[t.Enum=15]="Enum",t[t.EnumMember=16]="EnumMember",t[t.Keyword=17]="Keyword",t[t.Text=18]="Text",t[t.Color=19]="Color",t[t.File=20]="File",t[t.Reference=21]="Reference",t[t.Customcolor=22]="Customcolor",t[t.Folder=23]="Folder",t[t.TypeParameter=24]="TypeParameter",t[t.User=25]="User",t[t.Issue=26]="Issue",t[t.Snippet=27]="Snippet",t))(L||{}),w=(t=>(t[t.None=0]="None",t[t.KeepWhitespace=1]="KeepWhitespace",t[t.InsertAsSnippet=4]="InsertAsSnippet",t))(w||{});function ge(t){switch(t){case m.Schema:return L.Module;case m.Table:return L.Class;case m.Column:return L.Field;case m.Enum:return L.Enum;case m.EnumField:return L.EnumMember;case m.TableGroup:return L.Struct;case m.TableGroupField:return L.Field;default:return L.Text}}function Se(t,e){if(!t||Ve(t))return!1;for(const s of t.trailingTrivia){if(s.start>e)break;if(s.kind===c.NEWLINE&&s.end<=e)return!1}return!0}function O(){return{suggestions:[]}}function Oe(t){return{...t,suggestions:t.suggestions.map(e=>({...e,insertText:` ${e.insertText}`}))}}function Ue(t){return{...t,suggestions:t.suggestions.map(e=>({...e,insertText:e.insertText.search(/[^a-zA-Z\d_]/)!==-1||e.insertText[0].match(/\d/)?`"${e.insertText}"`:e.insertText}))}}function et(t,e){return t.getOffsetAt(e)}class Mt{constructor(e,s=[]){this.compiler=e,this.triggerCharacters=s}provideCompletionItems(e,s){var T,f;const n=et(e,s),i=this.compiler.token.flatStream(),{token:r,index:a}=this.compiler.container.token(n),l=a===void 0?i[0]:i[a+1];if([...(r==null?void 0:r.trailingTrivia)||[],...(r==null?void 0:r.leadingTrivia)||[],...(l==null?void 0:l.leadingTrivia)||[]].find(N=>$t(N)&&Ie(n,N)))return O();if(a===void 0)return Tt();if([c.STRING_LITERAL,c.QUOTED_STRING].includes(r.kind)&&Ie(n,r))return O();const p=this.compiler.container.element(n);if(this.compiler.container.scopeKind(n)===D.TOPLEVEL||p instanceof _&&p.type&&p.type.start<=n&&p.type.end>=n)return Tt();const h=[...this.compiler.container.stack(n)].reverse();for(const N of h)if(N instanceof q)switch((T=N.op)==null?void 0:T.value){case">":case"<":case"<>":case"-":return dt(this.compiler,n,N)}else if(N instanceof Q)switch((f=N.op)==null?void 0:f.value){case">":case"<":case"<>":case"-":return dt(this.compiler,n,N);case".":return Ft(this.compiler,n,N)}else{if(N instanceof ne)return Et(this.compiler,n,N);if(N instanceof U)return Et(this.compiler,n,N);if(N instanceof J)return Hn(this.compiler,n);if(N instanceof x)return mt(this.compiler,n,N);if(N instanceof _&&(N.bodyColon&&n>=N.bodyColon.end||N.body&&Ie(n,N.body)))return mt(this.compiler,n,void 0)}return O()}}function dt(t,e,s){const n=t.container.scopeKind(e);if([D.REF,D.TABLE].includes(n)){const i=Me(t,e,t.container.element(e),[m.Table,m.Schema,m.Column]);return Se(s.op,e)?Oe(i):i}return O()}function Me(t,e,s,n){var a;if(s===void 0)return O();let i=s;const r={suggestions:[]};for(;i;){if((a=i==null?void 0:i.symbol)!=null&&a.symbolTable){const{symbol:l}=i;r.suggestions.push(...t.symbol.members(l).filter(({kind:p})=>n.includes(p)).map(({name:p,kind:h})=>({label:p,insertText:p,insertTextRules:w.KeepWhitespace,kind:ge(h),sortText:ge(h).toString().padStart(2,"0"),range:void 0})))}i=i instanceof _?i.parent:void 0}return Ue(r)}function Hn(t,e){var n;switch(t.container.scopeKind(e)){case D.INDEXES:return Vt(t,e);case D.REF:{const i=[...t.container.stack(e)];for(;i.length>0;){const r=i.pop();if(r instanceof Q&&((n=r.op)==null?void 0:n.value)===".")return Ft(t,e,r)}}return Bt(t,e)}return O()}function Et(t,e,s){const{token:n}=t.container.token(e);if([c.COMMA,c.LBRACKET].includes(n==null?void 0:n.kind)){const i=Nt(t,e);return(n==null?void 0:n.kind)===c.COMMA&&Se(n,e)?Oe(i):i}if(s.name&&s.name.start<=e&&s.name.end>=e)return Nt(t,e);if(s.name){const i=Jn(t,e,Re(s.name).unwrap());return(n==null?void 0:n.kind)===c.COLON&&Se(n,e)?Oe(i):i}return O()}function Nt(t,e){const s=t.container.element(e),n=t.container.scopeKind(e);if(s instanceof C)return O();if(s.body&&!Ie(e,s.body))switch(n){case D.TABLE:return{suggestions:[{label:"headercolor",insertText:"headercolor: ",kind:L.Field,insertTextRules:w.KeepWhitespace,range:void 0},{label:"note",insertText:"note: ",kind:L.Field,insertTextRules:w.KeepWhitespace,range:void 0}]};default:return O()}switch(n){case D.TABLE:return{suggestions:[...["primary key","null","not null","increment","pk","unique"].map(i=>({label:i,insertText:i,kind:L.Property,insertTextRules:w.KeepWhitespace,range:void 0})),...["ref","default"].map(i=>({label:i,insertText:`${i}: `,kind:L.Property,insertTextRules:w.KeepWhitespace,range:void 0})),{label:"note",insertText:"note: ",kind:L.Property,insertTextRules:w.KeepWhitespace,range:void 0}]};case D.ENUM:return{suggestions:[{label:"note",insertText:"note: ",kind:L.Property,insertTextRules:w.KeepWhitespace,range:void 0}]};case D.INDEXES:return{suggestions:[...["unique","pk"].map(i=>({label:i,insertText:i,insertTextRules:w.KeepWhitespace,kind:L.Property,range:void 0})),...["note","name","type"].map(i=>({label:i,insertText:`${i}: `,kind:L.Property,insertTextRules:w.KeepWhitespace,range:void 0}))]};case D.REF:return{suggestions:["update","delete"].map(i=>({label:i,insertText:`${i}: `,kind:L.Property,insertTextRules:w.KeepWhitespace,range:void 0}))}}return O()}function Jn(t,e,s){switch(s==null?void 0:s.toLowerCase()){case"update":case"delete":return{suggestions:["cascade","set default","set null","restrict"].map(n=>({label:n,insertText:n,kind:L.Value,insertTextRules:w.KeepWhitespace,range:void 0}))};case"type":return{suggestions:["btree","hash"].map(n=>({label:n,insertText:`${n}`,kind:L.Value,insertTextRules:w.KeepWhitespace,range:void 0}))}}return O()}function Ft(t,e,s){const n=Ee(s).unwrap_or([]);if(n.pop(),n.some(r=>!M(r)))return O();const i=n.map(r=>G(r).unwrap());return Ue({suggestions:t.symbol.ofName({nameStack:i,owner:t.container.element(e)}).flatMap(({symbol:r})=>t.symbol.members(r)).map(({kind:r,name:a})=>({label:a,insertText:a,kind:ge(r),range:void 0}))})}function mt(t,e,s){var i;switch(t.container.scopeKind(e)){case D.TABLE:return Kn(t,e,s);case D.PROJECT:return es(t,e,s);case D.INDEXES:return ns(t,e);case D.ENUM:return Zn(t,e,s);case D.REF:{const r=Bt(t,e);return((i=t.container.token(e).token)==null?void 0:i.kind)===c.COLON&&Se(t.container.token(e).token,e)?Oe(r):r}case D.TABLEGROUP:return ts(t);default:return O()}}function Tt(){return{suggestions:["Table","TableGroup","Enum","Project","Ref"].map(t=>({label:t,insertText:t,insertTextRules:w.KeepWhitespace,kind:L.Keyword,range:void 0}))}}function Zn(t,e,s){return s!=null&&s.callee&&tt(e,s)===1?Me(t,e,t.container.element(e),[m.Schema,m.Table,m.Column]):O()}function Kn(t,e,s){if(!(s!=null&&s.callee))return{suggestions:["Ref","Note","indexes"].map(i=>({label:i,insertText:i,insertTextRules:w.KeepWhitespace,kind:L.Keyword,range:void 0}))};const n=tt(e,s);return n===0?{suggestions:["Ref","Note","indexes"].map(i=>({label:i,insertText:i,insertTextRules:w.KeepWhitespace,kind:L.Keyword,range:void 0}))}:n===1?ss(t,e):O()}function es(t,e,s){return s!=null&&s.callee?tt(e,s)===0?{suggestions:["Table","TableGroup","Enum","Note","Ref"].map(i=>({label:i,insertText:i,insertTextRules:w.KeepWhitespace,kind:L.Keyword,range:void 0}))}:O():{suggestions:["Table","TableGroup","Enum","Note","Ref"].map(i=>({label:i,insertText:i,insertTextRules:w.KeepWhitespace,kind:L.Keyword,range:void 0}))}}function Bt(t,e){return Me(t,e,t.container.element(e),[m.Schema,m.Table,m.Column])}function ts(t){return Ue({suggestions:[...t.parse.publicSymbolTable().entries()].flatMap(([e])=>{const s=se(e).unwrap_or(void 0);if(s===void 0)return[];const{kind:n,name:i}=s;return n!==m.Table&&n!==m.Schema?[]:{label:i,insertText:i,insertTextRules:w.KeepWhitespace,kind:ge(n),range:void 0}})})}function ns(t,e){return Vt(t,e)}function ss(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(s=>({label:s,insertText:s,insertTextRules:w.KeepWhitespace,kind:L.TypeParameter,sortText:L.TypeParameter.toString().padStart(2,"0"),range:void 0})),...Me(t,e,t.container.element(e),[m.Enum,m.Schema]).suggestions]}}function Vt(t,e){const n=t.container.element(e).parent;if(!((n==null?void 0:n.symbol)instanceof At))return O();const{symbolTable:i}=n.symbol;return Ue({suggestions:[...i.entries()].flatMap(([r])=>{const a=se(r).unwrap_or(void 0);if(a===void 0)return[];const{name:l}=a;return{label:l,insertText:l,insertTextRules:w.KeepWhitespace,kind:ge(m.Column),range:void 0}})})}function tt(t,e){if(!e.callee)return-1;const s=[e.callee,...e.args],n=s.findIndex(i=>t<=i.end);return n===-1?s.length:n}class Gt{constructor(e){this.compiler=e}provideDefinition(e,s){var a;const{uri:n}=e,i=et(e,s),r=[...this.compiler.container.stack(i)];for(;r.length!==0;){const l=r.pop();if((a=l==null?void 0:l.referee)!=null&&a.declaration&&[ue.PRIMARY_EXPRESSION,ue.VARIABLE].includes(l==null?void 0:l.kind)){const{startPos:p,endPos:h}=l.referee.declaration;return[{range:{startColumn:p.column+1,startLineNumber:p.line+1,endColumn:h.column+1,endLineNumber:h.line+1},uri:n}]}}return[]}}class Ct{constructor(e){this.compiler=e}provideReferences(e,s){const{uri:n}=e,i=et(e,s),r=[...this.compiler.container.stack(i)];for(;r.length!==0;){const a=r.pop();if(a&&[ue.ELEMENT_DECLARATION,ue.FUNCTION_APPLICATION,ue.PRIMARY_EXPRESSION].includes(a==null?void 0:a.kind)){const{symbol:l}=a;if(l!=null&&l.references.length)return l.references.map(({startPos:p,endPos:h})=>({range:{startColumn:p.column+1,startLineNumber:p.line+1,endColumn:h.column+1,endLineNumber:h.line+1},uri:n}))}}return[]}}const is=Object.freeze(Object.defineProperty({__proto__:null,CompletionItemInsertTextRule:w,CompletionItemKind:L,DBMLCompletionItemProvider:Mt,DBMLDefinitionProvider:Gt,DBMLReferencesProvider:Ct},Symbol.toStringTag,{value:"Module"}));var D=(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))(D||{});class rs{constructor(){this.source="",this.cache=new Array(16).fill(null),this.nodeIdGenerator=new Wt,this.symbolIdGenerator=new Qt,this.token={invalidStream:this.createQuery(6,()=>this.parse.tokens().filter(vt)),flatStream:this.createQuery(7,()=>this.parse.tokens().flatMap(e=>[...e.leadingInvalid,e,...e.trailingInvalid]))},this.parse={source:()=>this.source,_:this.createQuery(0,()=>{const e=new an(this.source).lex().chain(s=>new cn(s,this.nodeIdGenerator).parse()).chain(({ast:s,tokens:n})=>new $n(s,this.symbolIdGenerator).analyze().map(()=>({ast:s,tokens:n})));return e.getErrors().length>0?e:e.chain(({ast:s,tokens:n})=>new qn(s).interpret().map(r=>({ast:s,tokens:n,rawDb:r})))}),ast:this.createQuery(1,()=>this.parse._().getValue().ast),errors:this.createQuery(2,()=>this.parse._().getErrors()),tokens:this.createQuery(4,()=>this.parse._().getValue().tokens),rawDb:this.createQuery(3,()=>this.parse._().getValue().rawDb),publicSymbolTable:this.createQuery(5,()=>this.parse._().getValue().ast.symbol.symbolTable)},this.container={stack:this.createQuery(10,e=>{const s=this.parse.tokens();let{index:n}=this.container.token(e);const{token:i}=this.container.token(e);if(n===void 0)return[this.parse.ast()];for(;s[n].isInvalid&&n>=0;)n-=1;if(n===-1)return[this.parse.ast()];const r=s[n].start;let a=this.parse.ast();const l=[a];for(;;){const h=rn(a).find(T=>Ie(r,T));if(h===void 0||h instanceof B)break;l.push(h),a=h}if((i==null?void 0:i.kind)===c.COLON)return l;for(;l.length>0;){let p=!1;const h=I.last(l);if(h instanceof x){const T=this.parse.source();for(let f=h.end;f<e;f+=1)T[f]===`
|
|
8
|
-
`&&(l.pop(),p=!0)}else h instanceof q||h instanceof Q?this.container.token(e).token!==h.op&&(l.pop(),p=!0):h instanceof U?h.listCloseBracket&&h.end<=e&&(l.pop(),p=!0):h instanceof J?h.tupleCloseParen&&h.end<=e&&(l.pop(),p=!0):h instanceof ee?h.blockCloseBrace&&h.end<=e&&(l.pop(),p=!0):h instanceof te||h.end<e&&(l.pop(),p=!0);if(p){const T=I.last(l);T instanceof _&&T.end<=e&&l.pop()}if(!p)break}return l}),token:this.createQuery(11,e=>{const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I=require("lodash");var u=(t=>(t.SPACE="<space>",t.TAB="<tab>",t.NEWLINE="<newline>",t.COMMA="<comma>",t.LPAREN="<lparen>",t.RPAREN="<rparen>",t.LBRACE="<lbrace>",t.RBRACE="<rbrace>",t.LBRACKET="<lbracket>",t.RBRACKET="<rbracket>",t.LANGLE="<langle>",t.RANGLE="<rangle>",t.OP="<op>",t.EOF="<eof>",t.NUMERIC_LITERAL="<number>",t.STRING_LITERAL="<string>",t.COLOR_LITERAL="<color>",t.FUNCTION_EXPRESSION="<function-expression>",t.QUOTED_STRING="<variable>",t.IDENTIFIER="<identifier>",t.SEMICOLON="<semicolon>",t.COLON="<colon>",t.SINGLE_LINE_COMMENT="<single-line-comment>",t.MULTILINE_COMMENT="<multiline-comment>",t))(u||{});function $t(t){switch(t.kind){case"<newline>":case"<space>":case"<tab>":case"<single-line-comment>":case"<multiline-comment>":return!0;default:return!1}}function rt(t){if(!t)return!1;switch(t){case"+":case"-":case"*":case"/":case"%":case"<":case">":case"=":case"!":case".":case"&":case"|":return!0;default:return!1}}function at(t){return t!==void 0&&t.kind==="<op>"}class V{constructor(e,n,s,i,r){this.kind=e,this.startPos=n,this.endPos=s,this.value=i,this.leadingTrivia=[],this.trailingTrivia=[],this.leadingInvalid=[],this.trailingInvalid=[],this.isInvalid=r,this.start=n.offset,this.end=s.offset}static create(e,n,s,i,r){return new V(e,n,s,i,r)}}function bt(t){return t.trailingTrivia.find(({kind:e})=>e===u.NEWLINE)!==void 0}function ot(t,e){return e.leadingTrivia.find(({kind:s})=>s===u.NEWLINE)!==void 0||bt(t)}function Ve(t){return t.trailingTrivia.find(({kind:e})=>e===u.SPACE)!==void 0}function It(t){return t.trailingTrivia.length===0?t.end:It(I.last(t.trailingTrivia))}function Lt(t){return t.leadingTrivia.length===0?t.start:Lt(t.leadingTrivia[0])}function Wt(t){return[u.SINGLE_LINE_COMMENT,u.MULTILINE_COMMENT].includes(t.kind)}class jt{constructor(){this.id=0}reset(){this.id=0}nextId(){return this.id++}}class k{constructor(e,n,s){this.id=e,this.kind=n;const i=s.find(a=>a!==void 0&&!Number.isNaN(a.start));i?(this.startPos=i.startPos,this.fullStart=i instanceof V?Lt(i):i.fullStart):(this.startPos={offset:NaN,column:NaN,line:NaN},this.fullStart=NaN);const r=[...s].reverse().find(a=>a!==void 0&&!Number.isNaN(a.end));r?(this.endPos=r.endPos,this.fullEnd=r instanceof V?It(r):r.fullEnd):(this.endPos={offset:NaN,column:NaN,line:NaN},this.fullEnd=NaN),this.start=this.startPos.offset,this.end=this.endPos.offset}}var ue=(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))(ue||{});class F extends k{constructor({body:e=[],eof:n},s){super(s,"<program>",[...e,n]),this.body=e,this.eof=n}}class _ extends k{constructor({type:e,name:n,as:s,alias:i,attributeList:r,bodyColon:a,body:l},p){if(super(p,"<element-declaration>",[e,n,s,i,r,a,l]),l&&a&&!(l instanceof v||l instanceof _))throw new Error("If an element has a simple body, it must be a function application node");this.type=e,this.name=n,this.as=s,this.alias=i,this.attributeList=r,this.bodyColon=a,this.body=l}}class te extends k{constructor({identifiers:e=[]},n){super(n,"<identifer-stream>",e||[]),this.identifiers=e}}class ne extends k{constructor({name:e,colon:n,value:s},i){super(i,"<attribute>",[e,n,s]),this.name=e,this.value=s,this.colon=n}}class q extends k{constructor({op:e,expression:n},s){super(s,"<prefix-expression>",[e,n]),this.op=e,this.expression=n}}class Q extends k{constructor({op:e,leftExpression:n,rightExpression:s},i){super(i,"<infix-expression>",[n,e,s]),this.op=e,this.leftExpression=n,this.rightExpression=s}}class De extends k{constructor({op:e,expression:n},s){super(s,"<postfix-expression>",[n,e]),this.op=e,this.expression=n}}class K extends k{constructor({value:e},n){super(n,"<function-expression>",[e]),this.value=e}}class v extends k{constructor({callee:e,args:n=[]},s){super(s,"<function-application>",[e,...n]),this.callee=e,this.args=n}}class ee extends k{constructor({blockOpenBrace:e,body:n=[],blockCloseBrace:s},i){super(i,"<block-expression>",[e,...n,s]),this.blockOpenBrace=e,this.body=n,this.blockCloseBrace=s}}class U extends k{constructor({listOpenBracket:e,elementList:n=[],commaList:s=[],listCloseBracket:i},r){super(r,"<list-expression>",[e,...gt(n,s),i]),this.listOpenBracket=e,this.elementList=n,this.commaList=s,this.listCloseBracket=i}}class J extends k{constructor({tupleOpenParen:e,elementList:n=[],commaList:s=[],tupleCloseParen:i},r){super(r,"<tuple-expression>",[e,...gt(n,s),i]),this.tupleOpenParen=e,this.elementList=n,this.commaList=s,this.tupleCloseParen=i}}class Xe extends J{constructor({groupOpenParen:e,expression:n,groupCloseParen:s},i){super({tupleOpenParen:e,elementList:n&&[n],commaList:[],tupleCloseParen:s},i),this.kind="<group-expression>"}}class H extends k{constructor({callee:e,argumentList:n},s){super(s,"<call-expression>",[e,n]),this.callee=e,this.argumentList=n}}class pe extends k{constructor({literal:e},n){super(n,"<literal>",[e]),this.literal=e}}class W extends k{constructor({variable:e},n){super(n,"<variable>",[e]),this.variable=e}}class R extends k{constructor({expression:e},n){super(n,"<primary-expression>",[e]),this.expression=e}}class we extends k{constructor({pre:e},n){const s=V.create(u.SPACE,e.endPos,e.endPos," ",!1);super(n,"<dummy>",[s])}}class he extends k{constructor({expression:e,indexer:n},s){super(s,"<array>",[e,n]),this.array=e,this.indexer=n}}function gt(t,e){if(!t||t.length===0)return e||[];if(!e||e.length===0)return t||[];const[n]=t,[s]=e;return(n.start<s.start?I.flatten(I.zip(t,e)):I.flatten(I.zip(e,t))).filter(i=>i!==null)}function Yt(t,e=!1){return JSON.stringify(t,function(n,s){var i;return!(this instanceof F)&&n==="symbol"?s==null?void 0:s.id:n==="symbol"?{symbolTable:s==null?void 0:s.symbolTable,id:s==null?void 0:s.id,references:s==null?void 0:s.references.map(r=>r.id),declaration:(i=s==null?void 0:s.declaration)==null?void 0:i.id}:n==="referee"||n==="parent"||n==="declaration"?s==null?void 0:s.id:n==="symbolTable"?Object.fromEntries(s.table):s},e?2:0)}class S{constructor(e){this.value=e}unwrap(){return this.value}unwrap_or(e){return this.value}and_then(e){return e(this.value)}map(e){return new S(e(this.value))}isOk(){return!0}}class A{unwrap(){throw new Error("Trying to unwrap a None value")}unwrap_or(e){return e}and_then(e){return new A}map(e){return new A}isOk(){return!1}}var m=(t=>(t.Schema="Schema",t.Table="Table",t.Column="Column",t.TableGroup="TableGroup",t.TableGroupField="TableGroup field",t.Enum="Enum",t.EnumField="Enum field",t.Note="Note",t))(m||{});function $e(t){return`Schema:${t}`}function ke(t){return`Table:${t}`}function We(t){return`Column:${t}`}function je(t){return`Enum:${t}`}function Ye(t){return`Enum field:${t}`}function ze(t){return`TableGroup:${t}`}function qe(t){return`TableGroup field:${t}`}function zt(t){return`Note:${t}`}function Fe(t,e){switch(e){case"Column":return We(t);case"Enum":return je(t);case"Enum field":return Ye(t);case"Schema":return $e(t);case"Table":return ke(t);case"TableGroup":return ze(t);case"TableGroup field":return qe(t);default:throw new Error("Unreachable")}}function se(t){const[e,n]=t.split(":");return Object.values(m).includes(e)?new S({name:n,kind:e}):new A}function qt(t){const e=se(t).unwrap_or(void 0);if(!e)return!1;const{kind:n,name:s}=e;return n==="Schema"&&s==="public"}function Qt(t){return[$e,ke,je,ze,We,Ye,qe].map(e=>e(t))}function Qe(t){const[e]=t;return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"}function xe(t){const[e]=t;return e>="0"&&e<="9"}function Ht(t){const[e]=t;return xe(e)||Qe(e)&&e.toLowerCase()>="a"&&e.toLowerCase()<="f"}function Ie(t){return Qe(t)||xe(t)}function lt(t,e){const n=[],s=Math.min(t.length,e.length);for(let i=0;i<s;i+=1)n.push(t[i],e[i]);return n.push(...t.slice(s),...e.slice(s)),n}function Le(t,e){return t>=e.start&&t<e.end}class Jt{constructor(){this.id=0}reset(){this.id=0}nextId(){return this.id++}}class _t{constructor({symbolTable:e},n){this.references=[],this.id=n,this.symbolTable=e}}class Zt{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class Kt{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}class At{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class en{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}class tn{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class nn{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}var o=(t=>(t[t.UNKNOWN_SYMBOL=1e3]="UNKNOWN_SYMBOL",t[t.UNEXPECTED_SYMBOL=1001]="UNEXPECTED_SYMBOL",t[t.UNEXPECTED_EOF=1002]="UNEXPECTED_EOF",t[t.UNEXPECTED_NEWLINE=1003]="UNEXPECTED_NEWLINE",t[t.UNKNOWN_TOKEN=1004]="UNKNOWN_TOKEN",t[t.UNEXPECTED_TOKEN=1005]="UNEXPECTED_TOKEN",t[t.UNEXPECTED_ELEMENT_DECLARATION=1006]="UNEXPECTED_ELEMENT_DECLARATION",t[t.MISSING_SPACES=1007]="MISSING_SPACES",t[t.UNKNOWN_PREFIX_OP=1008]="UNKNOWN_PREFIX_OP",t[t.INVALID_OPERAND=1009]="INVALID_OPERAND",t[t.EMPTY_ATTRIBUTE_NAME=1010]="EMPTY_ATTRIBUTE_NAME",t[t.INVALID_NAME=3e3]="INVALID_NAME",t[t.UNEXPECTED_NAME=3001]="UNEXPECTED_NAME",t[t.NAME_NOT_FOUND=3002]="NAME_NOT_FOUND",t[t.DUPLICATE_NAME=3003]="DUPLICATE_NAME",t[t.INVALID_ALIAS=3004]="INVALID_ALIAS",t[t.UNEXPECTED_ALIAS=3005]="UNEXPECTED_ALIAS",t[t.UNEXPECTED_SETTINGS=3006]="UNEXPECTED_SETTINGS",t[t.INVALID_SETTINGS=3007]="INVALID_SETTINGS",t[t.UNEXPECTED_SIMPLE_BODY=3008]="UNEXPECTED_SIMPLE_BODY",t[t.UNEXPECTED_COMPLEX_BODY=3009]="UNEXPECTED_COMPLEX_BODY",t[t.INVALID_TABLE_CONTEXT=3010]="INVALID_TABLE_CONTEXT",t[t.INVALID_TABLE_SETTING=3011]="INVALID_TABLE_SETTING",t[t.DUPLICATE_TABLE_SETTING=3012]="DUPLICATE_TABLE_SETTING",t[t.INVALID_TABLEGROUP_CONTEXT=3013]="INVALID_TABLEGROUP_CONTEXT",t[t.INVALID_TABLEGROUP_ELEMENT_NAME=3014]="INVALID_TABLEGROUP_ELEMENT_NAME",t[t.DUPLICATE_TABLEGROUP_ELEMENT_NAME=3015]="DUPLICATE_TABLEGROUP_ELEMENT_NAME",t[t.DUPLICATE_TABLEGROUP_FIELD_NAME=3016]="DUPLICATE_TABLEGROUP_FIELD_NAME",t[t.INVALID_TABLEGROUP_FIELD=3017]="INVALID_TABLEGROUP_FIELD",t[t.EMPTY_TABLE=3018]="EMPTY_TABLE",t[t.INVALID_COLUMN=3019]="INVALID_COLUMN",t[t.INVALID_COLUMN_NAME=3020]="INVALID_COLUMN_NAME",t[t.UNKNOWN_COLUMN_SETTING=3021]="UNKNOWN_COLUMN_SETTING",t[t.INVALID_COLUMN_TYPE=3022]="INVALID_COLUMN_TYPE",t[t.DUPLICATE_COLUMN_NAME=3023]="DUPLICATE_COLUMN_NAME",t[t.DUPLICATE_COLUMN_SETTING=3024]="DUPLICATE_COLUMN_SETTING",t[t.INVALID_COLUMN_SETTING_VALUE=3025]="INVALID_COLUMN_SETTING_VALUE",t[t.INVALID_ENUM_CONTEXT=3026]="INVALID_ENUM_CONTEXT",t[t.INVALID_ENUM_ELEMENT_NAME=3027]="INVALID_ENUM_ELEMENT_NAME",t[t.INVALID_ENUM_ELEMENT=3028]="INVALID_ENUM_ELEMENT",t[t.DUPLICATE_ENUM_ELEMENT_NAME=3029]="DUPLICATE_ENUM_ELEMENT_NAME",t[t.UNKNOWN_ENUM_ELEMENT_SETTING=3030]="UNKNOWN_ENUM_ELEMENT_SETTING",t[t.DUPLICATE_ENUM_ELEMENT_SETTING=3031]="DUPLICATE_ENUM_ELEMENT_SETTING",t[t.INVALID_ENUM_ELEMENT_SETTING=3032]="INVALID_ENUM_ELEMENT_SETTING",t[t.EMPTY_ENUM=3033]="EMPTY_ENUM",t[t.INVALID_REF_CONTEXT=3034]="INVALID_REF_CONTEXT",t[t.UNKNOWN_REF_SETTING=3035]="UNKNOWN_REF_SETTING",t[t.DUPLICATE_REF_SETTING=3036]="DUPLICATE_REF_SETTING",t[t.INVALID_REF_SETTING_VALUE=3037]="INVALID_REF_SETTING_VALUE",t[t.INVALID_REF_RELATIONSHIP=3038]="INVALID_REF_RELATIONSHIP",t[t.INVALID_REF_FIELD=3039]="INVALID_REF_FIELD",t[t.EMPTY_REF=3040]="EMPTY_REF",t[t.REF_REDEFINED=3041]="REF_REDEFINED",t[t.INVALID_NOTE_CONTEXT=3042]="INVALID_NOTE_CONTEXT",t[t.INVALID_NOTE=3043]="INVALID_NOTE",t[t.NOTE_REDEFINED=3044]="NOTE_REDEFINED",t[t.NOTE_CONTENT_REDEFINED=3045]="NOTE_CONTENT_REDEFINED",t[t.EMPTY_NOTE=3046]="EMPTY_NOTE",t[t.INVALID_INDEXES_CONTEXT=3047]="INVALID_INDEXES_CONTEXT",t[t.INVALID_INDEXES_FIELD=3048]="INVALID_INDEXES_FIELD",t[t.INVALID_INDEX=3049]="INVALID_INDEX",t[t.UNKNOWN_INDEX_SETTING=3050]="UNKNOWN_INDEX_SETTING",t[t.DUPLICATE_INDEX_SETTING=3051]="DUPLICATE_INDEX_SETTING",t[t.UNEXPECTED_INDEX_SETTING_VALUE=3052]="UNEXPECTED_INDEX_SETTING_VALUE",t[t.INVALID_INDEX_SETTING_VALUE=3053]="INVALID_INDEX_SETTING_VALUE",t[t.INVALID_PROJECT_CONTEXT=3054]="INVALID_PROJECT_CONTEXT",t[t.PROJECT_REDEFINED=3055]="PROJECT_REDEFINED",t[t.INVALID_PROJECT_FIELD=3056]="INVALID_PROJECT_FIELD",t[t.INVALID_CUSTOM_CONTEXT=3057]="INVALID_CUSTOM_CONTEXT",t[t.INVALID_CUSTOM_ELEMENT_VALUE=3058]="INVALID_CUSTOM_ELEMENT_VALUE",t[t.INVALID_ELEMENT_IN_SIMPLE_BODY=3059]="INVALID_ELEMENT_IN_SIMPLE_BODY",t[t.BINDING_ERROR=4e3]="BINDING_ERROR",t[t.UNSUPPORTED=5e3]="UNSUPPORTED",t[t.CIRCULAR_REF=5001]="CIRCULAR_REF",t[t.SAME_ENDPOINT=5002]="SAME_ENDPOINT",t[t.UNEQUAL_FIELDS_BINARY_REF=5003]="UNEQUAL_FIELDS_BINARY_REF",t[t.CONFLICTING_SETTING=5004]="CONFLICTING_SETTING",t))(o||{});class c extends Error{constructor(e,n,s){super(n),this.code=e,this.diagnostic=n,this.nodeOrToken=s,this.start=s.start,this.end=s.end,this.name=this.constructor.name,Object.setPrototypeOf(this,c.prototype)}}class B{constructor(e,n){this.value=e,this.errors=n===void 0?[]:n}getValue(){return this.value}getErrors(){return this.errors}chain(e){const n=e(this.value),s=[...this.errors,...n.errors];return new B(n.value,s)}map(e){return new B(e(this.value),this.errors)}}function sn(t,e,n){if(!t||!fe(t)||e.length===0)return new A;const s=[...e],i=Be(t).unwrap(),r=s.pop();if(!(r instanceof ee))return new A;const a=I.last(s)instanceof U?s.pop():void 0;return s.length===3&&Be(s[1]).unwrap().value==="as"?new S(n.create(_,{type:i,name:s[0],as:Be(s[1]).unwrap(),alias:s[2],attributeList:a,body:r})):s.length===1?new S(n.create(_,{type:i,name:s[0],attributeList:a,body:r})):s.length===0?new S(n.create(_,{type:i,attributeList:a,body:r})):new A}function ct(t){return t.kind===u.IDENTIFIER&&t.value==="as"}function E(t){t&&(t instanceof V?rn(t):an(t))}function rn(t){t.kind!==u.EOF&&(t.isInvalid=!0)}function an(t){if(t instanceof _)E(t.type),E(t.name),E(t.as),E(t.alias),E(t.bodyColon),E(t.attributeList),E(t.body);else if(t instanceof te)t.identifiers.forEach(E);else if(t instanceof ne)E(t.name),E(t.colon),E(t.value);else if(t instanceof q)E(t.op),E(t.expression);else if(t instanceof Q)E(t.leftExpression),E(t.op),E(t.rightExpression);else if(t instanceof De)E(t.op),E(t.expression);else if(t instanceof ee)E(t.blockOpenBrace),t.body.forEach(E),E(t.blockCloseBrace);else if(t instanceof U)E(t.listOpenBracket),t.commaList.forEach(E),t.elementList.forEach(E),E(t.listCloseBracket);else if(t instanceof J)E(t.tupleOpenParen),t.commaList.forEach(E),t.elementList.forEach(E),E(t.tupleCloseParen);else if(t instanceof H)E(t.callee),E(t.argumentList);else if(t instanceof v)E(t.callee),t.args.forEach(E);else if(t instanceof R)E(t.expression);else if(t instanceof K)E(t.value);else if(t instanceof W)E(t.variable);else if(t instanceof pe)E(t.literal);else throw t instanceof Xe?new Error("This case is handled by the TupleExpressionNode case"):new Error("Unreachable case in markInvalidNode")}function vt(t){return!!(t!=null&&t.isInvalid)}function P(...t){return t.filter(e=>e!==void 0)}function on(t){if(t instanceof F)return P(...t.body,t.eof);if(t instanceof _)return P(t.type,t.name,t.as,t.alias,t.attributeList,t.bodyColon,t.body);if(t instanceof ne)return P(t.name,t.colon,t.value);if(t instanceof te)return t.identifiers;if(t instanceof pe)return t.literal?[t.literal]:[];if(t instanceof W)return P(t.variable);if(t instanceof q)return P(t.op,t.expression);if(t instanceof Q)return P(t.leftExpression,t.op,t.rightExpression);if(t instanceof De)return P(t.expression,t.op);if(t instanceof K)return P(t.value);if(t instanceof v)return P(t.callee,...t.args);if(t instanceof ee)return P(t.blockOpenBrace,...t.body,t.blockCloseBrace);if(t instanceof U)return P(t.listOpenBracket,...lt(t.elementList,t.commaList),t.listCloseBracket);if(t instanceof J)return P(t.tupleOpenParen,...lt(t.elementList,t.commaList),t.tupleCloseParen);if(t instanceof H)return P(t.callee,t.argumentList);if(t instanceof R)return P(t.expression);throw t instanceof Xe?new Error("This case is already handled by TupleExpressionNode"):new Error("Unreachable - no other possible cases")}function Be(t){return M(t)?new S(t.expression.variable):new A}function j(t){var e;return t instanceof R&&(t.expression instanceof W&&t.expression.variable instanceof V&&t.expression.variable.kind===u.QUOTED_STRING||t.expression instanceof pe&&((e=t.expression.literal)==null?void 0:e.kind)===u.STRING_LITERAL)}function M(t){return t instanceof R&&t.expression instanceof W&&t.expression.variable instanceof V}function fe(t){var e;return t instanceof R&&t.expression instanceof W&&((e=t.expression.variable)==null?void 0:e.kind)===u.IDENTIFIER}function He(t){var e;return t instanceof Q&&t.leftExpression instanceof k&&t.rightExpression instanceof k&&((e=t.op)==null?void 0:e.value)==="."}function Re(t){if(t===void 0)return new A;const e=t.identifiers.map(n=>n.value).join(" ");return e===""?new A:new S(e)}class ln{constructor(e){this.start={offset:0,line:0,column:0},this.current={offset:0,line:0,column:0},this.tokens=[],this.errors=[],this.text=e}isAtEnd(){return this.current.offset>=this.text.length}advance(){const e=this.peek();return this.current={...this.current},e===`
|
|
2
|
+
`?(this.current.line+=1,this.current.column=0):this.current.column+=1,this.current.offset+=1,e}peek(e=0){if(!(this.current.offset+e>=this.text.length))return this.text[this.current.offset+e]}check(e){for(let n=0;n<e.length;n+=1)if(e[n]!==this.peek(n))return!1;return!0}match(e){return this.check(e)?(e.split("").forEach(()=>this.advance()),!0):!1}addToken(e,n=!1){this.tokens.push(this.createToken(e,n))}createToken(e,n=!1){return V.create(e,this.start,this.current,this.text.substring(this.start.offset,this.current.offset),n)}lex(){return this.scanTokens(),this.tokens.push(V.create(u.EOF,this.start,this.current,"",!1)),this.gatherTrivia(),this.gatherInvalid(),new B(this.tokens,this.errors)}scanTokens(){for(;!this.isAtEnd();){const e=this.advance();switch(e){case" ":this.addToken(u.SPACE);break;case"\r":break;case`
|
|
3
|
+
`:this.addToken(u.NEWLINE);break;case" ":this.addToken(u.TAB);break;case",":this.addToken(u.COMMA);break;case"(":this.addToken(u.LPAREN);break;case")":this.addToken(u.RPAREN);break;case"[":this.addToken(u.LBRACKET);break;case"]":this.addToken(u.RBRACKET);break;case"{":this.addToken(u.LBRACE);break;case"}":this.addToken(u.RBRACE);break;case";":this.addToken(u.SEMICOLON);break;case":":this.addToken(u.COLON);break;case"'":this.match("''")?this.multilineStringLiteral():this.singleLineStringLiteral();break;case'"':this.quotedVariable();break;case"`":this.functionExpression();break;case"#":this.colorLiteral();break;case"/":this.match("/")?this.singleLineComment():this.match("*")?this.multilineComment():this.operator();break;default:if(rt(e)){this.operator();break}if(Qe(e)){this.identifier();break}if(xe(e)){this.numericLiteral();break}this.addToken(u.OP,!0),this.errors.push(new c(o.UNKNOWN_SYMBOL,`Unexpected token '${e}'`,this.createToken(u.OP,!0)));break}this.start={...this.current}}}gatherTrivia(){let e=!0,n=[],s;const i=[];for(const r of this.tokens)$t(r)?(n.push(r),r.kind===u.NEWLINE&&s&&(s.trailingTrivia=n,e=!0,s=void 0,n=[])):(e?r.leadingTrivia=n:s.trailingTrivia=n,i.push(r),n=[],s=r,e=!1);this.tokens=i}gatherInvalid(){let e;const n=[],s=[];for(e=0;e<this.tokens.length&&vt(this.tokens[e]);e+=1)s.push(this.tokens[e]);let i=this.tokens[e];for(i.leadingInvalid=[...s,...i.leadingInvalid];e<this.tokens.length;e+=1){const r=this.tokens[e];r.isInvalid?i.trailingInvalid.push(r):(i=r,n.push(r))}this.tokens=n}consumeUntil(e,n,{allowNewline:s,allowEof:i,raw:r,consumeStopSequence:a=!0}){let l="";for(;!this.isAtEnd()&&(s||!this.check(`
|
|
4
|
+
`))&&!this.check(n);)this.peek()==="\\"&&!r?(this.advance(),l+=this.escapedString()):l+=this.advance();if(this.isAtEnd()&&!i){const p=this.createToken(e,!0);this.tokens.push(p),this.errors.push(new c(o.UNEXPECTED_EOF,"EOF reached while parsing",p));return}if(this.check(`
|
|
5
|
+
`)&&!s){const p=this.createToken(e,!0);this.tokens.push(p),this.errors.push(new c(o.UNEXPECTED_NEWLINE,"Invalid newline encountered while parsing",p));return}a&&this.match(n),this.tokens.push(V.create(e,this.start,this.current,l,!1))}singleLineStringLiteral(){this.consumeUntil(u.STRING_LITERAL,"'",{allowNewline:!1,allowEof:!1,raw:!1})}multilineStringLiteral(){this.consumeUntil(u.STRING_LITERAL,"'''",{allowNewline:!0,allowEof:!1,raw:!1})}functionExpression(){this.consumeUntil(u.FUNCTION_EXPRESSION,"`",{allowNewline:!1,allowEof:!1,raw:!0})}quotedVariable(){this.consumeUntil(u.QUOTED_STRING,'"',{allowNewline:!1,allowEof:!1,raw:!1})}singleLineComment(){this.consumeUntil(u.SINGLE_LINE_COMMENT,`
|
|
6
|
+
`,{allowNewline:!0,allowEof:!0,raw:!0,consumeStopSequence:!1})}multilineComment(){this.consumeUntil(u.MULTILINE_COMMENT,"*/",{allowNewline:!0,allowEof:!1,raw:!0})}identifier(){for(;!this.isAtEnd()&&Ie(this.peek());)this.advance();this.addToken(u.IDENTIFIER)}operator(){for(;rt(this.peek());)this.advance();this.addToken(u.OP)}numericLiteral(){let e=0;if(this.isAtEnd())return this.addToken(u.NUMERIC_LITERAL);for(;!this.isAtEnd();){const s=this.check(".");if(e+=s?1:0,e>1)break;if(!s&&this.current.offset===this.text.length-1)return this.advance(),this.addToken(u.NUMERIC_LITERAL);if(!s&&!Ie(this.peek()))return this.addToken(u.NUMERIC_LITERAL);if(!s&&!xe(this.peek()))break;this.advance()}for(;!this.isAtEnd()&&(this.check(".")||Ie(this.peek()));)this.advance();const n=this.createToken(u.NUMERIC_LITERAL,!0);this.tokens.push(n),this.errors.push(new c(o.UNKNOWN_TOKEN,"Invalid number",n))}colorLiteral(){for(;!this.isAtEnd()&&Ie(this.peek());)this.advance();this.addToken(u.COLOR_LITERAL)}escapedString(){if(this.isAtEnd())return"\\";switch(this.advance()){case"t":return" ";case"n":return`
|
|
7
|
+
`;case"\\":return"\\";case"r":return"\r";case"'":return"'";case'"':return'"';case"0":return"\0";case"b":return"\b";case"v":return"\v";case"f":return"\f";case"u":{let e="";for(let n=0;n<=3;n+=1){if(this.isAtEnd()||!Ie(this.peek()))return`\\u${e}`;e+=this.advance()}return String.fromCharCode(parseInt(e,16))}default:return`\\${this.tokens[this.current.offset-1]}`}}}var ye=(t=>(t[t.ListExpression=0]="ListExpression",t[t.GroupExpression=1]="GroupExpression",t[t.BlockExpression=2]="BlockExpression",t))(ye||{});class cn{constructor(){this.stack=[],this.numberOfNestedLParens=0,this.numberOfNestedLBrackets=0,this.numberOfNestedLBraces=0}push(e){this.stack.push(e),e===0&&(this.numberOfNestedLBrackets+=1),e===1&&(this.numberOfNestedLParens+=1),e===2&&(this.numberOfNestedLBraces+=1)}pop(){const e=this.stack.pop();return e===0&&(this.numberOfNestedLBrackets-=1),e===1&&(this.numberOfNestedLParens-=1),e===2&&(this.numberOfNestedLBraces-=1),e}top(){return I.last(this.stack)}isWithinGroupExpressionContext(){return this.numberOfNestedLParens>0}isWithinListExpressionContext(){return this.numberOfNestedLBrackets>0}isWithinBlockExpressionContext(){return this.numberOfNestedLBraces>0}withContextDo(e,n){return()=>{this.push(e);try{return n()}finally{this.pop()}}}findHandlerContext(e,n){if(!(this.numberOfNestedLBraces<=0&&this.numberOfNestedLBrackets<=0&&this.numberOfNestedLParens<=0))for(let s=n;s<e.length-1;s+=1)switch(e[s].kind){case u.COMMA:if(this.isWithinGroupExpressionContext()||this.isWithinListExpressionContext())return[...this.stack].reverse().find(r=>[1,0].includes(r));break;case u.RPAREN:if(this.isWithinGroupExpressionContext())return 1;break;case u.RBRACE:if(this.isWithinBlockExpressionContext())return 2;break;case u.RBRACKET:if(this.isWithinListExpressionContext())return 0;break}}}class un{constructor(e){this.generator=e}create(e,n){return new e(n,this.generator.nextId())}}class d{constructor(e,n,s){this.token=e,this.partialNode=n,this.handlerContext=s}}class hn{constructor(e,n){this.current=0,this.errors=[],this.contextStack=new cn,this.synchronizeProgram=()=>{const s=this.peek();s.kind!==u.EOF?E(this.advance()):(E(this.peek()),this.logError(s,o.UNEXPECTED_EOF,"Unexpected EOF"))},this.synchronizeElementDeclarationName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(ct(s)||this.check(u.COLON,u.LBRACE,u.LBRACKET))break;E(s),this.advance()}},this.synchronizeElementDeclarationAlias=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.COLON,u.LBRACE,u.LBRACKET))break;E(s),this.advance()}},this.blockExpression=this.contextStack.withContextDo(ye.BlockExpression,()=>{const s={body:[]},i=()=>this.nodeFactory.create(ee,s);try{this.consume("Expect an opening brace '{'",u.LBRACE),s.blockOpenBrace=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.blockOpenBrace=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}for(;!this.isAtEnd()&&!this.check(u.RBRACE);)try{s.body.push(this.canBeField()?this.fieldDeclaration():this.expression())}catch(r){if(!(r instanceof d))throw r;if(s.body.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}try{this.consume("Expect a closing brace '}'",u.RBRACE),s.blockCloseBrace=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.blockCloseBrace=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}return i()}),this.synchronizeBlock=()=>{if(!this.check(u.RBRACE))for(E(this.advance());!this.isAtEnd();){const s=this.peek();if(this.check(u.RBRACE)||ot(this.previous(),s))break;E(s),this.advance()}},this.tupleExpression=this.contextStack.withContextDo(ye.GroupExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(Xe,{groupOpenParen:s.tupleOpenParen,groupCloseParen:s.tupleCloseParen,expression:s.elementList[0]}),r=()=>this.nodeFactory.create(J,s);try{this.consume("Expect an opening parenthesis '('",u.LPAREN),s.tupleOpenParen=this.previous()}catch(a){if(!(a instanceof d))throw a;if(s.tupleOpenParen=a.partialNode,!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}if(!this.isAtEnd()&&!this.check(u.RPAREN))try{s.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof d))throw a;if(s.elementList.push(a.partialNode),!this.canHandle(a))throw new d(a.token,i(),a.handlerContext);this.synchronizeTuple()}for(;!this.isAtEnd()&&!this.check(u.RPAREN);)try{this.consume("Expect a comma ','",u.COMMA),s.commaList.push(this.previous()),s.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof d))throw a;if(a.partialNode instanceof k&&s.elementList.push(a.partialNode),!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}try{this.consume("Expect a closing parenthesis ')'",u.RPAREN),s.tupleCloseParen=this.previous()}catch(a){if(!(a instanceof d))throw a;if(s.tupleCloseParen=a.partialNode,!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}return s.elementList.length===1?i():r()}),this.synchronizeTuple=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.RPAREN,u.COMMA))break;E(s),this.advance()}},this.listExpression=this.contextStack.withContextDo(ye.ListExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(U,s);try{this.consume("Expect an opening bracket '['",u.LBRACKET),s.listOpenBracket=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.listOpenBracket=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}if(!this.isAtEnd()&&!this.check(u.RBRACKET))try{s.elementList.push(this.attribute())}catch(r){if(!(r instanceof d))throw r;if(s.elementList.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}for(;!this.isAtEnd()&&!this.check(u.RBRACKET);)try{this.consume("Expect a comma ','",u.COMMA),s.commaList.push(this.previous()),s.elementList.push(this.attribute())}catch(r){if(!(r instanceof d))throw r;if(r.partialNode instanceof k&&s.elementList.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}try{this.consume("Expect a closing bracket ']'",u.RBRACKET),s.listCloseBracket=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.listCloseBracket=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}return i()}),this.synchronizeList=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.COMMA,u.RBRACKET))break;E(s),this.advance()}},this.synchronizeAttributeName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.COMMA,u.RBRACKET,u.COLON))break;E(s),this.advance()}},this.synchronizeAttributeValue=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.COMMA,u.RBRACKET))break;E(s),this.advance()}},this.tokens=e,this.nodeFactory=new un(n)}isAtEnd(){return this.current>=this.tokens.length||this.tokens[this.current].kind===u.EOF}advance(){return this.isAtEnd()?I.last(this.tokens):this.tokens[this.current++]}peek(e=0){return e+this.current>=this.tokens.length?I.last(this.tokens):this.tokens[this.current+e]}match(...e){const n=this.check(...e);return n&&this.advance(),n}check(...e){const n=this.peek();return e.includes(n.kind)}previous(){return this.tokens[this.current-1]}canHandle(e){return e.handlerContext===void 0||e.handlerContext===this.contextStack.top()}consume(e,...n){if(!this.match(...n))throw this.logError(this.peek(),o.UNEXPECTED_TOKEN,e),new d(this.peek(),void 0,this.contextStack.findHandlerContext(this.tokens,this.current))}discardUntil(e,...n){if(this.isAtEnd()||!this.check(...n)){for(E(this.peek()),this.logError(this.advance(),o.UNEXPECTED_TOKEN,e);!this.isAtEnd()&&!this.check(...n);)E(this.advance());return!this.isAtEnd()}return!0}gatherInvalid(){const e=[],n=[];let s,i=0;for(;i<this.tokens.length&&this.tokens[i].isInvalid;i+=1)n.push(this.tokens[i]);for(s=this.tokens[i],s.leadingInvalid=n,e.push(s),i+=1;i<this.tokens.length;i+=1){const r=this.tokens[i];r.isInvalid?s.trailingInvalid.push(r):(s=r,e.push(s))}this.tokens=e}parse(){const e=this.program(),n=this.advance(),s=this.nodeFactory.create(F,{body:e,eof:n});return this.gatherInvalid(),new B({ast:s,tokens:this.tokens},this.errors)}program(){const e=[];for(;!this.isAtEnd();)try{const n=this.elementDeclaration();e.push(n)}catch(n){if(!(n instanceof d))throw n;e.push(n.partialNode),this.synchronizeProgram()}return e}elementDeclaration(){const e={},n=()=>this.nodeFactory.create(_,e);try{this.consume("Expect an identifier",u.IDENTIFIER),e.type=this.previous()}catch(s){throw s instanceof d?(e.type=s.partialNode,new d(s.token,n(),s.handlerContext)):s}if(!this.check(u.COLON,u.LBRACE,u.LBRACKET))try{e.name=this.normalExpression()}catch(s){if(!(s instanceof d))throw s;if(e.name=s.partialNode,!this.canHandle(s))throw new d(s.token,n(),s.handlerContext);this.synchronizeElementDeclarationName()}if(ct(this.peek()))if(e.as=this.advance(),this.check(u.COLON,u.LBRACE,u.LBRACKET))this.logError(this.peek(),o.UNEXPECTED_TOKEN,"Expect an alias");else try{e.alias=this.normalExpression()}catch(s){if(!(s instanceof d))throw s;if(e.alias=s.partialNode,!this.canHandle(s))throw new d(s.token,n(),s.handlerContext);this.synchronizeElementDeclarationAlias()}try{e.attributeList=this.check(u.LBRACKET)?this.listExpression():void 0}catch(s){throw s instanceof d?(e.attributeList=s.partialNode,new d(s.token,n(),s.handlerContext)):s}if(!this.discardUntil("Expect an opening brace '{' or a colon ':'",u.LBRACE,u.COLON))return n();try{if(this.match(u.COLON)){e.bodyColon=this.previous();const s=this.expression();s instanceof _?(E(s),this.logError(s,o.UNEXPECTED_ELEMENT_DECLARATION,"An element's simple body must not be an element declaration")):e.body=s}else e.body=this.blockExpression()}catch(s){throw s instanceof d?(e.body=s.partialNode,new d(s.token,n(),s.handlerContext)):s}return this.nodeFactory.create(_,e)}fieldDeclaration(){const e={},n=()=>this.nodeFactory.create(_,e);try{this.consume("Expect an identifier",u.IDENTIFIER),e.type=this.previous()}catch(s){throw s instanceof d?(e.type=s.partialNode,new d(s.token,n(),s.handlerContext)):s}try{this.consume("Expect a colon ':'",u.COLON),e.bodyColon=this.previous()}catch(s){throw s instanceof d?(e.bodyColon=s.partialNode,new d(s.token,n(),s.handlerContext)):s}try{const s=this.expression();s instanceof _?this.errors.push(new c(o.INVALID_ELEMENT_IN_SIMPLE_BODY,"Simple body cannot be an element declaration",s)):e.body=s}catch(s){throw s instanceof d?(e.body=s.partialNode,new d(s.token,n(),s.handlerContext)):s}return this.nodeFactory.create(_,e)}expression(){const e={args:[]},n=()=>sn(e.callee,e.args,this.nodeFactory).unwrap_or(this.nodeFactory.create(v,e));try{e.callee=this.normalExpression()}catch(i){throw i instanceof d?(e.callee=i.partialNode,new d(i.token,n(),i.handlerContext)):i}if(this.shouldStopExpression())return n();let s=e.callee;for(;!this.shouldStopExpression();){Ve(this.previous())||this.logError(s,o.MISSING_SPACES,"Expect a following space");try{s=this.normalExpression(),e.args.push(s)}catch(i){throw i instanceof d?(s=i.partialNode,e.args.push(s),new d(i.token,n(),i.handlerContext)):i}}return n()}shouldStopExpression(){if(this.isAtEnd()||bt(this.previous()))return!0;const e=this.peek().kind;return e===u.RBRACE||e===u.RBRACKET||e===u.RPAREN||e===u.COMMA||e===u.COLON}normalExpression(){return this.expression_bp(0)}expression_bp(e){let n=this.leftExpression_bp();for(;!this.isAtEnd();){const s=this.peek();if(s.kind===u.LPAREN){const{left:i}=ut(s);if(i<e||ot(this.previous(),s)&&!this.contextStack.isWithinGroupExpressionContext()&&!this.contextStack.isWithinListExpressionContext())break;try{n=this.nodeFactory.create(H,{callee:n,argumentList:this.tupleExpression()})}catch(r){throw r instanceof d?(n=this.nodeFactory.create(H,{callee:n,argumentList:r.partialNode}),new d(r.token,n,r.handlerContext)):r}}else if(s.kind===u.LBRACKET){if(Ve(this.previous()))break;try{n=this.nodeFactory.create(he,{expression:n,indexer:this.listExpression()})}catch(i){throw i instanceof d?(n=this.nodeFactory.create(he,{expression:n,indexer:i.partialNode}),new d(i.token,n,i.handlerContext)):i}}else if(at(s)){const i=s,r=ut(i);if(r.left!==null){if(r.left<=e)break;this.advance(),n=this.nodeFactory.create(De,{expression:n,op:i})}else{const a=pn(i);if(a.left===null||a.left<=e)break;this.advance();try{n=this.nodeFactory.create(Q,{leftExpression:n,op:i,rightExpression:i.value==="."?this.extractOperand():this.expression_bp(a.right)})}catch(l){throw l instanceof d?(n=this.nodeFactory.create(Q,{leftExpression:n,op:i,rightExpression:l.partialNode}),new d(l.token,n,l.handlerContext)):l}}}else break}return n}leftExpression_bp(){let e;if(at(this.peek())){const n={};n.op=this.peek();const s=En(n.op);if(s.right===null)throw this.logError(n.op,o.UNKNOWN_PREFIX_OP,`Unexpected '${n.op.value}' in an expression`),new d(n.op,this.nodeFactory.create(we,{pre:n.op}),this.contextStack.findHandlerContext(this.tokens,this.current));this.advance();try{n.expression=this.expression_bp(s.right)}catch(i){throw i instanceof d?(n.expression=i.partialNode,new d(i.token,this.nodeFactory.create(q,n),i.handlerContext)):i}e=this.nodeFactory.create(q,n)}else if(e=this.extractOperand(),e instanceof we)throw new d(this.peek(),this.nodeFactory.create(we,{pre:this.peek()}),this.contextStack.findHandlerContext(this.tokens,this.current));return e}extractOperand(){return this.check(u.NUMERIC_LITERAL,u.STRING_LITERAL,u.COLOR_LITERAL,u.QUOTED_STRING,u.IDENTIFIER)?this.primaryExpression():this.check(u.FUNCTION_EXPRESSION)?this.functionExpression():this.check(u.LBRACKET)?this.listExpression():this.check(u.LBRACE)?this.blockExpression():this.check(u.LPAREN)?this.tupleExpression():(this.peek().kind===u.EOF?this.logError(this.peek(),o.UNEXPECTED_EOF,"Unexpected EOF"):this.logError(this.peek(),o.INVALID_OPERAND,`Invalid start of operand "${this.peek().value}"`),this.nodeFactory.create(we,{pre:this.previous()}))}functionExpression(){const e={};try{this.consume("Expect a function expression",u.FUNCTION_EXPRESSION),e.value=this.previous()}catch(n){throw n instanceof d?(e.value=n.partialNode,new d(n.token,this.nodeFactory.create(K,e),n.handlerContext)):n}return this.nodeFactory.create(K,e)}canBeField(){return this.peek().kind===u.IDENTIFIER&&this.peek(1).kind===u.COLON}primaryExpression(){if(this.match(u.COLOR_LITERAL,u.STRING_LITERAL,u.NUMERIC_LITERAL))return this.nodeFactory.create(R,{expression:this.nodeFactory.create(pe,{literal:this.previous()})});if(this.match(u.QUOTED_STRING,u.IDENTIFIER))return this.nodeFactory.create(R,{expression:this.nodeFactory.create(W,{variable:this.previous()})});throw this.logError(this.peek(),o.UNEXPECTED_TOKEN,"Expect a variable or literal"),new d(this.peek(),this.nodeFactory.create(R,{expression:this.nodeFactory.create(W,{})}),this.contextStack.findHandlerContext(this.tokens,this.current))}attribute(){const e={};if(this.check(u.COLON,u.RBRACKET,u.COMMA)){const n=this.peek();this.logError(n,o.EMPTY_ATTRIBUTE_NAME,"Expect a non-empty attribute name"),e.name=this.nodeFactory.create(te,{identifiers:[]})}else try{e.name=this.attributeName()}catch(n){if(!(n instanceof d))throw n;if(e.name=n.partialNode,!this.canHandle(n))throw new d(n.token,this.nodeFactory.create(ne,e),n.handlerContext);this.synchronizeAttributeName()}return this.match(u.COLON)&&(e.colon=this.previous(),e.value=this.attributeValue()),this.nodeFactory.create(ne,e)}attributeValue(){let e;try{e=this.peek().kind===u.IDENTIFIER&&this.peek(1).kind===u.IDENTIFIER?this.attributeName():this.normalExpression()}catch(n){if(!(n instanceof d)||!this.canHandle(n))throw n;e=n.partialNode,this.synchronizeAttributeValue()}return e}attributeName(){const e=[];if(this.peek().kind!==u.IDENTIFIER)return this.primaryExpression();for(;!this.isAtEnd()&&!this.check(u.COLON,u.COMMA,u.RBRACKET);)try{this.consume("Expect an identifier",u.IDENTIFIER),e.push(this.previous())}catch(n){throw n instanceof d?new d(n.token,this.nodeFactory.create(te,{identifiers:e}),n.handlerContext):n}return this.nodeFactory.create(te,{identifiers:e})}logError(e,n,s){this.errors.push(new c(n,s,e))}}const fn={"+":{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 pn(t){return fn[t.value]||{left:null,right:null}}const dn={"+":{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 En(t){return dn[t.value]||{left:null,right:null}}const Nn={"(":{left:14,right:null}};function ut(t){return Nn[t.value]||{left:null,right:null}}var b=(t=>(t.Table="table",t.Enum="enum",t.Ref="ref",t.Note="note",t.Project="project",t.Indexes="indexes",t.TableGroup="tablegroup",t))(b||{});function de(t){var n;const e=(n=t==null?void 0:t.type)==null?void 0:n.value.toLowerCase();switch(e){case b.Enum:case b.Table:case b.Indexes:case b.Note:case b.Project:case b.Ref:case b.TableGroup:return new S(e);default:return new A}}function Ee(t){if(!He(t))return new S([t]);const e=Ee(t.leftExpression).unwrap_or(void 0);return e?(e.push(t.rightExpression),new S(e)):new A}function C(t){if(t===void 0)return new A;const e=Ee(t).unwrap_or(void 0);if(!e)return new A;const n=[];for(const s of e){const i=X(s).unwrap_or(void 0);if(!i)return new A;n.push(i)}return new S(n)}function ge(t){if(t===void 0)return new A;const e=Ee(t).unwrap_or(void 0);if(!e||e.length===0)return new A;const n=[];let s;if(!M(I.last(e))){const i=e.pop();if(kt(i))s=i.elementList.map(r=>G(r).unwrap());else return new A}for(const i of e){const r=X(i).unwrap_or(void 0);if(!r)return new A;n.push(r)}return new S({variables:n,tupleElements:s})}function X(t){return M(t)?new S(t.expression.variable.value):new A}function Ge(t){if(ht(t))return t instanceof K?new S({functional:[t],nonFunctional:[]}):new S({functional:[],nonFunctional:[t]});if(t instanceof J&&t.elementList.every(ht)){const e=t.elementList.filter(s=>s instanceof K),n=t.elementList.filter(M);return new S({functional:e,nonFunctional:n})}return new A}function G(t){var n;const e=(n=t==null?void 0:t.expression.variable)==null?void 0:n.value;return e===void 0?new A:new S(e)}function z(t){return j(t)?t.expression instanceof W?new S(t.expression.variable.value):new S(t.expression.literal.value):new A}function mn(t){var e;return!(t instanceof Q)||!yt((e=t.op)==null?void 0:e.value)?!1:ge(t.leftExpression).and_then(()=>ge(t.rightExpression)).unwrap_or(void 0)!==void 0}function Tn(t){const e=ge(t.leftExpression),n=ge(t.rightExpression);if(!e.isOk()||!n.isOk())return!1;const{tupleElements:s}=e.unwrap(),{tupleElements:i}=n.unwrap();return(s==null?void 0:s.length)===(i==null?void 0:i.length)}function ht(t){return t instanceof R&&t.expression instanceof W||t instanceof K}function bn(t,e){var i,r,a,l;let n=e;const s=qt(t);for(;n;){if((r=(i=n.symbol)==null?void 0:i.symbolTable)!=null&&r.has(t))return(a=n.symbol.symbolTable)==null?void 0:a.get(t);if(((l=n.symbol)==null?void 0:l.declaration)instanceof F&&s)return n.symbol;if(n instanceof F)return;n=n.parent}}class In{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 F||de(this.declarationNode.parent).unwrap_or(void 0)!==b.Project?[new c(o.INVALID_CUSTOM_CONTEXT,"A custom element can only appear in a Project",this.declarationNode)]:[]}validateName(e){return e?[new c(o.UNEXPECTED_NAME,"A Custom element shouldn't have a name",e)]:[]}validateAlias(e){return e?[new c(o.UNEXPECTED_NAME,"A Custom element shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"A Custom element shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof ee)return[new c(o.UNEXPECTED_COMPLEX_BODY,"A Custom element can only have an inline field",e)];const n=[];return j(e.callee)||n.push(new c(o.INVALID_CUSTOM_ELEMENT_VALUE,"A Custom element value can only be a string",e)),e.args.length>0&&n.push(...e.args.map(s=>new c(o.INVALID_CUSTOM_ELEMENT_VALUE,"A Custom element value can only be a string",s))),n}}class Ae{constructor(){this.table=new Map}has(e){return this.table.has(e)}set(e,n){this.table.set(e,n)}get(e,n){return this.table.get(e)||n!==void 0&&this.set(e,n)||n}entries(){return this.table.entries()}}class Ln{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof _?[new c(o.INVALID_PROJECT_CONTEXT,"An Enum can only appear top-level",this.declarationNode)]:[]}validateName(e){return e?Je(e)?[]:[new c(o.INVALID_NAME,"An Enum name must be of the form <enum> or <schema>.<enum>",e)]:[new c(o.NAME_NOT_FOUND,"An Enum must have a name",this.declarationNode)]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}registerElement(){const e=[];this.declarationNode.symbol=this.symbolFactory.create(Zt,{declaration:this.declarationNode,symbolTable:new Ae});const{name:n}=this.declarationNode,s=C(n);if(s.isOk()){const i=s.unwrap(),r=i.pop(),a=Ze(i,this.publicSymbolTable,this.symbolFactory),l=je(r);a.has(l)&&e.push(new c(o.DUPLICATE_NAME,`Enum name ${r} already exists in schema '${i.join(".")||"public"}'`,n)),a.set(l,this.declarationNode.symbol)}return e}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"An Enum shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof 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 c(o.EMPTY_ENUM,"An Enum must have at least one element",this.declarationNode)]:e.flatMap(n=>{const s=[];return n.callee&&!M(n.callee)&&s.push(new c(o.INVALID_COLUMN_NAME,"A column name must be an identifier or a quoted identifier",n.callee)),I.last(n.args)instanceof U&&s.push(...this.validateFieldSetting(I.last(n.args))),n.args.length>1&&s.push(...n.args.map(i=>new c(o.INVALID_ENUM_ELEMENT,"An Enum must have only a field and optionally a setting list",i))),s.push(...this.registerField(n)),s})}validateFieldSetting(e){const n=$(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"note":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_ENUM_ELEMENT_SETTING,"'note' can only appear once",l))),a.forEach(l=>{j(l.value)||s.push(new c(o.INVALID_ENUM_ELEMENT_SETTING,"'note' must be a string",l))});break;default:a.forEach(l=>s.push(new c(o.UNKNOWN_ENUM_ELEMENT_SETTING,`Unknown enum field setting '${r}'`,l)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ie(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}registerField(e){if(e.callee&&M(e.callee)){const n=G(e.callee).unwrap(),s=Ye(n),i=this.symbolFactory.create(Kt,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(s)){const a=r.get(s);return[new c(o.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,e),new c(o.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,a.declaration)]}r.set(s,i)}return[]}}class 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 F||de(this.declarationNode.parent).unwrap_or(void 0)!==b.Table?[new c(o.INVALID_NOTE_CONTEXT,"An Indexes can only appear inside a Table",this.declarationNode)]:[]}validateName(e){return e?[new c(o.UNEXPECTED_NAME,"An Indexes shouldn't have a name",e)]:[]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"An Indexes shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"An Indexes shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof v)return[new c(o.UNEXPECTED_SIMPLE_BODY,"An Indexes must have a complex body",e)];const[n,s]=I.partition(e.body,i=>i instanceof 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 U&&s.push(...this.validateFieldSetting(i.pop())),i.forEach(r=>{for(;r instanceof H;)r.argumentList&&!Ge(r.argumentList).isOk()&&s.push(new c(o.INVALID_INDEXES_FIELD,"An index field must be an identifier, a quoted identifier, a functional expression or a tuple of such",r.argumentList)),r=r.callee;Ge(r).isOk()||s.push(new c(o.INVALID_INDEXES_FIELD,"An index field must be an identifier, a quoted identifier, a functional expression or a tuple of such",r))}),s})}validateFieldSetting(e){const n=$(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"note":case"name":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_INDEX_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{j(l.value)||s.push(new c(o.INVALID_INDEX_SETTING_VALUE,`'${r}' must be a string`,l))});break;case"unique":case"pk":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_INDEX_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{oe(l.value)||s.push(new c(o.INVALID_INDEX_SETTING_VALUE,`'${r}' must not have a value`,l))});break;case"type":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_INDEX_SETTING,"'type' can only appear once",l))),a.forEach(l=>{M(l.value)||s.push(new c(o.INVALID_INDEX_SETTING_VALUE,`'type' must be "btree" or "hash"`,l))});break;default:a.forEach(l=>s.push(new c(o.UNKNOWN_INDEX_SETTING,`Unknown index setting '${r}'`,l)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ie(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class _n{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return!(this.declarationNode.parent instanceof F)&&![b.Table,b.Project].includes(de(this.declarationNode.parent).unwrap_or(void 0))?[new c(o.INVALID_NOTE_CONTEXT,"A Note can only appear inside a Table or a Project. Sticky note can only appear at the global scope.",this.declarationNode)]:[]}validateName(e){if(!(this.declarationNode.parent instanceof F))return e?[new c(o.UNEXPECTED_NAME,"A Note shouldn't have a name",e)]:[];if(!e)return[new c(o.INVALID_NAME,"Sticky note must have a name",this.declarationNode)];const n=C(e);if(!n.isOk())return[];const i=n.unwrap().join("."),r=zt(i);return this.publicSymbolTable.has(r)?[new c(o.DUPLICATE_NAME,`Sticky note "${i}" has already been defined`,e)]:(this.publicSymbolTable.set(r,this.declarationNode.symbol),[])}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}validateSettingList(e){return e&&!(this.declarationNode.parent instanceof F)?[new c(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 c(o.EMPTY_NOTE,"A Note must have a content",this.declarationNode)]:(e.length>1&&e.slice(1).forEach(s=>n.push(new c(o.NOTE_CONTENT_REDEFINED,"A Note can only contain one string",s))),j(e[0].callee)||n.push(new c(o.INVALID_NOTE,"A Note content must be a quoted string",e[0])),e[0].args.length>0&&n.push(...e[0].args.map(s=>new c(o.INVALID_NOTE,"A Note can only contain one quoted string",s))),n)}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ie(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class An{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof _?[new c(o.INVALID_PROJECT_CONTEXT,"A Project can only appear top-level",this.declarationNode)]:[]}validateName(e){return e?Pe(e)?[]:[new c(o.INVALID_NAME,"A Project's name is optional or must be an identifier or a quoted identifer",e)]:[]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A Project shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"A Project shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof v)return[new c(o.UNEXPECTED_SIMPLE_BODY,"A Project's body must be a block",e)];const[n,s]=I.partition(e.body,i=>i instanceof v);return[...n.map(i=>new c(o.INVALID_PROJECT_FIELD,"A Project can not have inline fields",i)),...this.validateSubElements(s)]}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ie(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 F||de(this.declarationNode.parent).unwrap_or(void 0)===b.Table?[]:[new c(o.INVALID_REF_CONTEXT,"A Ref must appear top-level or inside a table",this.declarationNode)]}validateName(e){return e?Pe(e)?[]:[new c(o.INVALID_NAME,"A Ref's name is optional or must be an identifier or a quoted identifer",e)]:[]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"A Ref shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof 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 c(o.EMPTY_REF,"A Ref must have at least one field",this.declarationNode)];const n=[];return e.length>1&&n.push(...e.slice(1).map(s=>new c(o.REF_REDEFINED,"A Ref can only contain one binary relationship",s))),e.forEach(s=>{s.callee&&!mn(s.callee)&&n.push(new c(o.INVALID_REF_FIELD,"A Ref field must be a binary relationship",s.callee)),s.callee&&!Tn(s.callee)&&n.push(new c(o.UNEQUAL_FIELDS_BINARY_REF,"Unequal fields in ref endpoints",s.callee)),I.last(s.args)instanceof U&&this.validateFieldSettings(I.last(s.args)),s.args.length>1&&n.push(...s.args.map(i=>new c(o.INVALID_REF_FIELD,"A Ref field should only have a single binary relationship",i)))}),n}validateFieldSettings(e){const n=$(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"delete":case"update":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_REF_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{wn(l.value)||s.push(new c(o.INVALID_REF_SETTING_VALUE,`'${r}' can only have values "cascade", "no action", "set null", "set default" or "restrict"`,l))});break;default:a.forEach(l=>s.push(new c(o.UNKNOWN_REF_SETTING,`Unknown ref setting '${r}'`,l)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ie(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}function wn(t){if(!(M(t)&&t.expression.variable.kind!==u.QUOTED_STRING)&&!(t instanceof te))return!1;let e;if(t instanceof te?e=Re(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 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 _?[new c(o.INVALID_TABLE_CONTEXT,"Table must appear top-level",this.declarationNode)]:[]}validateName(e){return e?e instanceof he?[new c(o.INVALID_NAME,"Invalid array as Table name, maybe you forget to add a space between the name and the setting list?",e)]:Je(e)?[]:[new c(o.INVALID_NAME,"A Table name must be of the form <table> or <schema>.<table>",e)]:[new c(o.NAME_NOT_FOUND,"A Table must have a name",this.declarationNode)]}validateAlias(e){return e?On(e)?[]:[new c(o.INVALID_ALIAS,"Table aliases can only contains alphanumeric and underscore unless surrounded by double quotes",e)]:[]}validateSettingList(e){const n=$(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"headercolor":a.length>1&&s.push(...a.map(l=>new c(o.DUPLICATE_TABLE_SETTING,"'headercolor' can only appear once",l))),a.forEach(l=>{Dn(l.value)||s.push(new c(o.INVALID_TABLE_SETTING,"'headercolor' must be a color literal",l.value||l.name))});break;case"note":a.length>1&&s.push(...a.map(l=>new c(o.DUPLICATE_TABLE_SETTING,"'note' can only appear once",l))),a.forEach(l=>{j(l.value)||s.push(new c(o.INVALID_TABLE_SETTING,"'note' must be a string literal",l.value||l.name))});break;default:s.push(...a.map(l=>new c(o.INVALID_TABLE_SETTING,`Unknown '${r}' setting`,l)))}}return s}registerElement(){const e=[];this.declarationNode.symbol=this.symbolFactory.create(At,{declaration:this.declarationNode,symbolTable:new Ae});const{name:n,alias:s}=this.declarationNode,i=C(n);if(i.isOk()){const r=[...i.unwrap()],a=r.pop(),l=Ze(r,this.publicSymbolTable,this.symbolFactory),p=ke(a);l.has(p)&&e.push(new c(o.DUPLICATE_NAME,`Table name '${a}' already exists in schema '${r.join(".")||"public"}'`,n)),l.set(p,this.declarationNode.symbol)}if(s&&Pe(s)&&!xn(s.expression.variable.value,i.unwrap_or([]))){const r=G(s).unwrap(),a=ke(r);this.publicSymbolTable.has(a)&&e.push(new c(o.DUPLICATE_NAME,`Table name '${r}' already exists`,n)),this.publicSymbolTable.set(a,this.declarationNode.symbol)}return e}validateBody(e){if(!e)return[];if(e instanceof v)return[new c(o.UNEXPECTED_SIMPLE_BODY,"A Table's body must be a block",e)];const[n,s]=I.partition(e.body,i=>i instanceof v);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.length===0?[new c(o.EMPTY_TABLE,"A Table must have at least one column",this.declarationNode)]:e.flatMap(n=>{if(!n.callee)return[];const s=[];n.args.length===0&&s.push(new c(o.INVALID_COLUMN,"A column must have a type",n.callee)),M(n.callee)||s.push(new c(o.INVALID_COLUMN_NAME,"A column name must be an identifier or a quoted identifier",n.callee)),n.args[0]&&!kn(n.args[0])&&s.push(new c(o.INVALID_COLUMN_TYPE,"Invalid column type",n.args[0]));const i=n.args.slice(1);return s.push(...this.validateFieldSetting(i)),s.push(...this.registerField(n)),s})}registerField(e){if(e.callee&&M(e.callee)){const n=G(e.callee).unwrap(),s=We(n),i=this.symbolFactory.create(en,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(s)){const a=r.get(s);return[new c(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,e),new c(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,a.declaration)]}r.set(s,i)}return[]}validateFieldSetting(e){if(!e.slice(0,-1).every(fe)||!e.slice(-1).every(p=>fe(p)||p instanceof U))return[...e.map(p=>new c(o.INVALID_COLUMN,"These fields must be some inline settings optionally ended with a setting list",p))];if(e.length===0)return[];let n;I.last(e)instanceof U&&(n=e.pop());const s=$(n),i=s.getErrors(),r=s.getValue();for(const p of e){const h=G(p).unwrap_or("").toLowerCase();if(h!=="pk"&&h!=="unique"){i.push(new c(o.INVALID_SETTINGS,"Inline column settings can only be `pk` or `unique`",p));continue}r[h]===void 0?r[h]=[p]:r[h].push(p)}const a=r.pk||[],l=r["primary key"]||[];a.length>=1&&l.length>=1&&i.push(...[...a,...l].map(p=>new c(o.DUPLICATE_COLUMN_SETTING,"Either one of 'primary key' and 'pk' can appear",p)));for(const p in r){const h=r[p];switch(p){case"note":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_COLUMN_SETTING,"note can only appear once",f))),h.forEach(f=>{j(f.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'note' must be a quoted string",f.value||f.name))});break;case"ref":h.forEach(f=>{Pn(f.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'ref' must be a valid unary relationship",f.value||f.name))});break;case"primary key":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_COLUMN_SETTING,"primary key can only appear once",f))),h.forEach(f=>{oe(f.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'primary key' must not have a value",f.value||f.name))});break;case"pk":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_COLUMN_SETTING,"'pk' can only appear once",f))),h.forEach(f=>{f instanceof ne&&!oe(f.value)&&i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'pk' must not have a value",f.value||f.name))});break;case"not null":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_COLUMN_SETTING,"'not null' can only appear once",f)));const T=r.null||[];h.length>=1&&T.length>=1&&i.push(...[...h,...T].map(f=>new c(o.CONFLICTING_SETTING,"'not null' and 'null' can not be set at the same time",f))),h.forEach(f=>{oe(f.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'not null' must not have a value",f.value||f.name))});break;case"null":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_COLUMN_SETTING,"'null' can only appear once",f))),h.forEach(f=>{oe(f.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'null' must not have a value",f.value||f.name))});break;case"unique":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_COLUMN_SETTING,"'unique' can only appear once",f))),h.forEach(f=>{f instanceof ne&&!oe(f.value)&&i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'unique' must not have a value",f.value||f.name))});break;case"increment":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_COLUMN_SETTING,"'increment' can only appear once",f))),h.forEach(f=>{f instanceof ne&&!oe(f.value)&&i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'increment' must not have a value",f.value||f.name))});break;case"default":h.length>1&&i.push(...h.map(f=>new c(o.DUPLICATE_TABLE_SETTING,"'default' can only appear once",f))),h.forEach(f=>{Rn(f.value)||i.push(new c(o.INVALID_TABLE_SETTING,"'default' must be a string literal, number literal, function expression, true, false or null",f.value||f.name))});break;default:h.forEach(f=>i.push(new c(o.UNKNOWN_COLUMN_SETTING,`Unknown column setting '${p}'`,f)))}}return i}validateSubElements(e){const n=e.flatMap(i=>{if(i.parent=this.declarationNode,!i.type)return[];const r=ie(i);return new r(i,this.publicSymbolTable,this.symbolFactory).validate()}),s=e.filter(i=>{var r;return((r=i.type)==null?void 0:r.value.toLowerCase())==="note"});return s.length>1&&(n.push(...s.map(i=>new c(o.NOTE_REDEFINED,"Duplicate notes are defined",i))),n.push()),n}}function kn(t){if(!(t instanceof H||He(t)||t instanceof R||t instanceof he))return!1;if(t instanceof H){if(t.callee===void 0||t.argumentList===void 0||!t.argumentList.elementList.every(n=>le(n)||j(n)||fe(n)))return!1;t=t.callee}for(;t instanceof he;){if(t.array===void 0||t.indexer===void 0||!t.indexer.elementList.every(n=>!n.colon&&!n.value&&le(n.name)))return!1;t=t.array}const e=C(t).unwrap_or(void 0);return e!==void 0&&e.length>0}function xn(t,e){return e.length===1&&t===e[0]}class Sn{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 _?[new c(o.INVALID_TABLEGROUP_CONTEXT,"TableGroup must appear top-level",this.declarationNode)]:[]}validateName(e){return e?Je(e)?[]:[new c(o.INVALID_NAME,"A TableGroup name must be of the form <tablegroup> or <schema>.<tablegroup>",e)]:[new c(o.NAME_NOT_FOUND,"A TableGroup must have a name",this.declarationNode)]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A TableGroup shouldn't have an alias",e)]:[]}registerElement(){const{name:e}=this.declarationNode;this.declarationNode.symbol=this.symbolFactory.create(tn,{declaration:this.declarationNode,symbolTable:new Ae});const n=C(e);if(n.isOk()){const s=n.unwrap(),i=s.pop(),r=Ze(s,this.publicSymbolTable,this.symbolFactory),a=ze(i);if(r.has(a))return[new c(o.DUPLICATE_NAME,`TableGroup name '${i}' already exists in schema '${s.join(".")||"public"}'`,e)];r.set(a,this.declarationNode.symbol)}return[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"A TableGroup shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof v)return[new c(o.UNEXPECTED_SIMPLE_BODY,"A TableGroup's body must be a block",e)];const[n,s]=I.partition(e.body,i=>i instanceof v);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.flatMap(n=>{const s=[];return n.callee&&!C(n.callee).isOk()&&s.push(new c(o.INVALID_TABLEGROUP_FIELD,"A TableGroup field must be of the form <table> or <schema>.<table>",n.callee)),this.registerField(n),n.args.length>0&&s.push(...n.args.map(i=>new c(o.INVALID_TABLEGROUP_FIELD,"A TableGroup field should only have a single Table name",i))),s})}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ie(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}registerField(e){if(e.callee&&M(e.callee)){const n=G(e.callee).unwrap(),s=qe(n),i=this.symbolFactory.create(nn,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(s)){const a=r.get(s);return[new c(o.DUPLICATE_TABLEGROUP_FIELD_NAME,`${n} already exists in the group`,e),new c(o.DUPLICATE_TABLEGROUP_FIELD_NAME,`${n} already exists in the group`,a.declaration)]}r.set(s,i)}return[]}}const wt=["-","+"];function ie(t){switch(t.type.value.toLowerCase()){case b.Enum:return Ln;case b.Table:return yn;case b.TableGroup:return Sn;case b.Project:return An;case b.Ref:return vn;case b.Note:return _n;case b.Indexes:return gn;default:return In}}function Je(t){return!!C(t).unwrap_or(!1)}function On(t){return Pe(t)}function Pe(t){return t instanceof R&&t.expression instanceof W}function Ze(t,e,n){var i;t[0]==="public"&&(t=t.slice(1));let s=e;for(const r of t){let a;const l=$e(r);if(s.has(l)){if(a=(i=s.get(l))==null?void 0:i.symbolTable,!a)throw new Error("Expect a symbol table in a schema symbol")}else{a=new Ae;const p=n.create(_t,{symbolTable:a});s.set(l,p)}s=a}return s}function yt(t){return t==="-"||t==="<>"||t===">"||t==="<"}function Dn(t){var n;if(!(t instanceof R)||!(t.expression instanceof pe)||((n=t.expression.literal)==null?void 0:n.kind)!==u.COLOR_LITERAL)return!1;const e=t.expression.literal.value;if(e.length!==4&&e.length!==7||e[0]!=="#")return!1;for(let s=1;s<e.length;s+=1)if(!Ht(e[s]))return!1;return!0}function oe(t){return t===void 0}function Rn(t){var e;return!!(j(t)||le(t)||fe(t)&&["true","false","null"].includes(t.expression.variable.value.toLowerCase())||t instanceof q&&wt.includes((e=t.op)==null?void 0:e.value)&&le(t.expression)||t instanceof K)}function le(t){var e;return t instanceof R&&t.expression instanceof pe&&((e=t.expression.literal)==null?void 0:e.kind)===u.NUMERIC_LITERAL}function Pn(t){var n;if(!(t instanceof q)||!yt((n=t.op)==null?void 0:n.value))return!1;const e=C(t.expression).unwrap_or(void 0);return e!==void 0&&e.length>0}function kt(t){return t instanceof J&&t.elementList.every(M)}function $(t){var s;const e={},n=[];if(!t)return new B({});for(const i of t.elementList){if(!i.name)continue;if(i.name instanceof R){n.push(new c(o.INVALID_SETTINGS,"A setting name must be a stream of identifiers",i.name));continue}const r=(s=Re(i.name).unwrap_or(void 0))==null?void 0:s.toLowerCase();r&&(e[r]===void 0?e[r]=[i]:e[r].push(i))}return new B(e,n)}class ft{constructor(e,n){this.ast=e,this.symbolFactory=n,this.publicSchemaSymbol=this.symbolFactory.create(_t,{symbolTable:new Ae}),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=ie(s),r=new i(s,this.publicSchemaSymbol.symbolTable,this.symbolFactory);e.push(...r.validate())});const n=this.ast.body.filter(s=>de(s).unwrap_or(void 0)===b.Project);return n.length>1&&n.forEach(s=>e.push(new c(o.PROJECT_REDEFINED,"Only one project can exist",s))),new B(this.ast,e)}}class re{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 R)continue;const i=Re(s.name).unwrap_or(void 0);if(!i)continue;const r=n[i.toLowerCase()];r!=null&&r.shouldBind&&this.scanAndBind(s.value,r)}}bindBody(){const e=this.declarationNode;if(!e.body)return;const{body:n}=e;if(n instanceof ee)for(const s of n.body)if(s instanceof _){if(!s.type)continue;const i=xt(s);new i(s,this.errors).bind()}else this.bindSubfield(s);else this.bindSubfield(n)}bindSubfield(e){const n=[e.callee,...e.args],s=I.last(n);s instanceof U&&(n.pop(),this.bindSettingList(s,this.subfield.settingList));const{argBinderRules:i}=this.subfield.arg;for(let r=0;r<Math.min(n.length,i.length);r+=1)i[r].shouldBind&&this.scanAndBind(n[r],i[r])}scanAndBind(e,n){var s,i;if(e)if(e instanceof R){if(e.expression instanceof W&&((i=n.keywords)!=null&&i.includes((s=e.expression.variable)==null?void 0:s.value.toLowerCase())))return;this.bindFragments([e],n)}else e instanceof Q?He(e)?this.bindFragments(Ee(e).unwrap_or([]),n):(this.scanAndBind(e.leftExpression,n),this.scanAndBind(e.rightExpression,n)):e instanceof q?this.scanAndBind(e.expression,n):e instanceof De?this.scanAndBind(e.expression,n):e instanceof J&&e.elementList.forEach(r=>this.scanAndBind(r,n))}bindFragments(e,n){if(e.length===0)return;const s=[...n.topSubnamesSymbolKind],{remainingSubnamesSymbolKind:i}=n,r=e.findIndex(f=>!M(f)),l=r!==-1&&kt(e[r])?e[r]:void 0,p=r>=0?s.pop():void 0,h=e.slice(0,r===-1?void 0:r);if(h.length===0)return;const T=[];for(;s.length&&h.length;){const f=s.pop(),N=h.pop(),g=G(N).unwrap();T.unshift({index:Fe(g,f),referrer:N})}for(;h.length;){const f=h.pop(),N=G(f).unwrap();T.unshift({index:Fe(N,i),referrer:f})}return l?l.elementList.forEach(f=>this.resolveIndexStack([...T,{index:Fe(G(f).unwrap(),p),referrer:f}],n.ignoreNameNotFound)):this.resolveIndexStack(T,n.ignoreNameNotFound)}resolveIndexStack(e,n){if(e.length===0)throw new Error("Unreachable - An unresolved name must have at least one name component");const[s,...i]=e,r=bn(s.index,this.declarationNode);if(r===void 0){const{kind:h,name:T}=se(s.index).unwrap();this.logError(s.referrer,`Can not find ${h} '${T}'`,n);return}r.references.push(s.referrer),s.referrer.referee=r;let a=r.symbolTable,{kind:l,name:p}=se(s.index).unwrap();for(const h of i){const{kind:T,name:f}=se(h.index).unwrap(),N=a.get(h.index);if(!N){this.logError(h.referrer,`${l} '${p}' does not have ${T} '${f}'`,n);return}if(l=T,p=f,h.referrer.referee=N,N.references.push(h.referrer),!N.symbolTable)break;a=N.symbolTable}}logError(e,n,s){s||this.errors.push(new c(o.BINDING_ERROR,n,e))}}class Un extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Mn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Fn extends re{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 Bn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Vn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Gn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class Cn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Enum],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!0}]},settingList:{ref:{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},default:{shouldBind:!1}}},this.settingList={}}}class Xn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}function xt(t){switch(t.type.value.toLowerCase()){case b.Enum:return Mn;case b.Table:return Cn;case b.TableGroup:return Xn;case b.Project:return Vn;case b.Ref:return Gn;case b.Note:return Bn;case b.Indexes:return Fn;default:return Un}}class $n{constructor(e){this.ast=e,this.errors=[]}resolve(){for(const e of this.ast.body)if(e.type){const n=xt(e);new n(e,this.errors).bind()}return new B(this.ast,this.errors)}}class Wn{constructor(e){this.generator=e}create(e,n){return new e(n,this.generator.nextId())}}class jn{constructor(e,n){this.ast=e,this.symbolFactory=new Wn(n)}analyze(){return new ft(this.ast,this.symbolFactory).validate().chain(n=>new $n(n).resolve())}validate(){return new ft(this.ast,this.symbolFactory).validate().chain(n=>new B(n,[]))}}function pt(t,e){const{variables:n,tupleElements:s}=ge(t).unwrap();return s?n.length===0?{schemaName:e.schemaName,tableName:e.name,fieldNames:s}:{tableName:n.pop(),schemaName:n.pop()||null,fieldNames:s}:n.length===1?{schemaName:e.schemaName,tableName:e.name,fieldNames:[n[0]]}:{fieldNames:[n.pop()],tableName:n.pop(),schemaName:n.pop()||null}}function St(t){switch(t){case"<":return["1","*"];case"<>":return["*","*"];case">":return["*","1"];case"-":return["1","1"]}throw new Error("Invalid relation op")}function x(t){return{start:{offset:t.startPos.offset,line:t.startPos.line+1,column:t.startPos.column+1},end:{offset:t.endPos.offset,line:t.endPos.line+1,column:t.endPos.column+1}}}function Ce(t){var n;const e=(n=Ee(t).unwrap_or(void 0))==null?void 0:n.pop();return e instanceof J?e.elementList.map(s=>s.referee):[e.referee]}function Ne(t){const e=C(t).unwrap();return{name:e.pop(),schemaName:e}}function Ot(t){return t.expression.literal.value}function Dt(t,e){if(Array.isArray(t)){const i=t.map(({id:a})=>a).sort().join(","),r=e.map(({id:a})=>a).sort().join(",");return i<r?`${i}-${r}`:`${i}-${r}`}const n=t.id,s=e.id;return n<s?`${n}-${s}`:`${s}-${n}`}function Rt(t,e){if(Array.isArray(t)){const i=t.map(({id:a})=>a).sort(),r=e.map(({id:a})=>a).sort();return I.zip(i,r).every(([a,l])=>a===l)}const n=t.id,s=e.id;return n===s}class Ke{constructor(e,n){this.declarationNode=e,this.env=n,this.container=this.declarationNode.parent instanceof _?this.env.tables.get(this.declarationNode.parent):void 0,this.ref={}}interpret(){return this.ref.token=x(this.declarationNode),this.env.ref.set(this.declarationNode,this.ref),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(e){const n=[],s=C(this.declarationNode.name).unwrap_or([]);return this.ref.name=s.pop()||null,s.length>1&&n.push(new c(o.UNSUPPORTED,"Nested schema is not supported",this.declarationNode.name)),this.ref.schemaName=s.join(".")||null,n}interpretBody(e){return e instanceof v?this.interpretField(e):this.interpretField(e.body[0])}interpretField(e){var h,T,f,N;const n=e.callee.op.value,{leftExpression:s,rightExpression:i}=e.callee,r=Ce(s),a=Ce(i);if(Rt(r,a))return[new c(o.SAME_ENDPOINT,"Two endpoints are the same",e)];const l=Dt(r,a);if(this.env.refIds[l])return[new c(o.CIRCULAR_REF,"References with same endpoints exist",this.declarationNode),new c(o.CIRCULAR_REF,"References with same endpoints exist",this.env.refIds[l])];if(e.args[0]){const g=$(e.args[0]).getValue();this.ref.onDelete=X((T=(h=g.delete)==null?void 0:h.at(0))==null?void 0:T.value).unwrap_or(void 0),this.ref.onDelete=X((N=(f=g.delete)==null?void 0:f.at(0))==null?void 0:N.value).unwrap_or(void 0)}const p=St(n);return this.ref.endpoints=[{...pt(s,this.container),relation:p[0],token:x(s)},{...pt(i,this.container),relation:p[1],token:x(i)}],this.env.refIds[l]=this.declarationNode,[]}}class Pt{constructor(e,n){this.declarationNode=e,this.env=n,this.table={name:void 0,schemaName:void 0,alias:null,fields:[],token:void 0,indexes:[]},this.pkColumns=[]}interpret(){this.table.token=x(this.declarationNode),this.env.tables.set(this.declarationNode,this.table);const e=[...this.interpretName(this.declarationNode.name),...this.interpretAlias(this.declarationNode.alias),...this.interpretSettingList(this.declarationNode.attributeList),...this.interpretBody(this.declarationNode.body)];return this.pkColumns.length>=2&&(this.table.indexes.push({columns:this.pkColumns.map(({name:n})=>({value:n,type:"column"})),token:{start:{offset:-1,line:-1,column:-1},end:{offset:-1,line:-1,column:-1}},pk:!0}),this.pkColumns.forEach(n=>n.pk=!1)),e}interpretName(e){const{name:n,schemaName:s}=Ne(e);return s.length>1?(this.table.name=n,this.table.schemaName=s.join("."),[new c(o.UNSUPPORTED,"Nested schema is not supported",e)]):(this.table.name=n,this.table.schemaName=s.length?s[0]:null,[])}interpretAlias(e){if(!e)return[];const n=G(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 r,a,l;const n=$(e).getValue();this.table.headerColor=(r=n.headercolor)!=null&&r.length?Ot((l=(a=n.headercolor)==null?void 0:a.at(0))==null?void 0:l.value):void 0;const[s]=n.note||[],i=z(s==null?void 0:s.value).unwrap_or(void 0);return this.table.note=s&&{value:i,token:x(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.table.note={value:z(n.body instanceof ee?n.body.body[0].callee:n.body.callee).unwrap(),token:x(n)},[];case"indexes":return this.interpretIndexes(n);case"ref":return new Ke(n,this.env).interpret()}return[]})}interpretFields(e){return e.flatMap(n=>this.interpretColumn(n))}interpretColumn(e){var a,l,p,h,T,f,N,g;const n=[],s={};s.name=G(e.callee).unwrap();const i=Yn(e.args[0]);s.type=i.getValue(),n.push(...i.getErrors()),s.token=x(e),s.inline_refs=[];const r=e.args.slice(1);if(I.last(r)instanceof U){const w=$(r.pop()).getValue();s.pk=!!((a=w.pk)!=null&&a.length)||!!((l=w["primary key"])!=null&&l.length),s.increment=!!((p=w.increment)!=null&&p.length),s.unique=!!((h=w.unique)!=null&&h.length),s.not_null=!!((T=w["not null"])!=null&&T.length)&&!0,s.dbdefault=zn((N=(f=w.default)==null?void 0:f.at(0))==null?void 0:N.value);const me=(g=w.note)==null?void 0:g.at(0);s.note=me&&{value:z(me.value).unwrap(),token:x(me)};const Te=w.ref||[];s.inline_refs=Te.flatMap(Y=>{const[nt]=Ce(Y.value.expression);if(Rt(nt,e.symbol))return n.push(new c(o.SAME_ENDPOINT,"Two endpoints are the same",Y)),[];const ve=Y.value.op,Z=C(Y.value.expression).unwrap();let ce;if(Z.length===1){const[ae]=Z;ce={schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[ae],relation:ve.value,token:x(Y)}}else if(Z.length===2){const[ae,be]=Z;ce={schemaName:null,tableName:ae,fieldNames:[be],relation:ve.value,token:x(Y)}}else if(Z.length===3){const[ae,be,it]=Z;ce={schemaName:ae,tableName:be,fieldNames:[it],relation:ve.value,token:x(Y)}}else{n.push(new c(o.UNSUPPORTED,"Nested schema is not supported",Y));const ae=Z.pop(),be=Z.pop();ce={schemaName:Z.join("."),tableName:be,fieldNames:[ae],relation:ve.value,token:x(Y)}}const st=this.registerInlineRefToEnv(e,nt,ce,Y);return n.push(...st),st.length===0?ce:[]})}return s.pk||(s.pk=r.some(w=>X(w).unwrap().toLowerCase()==="pk")),s.unique||(s.unique=r.some(w=>X(w).unwrap().toLowerCase()==="unique")),this.table.fields.push(s),s.pk&&this.pkColumns.push(s),n}interpretIndexes(e){return this.table.indexes.push(...e.body.body.map(n=>{var a,l,p,h,T,f,N;const s={columns:[]},i=n;s.token=x(e);const r=[i.callee,...i.args];if(I.last(r)instanceof U){const g=$(r.pop()).getValue();s.pk=!!((a=g.pk)!=null&&a.length),s.unique=!!((l=g.unique)!=null&&l.length),s.name=z((h=(p=g.name)==null?void 0:p.at(0))==null?void 0:h.value).unwrap_or(void 0);const w=(T=g.note)==null?void 0:T.at(0);s.note=w&&{value:z(w.value).unwrap(),token:x(w)},s.type=X((N=(f=g.type)==null?void 0:f.at(0))==null?void 0:N.value).unwrap_or(void 0)}return r.flatMap(g=>{if(!(g instanceof H))return g;const w=[];for(;g instanceof H;)w.push(g.argumentList),g=g.callee;return w.push(g),w}).forEach(g=>{const{functional:w,nonFunctional:me}=Ge(g).unwrap();s.columns.push(...w.map(Te=>({value:Te.value.value,type:"expression"})),...me.map(Te=>({value:G(Te).unwrap(),type:"column"})))}),s})),[]}registerInlineRefToEnv(e,n,s,i){const r=Dt(e.symbol,n);if(this.env.refIds[r])return[new c(o.CIRCULAR_REF,"References with same endpoints exist",i),new c(o.CIRCULAR_REF,"References with same endpoints exist",this.env.refIds[r])];const a=St(s.relation);return this.env.refIds[r]=i,this.env.ref.set(i,{name:null,schemaName:null,token:s.token,endpoints:[{schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[X(e.callee).unwrap()],token:x(e),relation:a[0]},{...s,relation:a[1]}]}),[]}}function Yn(t){let e=null;t instanceof H&&(e=t.argumentList.elementList.map(r=>le(r)?r.expression.literal.value:j(r)?z(r).unwrap():X(r).unwrap()).join(","),t=t.callee);let n="";for(;t instanceof he;)n=`[${t.indexer.elementList.map(r=>r.name.expression.literal.value).join(",")}]${n}`,t=t.array;const{name:s,schemaName:i}=Ne(t);return i.length>1&&new B({schemaName:i.length===0?null:i[0],type_name:`${s}${n}${e?`(${e})`:""}`,args:e},[new c(o.UNSUPPORTED,"Nested schema is not supported",t)]),new B({schemaName:i.length===0?null:i[0],type_name:`${s}${n}${e?`(${e})`:""}`,args:e})}function zn(t){var e,n,s;if(t){if(j(t))return{value:z(t).unwrap(),type:"string"};if(le(t))return{type:"number",value:Number.parseFloat(t.expression.literal.value)};if(fe(t))return{value:t.expression.variable.value.toLowerCase(),type:"boolean"};if(t instanceof q&&wt.includes((e=t.op)==null?void 0:e.value)&&le(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 K)return{value:(s=t.value)==null?void 0:s.value,type:"expression"};throw new Error("Unreachable")}}class qn{constructor(e,n){this.declarationNode=e,this.env=n,this.note={name:void 0,content:void 0,token:void 0}}interpret(){return this.note.token=x(this.declarationNode),this.env.notes.set(this.declarationNode,this.note),[...this.interpretName(this.declarationNode.name),...this.interpretSettingList(this.declarationNode.attributeList),...this.interpretBody(this.declarationNode.body)]}interpretName(e){const{name:n}=Ne(e);return this.note.name=n,[]}interpretSettingList(e){var s,i,r;const n=$(e).getValue();return this.note.headerColor=(s=n.headercolor)!=null&&s.length?Ot((r=(i=n.headercolor)==null?void 0:i.at(0))==null?void 0:r.value):void 0,[]}interpretBody(e){const[n,s]=I.partition(e.body,i=>i instanceof v);return n.length!==1||s.length>0?[new c(o.INVALID_NOTE,"Invalid note syntax",e)]:[...this.interpretNote(n[0])]}interpretNote(e){const n=I.get(e,"callee.expression.literal.value","");return this.note.content=n,[]}}class Ut{constructor(e,n){this.declarationNode=e,this.env=n,this.tableGroup={tables:[]}}interpret(){const e=[];this.tableGroup.token=x(this.declarationNode),this.env.tableGroups.set(this.declarationNode,this.tableGroup);const{name:n,schemaName:s}=Ne(this.declarationNode.name);return s.length>=2&&(this.tableGroup.name=n,this.tableGroup.schemaName=s.join("."),e.push(new c(o.UNSUPPORTED,"Nested schema is not supported",this.declarationNode.name))),this.tableGroup.name=n,this.tableGroup.schemaName=s[0]||null,this.tableGroup.tables=this.declarationNode.body.body.map(i=>{const r=C(i.callee).unwrap();return r.length>2&&e.push(new c(o.UNSUPPORTED,"Nested schema is not supported",i)),{name:r.pop(),schemaName:r.join(".")}}),e}}class Mt{constructor(e,n){this.declarationNode=e,this.env=n,this.enum={values:[]}}interpret(){return this.enum.token=x(this.declarationNode),this.env.enums.set(this.declarationNode,this.enum),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(e){const{name:n,schemaName:s}=Ne(e);return s.length>1?(this.enum.name=n,this.enum.schemaName=s.join("."),[new c(o.UNSUPPORTED,"Nested schema is not supported",e)]):(this.enum.name=n,this.enum.schemaName=s.length?s[0]:null,[])}interpretBody(e){return e.body.flatMap(n=>{var l;const s=n,i={};i.token=x(s),i.name=X(s.callee).unwrap();const a=(l=$(s.args[0]).getValue().note)==null?void 0:l.at(0);return i.note=a&&{value:z(a.value).unwrap(),token:x(a)},this.enum.values.push(i),[]})}}class Qn{constructor(e,n){this.declarationNode=e,this.env=n,this.project={enums:[],refs:[],tableGroups:[],tables:[]}}interpret(){return this.env.project.set(this.declarationNode,this.project),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(e){if(!e)return this.project.name=null,[];const{name:n}=Ne(e);return this.project.name=n,[]}interpretBody(e){return e.body.flatMap(n=>{var i;const s=n;switch((i=s.type)==null?void 0:i.value.toLowerCase()){case"table":{const r=new Pt(s,this.env).interpret();return this.project.tables.push(this.env.tables.get(s)),r}case"ref":{const r=new Ke(s,this.env).interpret();return this.project.refs.push(this.env.ref.get(s)),r}case"tablegroup":{const r=new Ut(s,this.env).interpret();return this.project.tableGroups.push(this.env.tableGroups.get(s)),r}case"enum":{const r=new Mt(s,this.env).interpret();return this.project.enums.push(this.env.enums.get(s)),r}case"note":return this.project.note={value:z(s.body instanceof ee?s.body.body[0].callee:s.body.callee).unwrap(),token:x(s)},[];default:return this.project[s.type.value.toLowerCase()]=z(s.body.callee).unwrap(),[]}})}}class Hn{constructor(e){this.ast=e,this.env={schema:[],tables:new Map,notes:new Map,refIds:{},ref:new Map,enums:new Map,tableGroups:new Map,aliases:[],project:new Map}}interpret(){const e=this.ast.body.flatMap(n=>{switch(de(n).unwrap_or(void 0)){case b.Table:return new Pt(n,this.env).interpret();case b.Note:return new qn(n,this.env).interpret();case b.Ref:return new Ke(n,this.env).interpret();case b.TableGroup:return new Ut(n,this.env).interpret();case b.Enum:return new Mt(n,this.env).interpret();case b.Project:return new Qn(n,this.env).interpret();default:return[]}});return new B(Jn(this.env),e)}}function Jn(t){return{schemas:[],tables:Array.from(t.tables.values()),notes:Array.from(t.notes.values()),refs:Array.from(t.ref.values()),enums:Array.from(t.enums.values()),tableGroups:Array.from(t.tableGroups.values()),aliases:t.aliases,project:Array.from(t.project.values())[0]||{}}}var L=(t=>(t[t.Function=1]="Function",t[t.Constructor=2]="Constructor",t[t.Field=3]="Field",t[t.Variable=4]="Variable",t[t.Class=5]="Class",t[t.Struct=6]="Struct",t[t.Interface=7]="Interface",t[t.Module=8]="Module",t[t.Property=9]="Property",t[t.Event=10]="Event",t[t.Operator=11]="Operator",t[t.Unit=12]="Unit",t[t.Value=13]="Value",t[t.Constant=14]="Constant",t[t.Enum=15]="Enum",t[t.EnumMember=16]="EnumMember",t[t.Keyword=17]="Keyword",t[t.Text=18]="Text",t[t.Color=19]="Color",t[t.File=20]="File",t[t.Reference=21]="Reference",t[t.Customcolor=22]="Customcolor",t[t.Folder=23]="Folder",t[t.TypeParameter=24]="TypeParameter",t[t.User=25]="User",t[t.Issue=26]="Issue",t[t.Snippet=27]="Snippet",t))(L||{}),y=(t=>(t[t.None=0]="None",t[t.KeepWhitespace=1]="KeepWhitespace",t[t.InsertAsSnippet=4]="InsertAsSnippet",t))(y||{});function _e(t){switch(t){case m.Schema:return L.Module;case m.Table:return L.Class;case m.Column:return L.Field;case m.Enum:return L.Enum;case m.EnumField:return L.EnumMember;case m.TableGroup:return L.Struct;case m.TableGroupField:return L.Field;default:return L.Text}}function Se(t,e){if(!t||Ve(t))return!1;for(const n of t.trailingTrivia){if(n.start>e)break;if(n.kind===u.NEWLINE&&n.end<=e)return!1}return!0}function O(){return{suggestions:[]}}function Oe(t){return{...t,suggestions:t.suggestions.map(e=>({...e,insertText:` ${e.insertText}`}))}}function Ue(t){return{...t,suggestions:t.suggestions.map(e=>({...e,insertText:e.insertText.search(/[^a-zA-Z\d_]/)!==-1||e.insertText[0].match(/\d/)?`"${e.insertText}"`:e.insertText}))}}function et(t,e){return t.getOffsetAt(e)}class Ft{constructor(e,n=[]){this.compiler=e,this.triggerCharacters=n}provideCompletionItems(e,n){var T,f;const s=et(e,n),i=this.compiler.token.flatStream(),{token:r,index:a}=this.compiler.container.token(s),l=a===void 0?i[0]:i[a+1];if([...(r==null?void 0:r.trailingTrivia)||[],...(r==null?void 0:r.leadingTrivia)||[],...(l==null?void 0:l.leadingTrivia)||[]].find(N=>Wt(N)&&Le(s,N)))return O();if(a===void 0)return Tt();if([u.STRING_LITERAL,u.QUOTED_STRING].includes(r.kind)&&Le(s,r))return O();const p=this.compiler.container.element(s);if(this.compiler.container.scopeKind(s)===D.TOPLEVEL||p instanceof _&&p.type&&p.type.start<=s&&p.type.end>=s)return Tt();const h=[...this.compiler.container.stack(s)].reverse();for(const N of h)if(N instanceof q)switch((T=N.op)==null?void 0:T.value){case">":case"<":case"<>":case"-":return dt(this.compiler,s,N)}else if(N instanceof Q)switch((f=N.op)==null?void 0:f.value){case">":case"<":case"<>":case"-":return dt(this.compiler,s,N);case".":return Bt(this.compiler,s,N)}else{if(N instanceof ne)return Et(this.compiler,s,N);if(N instanceof U)return Et(this.compiler,s,N);if(N instanceof J)return Zn(this.compiler,s);if(N instanceof v)return mt(this.compiler,s,N);if(N instanceof _&&(N.bodyColon&&s>=N.bodyColon.end||N.body&&Le(s,N.body)))return mt(this.compiler,s,void 0)}return O()}}function dt(t,e,n){const s=t.container.scopeKind(e);if([D.REF,D.TABLE].includes(s)){const i=Me(t,e,t.container.element(e),[m.Table,m.Schema,m.Column]);return Se(n.op,e)?Oe(i):i}return O()}function Me(t,e,n,s){var a;if(n===void 0)return O();let i=n;const r={suggestions:[]};for(;i;){if((a=i==null?void 0:i.symbol)!=null&&a.symbolTable){const{symbol:l}=i;r.suggestions.push(...t.symbol.members(l).filter(({kind:p})=>s.includes(p)).map(({name:p,kind:h})=>({label:p,insertText:p,insertTextRules:y.KeepWhitespace,kind:_e(h),sortText:_e(h).toString().padStart(2,"0"),range:void 0})))}i=i instanceof _?i.parent:void 0}return Ue(r)}function Zn(t,e){var s;switch(t.container.scopeKind(e)){case D.INDEXES:return Gt(t,e);case D.REF:{const i=[...t.container.stack(e)];for(;i.length>0;){const r=i.pop();if(r instanceof Q&&((s=r.op)==null?void 0:s.value)===".")return Bt(t,e,r)}}return Vt(t,e)}return O()}function Et(t,e,n){const{token:s}=t.container.token(e);if([u.COMMA,u.LBRACKET].includes(s==null?void 0:s.kind)){const i=Nt(t,e);return(s==null?void 0:s.kind)===u.COMMA&&Se(s,e)?Oe(i):i}if(n.name&&n.name.start<=e&&n.name.end>=e)return Nt(t,e);if(n.name){const i=Kn(t,e,Re(n.name).unwrap());return(s==null?void 0:s.kind)===u.COLON&&Se(s,e)?Oe(i):i}return O()}function Nt(t,e){const n=t.container.element(e),s=t.container.scopeKind(e);if(n instanceof F)return O();if(n.body&&!Le(e,n.body))switch(s){case D.TABLE:return{suggestions:[{label:"headercolor",insertText:"headercolor: ",kind:L.Field,insertTextRules:y.KeepWhitespace,range:void 0},{label:"note",insertText:"note: ",kind:L.Field,insertTextRules:y.KeepWhitespace,range:void 0}]};default:return O()}switch(s){case D.TABLE:return{suggestions:[...["primary key","null","not null","increment","pk","unique"].map(i=>({label:i,insertText:i,kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0})),...["ref","default"].map(i=>({label:i,insertText:`${i}: `,kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0})),{label:"note",insertText:"note: ",kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0}]};case D.ENUM:return{suggestions:[{label:"note",insertText:"note: ",kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0}]};case D.INDEXES:return{suggestions:[...["unique","pk"].map(i=>({label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:L.Property,range:void 0})),...["note","name","type"].map(i=>({label:i,insertText:`${i}: `,kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0}))]};case D.REF:return{suggestions:["update","delete"].map(i=>({label:i,insertText:`${i}: `,kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0}))}}return O()}function Kn(t,e,n){switch(n==null?void 0:n.toLowerCase()){case"update":case"delete":return{suggestions:["cascade","set default","set null","restrict"].map(s=>({label:s,insertText:s,kind:L.Value,insertTextRules:y.KeepWhitespace,range:void 0}))};case"type":return{suggestions:["btree","hash"].map(s=>({label:s,insertText:`${s}`,kind:L.Value,insertTextRules:y.KeepWhitespace,range:void 0}))}}return O()}function Bt(t,e,n){const s=Ee(n).unwrap_or([]);if(s.pop(),s.some(r=>!M(r)))return O();const i=s.map(r=>X(r).unwrap());return Ue({suggestions:t.symbol.ofName({nameStack:i,owner:t.container.element(e)}).flatMap(({symbol:r})=>t.symbol.members(r)).map(({kind:r,name:a})=>({label:a,insertText:a,kind:_e(r),range:void 0}))})}function mt(t,e,n){var i;switch(t.container.scopeKind(e)){case D.TABLE:return ts(t,e,n);case D.PROJECT:return ns(t,e,n);case D.INDEXES:return is(t,e);case D.ENUM:return es(t,e,n);case D.REF:{const r=Vt(t,e);return((i=t.container.token(e).token)==null?void 0:i.kind)===u.COLON&&Se(t.container.token(e).token,e)?Oe(r):r}case D.TABLEGROUP:return ss(t);default:return O()}}function Tt(){return{suggestions:["Table","TableGroup","Enum","Project","Ref"].map(t=>({label:t,insertText:t,insertTextRules:y.KeepWhitespace,kind:L.Keyword,range:void 0}))}}function es(t,e,n){return n!=null&&n.callee&&tt(e,n)===1?Me(t,e,t.container.element(e),[m.Schema,m.Table,m.Column]):O()}function ts(t,e,n){if(!(n!=null&&n.callee))return{suggestions:["Ref","Note","indexes"].map(i=>({label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:L.Keyword,range:void 0}))};const s=tt(e,n);return s===0?{suggestions:["Ref","Note","indexes"].map(i=>({label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:L.Keyword,range:void 0}))}:s===1?rs(t,e):O()}function ns(t,e,n){return n!=null&&n.callee?tt(e,n)===0?{suggestions:["Table","TableGroup","Enum","Note","Ref"].map(i=>({label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:L.Keyword,range:void 0}))}:O():{suggestions:["Table","TableGroup","Enum","Note","Ref"].map(i=>({label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:L.Keyword,range:void 0}))}}function Vt(t,e){return Me(t,e,t.container.element(e),[m.Schema,m.Table,m.Column])}function ss(t){return Ue({suggestions:[...t.parse.publicSymbolTable().entries()].flatMap(([e])=>{const n=se(e).unwrap_or(void 0);if(n===void 0)return[];const{kind:s,name:i}=n;return s!==m.Table&&s!==m.Schema?[]:{label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:_e(s),range:void 0}})})}function is(t,e){return Gt(t,e)}function rs(t,e){return{suggestions:[...["integer","int","tinyint","smallint","mediumint","bigint","bit","bool","binary","varbinary","logical","char","nchar","varchar","varchar2","nvarchar","nvarchar2","binary_float","binary_double","float","double","decimal","dec","real","money","smallmoney","enum","tinyblob","tinytext","blob","text","mediumblob","mediumtext","longblob","longtext","ntext","set","inet6","uuid","image","date","time","datetime","datetime2","timestamp","year","smalldatetime","datetimeoffset","XML","sql_variant","uniqueidentifier","CURSOR","BFILE","CLOB","NCLOB","RAW"].map(n=>({label:n,insertText:n,insertTextRules:y.KeepWhitespace,kind:L.TypeParameter,sortText:L.TypeParameter.toString().padStart(2,"0"),range:void 0})),...Me(t,e,t.container.element(e),[m.Enum,m.Schema]).suggestions]}}function Gt(t,e){const s=t.container.element(e).parent;if(!((s==null?void 0:s.symbol)instanceof At))return O();const{symbolTable:i}=s.symbol;return Ue({suggestions:[...i.entries()].flatMap(([r])=>{const a=se(r).unwrap_or(void 0);if(a===void 0)return[];const{name:l}=a;return{label:l,insertText:l,insertTextRules:y.KeepWhitespace,kind:_e(m.Column),range:void 0}})})}function tt(t,e){if(!e.callee)return-1;const n=[e.callee,...e.args],s=n.findIndex(i=>t<=i.end);return s===-1?n.length:s}class Ct{constructor(e){this.compiler=e}provideDefinition(e,n){var a;const{uri:s}=e,i=et(e,n),r=[...this.compiler.container.stack(i)];for(;r.length!==0;){const l=r.pop();if((a=l==null?void 0:l.referee)!=null&&a.declaration&&[ue.PRIMARY_EXPRESSION,ue.VARIABLE].includes(l==null?void 0:l.kind)){const{startPos:p,endPos:h}=l.referee.declaration;return[{range:{startColumn:p.column+1,startLineNumber:p.line+1,endColumn:h.column+1,endLineNumber:h.line+1},uri:s}]}}return[]}}class Xt{constructor(e){this.compiler=e}provideReferences(e,n){const{uri:s}=e,i=et(e,n),r=[...this.compiler.container.stack(i)];for(;r.length!==0;){const a=r.pop();if(a&&[ue.ELEMENT_DECLARATION,ue.FUNCTION_APPLICATION,ue.PRIMARY_EXPRESSION].includes(a==null?void 0:a.kind)){const{symbol:l}=a;if(l!=null&&l.references.length)return l.references.map(({startPos:p,endPos:h})=>({range:{startColumn:p.column+1,startLineNumber:p.line+1,endColumn:h.column+1,endLineNumber:h.line+1},uri:s}))}}return[]}}const as=Object.freeze(Object.defineProperty({__proto__:null,CompletionItemInsertTextRule:y,CompletionItemKind:L,DBMLCompletionItemProvider:Ft,DBMLDefinitionProvider:Ct,DBMLReferencesProvider:Xt},Symbol.toStringTag,{value:"Module"}));var D=(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))(D||{});class os{constructor(){this.source="",this.cache=new Array(16).fill(null),this.nodeIdGenerator=new jt,this.symbolIdGenerator=new Jt,this.token={invalidStream:this.createQuery(6,()=>this.parse.tokens().filter(vt)),flatStream:this.createQuery(7,()=>this.parse.tokens().flatMap(e=>[...e.leadingInvalid,e,...e.trailingInvalid]))},this.parse={source:()=>this.source,_:this.createQuery(0,()=>{const e=new ln(this.source).lex().chain(n=>new hn(n,this.nodeIdGenerator).parse()).chain(({ast:n,tokens:s})=>new jn(n,this.symbolIdGenerator).analyze().map(()=>({ast:n,tokens:s})));return e.getErrors().length>0?e:e.chain(({ast:n,tokens:s})=>new Hn(n).interpret().map(r=>({ast:n,tokens:s,rawDb:r})))}),ast:this.createQuery(1,()=>this.parse._().getValue().ast),errors:this.createQuery(2,()=>this.parse._().getErrors()),tokens:this.createQuery(4,()=>this.parse._().getValue().tokens),rawDb:this.createQuery(3,()=>this.parse._().getValue().rawDb),publicSymbolTable:this.createQuery(5,()=>this.parse._().getValue().ast.symbol.symbolTable)},this.container={stack:this.createQuery(10,e=>{const n=this.parse.tokens();let{index:s}=this.container.token(e);const{token:i}=this.container.token(e);if(s===void 0)return[this.parse.ast()];for(;n[s].isInvalid&&s>=0;)s-=1;if(s===-1)return[this.parse.ast()];const r=n[s].start;let a=this.parse.ast();const l=[a];for(;;){const h=on(a).find(T=>Le(r,T));if(h===void 0||h instanceof V)break;l.push(h),a=h}if((i==null?void 0:i.kind)===u.COLON)return l;for(;l.length>0;){let p=!1;const h=I.last(l);if(h instanceof v){const T=this.parse.source();for(let f=h.end;f<e;f+=1)T[f]===`
|
|
8
|
+
`&&(l.pop(),p=!0)}else h instanceof q||h instanceof Q?this.container.token(e).token!==h.op&&(l.pop(),p=!0):h instanceof U?h.listCloseBracket&&h.end<=e&&(l.pop(),p=!0):h instanceof J?h.tupleCloseParen&&h.end<=e&&(l.pop(),p=!0):h instanceof ee?h.blockCloseBrace&&h.end<=e&&(l.pop(),p=!0):h instanceof te||h.end<e&&(l.pop(),p=!0);if(p){const T=I.last(l);T instanceof _&&T.end<=e&&l.pop()}if(!p)break}return l}),token:this.createQuery(11,e=>{const n=this.token.flatStream().findIndex(s=>s.start>=e);return n===void 0?{token:void 0,index:void 0}:n<=0?{token:void 0,index:void 0}:{token:this.token.flatStream()[n-1],index:n-1}}),element:this.createQuery(12,e=>{const n=this.container.stack(e);for(let s=n.length-1;s>=0;s-=1)if(n[s]instanceof _)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 F)return 8;switch((s=this.container.element(e).type)==null?void 0:s.value.toLowerCase()){case"table":return 0;case"enum":return 1;case"ref":return 5;case"tablegroup":return 2;case"indexes":return 3;case"note":return 4;case"project":return 6;default:return 7}})},this.symbol={ofName:this.createQuery(8,({nameStack:e,owner:n=this.parse.ast()})=>{var i;if(e.length===0)return[];const s=[];for(let r=n;r;r=r instanceof _?r.parent:void 0){if(!((i=r.symbol)!=null&&i.symbolTable))continue;const{symbolTable:a}=r.symbol;let l=[a],p=[];for(const h of e)p=l.flatMap(T=>Qt(h).flatMap(f=>{const N=T.get(f),g=se(f).unwrap_or(void 0);return!N||!g?[]:{...g,symbol:N}})),l=p.flatMap(T=>T.symbol.symbolTable?T.symbol.symbolTable:[]);s.push(...p)}return s},({nameStack:e,owner:n})=>`${e.join(".")}@${n.id}`),members:this.createQuery(9,e=>e.symbolTable?[...e.symbolTable.entries()].map(([n,s])=>({...se(n).unwrap(),symbol:s})):[])}}createQuery(e,n,s){return i=>{const r=this.cache[e],a=i&&s?s(i):i;if(r!==null){if(!(r instanceof Map))return r;if(r.has(a))return r.get(a)}const l=n(i);return i!==void 0?r instanceof Map?r.set(a,l):(this.cache[e]=new Map,this.cache[e].set(a,l)):this.cache[e]=l,l}}setSource(e){this.source=e,this.cache=new Array(16).fill(null),this.nodeIdGenerator.reset(),this.symbolIdGenerator.reset()}initMonacoServices(){return{definitionProvider:new Ct(this),referenceProvider:new Xt(this),autocompletionProvider:new Ft(this)}}}exports.Compiler=os;exports.serialize=Yt;exports.services=as;
|