@dbml/parse 0.0.1 → 3.1.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/LICENSE +202 -0
- package/dist/dbml-parse.js +10 -11
- package/dist/dbml-parse.mjs +2672 -3199
- package/package.json +3 -2
package/dist/dbml-parse.js
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("lodash");var l=(e=>(e.SPACE="<space>",e.TAB="<tab>",e.NEWLINE="<newline>",e.COMMA="<comma>",e.LPAREN="<lparen>",e.RPAREN="<rparen>",e.LBRACE="<lbrace>",e.RBRACE="<rbrace>",e.LBRACKET="<lbracket>",e.RBRACKET="<rbracket>",e.LANGLE="<langle>",e.RANGLE="<rangle>",e.OP="<op>",e.EOF="<eof>",e.NUMERIC_LITERAL="<number>",e.STRING_LITERAL="<string>",e.COLOR_LITERAL="<color>",e.FUNCTION_EXPRESSION="<function-expression>",e.QUOTED_STRING="<variable>",e.IDENTIFIER="<identifier>",e.SEMICOLON="<semicolon>",e.COLON="<colon>",e.SINGLE_LINE_COMMENT="<single-line-comment>",e.MULTILINE_COMMENT="<multiline-comment>",e))(l||{});function tr(e){switch(e.kind){case"<newline>":case"<space>":case"<tab>":case"<single-line-comment>":case"<multiline-comment>":return!0;default:return!1}}function at(e){if(!e)return!1;switch(e){case"+":case"-":case"*":case"/":case"%":case"<":case">":case"=":case"!":case".":case"&":case"|":return!0;default:return!1}}function ot(e){return e!==void 0&&e.kind==="<op>"}class P{constructor(t,r,s,n,i){this.kind=t,this.startPos=r,this.endPos=s,this.value=n,this.leadingTrivia=[],this.trailingTrivia=[],this.leadingInvalid=[],this.trailingInvalid=[],this.isInvalid=i,this.start=r.offset,this.end=s.offset}static create(t,r,s,n,i){return new P(t,r,s,n,i)}}function xt(e){return e.trailingTrivia.find(({kind:t})=>t===l.NEWLINE)!==void 0}function lt(e,t){return t.leadingTrivia.find(({kind:s})=>s===l.NEWLINE)!==void 0||xt(e)}function _t(e){return e.trailingTrivia.find(({kind:t})=>t===l.SPACE)!==void 0}function Ot(e){return e.trailingTrivia.length===0?e.end:Ot(C.last(e.trailingTrivia))}function vt(e){return e.leadingTrivia.length===0?e.start:vt(e.leadingTrivia[0])}function rr(e){return[l.SINGLE_LINE_COMMENT,l.MULTILINE_COMMENT].includes(e.kind)}class sr{constructor(){this.id=0}reset(){this.id=0}nextId(){return this.id++}}class O{constructor(t,r,s){this.id=t,this.kind=r;const n=s.find(a=>a!==void 0&&!Number.isNaN(a.start));n?(this.startPos=n.startPos,this.fullStart=n instanceof P?vt(n):n.fullStart):(this.startPos={offset:NaN,column:NaN,line:NaN},this.fullStart=NaN);const i=[...s].reverse().find(a=>a!==void 0&&!Number.isNaN(a.end));i?(this.endPos=i.endPos,this.fullEnd=i instanceof P?Ot(i):i.fullEnd):(this.endPos={offset:NaN,column:NaN,line:NaN},this.fullEnd=NaN),this.start=this.startPos.offset,this.end=this.endPos.offset}}var de=(e=>(e.PROGRAM="<program>",e.ELEMENT_DECLARATION="<element-declaration>",e.ATTRIBUTE="<attribute>",e.IDENTIFIER_STREAM="<identifer-stream>",e.LITERAL="<literal>",e.VARIABLE="<variable>",e.PREFIX_EXPRESSION="<prefix-expression>",e.INFIX_EXPRESSION="<infix-expression>",e.POSTFIX_EXPRESSION="<postfix-expression>",e.FUNCTION_EXPRESSION="<function-expression>",e.FUNCTION_APPLICATION="<function-application>",e.BLOCK_EXPRESSION="<block-expression>",e.LIST_EXPRESSION="<list-expression>",e.TUPLE_EXPRESSION="<tuple-expression>",e.CALL_EXPRESSION="<call-expression>",e.PRIMARY_EXPRESSION="<primary-expression>",e.GROUP_EXPRESSION="<group-expression>",e))(de||{});class ae extends O{constructor({body:t=[],eof:r},s){super(s,"<program>",[...t,r]),this.body=t,this.eof=r}}class A extends O{constructor({type:t,name:r,as:s,alias:n,attributeList:i,bodyColon:a,body:o},u){if(super(u,"<element-declaration>",[t,r,s,n,i,a,o]),a&&!(o instanceof te||o instanceof A))throw new Error("If an element has a simple body, it must be a function application node");this.type=t,this.name=r,this.as=s,this.alias=n,this.attributeList=i,this.bodyColon=a,this.body=o}}class q extends O{constructor({identifiers:t=[]},r){super(r,"<identifer-stream>",t||[]),this.identifiers=t}}class xe extends O{constructor({name:t,colon:r,value:s},n){super(n,"<attribute>",[t,r,s]),this.name=t,this.value=s,this.colon=r}}class z extends O{constructor({op:t,expression:r},s){super(s,"<prefix-expression>",[t,r]),this.op=t,this.expression=r}}class K extends O{constructor({op:t,leftExpression:r,rightExpression:s},n){super(n,"<infix-expression>",[r,t,s]),this.op=t,this.leftExpression=r,this.rightExpression=s}}class Ce extends O{constructor({op:t,expression:r},s){super(s,"<postfix-expression>",[r,t]),this.op=t,this.expression=r}}class B extends O{constructor({value:t},r){super(r,"<function-expression>",[t]),this.value=t}}class te extends O{constructor({callee:t,args:r=[]},s){super(s,"<function-application>",[t,...r]),this.callee=t,this.args=r}}class j extends O{constructor({blockOpenBrace:t,body:r=[],blockCloseBrace:s},n){super(n,"<block-expression>",[t,...r,s]),this.blockOpenBrace=t,this.body=r,this.blockCloseBrace=s}}class U extends O{constructor({listOpenBracket:t,elementList:r=[],commaList:s=[],listCloseBracket:n},i){super(i,"<list-expression>",[t,...yt(r,s),n]),this.listOpenBracket=t,this.elementList=r,this.commaList=s,this.listCloseBracket=n}}class Q extends O{constructor({tupleOpenParen:t,elementList:r=[],commaList:s=[],tupleCloseParen:n},i){super(i,"<tuple-expression>",[t,...yt(r,s),n]),this.tupleOpenParen=t,this.elementList=r,this.commaList=s,this.tupleCloseParen=n}}class qe extends Q{constructor({groupOpenParen:t,expression:r,groupCloseParen:s},n){super({tupleOpenParen:t,elementList:r&&[r],commaList:[],tupleCloseParen:s},n),this.kind="<group-expression>"}}class oe extends O{constructor({callee:t,argumentList:r},s){super(s,"<call-expression>",[t,r]),this.callee=t,this.argumentList=r}}class ue extends O{constructor({literal:t},r){super(r,"<literal>",[t]),this.literal=t}}class M extends O{constructor({variable:t},r){super(r,"<variable>",[t]),this.variable=t}}class S extends O{constructor({expression:t},r){super(r,"<primary-expression>",[t]),this.expression=t}}function yt(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e||[];const[r]=e,[s]=t;return(r.start<s.start?C.flatten(C.zip(e,t)):C.flatten(C.zip(t,e))).filter(n=>n!==null)}function nr(e,t=!1){return JSON.stringify(e,function(r,s){var n;return!(this instanceof ae)&&r==="symbol"?s==null?void 0:s.id:r==="symbol"?{symbolTable:s==null?void 0:s.symbolTable,id:s==null?void 0:s.id,references:s==null?void 0:s.references.map(i=>i.id),declaration:(n=s==null?void 0:s.declaration)==null?void 0:n.id}:r==="referee"||r==="parent"||r==="declaration"?s==null?void 0:s.id:r==="symbolTable"?Object.fromEntries(s.table):s},t?2:0)}class I{constructor(t){this.value=t}unwrap(){return this.value}unwrap_or(t){return this.value}and_then(t){return t(this.value)}map(t){return new I(t(this.value))}isOk(){return!0}}class T{unwrap(){throw new Error("Trying to unwrap a None value")}unwrap_or(t){return t}and_then(t){return new T}map(t){return new T}isOk(){return!1}}var N=(e=>(e.Schema="Schema",e.Table="Table",e.Column="Column",e.TableGroup="TableGroup",e.TableGroupField="TableGroup field",e.Enum="Enum",e.EnumField="Enum field",e))(N||{});function je(e){return`Schema:${e}`}function ze(e){return`Table:${e}`}function Ke(e){return`Column:${e}`}function Qe(e){return`Enum:${e}`}function Ye(e){return`Enum field:${e}`}function Me(e){return`TableGroup:${e}`}function kt(e){return`TableGroup field:${e}`}function Be(e,t){switch(t){case"Column":return Ke(e);case"Enum":return Qe(e);case"Enum field":return Ye(e);case"Schema":return je(e);case"Table":return ze(e);case"TableGroup":return Me(e);case"TableGroup field":return kt(e);default:throw new Error("Unreachable")}}function ee(e){const[t,r]=e.split(":");return Object.values(N).includes(t)?new I({name:r,kind:t}):new T}function ir(e){const t=ee(e).unwrap_or(void 0);if(!t)return!1;const{kind:r,name:s}=t;return r==="Schema"&&s==="public"}var x=(e=>(e[e.TopLevelContext=0]="TopLevelContext",e[e.ProjectContext=1]="ProjectContext",e[e.TableContext=2]="TableContext",e[e.TableGroupContext=3]="TableGroupContext",e[e.EnumContext=4]="EnumContext",e[e.RefContext=5]="RefContext",e[e.IndexesContext=6]="IndexesContext",e[e.NoteContext=7]="NoteContext",e[e.CustomContext=8]="CustomContext",e))(x||{});function ar(e,t){switch(e){case 0:return t===1||t===2||t===3||t===4||t===5;case 1:return t===2||t===3||t===4||t===7||t===5||t===8;case 2:return t===6||t===7||t===5;default:return!1}}class or{constructor(){this.stack=[0]}push(t){this.stack.push(t)}pop(){return this.stack.length===1?this.stack[0]:this.stack.pop()}top(){return this.stack[this.stack.length-1]}parent(){return this.stack.length===1?this.stack[0]:this.stack[this.stack.length-2]}isWithinContext(t){for(let r=this.stack.length-1;r>=0;r-=1)if(this.stack[r]===t)return!0;return!1}}class we{constructor(){this.table=new Map}has(t){return this.table.has(t)}set(t,r){this.table.set(t,r)}get(t,r){return this.table.get(t)||r!==void 0&&this.set(t,r)||r}entries(){return this.table.entries()}}class lr{constructor(){this.id=0}reset(){this.id=0}nextId(){return this.id++}}class St{constructor({symbolTable:t},r){this.references=[],this.id=r,this.symbolTable=t}}class cr{constructor({symbolTable:t,declaration:r},s){this.references=[],this.id=s,this.symbolTable=t,this.declaration=r}}class ur{constructor({declaration:t},r){this.references=[],this.id=r,this.declaration=t}}class Rt{constructor({symbolTable:t,declaration:r},s){this.references=[],this.id=s,this.symbolTable=t,this.declaration=r}}class Dt{constructor({declaration:t},r){this.references=[],this.id=r,this.declaration=t}}class hr{constructor({symbolTable:t,declaration:r},s){this.references=[],this.id=s,this.symbolTable=t,this.declaration=r}}class dr{constructor({declaration:t},r){this.references=[],this.id=r,this.declaration=t}}function fr(e,t){switch(t){case x.TableContext:return ze(e);case x.EnumContext:return Qe(e);case x.TableGroupContext:return Me(e);default:return}}function Er(e,t){switch(t){case x.TableContext:return Ke(e);case x.EnumContext:return Ye(e);case x.TableGroupContext:return Me(e);default:return}}function ct(e,t,r){switch(t){case x.TableContext:return r.create(Rt,{symbolTable:new we,declaration:e});case x.EnumContext:return r.create(cr,{symbolTable:new we,declaration:e});case x.TableGroupContext:return r.create(hr,{symbolTable:new we,declaration:e});default:return}}function pr(e,t,r){switch(t){case x.TableContext:return r.create(Dt,{declaration:e});case x.EnumContext:return r.create(ur,{declaration:e});case x.TableGroupContext:return r.create(dr,{declaration:e});default:return}}function Nr(e){return[je,ze,Qe,Me,Ke,Ye,kt].map(t=>t(e))}function He(e){const[t]=e;return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"}function ke(e){const[t]=e;return t>="0"&&t<="9"}function br(e){const[t]=e;return ke(t)||He(t)&&t.toLowerCase()>="a"&&t.toLowerCase()<="f"}function Ie(e){return He(e)||ke(e)}function ut(e,t){const r=[],s=Math.min(e.length,t.length);for(let n=0;n<s;n+=1)r.push(e[n],t[n]);return r.push(...e.slice(s),...t.slice(s)),r}function Ae(e,t){return e>=t.start&&e<t.end}var c=(e=>(e[e.UNKNOWN_SYMBOL=1e3]="UNKNOWN_SYMBOL",e[e.UNEXPECTED_SYMBOL=1001]="UNEXPECTED_SYMBOL",e[e.UNEXPECTED_EOF=1002]="UNEXPECTED_EOF",e[e.UNEXPECTED_NEWLINE=1003]="UNEXPECTED_NEWLINE",e[e.UNKNOWN_TOKEN=1004]="UNKNOWN_TOKEN",e[e.UNEXPECTED_TOKEN=1005]="UNEXPECTED_TOKEN",e[e.MISPLACED_LIST_NODE=1006]="MISPLACED_LIST_NODE",e[e.MISSING_SPACES=1007]="MISSING_SPACES",e[e.UNKNOWN_PREFIX_OP=1008]="UNKNOWN_PREFIX_OP",e[e.INVALID_OPERAND=1009]="INVALID_OPERAND",e[e.EMPTY_ATTRIBUTE_NAME=1010]="EMPTY_ATTRIBUTE_NAME",e[e.INVALID_NAME=3e3]="INVALID_NAME",e[e.UNEXPECTED_NAME=3001]="UNEXPECTED_NAME",e[e.NAME_NOT_FOUND=3002]="NAME_NOT_FOUND",e[e.DUPLICATE_NAME=3003]="DUPLICATE_NAME",e[e.INVALID_ALIAS=3004]="INVALID_ALIAS",e[e.UNEXPECTED_ALIAS=3005]="UNEXPECTED_ALIAS",e[e.UNEXPECTED_SETTINGS=3006]="UNEXPECTED_SETTINGS",e[e.INVALID_SETTINGS=3007]="INVALID_SETTINGS",e[e.UNEXPECTED_SIMPLE_BODY=3008]="UNEXPECTED_SIMPLE_BODY",e[e.UNEXPECTED_COMPLEX_BODY=3009]="UNEXPECTED_COMPLEX_BODY",e[e.INVALID_TABLE_CONTEXT=3010]="INVALID_TABLE_CONTEXT",e[e.INVALID_TABLE_SETTING=3011]="INVALID_TABLE_SETTING",e[e.DUPLICATE_TABLE_SETTING=3012]="DUPLICATE_TABLE_SETTING",e[e.INVALID_TABLEGROUP_CONTEXT=3013]="INVALID_TABLEGROUP_CONTEXT",e[e.INVALID_TABLEGROUP_ELEMENT_NAME=3014]="INVALID_TABLEGROUP_ELEMENT_NAME",e[e.DUPLICATE_TABLEGROUP_ELEMENT_NAME=3015]="DUPLICATE_TABLEGROUP_ELEMENT_NAME",e[e.INVALID_TABLEGROUP_FIELD=3016]="INVALID_TABLEGROUP_FIELD",e[e.INVALID_COLUMN=3017]="INVALID_COLUMN",e[e.INVALID_COLUMN_NAME=3018]="INVALID_COLUMN_NAME",e[e.UNKNOWN_COLUMN_SETTING=3019]="UNKNOWN_COLUMN_SETTING",e[e.INVALID_COLUMN_TYPE=3020]="INVALID_COLUMN_TYPE",e[e.DUPLICATE_COLUMN_NAME=3021]="DUPLICATE_COLUMN_NAME",e[e.DUPLICATE_COLUMN_SETTING=3022]="DUPLICATE_COLUMN_SETTING",e[e.INVALID_COLUMN_SETTING_VALUE=3023]="INVALID_COLUMN_SETTING_VALUE",e[e.INVALID_ENUM_CONTEXT=3024]="INVALID_ENUM_CONTEXT",e[e.INVALID_ENUM_ELEMENT_NAME=3025]="INVALID_ENUM_ELEMENT_NAME",e[e.INVALID_ENUM_ELEMENT=3026]="INVALID_ENUM_ELEMENT",e[e.DUPLICATE_ENUM_ELEMENT_NAME=3027]="DUPLICATE_ENUM_ELEMENT_NAME",e[e.UNKNOWN_ENUM_ELEMENT_SETTING=3028]="UNKNOWN_ENUM_ELEMENT_SETTING",e[e.DUPLICATE_ENUM_ELEMENT_SETTING=3029]="DUPLICATE_ENUM_ELEMENT_SETTING",e[e.INVALID_ENUM_ELEMENT_SETTING=3030]="INVALID_ENUM_ELEMENT_SETTING",e[e.INVALID_REF_CONTEXT=3031]="INVALID_REF_CONTEXT",e[e.UNKNOWN_REF_SETTING=3032]="UNKNOWN_REF_SETTING",e[e.DUPLICATE_REF_SETTING=3033]="DUPLICATE_REF_SETTING",e[e.INVALID_REF_SETTING_VALUE=3034]="INVALID_REF_SETTING_VALUE",e[e.INVALID_REF_RELATIONSHIP=3035]="INVALID_REF_RELATIONSHIP",e[e.INVALID_REF_FIELD=3036]="INVALID_REF_FIELD",e[e.INVALID_NOTE_CONTEXT=3037]="INVALID_NOTE_CONTEXT",e[e.INVALID_NOTE=3038]="INVALID_NOTE",e[e.NOTE_REDEFINED=3039]="NOTE_REDEFINED",e[e.NOTE_CONTENT_REDEFINED=3040]="NOTE_CONTENT_REDEFINED",e[e.INVALID_INDEXES_CONTEXT=3041]="INVALID_INDEXES_CONTEXT",e[e.INVALID_INDEXES_FIELD=3042]="INVALID_INDEXES_FIELD",e[e.INVALID_INDEX=3043]="INVALID_INDEX",e[e.UNKNOWN_INDEX_SETTING=3044]="UNKNOWN_INDEX_SETTING",e[e.DUPLICATE_INDEX_SETTING=3045]="DUPLICATE_INDEX_SETTING",e[e.UNEXPECTED_INDEX_SETTING_VALUE=3046]="UNEXPECTED_INDEX_SETTING_VALUE",e[e.INVALID_INDEX_SETTING_VALUE=3047]="INVALID_INDEX_SETTING_VALUE",e[e.INVALID_PROJECT_CONTEXT=3048]="INVALID_PROJECT_CONTEXT",e[e.PROJECT_REDEFINED=3049]="PROJECT_REDEFINED",e[e.INVALID_PROJECT_FIELD=3050]="INVALID_PROJECT_FIELD",e[e.INVALID_CUSTOM_CONTEXT=3051]="INVALID_CUSTOM_CONTEXT",e[e.INVALID_CUSTOM_ELEMENT_VALUE=3052]="INVALID_CUSTOM_ELEMENT_VALUE",e[e.INVALID_ELEMENT_IN_SIMPLE_BODY=3053]="INVALID_ELEMENT_IN_SIMPLE_BODY",e[e.BINDING_ERROR=4e3]="BINDING_ERROR",e[e.UNSUPPORTED=5e3]="UNSUPPORTED",e[e.CIRCULAR_REF=5001]="CIRCULAR_REF",e[e.SAME_ENDPOINT=5002]="SAME_ENDPOINT",e[e.UNEQUAL_FIELDS_BINARY_REF=5003]="UNEQUAL_FIELDS_BINARY_REF",e[e.CONFLICTING_SETTING=5004]="CONFLICTING_SETTING",e))(c||{});class w extends Error{constructor(t,r,s){super(r),this.code=t,this.diagnostic=r,this.nodeOrToken=s,this.start=s.start,this.end=s.end,this.name=this.constructor.name,Object.setPrototypeOf(this,w.prototype)}isTokenError(){return this.nodeOrToken instanceof P}isNodeError(){return!(this.nodeOrToken instanceof P)}}class H{constructor(t,r){this.value=t,this.errors=r===void 0?[]:r}getValue(){return this.value}getErrors(){return this.errors}chain(t){const r=t(this.value),s=[...this.errors,...r.errors];return new H(r.value,s)}map(t){return new H(t(this.value),this.errors)}}function mr(e,t,r){if(!e||!Lr(e)||t.length===0)return new T;const s=[...t],n=ve(e).unwrap(),i=s.pop();if(!(i instanceof j))return new T;const a=C.last(s)instanceof U?s.pop():void 0;return s.length===3&&ve(s[1]).unwrap().value==="as"?new I(r.create(A,{type:n,name:s[0],as:ve(s[1]).unwrap(),alias:s[2],attributeList:a,body:i})):s.length===1?new I(r.create(A,{type:n,name:s[0],attributeList:a,body:i})):s.length===0?new I(r.create(A,{type:n,attributeList:a,body:i})):new T}function ht(e){return e.kind===l.IDENTIFIER&&e.value==="as"}function E(e){e&&(e instanceof P?gr(e):Tr(e))}function gr(e){e.kind!==l.EOF&&(e.isInvalid=!0)}function Tr(e){if(e instanceof A)E(e.type),E(e.name),E(e.as),E(e.alias),E(e.bodyColon),E(e.attributeList),E(e.body);else if(e instanceof q)e.identifiers.forEach(E);else if(e instanceof xe)E(e.name),E(e.colon),E(e.value);else if(e instanceof z)E(e.op),E(e.expression);else if(e instanceof K)E(e.leftExpression),E(e.op),E(e.rightExpression);else if(e instanceof Ce)E(e.op),E(e.expression);else if(e instanceof j)E(e.blockOpenBrace),e.body.forEach(E),E(e.blockCloseBrace);else if(e instanceof U)E(e.listOpenBracket),e.commaList.forEach(E),e.elementList.forEach(E),E(e.listCloseBracket);else if(e instanceof Q)E(e.tupleOpenParen),e.commaList.forEach(E),e.elementList.forEach(E),E(e.tupleCloseParen);else if(e instanceof oe)E(e.callee),E(e.argumentList);else if(e instanceof te)E(e.callee),e.args.forEach(E);else if(e instanceof S)E(e.expression);else if(e instanceof B)E(e.value);else if(e instanceof M)E(e.variable);else if(e instanceof ue)E(e.literal);else throw e instanceof qe?new Error("This case is handled by the TupleExpressionNode case"):new Error("Unreachable case in markInvalidNode")}function Ct(e){return!!(e!=null&&e.isInvalid)}function D(...e){return e.filter(t=>t!==void 0)}function Ir(e){if(e instanceof ae)return D(...e.body,e.eof);if(e instanceof A)return D(e.type,e.name,e.as,e.alias,e.attributeList,e.bodyColon,e.body);if(e instanceof xe)return D(e.name,e.colon,e.value);if(e instanceof q)return e.identifiers;if(e instanceof ue)return e.literal?[e.literal]:[];if(e instanceof M)return D(e.variable);if(e instanceof z)return D(e.op,e.expression);if(e instanceof K)return D(e.leftExpression,e.op,e.rightExpression);if(e instanceof Ce)return D(e.expression,e.op);if(e instanceof B)return D(e.value);if(e instanceof te)return D(e.callee,...e.args);if(e instanceof j)return D(e.blockOpenBrace,...e.body,e.blockCloseBrace);if(e instanceof U)return D(e.listOpenBracket,...ut(e.elementList,e.commaList),e.listCloseBracket);if(e instanceof Q)return D(e.tupleOpenParen,...ut(e.elementList,e.commaList),e.tupleCloseParen);if(e instanceof oe)return D(e.callee,e.argumentList);if(e instanceof S)return D(e.expression);throw e instanceof qe?new Error("This case is already handled by TupleExpressionNode"):new Error("Unreachable - no other possible cases")}function ve(e){return Y(e)?new I(e.expression.variable):new T}function J(e){var t;return e instanceof S&&(e.expression instanceof M&&e.expression.variable instanceof P||e.expression instanceof ue&&((t=e.expression.literal)==null?void 0:t.kind)===l.STRING_LITERAL)}function Y(e){return e instanceof S&&e.expression instanceof M&&e.expression.variable instanceof P}function Lr(e){var t;return e instanceof S&&e.expression instanceof M&&((t=e.expression.variable)==null?void 0:t.kind)===l.IDENTIFIER}function Pe(e){var t;return e instanceof K&&e.leftExpression instanceof O&&e.rightExpression instanceof O&&((t=e.op)==null?void 0:t.value)==="."}function le(e){if(e===void 0)return new T;const t=e.identifiers.map(r=>r.value).join(" ");return t===""?new T:new I(t)}function dt(e){return e.create(B,{})}function Mt(e){return e instanceof B&&e.value===void 0}class wr{constructor(t){this.start={offset:0,line:0,column:0},this.current={offset:0,line:0,column:0},this.tokens=[],this.errors=[],this.text=t}isAtEnd(){return this.current.offset>=this.text.length}advance(){const t=this.peek();return this.current={...this.current},t===`
|
|
2
|
-
`?(this.current.line+=1,this.current.column=0):this.current.column+=1,this.current.offset+=1,
|
|
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 t="";for(let r=0;r<=3;r+=1){if(this.isAtEnd()||!Ie(this.peek()))return`\\u${t}`;t+=this.advance()}return String.fromCharCode(parseInt(t,16))}default:return`\\${this.tokens[this.current.offset-1]}`}}}var ye=(e=>(e[e.ListExpression=0]="ListExpression",e[e.GroupExpression=1]="GroupExpression",e[e.BlockExpression=2]="BlockExpression",e))(ye||{});class Ar{constructor(){this.stack=[],this.numberOfNestedLParens=0,this.numberOfNestedLBrackets=0,this.numberOfNestedLBraces=0}push(t){this.stack.push(t),t===0&&(this.numberOfNestedLBrackets+=1),t===1&&(this.numberOfNestedLParens+=1),t===2&&(this.numberOfNestedLBraces+=1)}pop(){const t=this.stack.pop();return t===0&&(this.numberOfNestedLBrackets-=1),t===1&&(this.numberOfNestedLParens-=1),t===2&&(this.numberOfNestedLBraces-=1),t}top(){return C.last(this.stack)}isWithinGroupExpressionContext(){return this.numberOfNestedLParens>0}isWithinListExpressionContext(){return this.numberOfNestedLBrackets>0}isWithinBlockExpressionContext(){return this.numberOfNestedLBraces>0}withContextDo(t,r){return()=>{this.push(t);try{return r()}finally{this.pop()}}}findHandlerContext(t,r){if(!(this.numberOfNestedLBraces<=0&&this.numberOfNestedLBrackets<=0&&this.numberOfNestedLParens<=0))for(let s=r;s<t.length-1;s+=1)switch(t[s].kind){case l.COMMA:if(this.isWithinGroupExpressionContext()||this.isWithinListExpressionContext())return[...this.stack].reverse().find(i=>[1,0].includes(i));break;case l.RPAREN:if(this.isWithinGroupExpressionContext())return 1;break;case l.RBRACE:if(this.isWithinBlockExpressionContext())return 2;break;case l.RBRACKET:if(this.isWithinListExpressionContext())return 0;break}}}class xr{constructor(t){this.generator=t}create(t,r){return new t(r,this.generator.nextId())}}class d{constructor(t,r,s){this.token=t,this.partialNode=r,this.handlerContext=s}}class _r{constructor(t,r){this.current=0,this.errors=[],this.contextStack=new Ar,this.synchronizeProgram=()=>{const s=this.peek();s.kind!==l.EOF?E(this.advance()):(E(this.peek()),this.logError(s,c.UNEXPECTED_EOF,"Unexpected EOF"))},this.synchronizeElementDeclarationName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(ht(s)||this.check(l.COLON,l.LBRACE,l.LBRACKET))break;E(s),this.advance()}},this.synchronizeElementDeclarationAlias=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(l.COLON,l.LBRACE,l.LBRACKET))break;E(s),this.advance()}},this.blockExpression=this.contextStack.withContextDo(ye.BlockExpression,()=>{const s={body:[]},n=()=>this.nodeFactory.create(j,s);try{this.consume("Expect an opening brace '{'",l.LBRACE),s.blockOpenBrace=this.previous()}catch(i){if(!(i instanceof d))throw i;if(s.blockOpenBrace=i.partialNode,!this.canHandle(i))throw new d(i.token,n(),i.handlerContext);this.synchronizeBlock()}for(;!this.isAtEnd()&&!this.check(l.RBRACE);)try{s.body.push(this.canBeField()?this.fieldDeclaration():this.expression())}catch(i){if(!(i instanceof d))throw i;if(s.body.push(i.partialNode),!this.canHandle(i))throw new d(i.token,n(),i.handlerContext);this.synchronizeBlock()}try{this.consume("Expect a closing brace '}'",l.RBRACE),s.blockCloseBrace=this.previous()}catch(i){if(!(i instanceof d))throw i;if(s.blockCloseBrace=i.partialNode,!this.canHandle(i))throw new d(i.token,n(),i.handlerContext);this.synchronizeBlock()}return n()}),this.synchronizeBlock=()=>{if(!this.check(l.RBRACE))for(E(this.advance());!this.isAtEnd();){const s=this.peek();if(this.check(l.RBRACE)||lt(this.previous(),s))break;E(s),this.advance()}},this.tupleExpression=this.contextStack.withContextDo(ye.GroupExpression,()=>{const s={elementList:[],commaList:[]},n=()=>this.nodeFactory.create(qe,{groupOpenParen:s.tupleOpenParen,groupCloseParen:s.tupleCloseParen,expression:s.elementList[0]}),i=()=>this.nodeFactory.create(Q,s);try{this.consume("Expect an opening parenthesis '('",l.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,i(),a.handlerContext);this.synchronizeTuple()}if(!this.isAtEnd()&&!this.check(l.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,n(),a.handlerContext);this.synchronizeTuple()}for(;!this.isAtEnd()&&!this.check(l.RPAREN);)try{this.consume("Expect a comma ','",l.COMMA),s.commaList.push(this.previous()),s.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof d))throw a;if(a.partialNode instanceof O&&s.elementList.push(a.partialNode),!this.canHandle(a))throw new d(a.token,i(),a.handlerContext);this.synchronizeTuple()}try{this.consume("Expect a closing parenthesis ')'",l.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,i(),a.handlerContext);this.synchronizeTuple()}return s.elementList.length===1?n():i()}),this.synchronizeTuple=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(l.RPAREN,l.COMMA))break;E(s),this.advance()}},this.listExpression=this.contextStack.withContextDo(ye.ListExpression,()=>{const s={elementList:[],commaList:[]},n=()=>this.nodeFactory.create(U,s);try{this.consume("Expect an opening bracket '['",l.LBRACKET),s.listOpenBracket=this.previous()}catch(i){if(!(i instanceof d))throw i;if(s.listOpenBracket=i.partialNode,!this.canHandle(i))throw new d(i.token,n(),i.handlerContext);this.synchronizeList()}if(!this.isAtEnd()&&!this.check(l.RBRACKET))try{s.elementList.push(this.attribute())}catch(i){if(!(i instanceof d))throw i;if(s.elementList.push(i.partialNode),!this.canHandle(i))throw new d(i.token,n(),i.handlerContext);this.synchronizeList()}for(;!this.isAtEnd()&&!this.check(l.RBRACKET);)try{this.consume("Expect a comma ','",l.COMMA),s.commaList.push(this.previous()),s.elementList.push(this.attribute())}catch(i){if(!(i instanceof d))throw i;if(s.elementList.push(i.partialNode),!this.canHandle(i))throw new d(i.token,n(),i.handlerContext);this.synchronizeList()}try{this.consume("Expect a closing bracket ']'",l.RBRACKET),s.listCloseBracket=this.previous()}catch(i){if(!(i instanceof d))throw i;if(s.listCloseBracket=i.partialNode,!this.canHandle(i))throw new d(i.token,n(),i.handlerContext);this.synchronizeList()}return n()}),this.synchronizeList=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(l.COMMA,l.RBRACKET))break;E(s),this.advance()}},this.synchronizeAttributeName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(l.COMMA,l.RBRACKET,l.COLON))break;E(s),this.advance()}},this.synchronizeAttributeValue=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(l.COMMA,l.RBRACKET))break;E(s),this.advance()}},this.tokens=t,this.nodeFactory=new xr(r)}isAtEnd(){return this.current>=this.tokens.length||this.tokens[this.current].kind===l.EOF}advance(){return this.isAtEnd()?C.last(this.tokens):this.tokens[this.current++]}peek(t=0){return t+this.current>=this.tokens.length?C.last(this.tokens):this.tokens[this.current+t]}match(...t){const r=this.check(...t);return r&&this.advance(),r}check(...t){const r=this.peek();return t.includes(r.kind)}previous(){return this.tokens[this.current-1]}canHandle(t){return t.handlerContext===void 0||t.handlerContext===this.contextStack.top()}consume(t,...r){if(!this.match(...r))throw this.logError(this.peek(),c.UNEXPECTED_TOKEN,t),new d(this.peek(),void 0,this.contextStack.findHandlerContext(this.tokens,this.current))}discardUntil(t,...r){if(this.isAtEnd()||!this.check(...r)){for(E(this.peek()),this.logError(this.advance(),c.UNEXPECTED_TOKEN,t);!this.isAtEnd()&&!this.check(...r);)E(this.advance());return!this.isAtEnd()}return!0}gatherInvalid(){const t=[],r=[];let s,n=0;for(;n<this.tokens.length&&this.tokens[n].isInvalid;n+=1)r.push(this.tokens[n]);for(s=this.tokens[n],s.leadingInvalid=r,t.push(s),n+=1;n<this.tokens.length;n+=1){const i=this.tokens[n];i.isInvalid?s.trailingInvalid.push(i):(s=i,t.push(s))}this.tokens=t}parse(){const t=this.program(),r=this.advance(),s=this.nodeFactory.create(ae,{body:t,eof:r});return this.gatherInvalid(),new H({ast:s,tokens:this.tokens},this.errors)}program(){const t=[];for(;!this.isAtEnd();)try{const r=this.elementDeclaration();t.push(r)}catch(r){if(!(r instanceof d))throw r;t.push(r.partialNode),this.synchronizeProgram()}return t}elementDeclaration(){const t={},r=()=>this.nodeFactory.create(A,t);try{this.consume("Expect an identifier",l.IDENTIFIER),t.type=this.previous()}catch(s){throw s instanceof d?(t.type=s.partialNode,new d(s.token,r(),s.handlerContext)):s}if(!this.check(l.COLON,l.LBRACE,l.LBRACKET))try{t.name=this.normalExpression()}catch(s){if(!(s instanceof d))throw s;if(t.name=s.partialNode,!this.canHandle(s))throw new d(s.token,r(),s.handlerContext);this.synchronizeElementDeclarationName()}if(ht(this.peek()))if(t.as=this.advance(),this.check(l.COLON,l.LBRACE,l.LBRACKET))this.logError(this.peek(),c.UNEXPECTED_TOKEN,"Expect an alias");else try{t.alias=this.normalExpression()}catch(s){if(!(s instanceof d))throw s;if(t.alias=s.partialNode,!this.canHandle(s))throw new d(s.token,r(),s.handlerContext);this.synchronizeElementDeclarationAlias()}try{t.attributeList=this.check(l.LBRACKET)?this.listExpression():void 0}catch(s){throw s instanceof d?(t.attributeList=s.partialNode,new d(s.token,r(),s.handlerContext)):s}if(!this.discardUntil("Expect an opening brace '{' or a colon ':'",l.LBRACE,l.COLON))return r();try{this.match(l.COLON)?(t.bodyColon=this.previous(),t.body=this.expression()):t.body=this.blockExpression()}catch(s){throw s instanceof d?(t.body=s.partialNode,new d(s.token,r(),s.handlerContext)):s}return this.nodeFactory.create(A,t)}fieldDeclaration(){const t={},r=()=>this.nodeFactory.create(A,t);try{this.consume("Expect an identifier",l.IDENTIFIER),t.type=this.previous()}catch(s){throw s instanceof d?(t.type=s.partialNode,new d(s.token,r(),s.handlerContext)):s}try{this.consume("Expect a colon ':'",l.COLON),t.bodyColon=this.previous()}catch(s){throw s instanceof d?(t.bodyColon=s.partialNode,new d(s.token,r(),s.handlerContext)):s}try{t.body=this.expression()}catch(s){throw s instanceof d?(t.body=s.partialNode,new d(s.token,r(),s.handlerContext)):s}return this.nodeFactory.create(A,t)}expression(){const t={args:[]},r=()=>mr(t.callee,t.args,this.nodeFactory).unwrap_or(this.nodeFactory.create(te,t));try{t.callee=this.normalExpression()}catch(n){throw n instanceof d?(t.callee=n.partialNode,new d(n.token,r(),n.handlerContext)):n}if(this.shouldStopExpression())return r();let s=t.callee;for(;!this.shouldStopExpression();){_t(this.previous())||this.logError(s,c.MISSING_SPACES,"Expect a following space");try{s=this.normalExpression(),t.args.push(s)}catch(n){throw n instanceof d?(s=n.partialNode,t.args.push(s),new d(n.token,r(),n.handlerContext)):n}}return r()}shouldStopExpression(){if(this.isAtEnd()||xt(this.previous()))return!0;const t=this.peek().kind;return t===l.RBRACE||t===l.RBRACKET||t===l.RPAREN||t===l.COMMA||t===l.COLON}normalExpression(){return this.expression_bp(0)}expression_bp(t){let r=this.leftExpression_bp();for(;!this.isAtEnd();){const s=this.peek();if(s.kind===l.LPAREN){const{left:n}=ft(s);if(n<t||lt(this.previous(),s)&&!this.contextStack.isWithinGroupExpressionContext()&&!this.contextStack.isWithinListExpressionContext())break;try{r=this.nodeFactory.create(oe,{callee:r,argumentList:this.tupleExpression()})}catch(i){throw i instanceof d?(r=this.nodeFactory.create(oe,{callee:r,argumentList:i.partialNode}),new d(i.token,r,i.handlerContext)):i}}else if(ot(s)){const n=s,i=ft(n);if(i.left!==null){if(i.left<=t)break;this.advance(),r=this.nodeFactory.create(Ce,{expression:r,op:n})}else{const a=vr(n);if(a.left===null||a.left<=t)break;this.advance();try{r=this.nodeFactory.create(K,{leftExpression:r,op:n,rightExpression:n.value==="."?this.extractOperand():this.expression_bp(a.right)})}catch(o){throw o instanceof d?(r=this.nodeFactory.create(K,{leftExpression:r,op:n,rightExpression:o.partialNode}),new d(o.token,r,o.handlerContext)):o}}}else break}return r}leftExpression_bp(){let t;if(ot(this.peek())){const r={};r.op=this.peek();const s=kr(r.op);s.right===null&&(this.logError(r.op,c.UNKNOWN_PREFIX_OP,`Unexpected '${r.op.value}' in an expression`),this.throwDummyOperand(r.op)),this.advance();try{r.expression=this.expression_bp(s.right)}catch(n){throw n instanceof d?(r.expression=n.partialNode,new d(n.token,this.nodeFactory.create(z,r),n.handlerContext)):n}t=this.nodeFactory.create(z,r)}else t=this.extractOperand(),Mt(t)&&this.throwDummyOperand(this.peek());return t}extractOperand(){return this.check(l.NUMERIC_LITERAL,l.STRING_LITERAL,l.COLOR_LITERAL,l.QUOTED_STRING,l.IDENTIFIER)?this.primaryExpression():this.check(l.FUNCTION_EXPRESSION)?this.functionExpression():this.check(l.LBRACKET)?this.listExpression():this.check(l.LBRACE)?this.blockExpression():this.check(l.LPAREN)?this.tupleExpression():(this.peek().kind===l.EOF?this.logError(this.peek(),c.UNEXPECTED_EOF,"Unexpected EOF"):this.logError(this.peek(),c.INVALID_OPERAND,`Invalid start of operand "${this.peek().value}"`),dt(this.nodeFactory))}throwDummyOperand(t){throw new d(t,dt(this.nodeFactory),this.contextStack.findHandlerContext(this.tokens,this.current))}functionExpression(){const t={};try{this.consume("Expect a function expression",l.FUNCTION_EXPRESSION),t.value=this.previous()}catch(r){throw r instanceof d?(t.value=r.partialNode,new d(r.token,this.nodeFactory.create(B,t),r.handlerContext)):r}return this.nodeFactory.create(B,t)}canBeField(){return this.peek().kind===l.IDENTIFIER&&this.peek(1).kind===l.COLON}primaryExpression(){if(this.match(l.COLOR_LITERAL,l.STRING_LITERAL,l.NUMERIC_LITERAL))return this.nodeFactory.create(S,{expression:this.nodeFactory.create(ue,{literal:this.previous()})});if(this.match(l.QUOTED_STRING,l.IDENTIFIER))return this.nodeFactory.create(S,{expression:this.nodeFactory.create(M,{variable:this.previous()})});throw this.logError(this.peek(),c.UNEXPECTED_TOKEN,"Expect a variable or literal"),new d(this.peek(),this.nodeFactory.create(S,{expression:this.nodeFactory.create(M,{})}),this.contextStack.findHandlerContext(this.tokens,this.current))}attribute(){const t={};if(this.check(l.COLON,l.RBRACKET,l.COMMA)){const r=this.peek();this.logError(r,c.EMPTY_ATTRIBUTE_NAME,"Expect a non-empty attribute name"),t.name=this.nodeFactory.create(q,{identifiers:[]})}else try{t.name=this.extractIdentifierStream()}catch(r){if(!(r instanceof d))throw r;if(t.name=r.partialNode,!this.canHandle(r))throw new d(r.token,this.nodeFactory.create(xe,t),r.handlerContext);this.synchronizeAttributeName()}return this.match(l.COLON)&&(t.colon=this.previous(),t.value=this.attributeValue()),this.nodeFactory.create(xe,t)}attributeValue(){let t;try{t=this.peek().kind===l.IDENTIFIER&&this.peek(1).kind===l.IDENTIFIER?this.extractIdentifierStream():this.normalExpression()}catch(r){if(!(r instanceof d)||!this.canHandle(r))throw r;t=r.partialNode,this.synchronizeAttributeValue()}return t}extractIdentifierStream(){const t=[];for(;!this.isAtEnd()&&!this.check(l.COLON,l.COMMA,l.RBRACKET);)if(this.match(l.QUOTED_STRING,l.STRING_LITERAL,l.NUMERIC_LITERAL))E(this.previous()),this.logError(this.previous(),c.UNEXPECTED_TOKEN,"Expect an identifier");else try{this.consume("Expect an identifier",l.IDENTIFIER),t.push(this.previous())}catch(r){throw r instanceof d?new d(r.token,this.nodeFactory.create(q,{identifiers:t}),r.handlerContext):r}return this.nodeFactory.create(q,{identifiers:t})}logError(t,r,s){this.errors.push(new w(r,s,t))}}const Or={"+":{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 vr(e){return Or[e.value]||{left:null,right:null}}const yr={"+":{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 kr(e){return yr[e.value]||{left:null,right:null}}const Sr={"(":{left:14,right:null}};function ft(e){return Sr[e.value]||{left:null,right:null}}function Ee(e){if(!Pe(e))return new I([e]);const t=Ee(e.leftExpression).unwrap_or(void 0);return t?(t.push(e.rightExpression),new I(t)):new T}function pe(e){if(e===void 0)return new T;const t=Ee(e).unwrap_or(void 0);if(!t)return new T;const r=[];for(const s of t){const n=Je(s).unwrap_or(void 0);if(!n)return new T;r.push(n)}return new I(r)}function Ge(e){if(e===void 0)return new T;const t=Ee(e).unwrap_or(void 0);if(!t||t.length===0)return new T;const r=[];let s;if(!Y(C.last(t))){const n=t.pop();if(jt(n))s=n.elementList.map(i=>W(i).unwrap());else return new T}for(const n of t){const i=Je(n).unwrap_or(void 0);if(!i)return new T;r.push(i)}return new I({variables:r,tupleElements:s})}function Je(e){return Y(e)?new I(e.expression.variable.value):new T}function Pt(e){if(Et(e))return e instanceof B?new I({functional:[e],nonFunctional:[]}):new I({functional:[],nonFunctional:[e]});if(e instanceof Q&&e.elementList.every(Et)){const t=e.elementList.filter(s=>s instanceof B),r=e.elementList.filter(Y);return new I({functional:t,nonFunctional:r})}return new T}function W(e){var r;const t=(r=e.expression.variable)==null?void 0:r.value;return t===void 0?new T:new I(t)}function fe(e){return J(e)?e.expression instanceof M?new I(e.expression.variable.value):new I(e.expression.literal.value):new T}function Rr(e){var t;return!(e instanceof K)||!qt((t=e.op)==null?void 0:t.value)?!1:Ge(e.leftExpression).and_then(()=>Ge(e.rightExpression)).unwrap_or(void 0)!==void 0}function Et(e){return e instanceof S&&e.expression instanceof M||e instanceof B}function Dr(e,t){var n,i,a,o;let r=t;const s=ir(e);for(;r;){if((i=(n=r.symbol)==null?void 0:n.symbolTable)!=null&&i.has(e))return(a=r.symbol.symbolTable)==null?void 0:a.get(e);if(((o=r.symbol)==null?void 0:o.declaration)instanceof ae&&s)return r.symbol;if(r instanceof ae)return;r=r.parent}}var m=(e=>(e.TABLE="Table",e.ENUM="Enum",e.INDEXES="Indexes",e.NOTE="Note",e.PROJECT="Project",e.REF="Ref",e.TABLEGROUP="TableGroup",e.CUSTOM="custom element",e))(m||{});function Ze(e){if(e.globally&&!e.notGloballyErrorCode)throw new Error("Misconfigurartion: If an element is globally unique, notGloballyErrorCode must be set");if(e.locally&&!e.notLocallyErrorCode)throw new Error("Misconfigurartion: If an element is locally unique, notLocallyErrorCode must be set");return e}function et(e){if(!e.optional&&!e.notOptionalErrorCode)throw new Error("Misconfiguration: If name is not optional, notOptionalErrorCode must be present");if(!e.allow&&!e.notAllowErrorCode)throw new Error("Misconfiguration: If name is not allowed, notAllowErrorCode must be present");if(e.shouldRegister&&!e.duplicateErrorCode)throw new Error("Misconfiguration: If name should be registered, duplicateErrorCode must be present");return e}function Ut(e){if(!e.optional&&!e.notOptionalErrorCode)throw new Error("Misconfiguration: If alias is not optional, notOptionalErrorCode must be present");if(!e.allow&&!e.notAllowErrorCode)throw new Error("Misconfiguration: If alias is not allowed, notAllowErrorCode must be present");return e}function Ne(e,t){if(!t.optional&&!t.notOptionalErrorCode)throw new Error("Misconfiguration: If settingList is not optional, notOptionalErrorCode must be present");if(!t.allow&&!t.notAllowErrorCode)throw new Error("Misconfiguration: If settingList is not allowed, notAllowErrorCode must be present");if(t.allow&&!t.unknownErrorCode)throw new Error("Misconfiguration: If settingList is allowed, unknownErrorCode must be present");if(t.allow&&!t.duplicateErrorCode)throw new Error("Misconfiguration: If settingList is allowed, duplicateErrorCode must be present");if(t.allow&&!t.invalidErrorCode)throw new Error("Misconfiguration: If settingList is allowed, notAllowErrorCode must be present");return{...t,isValid(r,s){const n=e[r];return n?new I(n.isValid(s)):new T},allowDuplicate(r){const s=e[r];return s?new I(s.allowDuplicate):new T}}}function tt(e){if(!e.allowSimple&&!e.simpleErrorCode)throw new Error("Misconfiguration: If simple body is not allowed, simpleErrorCode must be set");if(!e.allowComplex&&!e.complexErrorCode)throw new Error("Misconfiguration: If complex body is not allowed, complexErrorCode must be set");return e}function re(e){if(e.shouldRegister&&!e.duplicateErrorCode)throw new Error("Misconfiguration: If subfield should be registered, duplicateErrorCode must be present");return e}function Cr(e){return e===m.CUSTOM}function Ve(e){switch(e){case m.TABLE:return"column";case m.ENUM:return"field";case m.TABLEGROUP:return"table";default:return"subfield"}}function ce(e,t,r){return(s,n)=>e(s,n)?[]:[new w(t,r,s)]}class se{constructor(t,r,s,n,i,a,o){this.declarationNode=t,this.publicSchemaSymbol=r,this.contextStack=s,this.errors=n,this.kindsGloballyFound=i,this.kindsLocallyFound=a,this.symbolFactory=o}validate(){this.contextStack.push(this.context.name);const t=this.validateContext()&&this.validateUnique()&&this.validateName()&&this.validateAlias()&&this.validateSettingList()&&this.validateBodyForm()&&this.validateBodyContent();return this.contextStack.pop(),t}validateUnique(){return this.validateGloballyUnique()&&this.validateLocallyUnique()||!this.unique.stopOnError}validateLocallyUnique(){return this.unique.locally?this.kindsLocallyFound.has(this.elementKind)?(this.logError(this.declarationNode.type,this.unique.notLocallyErrorCode,`A(n) ${this.elementKind} has already been defined in this scope`),!1):(this.kindsLocallyFound.add(this.elementKind),!0):!0}validateGloballyUnique(){return this.unique.globally?this.kindsGloballyFound.has(this.elementKind)?(this.logError(this.declarationNode.type,this.unique.notGloballyErrorCode,`A(n) ${this.elementKind} has already been defined in this file`),!1):(this.kindsGloballyFound.add(this.elementKind),!0):!0}validateContext(){return ar(this.contextStack.parent(),this.contextStack.top())?!0:(this.logError(this.declarationNode.type,this.context.errorCode,Cr(this.elementKind)?"Unknown element type":`A(n) ${this.elementKind} can not appear here`),!this.context.stopOnError)}validateName(){return this.declarationNode.symbol=ct(this.declarationNode,this.context.name,this.symbolFactory),this.checkNameInValidForm()&&this.checkNameAllowed()&&this.checkNameOptional()&&this.checkNameComplex()&&this.registerName()||!this.name.stopOnError}checkNameInValidForm(){const{name:t}=this.declarationNode;return t&&Mt(t)?!1:t&&!Wt(t)?(this.logError(t,c.INVALID_NAME,"Invalid element name"),!1):!0}checkNameAllowed(){return!this.name.allow&&this.declarationNode.name?(this.logError(this.declarationNode.name,this.name.notAllowErrorCode,`A(n) ${this.elementKind} shouldn't have a name`),!1):!0}checkNameOptional(){return!this.name.optional&&!this.declarationNode.name?(this.logError(this.declarationNode.type,this.name.notOptionalErrorCode,`A(n) ${this.elementKind} must have a name`),!1):!0}checkNameComplex(){const{name:t}=this.declarationNode;return!this.name.allowComplex&&t&&!Xe(t)?(this.logError(t,this.name.complexErrorCode,`A(n) ${this.elementKind} must have a double-quoted string or an identifier name`),!1):!0}registerName(){if(this.declarationNode.name&&this.name.shouldRegister){const{registeredSymbol:t,ok:r}=this.registerElement(this.declarationNode.name);return this.declarationNode.symbol=t,r}return!0}validateAlias(){return this.checkAliasInValidForm()&&this.checkAliasAllow()&&this.checkAliasOptional()&&this.registerAlias()||!this.alias.stopOnError}checkAliasInValidForm(){const{alias:t}=this.declarationNode;return t&&!Zr(t)?(this.logError(t,c.INVALID_ALIAS,"Invalid element alias"),!1):!0}checkAliasAllow(){const{alias:t}=this.declarationNode;return!this.alias.allow&&t?(this.logError(t,this.alias.notAllowErrorCode,`A(n) ${this.elementKind} shouldn't have an alias`),!1):!0}checkAliasOptional(){const{alias:t}=this.declarationNode;return!this.alias.optional&&!t?(this.logError(this.declarationNode.type,this.alias.notOptionalErrorCode,`A(n) ${this.elementKind} must have an alias`),!1):!0}registerAlias(){const{alias:t}=this.declarationNode;if(t&&this.name.shouldRegister){const{ok:r}=this.registerElement(t,this.declarationNode.symbol);return r}return!0}registerElement(t,r){const s=pe(t).unwrap_or(void 0);if(!s)throw new Error(`${this.elementKind} must be a valid complex variable`);const n=s.pop();if(!n)throw new Error(`${this.elementKind} name shouldn't be empty`);const i=fr(n,this.context.name);s[0]==="public"&&s.shift();const a=rs(s,this.publicSchemaSymbol.symbolTable,this.symbolFactory);if(!i)throw new Error(`${this.elementKind} fails to create id to register in the symbol table`);const o=ct(this.declarationNode,this.context.name,this.symbolFactory);if(!o)throw new Error(`${this.elementKind} fails to create a symbol to register in the symbol table`);return a.has(i)?(this.logError(t,this.name.duplicateErrorCode,`${this.elementKind} "${n}" has been defined`),{registeredSymbol:r||o,ok:!1}):(a.set(i,r||o),{registeredSymbol:r||o,ok:!0})}validateSettingList(){return this.checkSettingListInValidForm()&&this.checkSettingListAllow()&&this.checkSettingListOptional()&&(!this.declarationNode.attributeList||this.validateSettingListContent(this.declarationNode.attributeList,this.settingList))||!this.settingList.stopOnError}checkSettingListInValidForm(){const{attributeList:t}=this.declarationNode;return t&&!es(t)?(this.logError(t,c.INVALID_SETTINGS,"SettingList must be a list"),!1):!0}checkSettingListAllow(){const{attributeList:t}=this.declarationNode;return!this.settingList.allow&&t?(this.logError(t,this.settingList.notAllowErrorCode,`A(n) ${this.elementKind} shouldn't have a setting list`),!1):!0}checkSettingListOptional(){const{attributeList:t}=this.declarationNode;return!this.settingList.optional&&!t?(this.logError(this.declarationNode.type,this.settingList.notOptionalErrorCode,`A(n) ${this.elementKind} must have a setting list`),!1):!0}validateBodyForm(){const t=this.declarationNode;if(!t.body)return!1;let r=!1;return!this.body.allowComplex&&Nt(t)&&(this.logError(t.body,this.body.complexErrorCode,`A(n) ${this.elementKind} should not have a complex body`),r=!0),!this.body.allowSimple&&ts(t)&&(this.logError(t.body,this.body.simpleErrorCode,`A(n) ${this.elementKind} should not have a simple body`),r=!0),!r||!this.body.stopOnError}validateBodyContent(){const t=this.declarationNode;if(!t.body)return!1;if(Nt(t)){if(!this.body.allowComplex)return!1;const r=new Set;let s=!1,n=-1;return s=!t.body.body.map(i=>i instanceof A?!i.type||this.validateNestedElementDeclaration(i,r):(n+=1,!i.callee||this.validateSubField(i,n))).every(i=>!!i)||s,!s}return t.body instanceof te&&t.body.callee?this.validateSubField(t.body,0):(this.logError(t.body,c.INVALID_ELEMENT_IN_SIMPLE_BODY,"An element's simple body can not contain an element declaration"),!1)}validateNestedElementDeclaration(t,r){if(t.parent=this.declarationNode,!t.type)return!1;const s=t,n=$t(s);return new n(s,this.publicSchemaSymbol,this.contextStack,this.errors,this.kindsGloballyFound,r,this.symbolFactory).validate()}validateSubField(t,r){const n=[t.callee,...t.args];if(n.length===0)throw new Error("A function application node always has at least 1 callee");const i=n[n.length-1];if(this.validateSubFieldSettingList(i),i instanceof U&&n.pop(),n.length!==this.subfield.argValidators.length)return this.logError(t,this.subfield.invalidArgNumberErrorCode,this.subfield.invalidArgNumberErrorMessage),!1;let a=!1;for(let o=0;o<n.length;o+=1){const u=this.subfield.argValidators[o].validateArg(n[o],r);u.length>0&&(this.errors.push(...u),a=!0)}if(this.subfield.shouldRegister&&!a){const o=this.registerSubField(t,n[0]).unwrap_or(void 0);a=o===void 0||a,t.symbol=o}return!a}registerSubField(t,r){if(!this.declarationNode.symbol||!this.declarationNode.symbol.symbolTable)throw new Error("If an element allows registering subfields, it must own a symbol table");if(!Xe(r))throw new Error("If an element allows registering subfields, their name must be simple");const s=ve(r).unwrap().value,{symbolTable:n}=this.declarationNode.symbol;if(!s)throw new Error(`${this.elementKind} subfield's name shouldn't be empty`);const i=Er(s,this.context.name);if(!i)throw new Error(`${this.elementKind} fails to create subfield id to register in the symbol table`);if(n.has(i))return this.logError(r,this.subfield.duplicateErrorCode,`${this.elementKind} ${Ve(this.elementKind)} "${s}" has been defined`),new T;const a=pr(t,this.context.name,this.symbolFactory);if(!a)throw new Error(`${this.elementKind} fails to create subfield symbol to register in the symbol table`);return new I(n.get(i,a))}validateSubFieldSettingList(t){return!(t instanceof U)&&!this.subfield.settingList.optional?(this.logError(t,this.subfield.settingList.notOptionalErrorCode,`A(n) ${this.elementKind} ${Ve(this.elementKind)} must have a setting list`),!1):t instanceof U&&!this.subfield.settingList.allow?(this.logError(t,this.subfield.settingList.notAllowErrorCode,`A(n) ${this.elementKind} ${Ve(this.elementKind)} should not have a setting list`),!1):t instanceof U?this.validateSettingListContent(t,this.subfield.settingList):!0}validateSettingListContent(t,r){var i;const s=new Set;let n=!1;for(const a of t.elementList){const o=(i=le(a.name).unwrap_or(void 0))==null?void 0:i.toLowerCase(),{value:u}=a;o!==void 0&&(r.isValid(o,u).isOk()?s.has(o)&&!r.allowDuplicate(o).unwrap()?(this.logError(a,r.duplicateErrorCode,"Duplicate setting"),n=!0):(s.add(o),r.isValid(o,u).unwrap()||(this.logError(a,r.invalidErrorCode,"Invalid value for this setting"),n=!0)):(this.logError(a,r.unknownErrorCode,"Unknown setting"),n=!0))}return!n}logError(t,r,s){if(r===void 0)throw Error(`This error shouldn't exist. Maybe a validator is misconfigured
|
|
8
|
-
Error message: ${s}`);this.errors.push(new w(r,s,t))}}class F{constructor(t){this.partialConfig=t}doNotStopOnError(){return this.partialConfig.stopOnError=!1,this.partialConfig}stopOnError(){return this.partialConfig.stopOnError=!0,this.partialConfig}}const Ft=new F(tt({allowSimple:!0,simpleErrorCode:void 0,allowComplex:!0,complexErrorCode:void 0,stopOnError:!1})),Mr=new F(tt({allowSimple:!0,simpleErrorCode:void 0,allowComplex:!1,complexErrorCode:c.UNEXPECTED_COMPLEX_BODY,stopOnError:!1})),Oe=new F(tt({allowSimple:!1,simpleErrorCode:c.UNEXPECTED_SIMPLE_BODY,allowComplex:!0,complexErrorCode:void 0,stopOnError:!1})),Pr=new F(Ut({optional:!0,notOptionalErrorCode:void 0,allow:!0,notAllowErrorCode:void 0,stopOnError:!1})),Bt=new F(et({optional:!0,notOptionalErrorCode:void 0,allow:!0,notAllowErrorCode:void 0,allowComplex:!0,complexErrorCode:void 0,shouldRegister:!1,duplicateErrorCode:void 0,stopOnError:!1})),rt=new F(et({optional:!1,notOptionalErrorCode:c.NAME_NOT_FOUND,allow:!0,notAllowErrorCode:void 0,allowComplex:!0,complexErrorCode:void 0,shouldRegister:!0,duplicateErrorCode:c.DUPLICATE_NAME,stopOnError:!1})),V=new F(Ne({},{optional:!0,notOptionalErrorCode:void 0,allow:!1,notAllowErrorCode:c.UNEXPECTED_SETTINGS,unknownErrorCode:void 0,duplicateErrorCode:void 0,invalidErrorCode:void 0,stopOnError:!1}));function Ur(e){return new F(Ze({globally:!1,notGloballyErrorCode:void 0,locally:!0,notLocallyErrorCode:e,stopOnError:!1}))}function Fr(e){return new F(Ze({globally:!0,notGloballyErrorCode:e,locally:!1,notLocallyErrorCode:void 0,stopOnError:!1}))}const be=new F(Ze({globally:!1,notGloballyErrorCode:void 0,locally:!1,notLocallyErrorCode:void 0,stopOnError:!1})),st=new F(et({optional:!0,notOptionalErrorCode:void 0,allow:!1,notAllowErrorCode:c.UNEXPECTED_NAME,allowComplex:!1,complexErrorCode:c.UNEXPECTED_NAME,shouldRegister:!1,duplicateErrorCode:void 0,stopOnError:!1})),he=new F(Ut({optional:!0,notOptionalErrorCode:void 0,allow:!1,notAllowErrorCode:c.UNEXPECTED_ALIAS,stopOnError:!1}));class Br extends se{constructor(t,r,s,n,i,a,o){super(t,r,s,n,i,a,o),this.elementKind=m.CUSTOM,this.context={name:x.CustomContext,errorCode:c.INVALID_CUSTOM_CONTEXT,stopOnError:!1},this.unique=be.doNotStopOnError(),this.name=st.doNotStopOnError(),this.alias=he.doNotStopOnError(),this.settingList=V.doNotStopOnError(),this.body=Mr.doNotStopOnError(),this.subfield=re({argValidators:[{validateArg:ce(J,c.INVALID_CUSTOM_ELEMENT_VALUE,"This field must be a string literal")}],invalidArgNumberErrorCode:c.INVALID_CUSTOM_ELEMENT_VALUE,invalidArgNumberErrorMessage:"A custom element field must be a single string literal",settingList:V.doNotStopOnError(),shouldRegister:!1,duplicateErrorCode:void 0})}}class Vr extends se{constructor(t,r,s,n,i,a,o){super(t,r,s,n,i,a,o),this.elementKind=m.ENUM,this.context={name:x.EnumContext,errorCode:c.INVALID_ENUM_CONTEXT,stopOnError:!1},this.unique=be.doNotStopOnError(),this.name=rt.doNotStopOnError(),this.alias=he.doNotStopOnError(),this.settingList=V.doNotStopOnError(),this.body=Oe.doNotStopOnError(),this.subfield=re({argValidators:[{validateArg:ce(Y,c.INVALID_ENUM_ELEMENT_NAME,"This field must be a simple variable")}],invalidArgNumberErrorCode:c.INVALID_ENUM_ELEMENT,invalidArgNumberErrorMessage:"An enum's field must be a simple variable",settingList:Gr(),shouldRegister:!0,duplicateErrorCode:c.DUPLICATE_ENUM_ELEMENT_NAME})}}const Gr=()=>Ne({note:{allowDuplicate:!0,isValid:J}},{optional:!0,notOptionalErrorCode:void 0,allow:!0,notAllowErrorCode:void 0,unknownErrorCode:c.UNKNOWN_ENUM_ELEMENT_SETTING,duplicateErrorCode:c.DUPLICATE_ENUM_ELEMENT_SETTING,invalidErrorCode:c.INVALID_ENUM_ELEMENT_SETTING,stopOnError:!1});class Xr extends se{constructor(t,r,s,n,i,a,o){super(t,r,s,n,i,a,o),this.elementKind=m.INDEXES,this.context={name:x.IndexesContext,errorCode:c.INVALID_INDEXES_CONTEXT,stopOnError:!1},this.unique=be.doNotStopOnError(),this.name=st.doNotStopOnError(),this.alias=he.doNotStopOnError(),this.settingList=V.doNotStopOnError(),this.body=Oe.doNotStopOnError(),this.subfield=re({argValidators:[{validateArg:ce(u=>Pt(u).unwrap_or(void 0)!==void 0,c.INVALID_INDEX,"This field must be a function expression, a column name or a tuple of such")}],invalidArgNumberErrorCode:c.INVALID_INDEX,invalidArgNumberErrorMessage:"An Indexes field must be a function expression, a column name or a tuple of such",settingList:Wr(),shouldRegister:!1,duplicateErrorCode:void 0})}}function $r(e){var r;if(!(e instanceof S)||!(e.expression instanceof M))return!1;const t=(r=e.expression.variable)==null?void 0:r.value;return t==="btree"||t==="hash"}const Wr=()=>Ne({note:{allowDuplicate:!1,isValid:J},name:{allowDuplicate:!1,isValid:J},type:{allowDuplicate:!1,isValid:$r},unique:{allowDuplicate:!1,isValid:Z},pk:{allowDuplicate:!1,isValid:Z}},{optional:!0,notOptionalErrorCode:void 0,allow:!0,notAllowErrorCode:void 0,unknownErrorCode:c.UNKNOWN_INDEX_SETTING,duplicateErrorCode:c.DUPLICATE_INDEX_SETTING,invalidErrorCode:c.INVALID_INDEX_SETTING_VALUE,stopOnError:!1});class qr extends se{constructor(t,r,s,n,i,a,o){super(t,r,s,n,i,a,o),this.elementKind=m.NOTE,this.context={name:x.NoteContext,errorCode:c.INVALID_NOTE_CONTEXT,stopOnError:!1},this.unique=Ur(c.NOTE_REDEFINED).doNotStopOnError(),this.name=st.doNotStopOnError(),this.alias=he.doNotStopOnError(),this.settingList=V.doNotStopOnError(),this.body=Ft.doNotStopOnError(),this.subfield=re({argValidators:[{validateArg:(u,h)=>h>0?[new w(c.NOTE_CONTENT_REDEFINED,"Only one note content can be defined",u)]:J(u)?[]:[new w(c.INVALID_NOTE,"A note's content must be doubly or singly quoted string",u)]}],invalidArgNumberErrorCode:c.INVALID_NOTE,invalidArgNumberErrorMessage:"A note content must be a doubly or singly quoted string",settingList:V.doNotStopOnError(),shouldRegister:!1,duplicateErrorCode:void 0})}}class jr extends se{constructor(t,r,s,n,i,a,o){super(t,r,s,n,i,a,o),this.elementKind=m.PROJECT,this.context={name:x.ProjectContext,errorCode:c.INVALID_PROJECT_CONTEXT,stopOnError:!1},this.unique=Fr(c.PROJECT_REDEFINED).doNotStopOnError(),this.name=Bt.doNotStopOnError(),this.alias=he.doNotStopOnError(),this.settingList=V.doNotStopOnError(),this.body=Oe.doNotStopOnError(),this.subfield=re({argValidators:[],invalidArgNumberErrorCode:c.INVALID_PROJECT_FIELD,invalidArgNumberErrorMessage:"A Project cannot have a subfield",settingList:V.doNotStopOnError(),shouldRegister:!1,duplicateErrorCode:void 0})}}class zr extends se{constructor(t,r,s,n,i,a,o){super(t,r,s,n,i,a,o),this.elementKind=m.REF,this.context={name:x.RefContext,errorCode:c.INVALID_REF_CONTEXT,stopOnError:!1},this.unique=be.doNotStopOnError(),this.name=Bt.doNotStopOnError(),this.alias=he.doNotStopOnError(),this.settingList=V.doNotStopOnError(),this.body=Ft.doNotStopOnError(),this.subfield=re({argValidators:[{validateArg:ce(Rr,c.INVALID_REF_RELATIONSHIP,"This field must be a valid binary relationship")}],invalidArgNumberErrorCode:c.INVALID_REF_FIELD,invalidArgNumberErrorMessage:"A ref's field must be a single valid binary relationship",settingList:Kr(),shouldRegister:!1,duplicateErrorCode:void 0})}}function pt(e){if(!(Y(e)&&e.expression.variable.kind!==l.QUOTED_STRING)&&!(e instanceof q))return!1;let t;if(e instanceof q?t=le(e).unwrap_or(""):t=e.expression.variable.value,t)switch(t.toLowerCase()){case"cascade":case"no action":case"set null":case"set default":case"restrict":return!0;default:return!1}return!1}const Kr=()=>Ne({delete:{allowDuplicate:!1,isValid:pt},update:{allowDuplicate:!1,isValid:pt}},{optional:!0,notOptionalErrorCode:void 0,allow:!0,notAllowErrorCode:void 0,unknownErrorCode:c.UNKNOWN_REF_SETTING,duplicateErrorCode:c.DUPLICATE_REF_SETTING,invalidErrorCode:c.INVALID_REF_SETTING_VALUE,stopOnError:!1});class Qr extends se{constructor(t,r,s,n,i,a,o){super(t,r,s,n,i,a,o),this.elementKind=m.TABLE,this.context={name:x.TableContext,errorCode:c.INVALID_TABLE_CONTEXT,stopOnError:!1},this.unique=be.doNotStopOnError(),this.name=rt.doNotStopOnError(),this.alias=Pr.doNotStopOnError(),this.settingList=Ne({headercolor:{allowDuplicate:!1,isValid:ss},note:{allowDuplicate:!1,isValid:J}},{optional:!0,notOptionalErrorCode:void 0,allow:!0,notAllowErrorCode:void 0,unknownErrorCode:c.INVALID_TABLE_SETTING,duplicateErrorCode:c.DUPLICATE_TABLE_SETTING,invalidErrorCode:c.INVALID_TABLE_SETTING,stopOnError:!1}),this.body=Oe.doNotStopOnError(),this.subfield=re({argValidators:[{validateArg:ce(Y,c.INVALID_COLUMN_NAME,"This field must be a valid column name")},{validateArg:ce(Yr,c.INVALID_COLUMN_TYPE,"This field must be a valid column type")}],invalidArgNumberErrorCode:c.INVALID_COLUMN,invalidArgNumberErrorMessage:"A Table's column must have a name and a type",settingList:Hr(),shouldRegister:!0,duplicateErrorCode:c.DUPLICATE_COLUMN_NAME})}}function Yr(e){var r,s;if(!(e instanceof oe||Pe(e)||e instanceof S))return!1;if(e instanceof oe){if(e.callee===void 0||(r=e.argumentList)!=null&&r.elementList.every(n=>n!==void 0))return!0;if(!((s=e.argumentList)!=null&&s.elementList.every(Se)))return!1;e=e.callee}const t=pe(e).unwrap_or(void 0);return t!==void 0&&t.length>0}const Hr=()=>Ne({note:{allowDuplicate:!1,isValid:J},ref:{allowDuplicate:!0,isValid:is},"primary key":{allowDuplicate:!1,isValid:Z},default:{allowDuplicate:!1,isValid:ns},increment:{allowDuplicate:!1,isValid:Z},"not null":{allowDuplicate:!1,isValid:Z},null:{allowDuplicate:!1,isValid:Z},pk:{allowDuplicate:!1,isValid:Z},unique:{allowDuplicate:!1,isValid:Z}},{optional:!0,notOptionalErrorCode:void 0,allow:!0,notAllowErrorCode:void 0,unknownErrorCode:c.UNKNOWN_COLUMN_SETTING,duplicateErrorCode:c.DUPLICATE_COLUMN_SETTING,invalidErrorCode:c.INVALID_COLUMN_SETTING_VALUE,stopOnError:!1});class Jr extends se{constructor(t,r,s,n,i,a,o){super(t,r,s,n,i,a,o),this.elementKind=m.TABLEGROUP,this.context={name:x.TableGroupContext,errorCode:c.INVALID_TABLEGROUP_CONTEXT,stopOnError:!1},this.unique=be.doNotStopOnError(),this.name=rt.doNotStopOnError(),this.alias=he.doNotStopOnError(),this.settingList=V.doNotStopOnError(),this.body=Oe.doNotStopOnError(),this.subfield=re({argValidators:[{validateArg:ce(Wt,c.INVALID_TABLEGROUP_ELEMENT_NAME,"This field must be a valid table name")}],invalidArgNumberErrorCode:c.INVALID_TABLEGROUP_FIELD,invalidArgNumberErrorMessage:"A TableGroup field must be a single valid table name",settingList:V.doNotStopOnError(),shouldRegister:!1,duplicateErrorCode:void 0})}}const Vt=["null","true","false"],Gt=["-","+"];function Xt(e){switch(e.toLowerCase()){case"enum":return m.ENUM;case"table":return m.TABLE;case"tablegroup":return m.TABLEGROUP;case"project":return m.PROJECT;case"ref":return m.REF;case"note":return m.NOTE;case"indexes":return m.INDEXES;default:return m.CUSTOM}}function $t(e){switch(Xt(e.type.value)){case m.ENUM:return Vr;case m.TABLE:return Qr;case m.TABLEGROUP:return Jr;case m.PROJECT:return jr;case m.REF:return zr;case m.NOTE:return qr;case m.INDEXES:return Xr;default:return Br}}function Wt(e){return!!pe(e).unwrap_or(!1)}function Zr(e){return Xe(e)}function Xe(e){return e instanceof S&&e.expression instanceof M}function es(e){return e instanceof U}function Nt(e){return e.body instanceof j&&!e.bodyColon}function ts(e){return!!e.bodyColon}function rs(e,t,r){var n;let s=t;for(const i of e){let a;const o=je(i);if(s.has(o)){if(a=(n=s.get(o))==null?void 0:n.symbolTable,!a)throw new Error("Expect a symbol table in a schema symbol")}else{a=new we;const u=r.create(St,{symbolTable:a});s.set(o,u)}s=a}return s}function qt(e){return e==="-"||e==="<>"||e===">"||e==="<"}function ss(e){var r;if(!(e instanceof S)||!(e.expression instanceof ue)||((r=e.expression.literal)==null?void 0:r.kind)!==l.COLOR_LITERAL)return!1;const t=e.expression.literal.value;if(t.length!==4&&t.length!==7||t[0]!=="#")return!1;for(let s=1;s<t.length;s+=1)if(!br(t[s]))return!1;return!0}function Z(e){return e===void 0||!Array.isArray(e)&&e.end===-1&&e.start===-1||Array.isArray(e)&&e.length===0}function ns(e){var r;if(e instanceof S&&(e.expression instanceof ue||e.expression instanceof M)||e instanceof z&&Gt.includes((r=e.op)==null?void 0:r.value)&&Se(e.expression)||e instanceof B)return!0;if(!e||Array.isArray(e)||!Pe(e))return!1;const t=pe(e).unwrap_or(void 0);return t!==void 0&&t.length>0}function Se(e){var t;return e instanceof S&&e.expression instanceof ue&&((t=e.expression.literal)==null?void 0:t.kind)===l.NUMERIC_LITERAL}function is(e){var r;if(!(e instanceof z)||!qt((r=e.op)==null?void 0:r.value))return!1;const t=pe(e.expression).unwrap_or(void 0);return t!==void 0&&t.length>0}function jt(e){return e instanceof Q&&e.elementList.every(Y)}class bt{constructor(t,r){this.ast=t,this.contextStack=new or,this.errors=[],this.symbolFactory=r,this.publicSchemaSymbol=this.symbolFactory.create(St,{symbolTable:new we}),this.kindsGloballyFound=new Set,this.kindsLocallyFound=new Set,this.ast.symbol=this.publicSchemaSymbol,this.ast.symbol.declaration=this.ast}validate(){return this.ast.body.forEach(t=>{if(t.parent=this.ast,t.type===void 0)return;const r=t,s=$t(r);new s(r,this.publicSchemaSymbol,this.contextStack,this.errors,this.kindsGloballyFound,this.kindsLocallyFound,this.symbolFactory).validate()}),new H(this.ast,this.errors)}}class ne{constructor(t,r){this.declarationNode=t,this.errors=r}bind(){this.bindSettingList(this.declarationNode.attributeList,this.settingList),this.bindBody()}bindSettingList(t,r){if(t)for(const s of t.elementList){const n=le(s.name).unwrap_or(void 0);if(!n)continue;const i=r[n.toLowerCase()];i!=null&&i.shouldBind&&this.scanAndBind(s.value,i)}}bindBody(){const t=this.declarationNode;if(!t.body)return;const{body:r}=t;if(r instanceof j)for(const s of r.body)if(s instanceof A&&s.type){const n=zt(s);new n(s,this.errors).bind()}else this.bindSubfield(s);else this.bindSubfield(r)}bindSubfield(t){if(t instanceof A)return;const r=[t.callee,...t.args],s=C.last(r);s instanceof U&&(r.pop(),this.bindSettingList(s,this.subfield.settingList));const{argBinderRules:n}=this.subfield.arg;for(let i=0;i<Math.min(r.length,n.length);i+=1)n[i].shouldBind&&this.scanAndBind(r[i],n[i])}scanAndBind(t,r){var s,n;if(t)if(t instanceof S){if(t.expression instanceof M&&((n=r.keywords)!=null&&n.includes((s=t.expression.variable)==null?void 0:s.value)))return;this.bindFragments([t],r)}else t instanceof K?Pe(t)?this.bindFragments(Ee(t).unwrap_or([]),r):(this.scanAndBind(t.leftExpression,r),this.scanAndBind(t.rightExpression,r)):t instanceof z?this.scanAndBind(t.expression,r):t instanceof Ce?this.scanAndBind(t.expression,r):t instanceof Q&&t.elementList.forEach(i=>this.scanAndBind(i,r))}bindFragments(t,r){if(t.length===0)return;const s=[...r.topSubnamesSymbolKind],{remainingSubnamesSymbolKind:n}=r,i=t.findIndex(p=>!Y(p)),o=i!==-1&&jt(t[i])?t[i]:void 0,u=i>=0?s.pop():void 0,h=t.slice(0,i===-1?void 0:i);if(h.length===0)return;const b=[];for(;s.length&&h.length;){const p=s.pop(),f=h.pop(),_=W(f).unwrap();b.unshift({index:Be(_,p),referrer:f})}for(;h.length;){const p=h.pop(),f=W(p).unwrap();b.unshift({index:Be(f,n),referrer:p})}return o?o.elementList.forEach(p=>this.resolveIndexStack([...b,{index:Be(W(p).unwrap(),u),referrer:p}],r.ignoreNameNotFound)):this.resolveIndexStack(b,r.ignoreNameNotFound)}resolveIndexStack(t,r){if(t.length===0)throw new Error("Unreachable - An unresolved name must have at least one name component");const[s,...n]=t,i=Dr(s.index,this.declarationNode);if(i===void 0){const{kind:h,name:b}=ee(s.index).unwrap();this.logError(s.referrer,`Can not find ${h} '${b}'`,r);return}i.references.push(s.referrer),s.referrer.referee=i;let a=i.symbolTable,{kind:o,name:u}=ee(s.index).unwrap();for(const h of n){const{kind:b,name:p}=ee(h.index).unwrap(),f=a.get(h.index);if(!f){this.logError(h.referrer,`${o} '${u}' does not have ${b} '${p}'`,r);return}if(o=b,u=p,h.referrer.referee=f,f.references.push(h.referrer),!f.symbolTable)break;a=f.symbolTable}}logError(t,r,s){s||this.errors.push(new w(c.BINDING_ERROR,r,t))}}class as extends ne{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class os extends ne{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class ls extends ne{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[N.Table,N.Column],remainingSubnamesSymbolKind:N.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class cs extends ne{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class us extends ne{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class hs extends ne{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[N.Table,N.Column],remainingSubnamesSymbolKind:N.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class ds extends ne{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1},{shouldBind:!0,topSubnamesSymbolKind:[N.Enum],remainingSubnamesSymbolKind:N.Schema,ignoreNameNotFound:!0}]},settingList:{ref:{shouldBind:!0,topSubnamesSymbolKind:[N.Table,N.Column],remainingSubnamesSymbolKind:N.Schema,ignoreNameNotFound:!1},default:{shouldBind:!0,topSubnamesSymbolKind:[N.Enum,N.EnumField],remainingSubnamesSymbolKind:N.Schema,ignoreNameNotFound:!1,keywords:Vt}}},this.settingList={}}}class fs extends ne{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[N.Table],remainingSubnamesSymbolKind:N.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}function zt(e){switch(Xt(e.type.value)){case m.ENUM:return os;case m.TABLE:return ds;case m.TABLEGROUP:return fs;case m.PROJECT:return us;case m.REF:return hs;case m.NOTE:return cs;case m.INDEXES:return ls;default:return as}}class Es{constructor(t){this.ast=t,this.errors=[]}resolve(){for(const t of this.ast.body)if(t.type){const r=zt(t);new r(t,this.errors).bind()}return new H(this.ast,this.errors)}}class ps{constructor(t){this.generator=t}create(t,r){return new t(r,this.generator.nextId())}}class Ns{constructor(t,r){this.ast=t,this.symbolFactory=new ps(r)}analyze(){return new bt(this.ast,this.symbolFactory).validate().chain(r=>new Es(r).resolve())}validate(){return new bt(this.ast,this.symbolFactory).validate().chain(r=>new H(r,[]))}}function bs(e,t,r){const s=e.map(a=>a.id),n=t.map(a=>a.id),i=s[0]<n[0]?`${s.join(",")}_${n.join(",")}`:`${n.join(",")}_${s.join(",")}`;return r.has(i)?!0:(r.add(i),!1)}function ms(e,t){return C.zip(e,t).every(([r,s])=>(r==null?void 0:r.id)===(s==null?void 0:s.id))}function mt(e){switch(e){case"<":return["1","*"];case"<>":return["*","*"];case">":return["*","1"];case"-":return["1","1"]}throw new Error("Invalid relation op")}function $e(e,t,r){const{tupleElements:s,variables:n}=Ge(e).unwrap(),i=s||[n.pop()],a=n.pop(),o=n.pop();if(n.length>0)return new w(c.UNSUPPORTED,"Nested schemas are currently not allowed",e);if(a===void 0&&t===null)throw new Error("A rel operand's table name must be defined");return{columnNames:i,tableName:a||t,schemaName:a?o||null:r}}function R(e){return{start:{offset:e.startPos.offset,line:e.startPos.line+1,column:e.startPos.column+1},end:{offset:e.endPos.offset,line:e.endPos.line+1,column:e.endPos.column+1}}}function We(e){var r;const t=(r=Ee(e).unwrap_or(void 0))==null?void 0:r.pop();return t instanceof Q?t.elementList.every(s=>!!s.referee)?new I(t.elementList.map(s=>s.referee)):new T:(t==null?void 0:t.referee)instanceof Dt?new I([t.referee]):new T}function Kt(e){return e.split(`
|
|
9
|
-
`).map(t=>t.trim()).join(`
|
|
10
|
-
`)}class gs{constructor(){this.map=new Map}insert(t,r){const s=this.map.get(t);s===void 0?this.map.set(t,[r]):s.push(r)}getValue(t){const r=this.map.get(t);if(r!==void 0)return r[0].value===void 0?!0:r.length>=2?r.map(s=>s.value):r[0].value}getAttributeNode(t){const r=this.map.get(t);if(r!==void 0)return r.length>=2?r:r[0]}}function Le(e,t){const r=new gs;if(!e)return new gt(r,t);for(const s of e.elementList){const n=le(s.name).unwrap_or("").toLowerCase();r.insert(n,s)}return new gt(r,t)}class gt{constructor(t,r){this.settingMap=t,this.errors=r}extractNote(){const t=this.settingMap.getValue("note");return t!==void 0?Kt(fe(t).unwrap()):void 0}extractDefault(){var s,n,i;const t=this.settingMap.getValue("default");if(t===void 0)return;const r=t;if(r instanceof S&&r.expression instanceof M&&Vt.includes((s=r.expression.variable)==null?void 0:s.value))return{type:"boolean",value:r.expression.variable.value};if(Se(r))return{type:"number",value:Number(r.expression.literal.value)};if(r instanceof z&&Gt.includes((n=r.op)==null?void 0:n.value)&&Se(r.expression))return{type:"number",value:Number(r.expression.expression.literal.value)*(((i=r.op)==null?void 0:i.value)==="+"?1:-1)};if(J(r))return{value:fe(r).unwrap(),type:"string"};if(r instanceof B)return{value:r.value.value,type:"expression"};this.errors.push(new w(c.UNSUPPORTED,"Unsupported default value",r))}extractRef(t,r){const s=this.settingMap.getValue("ref");if(s===void 0)return[];const n=Array.isArray(s)?s:[s],i=[];for(const a of n){const o=a.expression,u=$e(o,t,r);if(u instanceof w)this.errors.push(u);else{const{columnNames:h,tableName:b,schemaName:p}=u,f=a.op.value;i.push({schemaName:p,tableName:b,fieldNames:h,relation:f,token:R(a),referee:We(a.expression).unwrap()[0],node:a})}}return i}extractHeaderColor(){const t=this.settingMap.getValue("headercolor");if(t!==void 0)return t.expression.literal.value}extractUpdate(){const t=this.settingMap.getValue("update");if(t!==void 0)return t instanceof q?le(t).unwrap_or(""):t.expression.variable.value}extractDelete(){const t=this.settingMap.getValue("delete");if(t!==void 0)return t instanceof q?le(t).unwrap_or(""):t.expression.variable.value}extractIndexType(){const t=this.settingMap.getValue("type");if(t!==void 0)return t.expression.variable.value}extractPk(){if((this.settingMap.getValue("pk")||this.settingMap.getValue("primary key"))!==void 0)return!0}extractUnique(){if(this.settingMap.getValue("unique")!==void 0)return!0}extractIncrement(){if(this.settingMap.getValue("increment")!==void 0)return!0}extractNotNull(){const t=this.settingMap.getValue("not null"),r=this.settingMap.getValue("null");if(!(t===void 0&&r===void 0)){if(t&&r){this.errors.push(new w(c.CONFLICTING_SETTING,"null and not null can not be set at the same time",this.settingMap.getAttributeNode("not null")));return}return!!t}}extractIdxName(){const t=this.settingMap.getValue("name");if(t!==void 0)return fe(t).unwrap()}}class Ts{constructor(t){this.ast=t,this.db={schemas:[],tables:[],refs:[],enums:[],tableGroups:[],aliases:[],project:{}},this.endpointPairSet=new Set,this.errors=[]}interpret(){return this.ast.body.forEach(t=>{switch(t.type.value.toLowerCase()){case"table":ie(this.table(t),this.db.tables);break;case"ref":this.db.refs.push(...this.ref(t,null,null));break;case"tablegroup":ie(this.tableGroup(t),this.db.tableGroups);break;case"enum":ie(this.enum(t),this.db.enums);break;case"project":this.db.project=this.project(t),this.db.project&&(this.db.tables.push(...this.db.project.tables),this.db.enums.push(...this.db.project.enums),this.db.tableGroups.push(...this.db.project.tableGroups));break;default:throw new Error("Unreachable - unknown element type")}}),new H(this.db,this.errors)}table(t){const r=this.extractElementName(t.name);if(!r.isOk())return;const{name:s,schemaName:n}=r.unwrap(),i=t.alias?W(t.alias).unwrap_or(null):null;i&&this.db.aliases.push({name:i,kind:"table",value:{tableName:s,schemaName:n}});const a=Le(t.attributeList,this.errors),o=a.extractHeaderColor(),u=a.extractNote();let h;const b=a.settingMap.getAttributeNode("note"),p=[],f=[],_=[];return t.body.body.forEach(v=>{if(v instanceof te){const G=this.column(v,s,n);ie(G,p),G!=null&&G.pk&&_.push(G)}else if(v instanceof A)switch(v.type.value.toLowerCase()){case"ref":this.db.refs.push(...this.ref(v,s,n));break;case"indexes":f.push(...this.indexes(v));break;case"note":u!==void 0?this.logError(v,c.NOTE_REDEFINED,"Note already appears as a setting of the table"):h=this.note(v);break}}),_.length>=2&&(f.push({columns:_.map(({name:v})=>({value:v,type:"column"})),token:{start:{offset:-1,line:-1,column:-1},end:{offset:-1,line:-1,column:-1}},pk:!0}),_.forEach(v=>v.pk=!1)),{name:s,schemaName:n,alias:i,fields:p,token:R(t),indexes:f,headerColor:o,note:u===void 0?h:{value:u,token:R(b)}}}column(t,r,s){const n=W(t.callee);let i=t.args[0],a=null;i instanceof oe&&(a=i.argumentList.elementList.map(X=>X.expression.literal.value).join(","),i=i.callee);const o=this.extractElementName(i);if(!o.isOk())return;const{name:u,schemaName:h}=o.unwrap();let b,p,f,_,v,G,me,ge=[];const Te=[];if(t.args.length===2){const X=Le(t.args[1],this.errors);b=X.extractPk(),p=X.extractIncrement(),f=X.extractUnique(),_=X.extractNotNull(),me=X.extractDefault(),v=X.extractNote(),G=X.settingMap.getAttributeNode("note"),ge=X.extractRef(r,s),ge.forEach($=>{this.logIfSameEndpoint($.node,[t.symbol],[$.referee])&&this.logIfCircularRefError($.node,[t.symbol],[$.referee])&&(Te.push({schemaName:$.schemaName,tableName:$.tableName,fieldNames:$.fieldNames,relation:$.relation,token:$.token}),this.registerInlineRefEndpoints($,t,r,s))})}return{name:n.unwrap(),type:{schemaName:h,type_name:`${u}${a===null?"":`(${a})`}`,args:a},token:R(t),inline_refs:Te,pk:b,unique:f,not_null:_,dbdefault:me,increment:p,note:v===void 0?void 0:{value:v,token:R(G)}}}registerInlineRefEndpoints(t,r,s,n){const[i,a]=mt(t.relation),o={schemaName:null,name:null,endpoints:[{schemaName:n,tableName:s,fieldNames:[W(r.callee).unwrap()],relation:i,token:R(r)},{schemaName:t.schemaName,tableName:t.tableName,fieldNames:t.fieldNames,relation:a,token:t.token}],token:t.token};this.db.refs.push(o)}ref(t,r,s){let n=null,i=null;if(t.name){const o=this.extractElementName(t.name);if(!o.isOk())return[];n=o.unwrap().schemaName,i=o.unwrap().name}if(!(t.body instanceof j)){const o=this.refField(t.body,n,i,r,s);return o?[o]:[]}const a=[];for(const o of t.body.body){const u=this.refField(o,n,i,r,s);u&&a.push(u)}return a}refField(t,r,s,n,i){const a=[t.callee,...t.args],o=a[0],[u,h]=mt(o.op.value),b=We(o.leftExpression).unwrap(),p=We(o.rightExpression).unwrap();if(!this.logIfUnequalFields(o,b,p)||!this.logIfSameEndpoint(o,b,p)||!this.logIfCircularRefError(o,b,p))return;const f=$e(o.leftExpression,n,i),_=$e(o.rightExpression,n,i);if(f instanceof w&&this.errors.push(f),_ instanceof w&&this.errors.push(_),f instanceof w||_ instanceof w)return;const v={schemaName:f.schemaName,tableName:f.tableName,fieldNames:f.columnNames,relation:u,token:R(o.leftExpression)},G={schemaName:_.schemaName,tableName:_.tableName,fieldNames:_.columnNames,relation:h,token:R(o.rightExpression)};let me,ge;if(a.length===2){const Te=Le(a[1],this.errors);me=Te.extractDelete(),ge=Te.extractUpdate()}return{name:s,endpoints:[v,G],onDelete:me,onUpdate:ge,token:R(o),schemaName:r}}enum(t){const r=this.extractElementName(t.name);if(!r.isOk())return;const{name:s,schemaName:n}=r.unwrap(),i=t.body.body.map(a=>this.enumField(a));return{name:s,schemaName:n,token:R(t),values:i}}enumField(t){const r=[t.callee,...t.args];let s,n;if(r.length===2){const i=Le(r[1],this.errors);s=i.extractNote(),n=i.settingMap.getAttributeNode("note")}return{name:W(r[0]).unwrap(),token:R(t),note:s===void 0?void 0:{value:s,token:R(n)}}}project(t){var s;const r={name:((s=t.name&&W(t.name))==null?void 0:s.unwrap())||null,tables:[],refs:[],enums:[],tableGroups:[],note:void 0};return t.body.body.forEach(n=>{const i=n,a=i.type.value.toLowerCase();switch(a){case"table":ie(this.table(i),r.tables);break;case"ref":r.refs.push(...this.ref(i,null,null));break;case"tablegroup":ie(this.tableGroup(i),r.tableGroups);break;case"enum":ie(this.enum(i),r.enums);break;case"note":r.note=this.note(i);break;default:r[a]=this.custom(i);break}}),r}custom(t){return fe(t.body.callee).unwrap_or("")}tableGroup(t){const r=this.extractElementName(t.name);if(!r.isOk())return;const{name:s,schemaName:n}=r.unwrap(),i=[];for(const a of t.body.body){const o=this.tableGroupField(a);o&&i.push(o)}return{name:s,schemaName:n,tables:i,token:R(t)}}tableGroupField(t){const r=this.extractElementName(t.callee);if(!r.isOk())return;const{name:s,schemaName:n}=r.unwrap();return{name:s,schemaName:n}}note(t){if(t.body instanceof j&&t.body.body.length===0)return;const r=t.body instanceof j?fe(t.body.body[0].callee):fe(t.body.callee);return{value:Kt(r.unwrap()),token:R(t)}}indexes(t){const r=[];for(const s of t.body.body){const n=this.indexField(s);n&&r.push(n)}return r}indexField(t){const r=[t.callee,...t.args],{functional:s,nonFunctional:n}=Pt(r[0]).unwrap();let i,a,o,u,h,b;if(r.length===2){const p=Le(r[1],this.errors);i=p.extractPk(),a=p.extractUnique(),o=p.extractIdxName(),u=p.extractNote(),h=p.settingMap.getAttributeNode("note"),b=p.extractIndexType()}return{columns:[...s.map(p=>({value:p.value.value,type:"expression"})),...n.map(p=>({value:W(p).unwrap(),type:"column"}))],token:R(t),type:b,pk:i,unique:a,name:o,note:u===void 0?void 0:{value:u,token:R(h)}}}extractElementName(t){const r=pe(t).unwrap(),s=r.pop(),n=r.pop();return r.length>0?(this.logError(t,c.UNSUPPORTED,"Nested schemas are currently not allowed"),new T):new I({name:s,schemaName:n||null})}logIfUnequalFields(t,r,s){return r.length!==s.length?(this.logError(t,c.UNEQUAL_FIELDS_BINARY_REF,"Two endpoints have unequal number of fields"),!1):!0}logIfSameEndpoint(t,r,s){return ms(r,s)?(this.logError(t,c.SAME_ENDPOINT,"Two endpoints are the same"),!1):!0}logIfCircularRefError(t,r,s){return bs(r,s,this.endpointPairSet)?(this.logError(t,c.UNSUPPORTED,"Reference with the same endpoints already exists"),!1):!0}logError(t,r,s){this.errors.push(new w(r,s,t))}}function ie(e,t){e!==void 0&&t.push(e)}var g=(e=>(e[e.Function=1]="Function",e[e.Constructor=2]="Constructor",e[e.Field=3]="Field",e[e.Variable=4]="Variable",e[e.Class=5]="Class",e[e.Struct=6]="Struct",e[e.Interface=7]="Interface",e[e.Module=8]="Module",e[e.Property=9]="Property",e[e.Event=10]="Event",e[e.Operator=11]="Operator",e[e.Unit=12]="Unit",e[e.Value=13]="Value",e[e.Constant=14]="Constant",e[e.Enum=15]="Enum",e[e.EnumMember=16]="EnumMember",e[e.Keyword=17]="Keyword",e[e.Text=18]="Text",e[e.Color=19]="Color",e[e.File=20]="File",e[e.Reference=21]="Reference",e[e.Customcolor=22]="Customcolor",e[e.Folder=23]="Folder",e[e.TypeParameter=24]="TypeParameter",e[e.User=25]="User",e[e.Issue=26]="Issue",e[e.Snippet=27]="Snippet",e))(g||{}),L=(e=>(e[e.None=0]="None",e[e.KeepWhitespace=1]="KeepWhitespace",e[e.InsertAsSnippet=4]="InsertAsSnippet",e))(L||{});function _e(e){switch(e){case N.Schema:return g.Module;case N.Table:return g.Class;case N.Column:return g.Field;case N.Enum:return g.Enum;case N.EnumField:return g.EnumMember;case N.TableGroup:return g.Struct;case N.TableGroupField:return g.Field;default:return g.Text}}function Re(e,t){if(!e||_t(e))return!1;for(const r of e.trailingTrivia){if(r.start>t)break;if(r.kind===l.NEWLINE&&r.end<=t)return!1}return!0}function y(){return{suggestions:[]}}function De(e){return{...e,suggestions:e.suggestions.map(t=>({...t,insertText:` ${t.insertText}`}))}}function Ue(e){return{...e,suggestions:e.suggestions.map(t=>({...t,insertText:t.insertText.search(/[^a-zA-Z\d_]/)!==-1||t.insertText[0].match(/\d/)?`"${t.insertText}"`:t.insertText}))}}function nt(e,t){return e.getOffsetAt(t)}class Qt{constructor(t,r=[]){this.compiler=t,this.triggerCharacters=r}provideCompletionItems(t,r){var b,p;const s=nt(t,r),n=this.compiler.token.flatStream(),{token:i,index:a}=this.compiler.container.token(s),o=a===void 0?n[0]:n[a+1];if([...(i==null?void 0:i.trailingTrivia)||[],...(i==null?void 0:i.leadingTrivia)||[],...(o==null?void 0:o.leadingTrivia)||[]].find(f=>rr(f)&&Ae(s,f)))return y();if(a===void 0)return At();if([l.STRING_LITERAL,l.QUOTED_STRING].includes(i.kind)&&Ae(s,i))return y();const u=this.compiler.container.element(s);if(this.compiler.container.scopeKind(s)===k.TOPLEVEL||u instanceof A&&u.type&&u.type.start<=s&&u.type.end>=s)return At();const h=[...this.compiler.container.stack(s)].reverse();for(const f of h)if(f instanceof z)switch((b=f.op)==null?void 0:b.value){case">":case"<":case"<>":case"-":return Tt(this.compiler,s,f)}else if(f instanceof K)switch((p=f.op)==null?void 0:p.value){case">":case"<":case"<>":case"-":return Tt(this.compiler,s,f);case".":return Yt(this.compiler,s,f)}else{if(f instanceof xe)return It(this.compiler,s,f);if(f instanceof U)return It(this.compiler,s,f);if(f instanceof Q)return Is(this.compiler,s);if(f instanceof te)return wt(this.compiler,s,f);if(f instanceof A&&(f.bodyColon&&s>=f.bodyColon.end||f.body&&Ae(s,f.body)))return wt(this.compiler,s,void 0)}return y()}}function Tt(e,t,r){const s=e.container.scopeKind(t);if([k.REF,k.TABLE].includes(s)){const n=Fe(e,t,e.container.element(t),[N.Table,N.Schema,N.Column]);return Re(r.op,t)?De(n):n}return y()}function Fe(e,t,r,s){var a;if(r===void 0)return y();let n=r;const i={suggestions:[]};for(;n;){if((a=n==null?void 0:n.symbol)!=null&&a.symbolTable){const{symbol:o}=n;i.suggestions.push(...e.symbol.members(o).filter(({kind:u})=>s.includes(u)).map(({name:u,kind:h})=>({label:u,insertText:u,insertTextRules:L.KeepWhitespace,kind:_e(h),sortText:_e(h).toString().padStart(2,"0"),range:void 0})))}n=n instanceof A?n.parent:void 0}return Ue(i)}function Is(e,t){var s;switch(e.container.scopeKind(t)){case k.INDEXES:return Jt(e,t);case k.REF:{const n=[...e.container.stack(t)];for(;n.length>0;){const i=n.pop();if(i instanceof K&&((s=i.op)==null?void 0:s.value)===".")return Yt(e,t,i)}}return Ht(e,t)}return y()}function It(e,t,r){const{token:s}=e.container.token(t);if([l.COMMA,l.LBRACKET].includes(s==null?void 0:s.kind)){const n=Lt(e,t);return(s==null?void 0:s.kind)===l.COMMA&&Re(s,t)?De(n):n}if(r.name&&r.name.start<=t&&r.name.end>=t)return Lt(e,t);if(r.name){const n=Ls(e,t,le(r.name).unwrap());return(s==null?void 0:s.kind)===l.COLON&&Re(s,t)?De(n):n}return y()}function Lt(e,t){const r=e.container.element(t),s=e.container.scopeKind(t);if(r instanceof ae)return y();if(r.body&&!Ae(t,r.body))switch(s){case k.TABLE:return{suggestions:[{label:"headercolor",insertText:"headercolor: ",kind:g.Field,insertTextRules:L.KeepWhitespace,range:void 0},{label:"note",insertText:"note: ",kind:g.Field,insertTextRules:L.KeepWhitespace,range:void 0}]};default:return y()}switch(s){case k.TABLE:return{suggestions:[...["primary key","null","not null","increment","pk","unique"].map(n=>({label:n,insertText:n,kind:g.Property,insertTextRules:L.KeepWhitespace,range:void 0})),...["ref","default"].map(n=>({label:n,insertText:`${n}: `,kind:g.Property,insertTextRules:L.KeepWhitespace,range:void 0})),{label:"note",insertText:"note: ",kind:g.Property,insertTextRules:L.KeepWhitespace,range:void 0}]};case k.ENUM:return{suggestions:[{label:"note",insertText:"note: ",kind:g.Property,insertTextRules:L.KeepWhitespace,range:void 0}]};case k.INDEXES:return{suggestions:[...["unique","pk"].map(n=>({label:n,insertText:n,insertTextRules:L.KeepWhitespace,kind:g.Property,range:void 0})),...["note","name","type"].map(n=>({label:n,insertText:`${n}: `,kind:g.Property,insertTextRules:L.KeepWhitespace,range:void 0}))]};case k.REF:return{suggestions:["update","delete"].map(n=>({label:n,insertText:`${n}: `,kind:g.Property,insertTextRules:L.KeepWhitespace,range:void 0}))}}return y()}function Ls(e,t,r){switch(r==null?void 0:r.toLowerCase()){case"update":case"delete":return{suggestions:["cascade","set default","set null","restrict"].map(s=>({label:s,insertText:s,kind:g.Value,insertTextRules:L.KeepWhitespace,range:void 0}))};case"type":return{suggestions:["btree","hash"].map(s=>({label:s,insertText:`${s}`,kind:g.Value,insertTextRules:L.KeepWhitespace,range:void 0}))}}return y()}function Yt(e,t,r){const s=Ee(r).unwrap_or([]);if(s.pop(),s.some(i=>!Y(i)))return y();const n=s.map(i=>Je(i).unwrap());return Ue({suggestions:e.symbol.ofName({nameStack:n,owner:e.container.element(t)}).flatMap(({symbol:i})=>e.symbol.members(i)).map(({kind:i,name:a})=>({label:a,insertText:a,kind:_e(i),range:void 0}))})}function wt(e,t,r){var n;switch(e.container.scopeKind(t)){case k.TABLE:return As(e,t,r);case k.PROJECT:return xs(e,t,r);case k.INDEXES:return Os(e,t);case k.ENUM:return ws(e,t,r);case k.REF:{const i=Ht(e,t);return((n=e.container.token(t).token)==null?void 0:n.kind)===l.COLON&&Re(e.container.token(t).token,t)?De(i):i}case k.TABLEGROUP:return _s(e);default:return y()}}function At(){return{suggestions:["Table","TableGroup","Enum","Project","Ref"].map(e=>({label:e,insertText:e,insertTextRules:L.KeepWhitespace,kind:g.Keyword,range:void 0}))}}function ws(e,t,r){return r!=null&&r.callee&&it(t,r)===1?Fe(e,t,e.container.element(t),[N.Schema,N.Table,N.Column]):y()}function As(e,t,r){if(!(r!=null&&r.callee))return{suggestions:["Ref","Note","indexes"].map(n=>({label:n,insertText:n,insertTextRules:L.KeepWhitespace,kind:g.Keyword,range:void 0}))};const s=it(t,r);return s===0?{suggestions:["Ref","Note","indexes"].map(n=>({label:n,insertText:n,insertTextRules:L.KeepWhitespace,kind:g.Keyword,range:void 0}))}:s===1?vs(e,t):y()}function xs(e,t,r){return r!=null&&r.callee?it(t,r)===0?{suggestions:["Table","TableGroup","Enum","Note","Ref"].map(n=>({label:n,insertText:n,insertTextRules:L.KeepWhitespace,kind:g.Keyword,range:void 0}))}:y():{suggestions:["Table","TableGroup","Enum","Note","Ref"].map(n=>({label:n,insertText:n,insertTextRules:L.KeepWhitespace,kind:g.Keyword,range:void 0}))}}function Ht(e,t){return Fe(e,t,e.container.element(t),[N.Schema,N.Table,N.Column])}function _s(e){return Ue({suggestions:[...e.parse.publicSymbolTable().entries()].flatMap(([t])=>{const r=ee(t).unwrap_or(void 0);if(r===void 0)return[];const{kind:s,name:n}=r;return s!==N.Table&&s!==N.Schema?[]:{label:n,insertText:n,insertTextRules:L.KeepWhitespace,kind:_e(s),range:void 0}})})}function Os(e,t){return Jt(e,t)}function vs(e,t){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(r=>({label:r,insertText:r,insertTextRules:L.KeepWhitespace,kind:g.TypeParameter,sortText:g.TypeParameter.toString().padStart(2,"0"),range:void 0})),...Fe(e,t,e.container.element(t),[N.Enum,N.Schema]).suggestions]}}function Jt(e,t){const s=e.container.element(t).parent;if(!((s==null?void 0:s.symbol)instanceof Rt))return y();const{symbolTable:n}=s.symbol;return Ue({suggestions:[...n.entries()].flatMap(([i])=>{const a=ee(i).unwrap_or(void 0);if(a===void 0)return[];const{name:o}=a;return{label:o,insertText:o,insertTextRules:L.KeepWhitespace,kind:_e(N.Column),range:void 0}})})}function it(e,t){if(!t.callee)return-1;const r=[t.callee,...t.args],s=r.findIndex(n=>e<=n.end);return s===-1?r.length:s}class Zt{constructor(t){this.compiler=t}provideDefinition(t,r){var a;const{uri:s}=t,n=nt(t,r),i=[...this.compiler.container.stack(n)];for(;i.length!==0;){const o=i.pop();if((a=o==null?void 0:o.referee)!=null&&a.declaration&&[de.PRIMARY_EXPRESSION,de.VARIABLE].includes(o==null?void 0:o.kind)){const{startPos:u,endPos:h}=o.referee.declaration;return[{range:{startColumn:u.column+1,startLineNumber:u.line+1,endColumn:h.column+1,endLineNumber:h.line+1},uri:s}]}}return[]}}class er{constructor(t){this.compiler=t}provideReferences(t,r){const{uri:s}=t,n=nt(t,r),i=[...this.compiler.container.stack(n)];for(;i.length!==0;){const a=i.pop();if(a&&[de.ELEMENT_DECLARATION,de.FUNCTION_APPLICATION,de.PRIMARY_EXPRESSION].includes(a==null?void 0:a.kind)){const{symbol:o}=a;if(o!=null&&o.references.length)return o.references.map(({startPos:u,endPos:h})=>({range:{startColumn:u.column+1,startLineNumber:u.line+1,endColumn:h.column+1,endLineNumber:h.line+1},uri:s}))}}return[]}}const ys=Object.freeze(Object.defineProperty({__proto__:null,CompletionItemInsertTextRule:L,CompletionItemKind:g,DBMLCompletionItemProvider:Qt,DBMLDefinitionProvider:Zt,DBMLReferencesProvider:er},Symbol.toStringTag,{value:"Module"}));var k=(e=>(e[e.TABLE=0]="TABLE",e[e.ENUM=1]="ENUM",e[e.TABLEGROUP=2]="TABLEGROUP",e[e.INDEXES=3]="INDEXES",e[e.NOTE=4]="NOTE",e[e.REF=5]="REF",e[e.PROJECT=6]="PROJECT",e[e.CUSTOM=7]="CUSTOM",e[e.TOPLEVEL=8]="TOPLEVEL",e))(k||{});class ks{constructor(){this.source="",this.cache=new Array(16).fill(null),this.nodeIdGenerator=new sr,this.symbolIdGenerator=new lr,this.token={invalidStream:this.createQuery(6,()=>this.parse.tokens().filter(Ct)),flatStream:this.createQuery(7,()=>this.parse.tokens().flatMap(t=>[...t.leadingInvalid,t,...t.trailingInvalid]))},this.parse={source:()=>this.source,_:this.createQuery(0,()=>{const t=new wr(this.source).lex().chain(r=>new _r(r,this.nodeIdGenerator).parse()).chain(({ast:r,tokens:s})=>new Ns(r,this.symbolIdGenerator).analyze().map(()=>({ast:r,tokens:s})));return t.getErrors().length>0?t:t.chain(({ast:r,tokens:s})=>new Ts(r).interpret().map(i=>({ast:r,tokens:s,rawDb:i})))}),ast:this.createQuery(1,()=>this.parse._().getValue().ast),errors:this.createQuery(2,()=>{const t=[...this.parse._().getErrors()];return t.sort((r,s)=>r.start-s.start),t}),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,t=>{const r=this.parse.tokens();let{index:s}=this.container.token(t);const{token:n}=this.container.token(t);if(s===void 0)return[this.parse.ast()];for(;r[s].isInvalid&&s>=0;)s-=1;if(s===-1)return[this.parse.ast()];const i=r[s].start;let a=this.parse.ast();const o=[a];for(;;){const h=Ir(a).find(b=>Ae(i,b));if(h===void 0||h instanceof P)break;o.push(h),a=h}if((n==null?void 0:n.kind)===l.COLON)return o;for(;o.length>0;){let u=!1;const h=C.last(o);if(h instanceof te){const b=this.parse.source();for(let p=h.end;p<t;p+=1)b[p]===`
|
|
11
|
-
`&&(o.pop(),u=!0)}else h instanceof z||h instanceof K?this.container.token(t).token!==h.op&&(o.pop(),u=!0):h instanceof U?h.listCloseBracket&&h.end<=t&&(o.pop(),u=!0):h instanceof Q?h.tupleCloseParen&&h.end<=t&&(o.pop(),u=!0):h instanceof j?h.blockCloseBrace&&h.end<=t&&(o.pop(),u=!0):h instanceof q||h.end<t&&(o.pop(),u=!0);if(u){const b=C.last(o);b instanceof A&&b.end<=t&&o.pop()}if(!u)break}return o}),token:this.createQuery(11,t=>{const r=this.token.flatStream().findIndex(s=>s.start>=t);return r===void 0?{token:void 0,index:void 0}:r<=0?{token:void 0,index:void 0}:{token:this.token.flatStream()[r-1],index:r-1}}),element:this.createQuery(12,t=>{const r=this.container.stack(t);for(let s=r.length-1;s>=0;s-=1)if(r[s]instanceof A)return r[s];return this.parse.ast()}),scope:this.createQuery(14,t=>{var r,s;return(s=(r=this.container.element(t))==null?void 0:r.symbol)==null?void 0:s.symbolTable}),scopeKind:this.createQuery(15,t=>{var s;if(this.container.element(t)instanceof ae)return 8;switch((s=this.container.element(t).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:t,owner:r=this.parse.ast()})=>{var n;if(t.length===0)return[];const s=[];for(let i=r;i;i=i instanceof A?i.parent:void 0){if(!((n=i.symbol)!=null&&n.symbolTable))continue;const{symbolTable:a}=i.symbol;let o=[a],u=[];for(const h of t)u=o.flatMap(b=>Nr(h).flatMap(p=>{const f=b.get(p),_=ee(p).unwrap_or(void 0);return!f||!_?[]:{..._,symbol:f}})),o=u.flatMap(b=>b.symbol.symbolTable?b.symbol.symbolTable:[]);s.push(...u)}return s},({nameStack:t,owner:r})=>`${t.join(".")}@${r.id}`),members:this.createQuery(9,t=>t.symbolTable?[...t.symbolTable.entries()].map(([r,s])=>({...ee(r).unwrap(),symbol:s})):[])}}createQuery(t,r,s){return n=>{const i=this.cache[t],a=n&&s?s(n):n;if(i!==null){if(!(i instanceof Map))return i;if(i.has(a))return i.get(a)}const o=r(n);return n!==void 0?i instanceof Map?i.set(a,o):(this.cache[t]=new Map,this.cache[t].set(a,o)):this.cache[t]=o,o}}setSource(t){this.source=t,this.cache=new Array(16).fill(null),this.nodeIdGenerator.reset(),this.symbolIdGenerator.reset()}initMonacoServices(){return{definitionProvider:new Zt(this),referenceProvider:new er(this),autocompletionProvider:new Qt(this)}}}exports.Compiler=ks;exports.serialize=nr;exports.services=ys;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const L=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 V{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 V(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(L.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 w{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 V?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 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 C extends w{constructor({body:e=[],eof:s},n){super(n,"<program>",[...e,s]),this.body=e,this.eof=s}}class _ extends w{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 y||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 w{constructor({identifiers:e=[]},s){super(s,"<identifer-stream>",e||[]),this.identifiers=e}}class ne extends w{constructor({name:e,colon:s,value:n},i){super(i,"<attribute>",[e,s,n]),this.name=e,this.value=n,this.colon=s}}class Y extends w{constructor({op:e,expression:s},n){super(n,"<prefix-expression>",[e,s]),this.op=e,this.expression=s}}class z extends w{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 Oe extends w{constructor({op:e,expression:s},n){super(n,"<postfix-expression>",[s,e]),this.op=e,this.expression=s}}class Z extends w{constructor({value:e},s){super(s,"<function-expression>",[e]),this.value=e}}class y extends w{constructor({callee:e,args:s=[]},n){super(n,"<function-application>",[e,...s]),this.callee=e,this.args=s}}class ee extends w{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 w{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 q extends w{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 q{constructor({groupOpenParen:e,expression:s,groupCloseParen:n},i){super({tupleOpenParen:e,elementList:s&&[s],commaList:[],tupleCloseParen:n},i),this.kind="<group-expression>"}}class Q extends w{constructor({callee:e,argumentList:s},n){super(n,"<call-expression>",[e,s]),this.callee=e,this.argumentList=s}}class pe extends w{constructor({literal:e},s){super(s,"<literal>",[e]),this.literal=e}}class X extends w{constructor({variable:e},s){super(s,"<variable>",[e]),this.variable=e}}class D extends w{constructor({expression:e},s){super(s,"<primary-expression>",[e]),this.expression=e}}class ve extends w{constructor({pre:e},s){const n=V.create(c.SPACE,e.endPos,e.endPos," ",!1);super(s,"<dummy>",[n])}}class he extends w{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?L.flatten(L.zip(t,e)):L.flatten(L.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 k{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 k(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 ye(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 ye(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 k({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,ye,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 Qt(t){const[e]=t;return xe(e)||qe(e)&&e.toLowerCase()>="a"&&e.toLowerCase()<="f"}function me(t){return qe(t)||xe(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 Te(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 B{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 B(s.value,n)}map(e){return new B(e(this.value),this.errors)}}function tn(t,e,s){if(!t||!be(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=L.last(n)instanceof U?n.pop():void 0;return n.length===3&&Be(n[1]).unwrap().value==="as"?new k(s.create(_,{type:i,name:n[0],as:Be(n[1]).unwrap(),alias:n[2],attributeList:a,body:r})):n.length===1?new k(s.create(_,{type:i,name:n[0],attributeList:a,body:r})):n.length===0?new k(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 V?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 Y)E(t.op),E(t.expression);else if(t instanceof z)E(t.leftExpression),E(t.op),E(t.rightExpression);else if(t instanceof Oe)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 q)E(t.tupleOpenParen),t.commaList.forEach(E),t.elementList.forEach(E),E(t.tupleCloseParen);else if(t instanceof Q)E(t.callee),E(t.argumentList);else if(t instanceof y)E(t.callee),t.args.forEach(E);else if(t instanceof D)E(t.expression);else if(t instanceof Z)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 Y)return P(t.op,t.expression);if(t instanceof z)return P(t.leftExpression,t.op,t.rightExpression);if(t instanceof Oe)return P(t.expression,t.op);if(t instanceof Z)return P(t.value);if(t instanceof y)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 q)return P(t.tupleOpenParen,...lt(t.elementList,t.commaList),t.tupleCloseParen);if(t instanceof Q)return P(t.callee,t.argumentList);if(t instanceof D)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 k(t.expression.variable):new A}function K(t){var e;return t instanceof D&&(t.expression instanceof X&&t.expression.variable instanceof V&&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 D&&t.expression instanceof X&&t.expression.variable instanceof V}function be(t){var e;return t instanceof D&&t.expression instanceof X&&((e=t.expression.variable)==null?void 0:e.kind)===c.IDENTIFIER}function He(t){var e;return t instanceof z&&t.leftExpression instanceof w&&t.rightExpression instanceof w&&((e=t.op)==null?void 0:e.value)==="."}function De(t){if(t===void 0)return new A;const e=t.identifiers.map(s=>s.value).join(" ");return e===""?new A:new k(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 s=0;s<e.length;s+=1)if(e[s]!==this.peek(s))return!1;return!0}match(e){return this.check(e)?(e.split("").forEach(()=>this.advance()),!0):!1}addToken(e,s=!1){this.tokens.push(this.createToken(e,s))}createToken(e,s=!1){return V.create(e,this.start,this.current,this.text.substring(this.start.offset,this.current.offset),s)}lex(){return this.scanTokens(),this.tokens.push(V.create(c.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(c.SPACE);break;case"\r":break;case`
|
|
3
|
+
`:this.addToken(c.NEWLINE);break;case" ":this.addToken(c.TAB);break;case",":this.addToken(c.COMMA);break;case"(":this.addToken(c.LPAREN);break;case")":this.addToken(c.RPAREN);break;case"[":this.addToken(c.LBRACKET);break;case"]":this.addToken(c.RBRACKET);break;case"{":this.addToken(c.LBRACE);break;case"}":this.addToken(c.RBRACE);break;case";":this.addToken(c.SEMICOLON);break;case":":this.addToken(c.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(c.OP,!0),this.errors.push(new u(o.UNKNOWN_SYMBOL,`Unexpected token '${e}'`,this.createToken(c.OP,!0)));break}this.start={...this.current}}}gatherTrivia(){let e=!0,s=[],n;const i=[];for(const r of this.tokens)Xt(r)?(s.push(r),r.kind===c.NEWLINE&&n&&(n.trailingTrivia=s,e=!0,n=void 0,s=[])):(e?r.leadingTrivia=s:n.trailingTrivia=s,i.push(r),s=[],n=r,e=!1);this.tokens=i}gatherInvalid(){let e;const s=[],n=[];for(e=0;e<this.tokens.length&&vt(this.tokens[e]);e+=1)n.push(this.tokens[e]);let i=this.tokens[e];for(i.leadingInvalid=[...n,...i.leadingInvalid];e<this.tokens.length;e+=1){const r=this.tokens[e];r.isInvalid?i.trailingInvalid.push(r):(i=r,s.push(r))}this.tokens=s}consumeUntil(e,s,{allowNewline:n,allowEof:i,raw:r,consumeStopSequence:a=!0}){let l="";for(;!this.isAtEnd()&&(n||!this.check(`
|
|
4
|
+
`))&&!this.check(s);)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 u(o.UNEXPECTED_EOF,"EOF reached while parsing",p));return}if(this.check(`
|
|
5
|
+
`)&&!n){const p=this.createToken(e,!0);this.tokens.push(p),this.errors.push(new u(o.UNEXPECTED_NEWLINE,"Invalid newline encountered while parsing",p));return}a&&this.match(s),this.tokens.push(V.create(e,this.start,this.current,l,!1))}singleLineStringLiteral(){this.consumeUntil(c.STRING_LITERAL,"'",{allowNewline:!1,allowEof:!1,raw:!1})}multilineStringLiteral(){this.consumeUntil(c.STRING_LITERAL,"'''",{allowNewline:!0,allowEof:!1,raw:!1})}functionExpression(){this.consumeUntil(c.FUNCTION_EXPRESSION,"`",{allowNewline:!1,allowEof:!1,raw:!0})}quotedVariable(){this.consumeUntil(c.QUOTED_STRING,'"',{allowNewline:!1,allowEof:!1,raw:!1})}singleLineComment(){this.consumeUntil(c.SINGLE_LINE_COMMENT,`
|
|
6
|
+
`,{allowNewline:!0,allowEof:!0,raw:!0,consumeStopSequence:!1})}multilineComment(){this.consumeUntil(c.MULTILINE_COMMENT,"*/",{allowNewline:!0,allowEof:!1,raw:!0})}identifier(){for(;!this.isAtEnd()&&me(this.peek());)this.advance();this.addToken(c.IDENTIFIER)}operator(){for(;rt(this.peek());)this.advance();this.addToken(c.OP)}numericLiteral(){let e=0;if(this.isAtEnd())return this.addToken(c.NUMERIC_LITERAL);for(;!this.isAtEnd();){const n=this.check(".");if(e+=n?1:0,e>1)break;if(!n&&this.current.offset===this.text.length-1)return this.advance(),this.addToken(c.NUMERIC_LITERAL);if(!n&&!me(this.peek()))return this.addToken(c.NUMERIC_LITERAL);if(!n&&!xe(this.peek()))break;this.advance()}for(;!this.isAtEnd()&&(this.check(".")||me(this.peek()));)this.advance();const s=this.createToken(c.NUMERIC_LITERAL,!0);this.tokens.push(s),this.errors.push(new u(o.UNKNOWN_TOKEN,"Invalid number",s))}colorLiteral(){for(;!this.isAtEnd()&&me(this.peek());)this.advance();this.addToken(c.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 s=0;s<=3;s+=1){if(this.isAtEnd()||!me(this.peek()))return`\\u${e}`;e+=this.advance()}return String.fromCharCode(parseInt(e,16))}default:return`\\${this.tokens[this.current.offset-1]}`}}}var we=(t=>(t[t.ListExpression=0]="ListExpression",t[t.GroupExpression=1]="GroupExpression",t[t.BlockExpression=2]="BlockExpression",t))(we||{});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 L.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(we.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(we.GroupExpression,()=>{const n={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(Xe,{groupOpenParen:n.tupleOpenParen,groupCloseParen:n.tupleCloseParen,expression:n.elementList[0]}),r=()=>this.nodeFactory.create(q,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 w&&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(we.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 w&&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()?L.last(this.tokens):this.tokens[this.current++]}peek(e=0){return e+this.current>=this.tokens.length?L.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 B({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(y,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(Q,{callee:s,argumentList:this.tupleExpression()})}catch(r){throw r instanceof d?(s=this.nodeFactory.create(Q,{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(Oe,{expression:s,op:i})}else{const a=hn(i);if(a.left===null||a.left<=e)break;this.advance();try{s=this.nodeFactory.create(z,{leftExpression:s,op:i,rightExpression:i.value==="."?this.extractOperand():this.expression_bp(a.right)})}catch(l){throw l instanceof d?(s=this.nodeFactory.create(z,{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(ve,{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(Y,s),i.handlerContext)):i}e=this.nodeFactory.create(Y,s)}else if(e=this.extractOperand(),e instanceof ve)throw new d(this.peek(),this.nodeFactory.create(ve,{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(ve,{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(Z,e),s.handlerContext)):s}return this.nodeFactory.create(Z,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(D,{expression:this.nodeFactory.create(pe,{literal:this.previous()})});if(this.match(c.QUOTED_STRING,c.IDENTIFIER))return this.nodeFactory.create(D,{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(D,{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 I=(t=>(t.Table="table",t.Enum="enum",t.Ref="ref",t.Note="note",t.Project="project",t.Indexes="indexes",t.TableGroup="tablegroup",t))(I||{});function de(t){var s;const e=(s=t==null?void 0:t.type)==null?void 0:s.value.toLowerCase();switch(e){case I.Enum:case I.Table:case I.Indexes:case I.Note:case I.Project:case I.Ref:case I.TableGroup:return new k(e);default:return new A}}function Ee(t){if(!He(t))return new k([t]);const e=Ee(t.leftExpression).unwrap_or(void 0);return e?(e.push(t.rightExpression),new k(e)):new A}function $(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=W(n).unwrap_or(void 0);if(!i)return new A;s.push(i)}return new k(s)}function Ie(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(L.last(e))){const i=e.pop();if(xt(i))n=i.elementList.map(r=>G(r).unwrap());else return new A}for(const i of e){const r=W(i).unwrap_or(void 0);if(!r)return new A;s.push(r)}return new k({variables:s,tupleElements:n})}function W(t){return M(t)?new k(t.expression.variable.value):new A}function Ge(t){if(ht(t))return t instanceof Z?new k({functional:[t],nonFunctional:[]}):new k({functional:[],nonFunctional:[t]});if(t instanceof q&&t.elementList.every(ht)){const e=t.elementList.filter(n=>n instanceof Z),s=t.elementList.filter(M);return new k({functional:e,nonFunctional:s})}return new A}function G(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 k(e)}function J(t){return K(t)?t.expression instanceof X?new k(t.expression.variable.value):new k(t.expression.literal.value):new A}function En(t){var e;return!(t instanceof z)||!yt((e=t.op)==null?void 0:e.value)?!1:Ie(t.leftExpression).and_then(()=>Ie(t.rightExpression)).unwrap_or(void 0)!==void 0}function Nn(t){const e=Ie(t.leftExpression),s=Ie(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 D&&t.expression instanceof X||t instanceof Z}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)!==I.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 K(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 ge{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 ge});const{name:s}=this.declarationNode,n=$(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 y)return this.validateFields([e]);const[s,n]=L.partition(e.body,i=>i instanceof y);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)),L.last(s.args)instanceof U&&n.push(...this.validateFieldSetting(L.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=j(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=>{K(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=G(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)!==I.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 y)return[new u(o.UNEXPECTED_SIMPLE_BODY,"An Indexes must have a complex body",e)];const[s,n]=L.partition(e.body,i=>i instanceof y);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 L.last(i)instanceof U&&n.push(...this.validateFieldSetting(i.pop())),i.forEach(r=>{for(;r instanceof Q;)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=j(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=>{K(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||![I.Table,I.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 y)return this.validateFields([e]);const[s,n]=L.partition(e.body,i=>i instanceof y);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))),K(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?Re(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 y)return[new u(o.UNEXPECTED_SIMPLE_BODY,"A Project's body must be a block",e)];const[s,n]=L.partition(e.body,i=>i instanceof y);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)===I.Table?[]:[new u(o.INVALID_REF_CONTEXT,"A Ref must appear top-level or inside a table",this.declarationNode)]}validateName(e){return e?Re(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 y)return this.validateFields([e]);const[s,n]=L.partition(e.body,i=>i instanceof y);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)),L.last(n.args)instanceof U&&this.validateFieldSettings(L.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=j(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=De(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?xn(e)?[]:[new u(o.INVALID_ALIAS,"A Table alias must be of the form <alias>",e)]:[]}validateSettingList(e){const s=j(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=>{kn(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=>{K(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 ge});const{name:s,alias:n}=this.declarationNode,i=$(s);if(i.isOk()){const r=i.unwrap(),a=r.pop(),l=Ze(r,this.publicSymbolTable,this.symbolFactory),p=ye(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&&Re(n)){const r=ye(G(n).unwrap());this.publicSymbolTable.has(r)&&e.push(new u(o.DUPLICATE_NAME,`Table name '${n}' already exists`,s)),this.publicSymbolTable.set(r,this.declarationNode.symbol)}return e}validateBody(e){if(!e)return[];if(e instanceof y)return[new u(o.UNEXPECTED_SIMPLE_BODY,"A Table's body must be a block",e)];const[s,n]=L.partition(e.body,i=>i instanceof y);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=G(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(be)||!e.slice(-1).every(p=>be(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;L.last(e)instanceof U&&(s=e.pop());const n=j(s),i=n.getErrors(),r=n.getValue();for(const p of e){const h=G(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=>{K(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=>{On(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=>{Sn(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 Q||He(t)||t instanceof D||t instanceof he))return!1;if(t instanceof Q){if(t.callee===void 0||t.argumentList===void 0||!t.argumentList.elementList.every(fe))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&&fe(s.name)))return!1;t=t.array}const e=$(t).unwrap_or(void 0);return e!==void 0&&e.length>0}class yn{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 ge});const s=$(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 y)return[new u(o.UNEXPECTED_SIMPLE_BODY,"A TableGroup's body must be a block",e)];const[s,n]=L.partition(e.body,i=>i instanceof y);return[...this.validateFields(s),...this.validateSubElements(n)]}validateFields(e){return e.flatMap(s=>{const n=[];return s.callee&&!$(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=G(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 I.Enum:return bn;case I.Table:return vn;case I.TableGroup:return yn;case I.Project:return gn;case I.Ref:return _n;case I.Note:return Ln;case I.Indexes:return In;default:return Tn}}function Je(t){return!!$(t).unwrap_or(!1)}function xn(t){return Re(t)}function Re(t){return t instanceof D&&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 ge;const p=s.create(_t,{symbolTable:a});n.set(l,p)}n=a}return n}function yt(t){return t==="-"||t==="<>"||t===">"||t==="<"}function kn(t){var s;if(!(t instanceof D)||!(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 Sn(t){var e;return!!(K(t)||fe(t)||be(t)&&["true","false","null"].includes(t.expression.variable.value.toLowerCase())||t instanceof Y&&wt.includes((e=t.op)==null?void 0:e.value)&&fe(t.expression)||t instanceof Z)}function fe(t){var e;return t instanceof D&&t.expression instanceof pe&&((e=t.expression.literal)==null?void 0:e.kind)===c.NUMERIC_LITERAL}function On(t){var s;if(!(t instanceof Y)||!yt((s=t.op)==null?void 0:s.value))return!1;const e=$(t.expression).unwrap_or(void 0);return e!==void 0&&e.length>0}function xt(t){return t instanceof q&&t.elementList.every(M)}function j(t){var n;const e={},s=[];if(!t)return new B({});for(const i of t.elementList){if(!i.name)continue;if(i.name instanceof D){s.push(new u(o.INVALID_SETTINGS,"A setting name must be a stream of identifiers",i.name));continue}const r=(n=De(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 B(e,s)}class ft{constructor(e,s){this.ast=e,this.symbolFactory=s,this.publicSchemaSymbol=this.symbolFactory.create(_t,{symbolTable:new ge}),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)===I.Project);return s.length>1&&s.forEach(n=>e.push(new u(o.PROJECT_REDEFINED,"Only one project can exist",n))),new B(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 D)continue;const i=De(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=L.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 D){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 z?He(e)?this.bindFragments(Ee(e).unwrap_or([]),s):(this.scanAndBind(e.leftExpression,s),this.scanAndBind(e.rightExpression,s)):e instanceof Y?this.scanAndBind(e.expression,s):e instanceof Oe?this.scanAndBind(e.expression,s):e instanceof q&&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(),b=G(N).unwrap();T.unshift({index:Fe(b,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}],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 Dn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Rn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Pn 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 Un extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Mn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},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}]},settingList:{}},this.settingList={}}}class Bn 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 Vn 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 I.Enum:return Rn;case I.Table:return Bn;case I.TableGroup:return Vn;case I.Project:return Mn;case I.Ref:return Fn;case I.Note:return Un;case I.Indexes:return Pn;default:return Dn}}class Gn{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 B(this.ast,this.errors)}}class Cn{constructor(e){this.generator=e}create(e,s){return new e(s,this.generator.nextId())}}class Xn{constructor(e,s){this.ast=e,this.symbolFactory=new Cn(s)}analyze(){return new ft(this.ast,this.symbolFactory).validate().chain(s=>new Gn(s).resolve())}validate(){return new ft(this.ast,this.symbolFactory).validate().chain(s=>new B(s,[]))}}function pt(t,e){const{variables:s,tupleElements:n}=Ie(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 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 s;const e=(s=Ee(t).unwrap_or(void 0))==null?void 0:s.pop();return e instanceof q?e.elementList.map(n=>n.referee):[e.referee]}function ce(t){return t.split(`
|
|
8
|
+
`).map(e=>e.trim()).join(`
|
|
9
|
+
`)}function _e(t){const e=$(t).unwrap();return{name:e.pop(),schemaName:e}}function $n(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 L.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=x(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=$(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 y?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 b=j(e.args[0]).getValue();this.ref.onDelete=W((T=(h=b.delete)==null?void 0:h.at(0))==null?void 0:T.value).unwrap_or(void 0),this.ref.onDelete=W((N=(f=b.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:x(n)},{...pt(i,this.container),relation:p[1],token:x(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=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: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}=_e(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=G(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=j(e).getValue();this.table.headerColor=(r=s.headercolor)!=null&&r.length?$n((l=(a=s.headercolor)==null?void 0:a.at(0))==null?void 0:l.value):void 0;const[n]=s.note||[],i=J(n==null?void 0:n.value).unwrap_or(void 0);return this.table.note=n&&{value:ce(i),token:x(n)},[]}interpretBody(e){const[s,n]=L.partition(e.body,i=>i instanceof y);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:ce(J(s.body instanceof ee?s.body.body[0].callee:s.body.callee).unwrap()),token:x(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;const s=[],n={};n.name=G(e.callee).unwrap();const i=Wn(e.args[0]);n.type=i.getValue(),s.push(...i.getErrors()),n.token=x(e),n.inline_refs=[];const r=e.args.slice(1);if(L.last(r)instanceof U){const b=j(r.pop()).getValue();n.pk=!!((a=b.pk)!=null&&a.length),n.increment=!!((l=b.increment)!=null&&l.length),n.unique=!!((p=b.unique)!=null&&p.length),n.not_null=!!((h=b["not null"])!=null&&h.length)&&!0,n.dbdefault=jn((f=(T=b.default)==null?void 0:T.at(0))==null?void 0:f.value);const F=(N=b.note)==null?void 0:N.at(0);n.note=F&&{value:ce(J(F.value).unwrap()),token:x(F)};const Me=b.ref||[];n.inline_refs=Me.flatMap(R=>{const[nt]=Ce(R.value.expression);if(Dt(nt,e.symbol))return s.push(new u(o.SAME_ENDPOINT,"Two endpoints are the same",R)),[];const Ae=R.value.op,H=$(R.value.expression).unwrap();let le;if(H.length===1){const[ae]=H;le={schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[ae],relation:Ae.value,token:x(R)}}else if(H.length===2){const[ae,Ne]=H;le={schemaName:null,tableName:ae,fieldNames:[Ne],relation:Ae.value,token:x(R)}}else if(H.length===3){const[ae,Ne,it]=H;le={schemaName:ae,tableName:Ne,fieldNames:[it],relation:Ae.value,token:x(R)}}else{s.push(new u(o.UNSUPPORTED,"Nested schema is not supported",R));const ae=H.pop(),Ne=H.pop();le={schemaName:H.join("."),tableName:Ne,fieldNames:[ae],relation:Ae.value,token:x(R)}}const st=this.registerInlineRefToEnv(e,nt,le,R);return s.push(...st),st.length===0?le:[]})}return n.pk||(n.pk=r.some(b=>W(b).unwrap().toLowerCase()==="pk")),n.unique||(n.unique=r.some(b=>W(b).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=x(e);const r=[i.callee,...i.args];if(L.last(r)instanceof U){const b=j(r.pop()).getValue();n.pk=!!((a=b.pk)!=null&&a.length),n.unique=!!((l=b.unique)!=null&&l.length),n.name=J((h=(p=b.name)==null?void 0:p.at(0))==null?void 0:h.value).unwrap_or(void 0);const F=(T=b.note)==null?void 0:T.at(0);n.note=F&&{value:ce(J(F.value).unwrap()),token:x(F)},n.type=W((N=(f=b.type)==null?void 0:f.at(0))==null?void 0:N.value).unwrap_or(void 0)}return r.flatMap(b=>{if(!(b instanceof Q))return b;const F=[];for(;b instanceof Q;)F.push(b.argumentList),b=b.callee;return F.push(b),F}).forEach(b=>{const{functional:F,nonFunctional:Me}=Ge(b).unwrap();n.columns.push(...F.map(R=>({value:R.value.value,type:"expression"})),...Me.map(R=>({value:G(R).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:[W(e.callee).unwrap()],token:x(e),relation:a[0]},{...n,relation:a[1]}]}),[]}}function Wn(t){let e=null;t instanceof Q&&(e=t.argumentList.elementList.map(r=>r.expression.literal.value).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}=_e(t);return i.length>1&&new B({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 B({schemaName:i.length===0?null:i[0],type_name:`${n}${s}${e?`(${e})`:""}`,args:e})}function jn(t){var e,s,n;if(t){if(K(t))return{value:J(t).unwrap(),type:"string"};if(fe(t))return{type:"number",value:Number.parseFloat(t.expression.literal.value)};if(be(t))return{value:t.expression.variable.value.toLowerCase(),type:"boolean"};if(t instanceof Y&&wt.includes((e=t.op)==null?void 0:e.value)&&fe(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 Z)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=x(this.declarationNode),this.env.tableGroups.set(this.declarationNode,this.tableGroup);const{name:s,schemaName:n}=_e(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=$(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=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:s,schemaName:n}=_e(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=x(n),i.name=W(n.callee).unwrap();const a=(l=j(n.args[0]).getValue().note)==null?void 0:l.at(0);return i.note=a&&{value:ce(J(a.value).unwrap()),token:x(a)},this.enum.values.push(i),[]})}}class Yn{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}=_e(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:ce(J(n.body instanceof ee?n.body.body[0].callee:n.body.callee).unwrap()),token:x(n)},[];default:return this.project[n.type.value.toLowerCase()]=J(n.body.callee).unwrap(),[]}})}}class zn{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 I.Table:return new Rt(s,this.env).interpret();case I.Ref:return new Ke(s,this.env).interpret();case I.TableGroup:return new Pt(s,this.env).interpret();case I.Enum:return new Ut(s,this.env).interpret();case I.Project:return new Yn(s,this.env).interpret();default:return[]}});return new B(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 g=(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))(g||{}),v=(t=>(t[t.None=0]="None",t[t.KeepWhitespace=1]="KeepWhitespace",t[t.InsertAsSnippet=4]="InsertAsSnippet",t))(v||{});function Le(t){switch(t){case m.Schema:return g.Module;case m.Table:return g.Class;case m.Column:return g.Field;case m.Enum:return g.Enum;case m.EnumField:return g.EnumMember;case m.TableGroup:return g.Struct;case m.TableGroupField:return g.Field;default:return g.Text}}function ke(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 S(){return{suggestions:[]}}function Se(t){return{...t,suggestions:t.suggestions.map(e=>({...e,insertText:` ${e.insertText}`}))}}function Pe(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)&&Te(n,N)))return S();if(a===void 0)return Tt();if([c.STRING_LITERAL,c.QUOTED_STRING].includes(r.kind)&&Te(n,r))return S();const p=this.compiler.container.element(n);if(this.compiler.container.scopeKind(n)===O.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 Y)switch((T=N.op)==null?void 0:T.value){case">":case"<":case"<>":case"-":return dt(this.compiler,n,N)}else if(N instanceof z)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 q)return qn(this.compiler,n);if(N instanceof y)return mt(this.compiler,n,N);if(N instanceof _&&(N.bodyColon&&n>=N.bodyColon.end||N.body&&Te(n,N.body)))return mt(this.compiler,n,void 0)}return S()}}function dt(t,e,s){const n=t.container.scopeKind(e);if([O.REF,O.TABLE].includes(n)){const i=Ue(t,e,t.container.element(e),[m.Table,m.Schema,m.Column]);return ke(s.op,e)?Se(i):i}return S()}function Ue(t,e,s,n){var a;if(s===void 0)return S();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:v.KeepWhitespace,kind:Le(h),sortText:Le(h).toString().padStart(2,"0"),range:void 0})))}i=i instanceof _?i.parent:void 0}return Pe(r)}function qn(t,e){var n;switch(t.container.scopeKind(e)){case O.INDEXES:return Vt(t,e);case O.REF:{const i=[...t.container.stack(e)];for(;i.length>0;){const r=i.pop();if(r instanceof z&&((n=r.op)==null?void 0:n.value)===".")return Ft(t,e,r)}}return Bt(t,e)}return S()}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&&ke(n,e)?Se(i):i}if(s.name&&s.name.start<=e&&s.name.end>=e)return Nt(t,e);if(s.name){const i=Hn(t,e,De(s.name).unwrap());return(n==null?void 0:n.kind)===c.COLON&&ke(n,e)?Se(i):i}return S()}function Nt(t,e){const s=t.container.element(e),n=t.container.scopeKind(e);if(s instanceof C)return S();if(s.body&&!Te(e,s.body))switch(n){case O.TABLE:return{suggestions:[{label:"headercolor",insertText:"headercolor: ",kind:g.Field,insertTextRules:v.KeepWhitespace,range:void 0},{label:"note",insertText:"note: ",kind:g.Field,insertTextRules:v.KeepWhitespace,range:void 0}]};default:return S()}switch(n){case O.TABLE:return{suggestions:[...["primary key","null","not null","increment","pk","unique"].map(i=>({label:i,insertText:i,kind:g.Property,insertTextRules:v.KeepWhitespace,range:void 0})),...["ref","default"].map(i=>({label:i,insertText:`${i}: `,kind:g.Property,insertTextRules:v.KeepWhitespace,range:void 0})),{label:"note",insertText:"note: ",kind:g.Property,insertTextRules:v.KeepWhitespace,range:void 0}]};case O.ENUM:return{suggestions:[{label:"note",insertText:"note: ",kind:g.Property,insertTextRules:v.KeepWhitespace,range:void 0}]};case O.INDEXES:return{suggestions:[...["unique","pk"].map(i=>({label:i,insertText:i,insertTextRules:v.KeepWhitespace,kind:g.Property,range:void 0})),...["note","name","type"].map(i=>({label:i,insertText:`${i}: `,kind:g.Property,insertTextRules:v.KeepWhitespace,range:void 0}))]};case O.REF:return{suggestions:["update","delete"].map(i=>({label:i,insertText:`${i}: `,kind:g.Property,insertTextRules:v.KeepWhitespace,range:void 0}))}}return S()}function Hn(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:g.Value,insertTextRules:v.KeepWhitespace,range:void 0}))};case"type":return{suggestions:["btree","hash"].map(n=>({label:n,insertText:`${n}`,kind:g.Value,insertTextRules:v.KeepWhitespace,range:void 0}))}}return S()}function Ft(t,e,s){const n=Ee(s).unwrap_or([]);if(n.pop(),n.some(r=>!M(r)))return S();const i=n.map(r=>W(r).unwrap());return Pe({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:Le(r),range:void 0}))})}function mt(t,e,s){var i;switch(t.container.scopeKind(e)){case O.TABLE:return Zn(t,e,s);case O.PROJECT:return Kn(t,e,s);case O.INDEXES:return ts(t,e);case O.ENUM:return Jn(t,e,s);case O.REF:{const r=Bt(t,e);return((i=t.container.token(e).token)==null?void 0:i.kind)===c.COLON&&ke(t.container.token(e).token,e)?Se(r):r}case O.TABLEGROUP:return es(t);default:return S()}}function Tt(){return{suggestions:["Table","TableGroup","Enum","Project","Ref"].map(t=>({label:t,insertText:t,insertTextRules:v.KeepWhitespace,kind:g.Keyword,range:void 0}))}}function Jn(t,e,s){return s!=null&&s.callee&&tt(e,s)===1?Ue(t,e,t.container.element(e),[m.Schema,m.Table,m.Column]):S()}function Zn(t,e,s){if(!(s!=null&&s.callee))return{suggestions:["Ref","Note","indexes"].map(i=>({label:i,insertText:i,insertTextRules:v.KeepWhitespace,kind:g.Keyword,range:void 0}))};const n=tt(e,s);return n===0?{suggestions:["Ref","Note","indexes"].map(i=>({label:i,insertText:i,insertTextRules:v.KeepWhitespace,kind:g.Keyword,range:void 0}))}:n===1?ns(t,e):S()}function Kn(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:v.KeepWhitespace,kind:g.Keyword,range:void 0}))}:S():{suggestions:["Table","TableGroup","Enum","Note","Ref"].map(i=>({label:i,insertText:i,insertTextRules:v.KeepWhitespace,kind:g.Keyword,range:void 0}))}}function Bt(t,e){return Ue(t,e,t.container.element(e),[m.Schema,m.Table,m.Column])}function es(t){return Pe({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:v.KeepWhitespace,kind:Le(n),range:void 0}})})}function ts(t,e){return Vt(t,e)}function ns(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:v.KeepWhitespace,kind:g.TypeParameter,sortText:g.TypeParameter.toString().padStart(2,"0"),range:void 0})),...Ue(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 S();const{symbolTable:i}=n.symbol;return Pe({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:v.KeepWhitespace,kind:Le(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 ss=Object.freeze(Object.defineProperty({__proto__:null,CompletionItemInsertTextRule:v,CompletionItemKind:g,DBMLCompletionItemProvider:Mt,DBMLDefinitionProvider:Gt,DBMLReferencesProvider:Ct},Symbol.toStringTag,{value:"Module"}));var O=(t=>(t[t.TABLE=0]="TABLE",t[t.ENUM=1]="ENUM",t[t.TABLEGROUP=2]="TABLEGROUP",t[t.INDEXES=3]="INDEXES",t[t.NOTE=4]="NOTE",t[t.REF=5]="REF",t[t.PROJECT=6]="PROJECT",t[t.CUSTOM=7]="CUSTOM",t[t.TOPLEVEL=8]="TOPLEVEL",t))(O||{});class is{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 Xn(s,this.symbolIdGenerator).analyze().map(()=>({ast:s,tokens:n})));return e.getErrors().length>0?e:e.chain(({ast:s,tokens:n})=>new zn(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=>Te(r,T));if(h===void 0||h instanceof V)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=L.last(l);if(h instanceof y){const T=this.parse.source();for(let f=h.end;f<e;f+=1)T[f]===`
|
|
10
|
+
`&&(l.pop(),p=!0)}else h instanceof Y||h instanceof z?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 q?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=L.last(l);T instanceof _&&T.end<=e&&l.pop()}if(!p)break}return l}),token:this.createQuery(11,e=>{const s=this.token.flatStream().findIndex(n=>n.start>=e);return s===void 0?{token:void 0,index:void 0}:s<=0?{token:void 0,index:void 0}:{token:this.token.flatStream()[s-1],index:s-1}}),element:this.createQuery(12,e=>{const s=this.container.stack(e);for(let n=s.length-1;n>=0;n-=1)if(s[n]instanceof _)return s[n];return this.parse.ast()}),scope:this.createQuery(14,e=>{var s,n;return(n=(s=this.container.element(e))==null?void 0:s.symbol)==null?void 0:n.symbolTable}),scopeKind:this.createQuery(15,e=>{var n;if(this.container.element(e)instanceof C)return 8;switch((n=this.container.element(e).type)==null?void 0:n.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:s=this.parse.ast()})=>{var i;if(e.length===0)return[];const n=[];for(let r=s;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=>zt(h).flatMap(f=>{const N=T.get(f),b=se(f).unwrap_or(void 0);return!N||!b?[]:{...b,symbol:N}})),l=p.flatMap(T=>T.symbol.symbolTable?T.symbol.symbolTable:[]);n.push(...p)}return n},({nameStack:e,owner:s})=>`${e.join(".")}@${s.id}`),members:this.createQuery(9,e=>e.symbolTable?[...e.symbolTable.entries()].map(([s,n])=>({...se(s).unwrap(),symbol:n})):[])}}createQuery(e,s,n){return i=>{const r=this.cache[e],a=i&&n?n(i):i;if(r!==null){if(!(r instanceof Map))return r;if(r.has(a))return r.get(a)}const l=s(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 Gt(this),referenceProvider:new Ct(this),autocompletionProvider:new Mt(this)}}}exports.Compiler=is;exports.serialize=jt;exports.services=ss;
|