@dbml/parse 3.1.6 → 3.1.7

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.
@@ -4,5 +4,5 @@
4
4
  `))&&!this.check(n);)this.peek()==="\\"&&!r?(this.advance(),l+=this.escapedString()):l+=this.advance();if(this.isAtEnd()&&!i){const p=this.createToken(e,!0);this.tokens.push(p),this.errors.push(new u(o.UNEXPECTED_EOF,"EOF reached while parsing",p));return}if(this.check(`
5
5
  `)&&!s){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(n),this.tokens.push(B.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
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()&&fe(this.peek());)this.advance();this.addToken(c.IDENTIFIER)}operator(){for(;it(this.peek());)this.advance();this.addToken(c.OP)}numericLiteralOrIdentifier(){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&&!fe(this.peek()))return this.addToken(c.NUMERIC_LITERAL);if(!n&&!xe(this.peek()))break;this.advance()}if(e>0){for(;!this.isAtEnd()&&(this.check(".")||fe(this.peek()));)this.advance();const n=this.createToken(c.NUMERIC_LITERAL,!0);this.tokens.push(n),this.errors.push(new u(o.UNKNOWN_TOKEN,"Invalid number",n))}else{for(;!this.isAtEnd()&&fe(this.peek());)this.advance();const n=this.createToken(c.IDENTIFIER,!1);this.tokens.push(n)}}colorLiteral(){for(;!this.isAtEnd()&&fe(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 n=0;n<=3;n+=1){if(this.isAtEnd()||!fe(this.peek()))return`\\u${e}`;e+=this.advance()}return String.fromCharCode(parseInt(e,16))}default:return`\\${this.tokens[this.current.offset-1]}`}}}var ye=(t=>(t[t.ListExpression=0]="ListExpression",t[t.GroupExpression=1]="GroupExpression",t[t.BlockExpression=2]="BlockExpression",t))(ye||{});class on{constructor(){this.stack=[],this.numberOfNestedLParens=0,this.numberOfNestedLBrackets=0,this.numberOfNestedLBraces=0}push(e){this.stack.push(e),e===0&&(this.numberOfNestedLBrackets+=1),e===1&&(this.numberOfNestedLParens+=1),e===2&&(this.numberOfNestedLBraces+=1)}pop(){const e=this.stack.pop();return e===0&&(this.numberOfNestedLBrackets-=1),e===1&&(this.numberOfNestedLParens-=1),e===2&&(this.numberOfNestedLBraces-=1),e}top(){return I.last(this.stack)}isWithinGroupExpressionContext(){return this.numberOfNestedLParens>0}isWithinListExpressionContext(){return this.numberOfNestedLBrackets>0}isWithinBlockExpressionContext(){return this.numberOfNestedLBraces>0}withContextDo(e,n){return()=>{this.push(e);try{return n()}finally{this.pop()}}}findHandlerContext(e,n){if(!(this.numberOfNestedLBraces<=0&&this.numberOfNestedLBrackets<=0&&this.numberOfNestedLParens<=0))for(let s=n;s<e.length-1;s+=1)switch(e[s].kind){case 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,n){return new e(n,this.generator.nextId())}}class d{constructor(e,n,s){this.token=e,this.partialNode=n,this.handlerContext=s}}class cn{constructor(e,n){this.current=0,this.errors=[],this.contextStack=new on,this.synchronizeProgram=()=>{const s=this.peek();s.kind!==c.EOF?E(this.advance()):(E(this.peek()),this.logError(s,o.UNEXPECTED_EOF,"Unexpected EOF"))},this.synchronizeElementDeclarationName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(lt(s)||this.check(c.COLON,c.LBRACE,c.LBRACKET))break;E(s),this.advance()}},this.synchronizeElementDeclarationAlias=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(c.COLON,c.LBRACE,c.LBRACKET))break;E(s),this.advance()}},this.blockExpression=this.contextStack.withContextDo(ye.BlockExpression,()=>{const s={body:[]},i=()=>this.nodeFactory.create(te,s);try{this.consume("Expect an opening brace '{'",c.LBRACE),s.blockOpenBrace=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.blockOpenBrace=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}for(;!this.isAtEnd()&&!this.check(c.RBRACE);)try{s.body.push(this.canBeField()?this.fieldDeclaration():this.expression())}catch(r){if(!(r instanceof d))throw r;if(s.body.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}try{this.consume("Expect a closing brace '}'",c.RBRACE),s.blockCloseBrace=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.blockCloseBrace=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}return i()}),this.synchronizeBlock=()=>{if(!this.check(c.RBRACE))for(E(this.advance());!this.isAtEnd();){const s=this.peek();if(this.check(c.RBRACE)||at(this.previous(),s))break;E(s),this.advance()}},this.tupleExpression=this.contextStack.withContextDo(ye.GroupExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(Xe,{groupOpenParen:s.tupleOpenParen,groupCloseParen:s.tupleCloseParen,expression:s.elementList[0]}),r=()=>this.nodeFactory.create(J,s);try{this.consume("Expect an opening parenthesis '('",c.LPAREN),s.tupleOpenParen=this.previous()}catch(a){if(!(a instanceof d))throw a;if(s.tupleOpenParen=a.partialNode,!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}if(!this.isAtEnd()&&!this.check(c.RPAREN))try{s.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof d))throw a;if(s.elementList.push(a.partialNode),!this.canHandle(a))throw new d(a.token,i(),a.handlerContext);this.synchronizeTuple()}for(;!this.isAtEnd()&&!this.check(c.RPAREN);)try{this.consume("Expect a comma ','",c.COMMA),s.commaList.push(this.previous()),s.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof d))throw a;if(a.partialNode instanceof y&&s.elementList.push(a.partialNode),!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}try{this.consume("Expect a closing parenthesis ')'",c.RPAREN),s.tupleCloseParen=this.previous()}catch(a){if(!(a instanceof d))throw a;if(s.tupleCloseParen=a.partialNode,!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}return s.elementList.length===1?i():r()}),this.synchronizeTuple=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(c.RPAREN,c.COMMA))break;E(s),this.advance()}},this.listExpression=this.contextStack.withContextDo(ye.ListExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(P,s);try{this.consume("Expect an opening bracket '['",c.LBRACKET),s.listOpenBracket=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.listOpenBracket=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}if(!this.isAtEnd()&&!this.check(c.RBRACKET))try{s.elementList.push(this.attribute())}catch(r){if(!(r instanceof d))throw r;if(s.elementList.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}for(;!this.isAtEnd()&&!this.check(c.RBRACKET);)try{this.consume("Expect a comma ','",c.COMMA),s.commaList.push(this.previous()),s.elementList.push(this.attribute())}catch(r){if(!(r instanceof d))throw r;if(r.partialNode instanceof y&&s.elementList.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}try{this.consume("Expect a closing bracket ']'",c.RBRACKET),s.listCloseBracket=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.listCloseBracket=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}return i()}),this.synchronizeList=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(c.COMMA,c.RBRACKET))break;E(s),this.advance()}},this.synchronizeAttributeName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(c.COMMA,c.RBRACKET,c.COLON))break;E(s),this.advance()}},this.synchronizeAttributeValue=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(c.COMMA,c.RBRACKET))break;E(s),this.advance()}},this.tokens=e,this.nodeFactory=new ln(n)}isAtEnd(){return this.current>=this.tokens.length||this.tokens[this.current].kind===c.EOF}advance(){return this.isAtEnd()?I.last(this.tokens):this.tokens[this.current++]}peek(e=0){return e+this.current>=this.tokens.length?I.last(this.tokens):this.tokens[this.current+e]}match(...e){const n=this.check(...e);return n&&this.advance(),n}check(...e){const n=this.peek();return e.includes(n.kind)}previous(){return this.tokens[this.current-1]}canHandle(e){return e.handlerContext===void 0||e.handlerContext===this.contextStack.top()}consume(e,...n){if(!this.match(...n))throw this.logError(this.peek(),o.UNEXPECTED_TOKEN,e),new d(this.peek(),void 0,this.contextStack.findHandlerContext(this.tokens,this.current))}discardUntil(e,...n){if(this.isAtEnd()||!this.check(...n)){for(E(this.peek()),this.logError(this.advance(),o.UNEXPECTED_TOKEN,e);!this.isAtEnd()&&!this.check(...n);)E(this.advance());return!this.isAtEnd()}return!0}gatherInvalid(){const e=[],n=[];let s,i=0;for(;i<this.tokens.length&&this.tokens[i].isInvalid;i+=1)n.push(this.tokens[i]);for(s=this.tokens[i],s.leadingInvalid=n,e.push(s),i+=1;i<this.tokens.length;i+=1){const r=this.tokens[i];r.isInvalid?s.trailingInvalid.push(r):(s=r,e.push(s))}this.tokens=e}parse(){const e=this.program(),n=this.advance(),s=this.nodeFactory.create(C,{body:e,eof:n});return this.gatherInvalid(),new F({ast:s,tokens:this.tokens},this.errors)}program(){const e=[];for(;!this.isAtEnd();)try{const n=this.elementDeclaration();e.push(n)}catch(n){if(!(n instanceof d))throw n;e.push(n.partialNode),this.synchronizeProgram()}return e}elementDeclaration(){const e={},n=()=>this.nodeFactory.create(_,e);try{this.consume("Expect an identifier",c.IDENTIFIER),e.type=this.previous()}catch(s){throw s instanceof d?(e.type=s.partialNode,new d(s.token,n(),s.handlerContext)):s}if(!this.check(c.COLON,c.LBRACE,c.LBRACKET))try{e.name=this.normalExpression()}catch(s){if(!(s instanceof d))throw s;if(e.name=s.partialNode,!this.canHandle(s))throw new d(s.token,n(),s.handlerContext);this.synchronizeElementDeclarationName()}if(lt(this.peek()))if(e.as=this.advance(),this.check(c.COLON,c.LBRACE,c.LBRACKET))this.logError(this.peek(),o.UNEXPECTED_TOKEN,"Expect an alias");else try{e.alias=this.normalExpression()}catch(s){if(!(s instanceof d))throw s;if(e.alias=s.partialNode,!this.canHandle(s))throw new d(s.token,n(),s.handlerContext);this.synchronizeElementDeclarationAlias()}try{e.attributeList=this.check(c.LBRACKET)?this.listExpression():void 0}catch(s){throw s instanceof d?(e.attributeList=s.partialNode,new d(s.token,n(),s.handlerContext)):s}if(!this.discardUntil("Expect an opening brace '{' or a colon ':'",c.LBRACE,c.COLON))return n();try{if(this.match(c.COLON)){e.bodyColon=this.previous();const s=this.expression();s instanceof _?(E(s),this.logError(s,o.UNEXPECTED_ELEMENT_DECLARATION,"An element's simple body must not be an element declaration")):e.body=s}else e.body=this.blockExpression()}catch(s){throw s instanceof d?(e.body=s.partialNode,new d(s.token,n(),s.handlerContext)):s}return this.nodeFactory.create(_,e)}fieldDeclaration(){const e={},n=()=>this.nodeFactory.create(_,e);try{this.consume("Expect an identifier",c.IDENTIFIER),e.type=this.previous()}catch(s){throw s instanceof d?(e.type=s.partialNode,new d(s.token,n(),s.handlerContext)):s}try{this.consume("Expect a colon ':'",c.COLON),e.bodyColon=this.previous()}catch(s){throw s instanceof d?(e.bodyColon=s.partialNode,new d(s.token,n(),s.handlerContext)):s}try{const s=this.expression();s instanceof _?this.errors.push(new u(o.INVALID_ELEMENT_IN_SIMPLE_BODY,"Simple body cannot be an element declaration",s)):e.body=s}catch(s){throw s instanceof d?(e.body=s.partialNode,new d(s.token,n(),s.handlerContext)):s}return this.nodeFactory.create(_,e)}expression(){const e={args:[]},n=()=>tn(e.callee,e.args,this.nodeFactory).unwrap_or(this.nodeFactory.create(k,e));try{e.callee=this.normalExpression()}catch(i){throw i instanceof d?(e.callee=i.partialNode,new d(i.token,n(),i.handlerContext)):i}if(this.shouldStopExpression())return n();let s=e.callee;for(;!this.shouldStopExpression();){Ve(this.previous())||this.logError(s,o.MISSING_SPACES,"Expect a following space");try{s=this.normalExpression(),e.args.push(s)}catch(i){throw i instanceof d?(s=i.partialNode,e.args.push(s),new d(i.token,n(),i.handlerContext)):i}}return n()}shouldStopExpression(){if(this.isAtEnd()||Tt(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 n=this.leftExpression_bp();for(;!this.isAtEnd();){const s=this.peek();if(s.kind===c.LPAREN){const{left:i}=ct(s);if(i<e||at(this.previous(),s)&&!this.contextStack.isWithinGroupExpressionContext()&&!this.contextStack.isWithinListExpressionContext())break;try{n=this.nodeFactory.create(H,{callee:n,argumentList:this.tupleExpression()})}catch(r){throw r instanceof d?(n=this.nodeFactory.create(H,{callee:n,argumentList:r.partialNode}),new d(r.token,n,r.handlerContext)):r}}else if(s.kind===c.LBRACKET){if(Ve(this.previous()))break;try{n=this.nodeFactory.create(le,{expression:n,indexer:this.listExpression()})}catch(i){throw i instanceof d?(n=this.nodeFactory.create(le,{expression:n,indexer:i.partialNode}),new d(i.token,n,i.handlerContext)):i}}else if(rt(s)){const i=s,r=ct(i);if(r.left!==null){if(r.left<=e)break;this.advance(),n=this.nodeFactory.create(Re,{expression:n,op:i})}else{const a=hn(i);if(a.left===null||a.left<=e)break;this.advance();try{n=this.nodeFactory.create(Q,{leftExpression:n,op:i,rightExpression:i.value==="."?this.extractOperand():this.expression_bp(a.right)})}catch(l){throw l instanceof d?(n=this.nodeFactory.create(Q,{leftExpression:n,op:i,rightExpression:l.partialNode}),new d(l.token,n,l.handlerContext)):l}}}else break}return n}leftExpression_bp(){let e;if(rt(this.peek())){const n={};n.op=this.peek();const s=pn(n.op);if(s.right===null)throw this.logError(n.op,o.UNKNOWN_PREFIX_OP,`Unexpected '${n.op.value}' in an expression`),new d(n.op,this.nodeFactory.create(we,{pre:n.op}),this.contextStack.findHandlerContext(this.tokens,this.current));this.advance();try{n.expression=this.expression_bp(s.right)}catch(i){throw i instanceof d?(n.expression=i.partialNode,new d(i.token,this.nodeFactory.create(q,n),i.handlerContext)):i}e=this.nodeFactory.create(q,n)}else if(e=this.extractOperand(),e instanceof we)throw new d(this.peek(),this.nodeFactory.create(we,{pre:this.peek()}),this.contextStack.findHandlerContext(this.tokens,this.current));return e}extractOperand(){return this.check(c.NUMERIC_LITERAL,c.STRING_LITERAL,c.COLOR_LITERAL,c.QUOTED_STRING,c.IDENTIFIER)?this.primaryExpression():this.check(c.FUNCTION_EXPRESSION)?this.functionExpression():this.check(c.LBRACKET)?this.listExpression():this.check(c.LBRACE)?this.blockExpression():this.check(c.LPAREN)?this.tupleExpression():(this.peek().kind===c.EOF?this.logError(this.peek(),o.UNEXPECTED_EOF,"Unexpected EOF"):this.logError(this.peek(),o.INVALID_OPERAND,`Invalid start of operand "${this.peek().value}"`),this.nodeFactory.create(we,{pre:this.previous()}))}functionExpression(){const e={};try{this.consume("Expect a function expression",c.FUNCTION_EXPRESSION),e.value=this.previous()}catch(n){throw n instanceof d?(e.value=n.partialNode,new d(n.token,this.nodeFactory.create(ee,e),n.handlerContext)):n}return this.nodeFactory.create(ee,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(Ee,{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 n=this.peek();this.logError(n,o.EMPTY_ATTRIBUTE_NAME,"Expect a non-empty attribute name"),e.name=this.nodeFactory.create(K,{identifiers:[]})}else try{e.name=this.attributeName()}catch(n){if(!(n instanceof d))throw n;if(e.name=n.partialNode,!this.canHandle(n))throw new d(n.token,this.nodeFactory.create(ne,e),n.handlerContext);this.synchronizeAttributeName()}return this.match(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(n){if(!(n instanceof d)||!this.canHandle(n))throw n;e=n.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(n){throw n instanceof d?new d(n.token,this.nodeFactory.create(K,{identifiers:e}),n.handlerContext):n}return this.nodeFactory.create(K,{identifiers:e})}logError(e,n,s){this.errors.push(new u(n,s,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 ct(t){return dn[t.value]||{left:null,right:null}}var b=(t=>(t.Table="table",t.Enum="enum",t.Ref="ref",t.Note="note",t.Project="project",t.Indexes="indexes",t.TableGroup="tablegroup",t))(b||{});function ge(t){var n;const e=(n=t==null?void 0:t.type)==null?void 0:n.value.toLowerCase();switch(e){case b.Enum:case b.Table:case b.Indexes:case b.Note:case b.Project:case b.Ref:case b.TableGroup:return new O(e);default:return new A}}function ue(t){if(!He(t))return new O([t]);const e=ue(t.leftExpression).unwrap_or(void 0);return e?(e.push(t.rightExpression),new O(e)):new A}function W(t){if(t===void 0)return new A;const e=ue(t).unwrap_or(void 0);if(!e)return new A;const n=[];for(const s of e){const i=G(s).unwrap_or(void 0);if(!i)return new A;n.push(i)}return new O(n)}function Ie(t){if(t===void 0)return new A;const e=ue(t).unwrap_or(void 0);if(!e||e.length===0)return new A;const n=[];let s;if(!M(I.last(e))){const i=e.pop();if(yt(i))s=i.elementList.map(r=>V(r).unwrap());else return new A}for(const i of e){const r=G(i).unwrap_or(void 0);if(!r)return new A;n.push(r)}return new O({variables:n,tupleElements:s})}function G(t){return M(t)?new O(t.expression.variable.value):new A}function Ge(t){if(ut(t))return t instanceof ee?new O({functional:[t],nonFunctional:[]}):new O({functional:[],nonFunctional:[t]});if(t instanceof J&&t.elementList.every(ut)){const e=t.elementList.filter(s=>s instanceof ee),n=t.elementList.filter(M);return new O({functional:e,nonFunctional:n})}return new A}function V(t){var n;const e=(n=t==null?void 0:t.expression.variable)==null?void 0:n.value;return e===void 0?new A:new O(e)}function Y(t){return $(t)?t.expression instanceof X?new O(t.expression.variable.value):new O(t.expression.literal.value):new A}function En(t){var e;return!(t instanceof Q)||!wt((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),n=Ie(t.rightExpression);if(!e.isOk()||!n.isOk())return!1;const{tupleElements:s}=e.unwrap(),{tupleElements:i}=n.unwrap();return(s==null?void 0:s.length)===(i==null?void 0:i.length)}function ut(t){return t instanceof D&&t.expression instanceof X||t instanceof ee}function mn(t,e){var i,r,a,l;let n=e;const s=Yt(t);for(;n;){if((r=(i=n.symbol)==null?void 0:i.symbolTable)!=null&&r.has(t))return(a=n.symbol.symbolTable)==null?void 0:a.get(t);if(((l=n.symbol)==null?void 0:l.declaration)instanceof C&&s)return n.symbol;if(n instanceof C)return;n=n.parent}}class Tn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof C||ge(this.declarationNode.parent).unwrap_or(void 0)!==b.Project?[new u(o.INVALID_CUSTOM_CONTEXT,"A custom element can only appear in a Project",this.declarationNode)]:[]}validateName(e){return e?[new u(o.UNEXPECTED_NAME,"A Custom element shouldn't have a name",e)]:[]}validateAlias(e){return e?[new u(o.UNEXPECTED_NAME,"A Custom element shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new u(o.UNEXPECTED_SETTINGS,"A Custom element shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof te)return[new u(o.UNEXPECTED_COMPLEX_BODY,"A Custom element can only have an inline field",e)];const n=[];return $(e.callee)||n.push(new u(o.INVALID_CUSTOM_ELEMENT_VALUE,"A Custom element value can only be a string",e)),e.args.length>0&&n.push(...e.args.map(s=>new u(o.INVALID_CUSTOM_ELEMENT_VALUE,"A Custom element value can only be a string",s))),n}}class _e{constructor(){this.table=new Map}has(e){return this.table.has(e)}set(e,n){this.table.set(e,n)}get(e,n){return this.table.get(e)||n!==void 0&&this.set(e,n)||n}entries(){return this.table.entries()}}class bn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof _?[new u(o.INVALID_PROJECT_CONTEXT,"An Enum can only appear top-level",this.declarationNode)]:[]}validateName(e){return e?Je(e)?[]:[new u(o.INVALID_NAME,"An Enum name must be of the form <enum> or <schema>.<enum>",e)]:[new u(o.NAME_NOT_FOUND,"An Enum must have a name",this.declarationNode)]}validateAlias(e){return e?[new u(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}registerElement(){const e=[];this.declarationNode.symbol=this.symbolFactory.create(Ht,{declaration:this.declarationNode,symbolTable:new _e});const{name:n}=this.declarationNode,s=W(n);if(s.isOk()){const i=s.unwrap(),r=i.pop(),a=Ze(i,this.publicSymbolTable,this.symbolFactory),l=je(r);a.has(l)&&e.push(new u(o.DUPLICATE_NAME,`Enum name ${r} already exists in schema '${i.join(".")||"public"}'`,n)),a.set(l,this.declarationNode.symbol)}return e}validateSettingList(e){return e?[new u(o.UNEXPECTED_SETTINGS,"An Enum shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof k)return this.validateFields([e]);const[n,s]=I.partition(e.body,i=>i instanceof k);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.length===0?[new u(o.EMPTY_ENUM,"An Enum must have at least one element",this.declarationNode)]:e.flatMap(n=>{const s=[];n.callee&&!M(n.callee)&&s.push(new u(o.INVALID_ENUM_ELEMENT_NAME,"An enum field must be an identifier or a quoted identifier",n.callee));const i=[...n.args];return I.last(i)instanceof P?(s.push(...this.validateFieldSettings(I.last(i))),i.pop()):i[0]instanceof P&&(s.push(...this.validateFieldSettings(i[0])),i.shift()),i.length>0&&s.push(...i.map(r=>new u(o.INVALID_ENUM_ELEMENT,"An Enum must have only a field and optionally a setting list",r))),s.push(...this.registerField(n)),s})}validateFieldSettings(e){const n=z(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"note":a.length>1&&a.forEach(l=>s.push(new u(o.DUPLICATE_ENUM_ELEMENT_SETTING,"'note' can only appear once",l))),a.forEach(l=>{$(l.value)||s.push(new u(o.INVALID_ENUM_ELEMENT_SETTING,"'note' must be a string",l))});break;default:a.forEach(l=>s.push(new u(o.UNKNOWN_ENUM_ELEMENT_SETTING,`Unknown enum field setting '${r}'`,l)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ie(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}registerField(e){if(e.callee&&M(e.callee)){const n=V(e.callee).unwrap(),s=Ye(n),i=this.symbolFactory.create(Jt,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(s)){const a=r.get(s);return[new u(o.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,e),new u(o.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,a.declaration)]}r.set(s,i)}return[]}}class In{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof C||ge(this.declarationNode.parent).unwrap_or(void 0)!==b.Table?[new u(o.INVALID_NOTE_CONTEXT,"An Indexes can only appear inside a Table",this.declarationNode)]:[]}validateName(e){return e?[new u(o.UNEXPECTED_NAME,"An Indexes shouldn't have a name",e)]:[]}validateAlias(e){return e?[new u(o.UNEXPECTED_ALIAS,"An Indexes shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new u(o.UNEXPECTED_SETTINGS,"An Indexes shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof k)return[new u(o.UNEXPECTED_SIMPLE_BODY,"An Indexes must have a complex body",e)];const[n,s]=I.partition(e.body,i=>i instanceof k);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.flatMap(n=>{if(!n.callee)return[];const s=[],i=[n.callee,...n.args];return I.last(i)instanceof P&&s.push(...this.validateFieldSetting(i.pop())),i.forEach(r=>{for(;r instanceof H;)r.argumentList&&!Ge(r.argumentList).isOk()&&s.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()||s.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))}),s})}validateFieldSetting(e){const n=z(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"note":case"name":a.length>1&&a.forEach(l=>s.push(new u(o.DUPLICATE_INDEX_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{$(l.value)||s.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=>s.push(new u(o.DUPLICATE_INDEX_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{oe(l.value)||s.push(new u(o.INVALID_INDEX_SETTING_VALUE,`'${r}' must not have a value`,l))});break;case"type":a.length>1&&a.forEach(l=>s.push(new u(o.DUPLICATE_INDEX_SETTING,"'type' can only appear once",l))),a.forEach(l=>{M(l.value)||s.push(new u(o.INVALID_INDEX_SETTING_VALUE,`'type' must be "btree" or "hash"`,l))});break;default:a.forEach(l=>s.push(new u(o.UNKNOWN_INDEX_SETTING,`Unknown index setting '${r}'`,l)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ie(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class Ln{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof C||![b.Table,b.Project].includes(ge(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 k)return this.validateFields([e]);const[n,s]=I.partition(e.body,i=>i instanceof k);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){const n=[];return e.length===0?[new u(o.EMPTY_NOTE,"A Note must have a content",this.declarationNode)]:(e.length>1&&e.slice(1).forEach(s=>n.push(new u(o.NOTE_CONTENT_REDEFINED,"A Note can only contain one string",s))),$(e[0].callee)||n.push(new u(o.INVALID_NOTE,"A Note content must be a quoted string",e[0])),e[0].args.length>0&&n.push(...e[0].args.map(s=>new u(o.INVALID_NOTE,"A Note can only contain one quoted string",s))),n)}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ie(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class gn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof _?[new u(o.INVALID_PROJECT_CONTEXT,"A Project can only appear top-level",this.declarationNode)]:[]}validateName(e){return e?Pe(e)?[]:[new u(o.INVALID_NAME,"A Project's name is optional or must be an identifier or a quoted identifer",e)]:[]}validateAlias(e){return e?[new u(o.UNEXPECTED_ALIAS,"A Project shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new u(o.UNEXPECTED_SETTINGS,"A Project shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof k)return[new u(o.UNEXPECTED_SIMPLE_BODY,"A Project's body must be a block",e)];const[n,s]=I.partition(e.body,i=>i instanceof k);return[...n.map(i=>new u(o.INVALID_PROJECT_FIELD,"A Project can not have inline fields",i)),...this.validateSubElements(s)]}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ie(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class _n{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof C?[]:[new u(o.INVALID_REF_CONTEXT,"A Ref must appear top-level",this.declarationNode)]}validateName(e){return e?Pe(e)?[]:[new u(o.INVALID_NAME,"A Ref's name is optional or must be an identifier or a quoted identifer",e)]:[]}validateAlias(e){return e?[new u(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new u(o.UNEXPECTED_SETTINGS,"A Ref shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof k)return this.validateFields([e]);const[n,s]=I.partition(e.body,i=>i instanceof k);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){if(e.length===0)return[new u(o.EMPTY_REF,"A Ref must have at least one field",this.declarationNode)];const n=[];return e.length>1&&n.push(...e.slice(1).map(s=>new u(o.REF_REDEFINED,"A Ref can only contain one binary relationship",s))),e.forEach(s=>{s.callee&&!En(s.callee)&&n.push(new u(o.INVALID_REF_FIELD,"A Ref field must be a binary relationship",s.callee)),s.callee&&!Nn(s.callee)&&n.push(new u(o.UNEQUAL_FIELDS_BINARY_REF,"Unequal fields in ref endpoints",s.callee));const i=[...s.args];I.last(i)instanceof P?(this.validateFieldSettings(I.last(i)),i.pop()):i[0]instanceof P&&(n.push(...this.validateFieldSettings(i[0])),i.shift()),i.length>0&&n.push(...i.map(r=>new u(o.INVALID_REF_FIELD,"A Ref field should only have a single binary relationship",r)))}),n}validateFieldSettings(e){const n=z(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"delete":case"update":a.length>1&&a.forEach(l=>s.push(new u(o.DUPLICATE_REF_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{An(l.value)||s.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=>s.push(new u(o.UNKNOWN_REF_SETTING,`Unknown ref setting '${r}'`,l)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ie(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}function An(t){if(!(M(t)&&t.expression.variable.kind!==c.QUOTED_STRING)&&!(t instanceof K))return!1;let e;if(t instanceof K?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,n,s){this.declarationNode=e,this.symbolFactory=s,this.publicSymbolTable=n}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof _?[new u(o.INVALID_TABLE_CONTEXT,"Table must appear top-level",this.declarationNode)]:[]}validateName(e){return e?e instanceof le?[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,"Table aliases can only contains alphanumeric and underscore unless surrounded by double quotes",e)]:[]}validateSettingList(e){const n=z(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"headercolor":a.length>1&&s.push(...a.map(l=>new u(o.DUPLICATE_TABLE_SETTING,"'headercolor' can only appear once",l))),a.forEach(l=>{On(l.value)||s.push(new u(o.INVALID_TABLE_SETTING,"'headercolor' must be a color literal",l.value||l.name))});break;case"note":a.length>1&&s.push(...a.map(l=>new u(o.DUPLICATE_TABLE_SETTING,"'note' can only appear once",l))),a.forEach(l=>{$(l.value)||s.push(new u(o.INVALID_TABLE_SETTING,"'note' must be a string literal",l.value||l.name))});break;default:s.push(...a.map(l=>new u(o.INVALID_TABLE_SETTING,`Unknown '${r}' setting`,l)))}}return s}registerElement(){const e=[];this.declarationNode.symbol=this.symbolFactory.create(_t,{declaration:this.declarationNode,symbolTable:new _e});const{name:n,alias:s}=this.declarationNode,i=W(n);if(i.isOk()){const r=[...i.unwrap()],a=r.pop(),l=Ze(r,this.publicSymbolTable,this.symbolFactory),p=ke(a);l.has(p)&&e.push(new u(o.DUPLICATE_NAME,`Table name '${a}' already exists in schema '${r.join(".")||"public"}'`,n)),l.set(p,this.declarationNode.symbol)}if(s&&Pe(s)&&!yn(s.expression.variable.value,i.unwrap_or([]))){const r=V(s).unwrap(),a=ke(r);this.publicSymbolTable.has(a)&&e.push(new u(o.DUPLICATE_NAME,`Table name '${r}' already exists`,n)),this.publicSymbolTable.set(a,this.declarationNode.symbol)}return e}validateBody(e){if(!e)return[];if(e instanceof k)return[new u(o.UNEXPECTED_SIMPLE_BODY,"A Table's body must be a block",e)];const[n,s]=I.partition(e.body,i=>i instanceof k);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.length===0?[new u(o.EMPTY_TABLE,"A Table must have at least one column",this.declarationNode)]:e.flatMap(n=>{if(!n.callee)return[];const s=[];n.args.length===0&&s.push(new u(o.INVALID_COLUMN,"A column must have a type",n.callee)),M(n.callee)||s.push(new u(o.INVALID_COLUMN_NAME,"A column name must be an identifier or a quoted identifier",n.callee)),n.args[0]&&!wn(n.args[0])&&s.push(new u(o.INVALID_COLUMN_TYPE,"Invalid column type",n.args[0]));const i=n.args.slice(1);return s.push(...this.validateFieldSetting(i)),s.push(...this.registerField(n)),s})}registerField(e){if(e.callee&&M(e.callee)){const n=V(e.callee).unwrap(),s=We(n),i=this.symbolFactory.create(Zt,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(s)){const a=r.get(s);return[new u(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,e),new u(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,a.declaration)]}r.set(s,i)}return[]}validateFieldSetting(e){if(!e.slice(0,-1).every(de)||!e.slice(-1).every(p=>de(p)||p instanceof P))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 n;I.last(e)instanceof P&&(n=e.pop());const s=z(n),i=s.getErrors(),r=s.getValue();for(const p of e){const h=V(p).unwrap_or("").toLowerCase();if(h!=="pk"&&h!=="unique"){i.push(new u(o.INVALID_SETTINGS,"Inline column settings can only be `pk` or `unique`",p));continue}r[h]===void 0?r[h]=[p]:r[h].push(p)}const a=r.pk||[],l=r["primary key"]||[];a.length>=1&&l.length>=1&&i.push(...[...a,...l].map(p=>new u(o.DUPLICATE_COLUMN_SETTING,"Either one of 'primary key' and 'pk' can appear",p)));for(const p in r){const h=r[p];switch(p){case"note":h.length>1&&i.push(...h.map(f=>new u(o.DUPLICATE_COLUMN_SETTING,"note can only appear once",f))),h.forEach(f=>{$(f.value)||i.push(new u(o.INVALID_COLUMN_SETTING_VALUE,"'note' must be a quoted string",f.value||f.name))});break;case"ref":h.forEach(f=>{Rn(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 n=e.flatMap(i=>{if(i.parent=this.declarationNode,!i.type)return[];const r=ie(i);return new r(i,this.publicSymbolTable,this.symbolFactory).validate()}),s=e.filter(i=>{var r;return((r=i.type)==null?void 0:r.value.toLowerCase())==="note"});return s.length>1&&(n.push(...s.map(i=>new u(o.NOTE_REDEFINED,"Duplicate notes are defined",i))),n.push()),n}}function wn(t){if(!(t instanceof H||He(t)||t instanceof D||t instanceof le))return!1;if(t instanceof H){if(t.callee===void 0||t.argumentList===void 0||!t.argumentList.elementList.every(n=>ce(n)||$(n)||de(n)))return!1;t=t.callee}for(;t instanceof le;){if(t.array===void 0||t.indexer===void 0||!t.indexer.elementList.every(n=>!n.colon&&!n.value&&ce(n.name)))return!1;t=t.array}const e=W(t).unwrap_or(void 0);return e!==void 0&&e.length>0}function yn(t,e){return e.length===1&&t===e[0]}class kn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof _?[new u(o.INVALID_TABLEGROUP_CONTEXT,"TableGroup must appear top-level",this.declarationNode)]:[]}validateName(e){return e?Je(e)?[]:[new u(o.INVALID_NAME,"A TableGroup name must be of the form <tablegroup> or <schema>.<tablegroup>",e)]:[new u(o.NAME_NOT_FOUND,"A TableGroup must have a name",this.declarationNode)]}validateAlias(e){return e?[new u(o.UNEXPECTED_ALIAS,"A TableGroup shouldn't have an alias",e)]:[]}registerElement(){const{name:e}=this.declarationNode;this.declarationNode.symbol=this.symbolFactory.create(Kt,{declaration:this.declarationNode,symbolTable:new _e});const n=W(e);if(n.isOk()){const s=n.unwrap(),i=s.pop(),r=Ze(s,this.publicSymbolTable,this.symbolFactory),a=ze(i);if(r.has(a))return[new u(o.DUPLICATE_NAME,`TableGroup name '${i}' already exists in schema '${s.join(".")||"public"}'`,e)];r.set(a,this.declarationNode.symbol)}return[]}validateSettingList(e){return e?[new u(o.UNEXPECTED_SETTINGS,"A TableGroup shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof k)return[new u(o.UNEXPECTED_SIMPLE_BODY,"A TableGroup's body must be a block",e)];const[n,s]=I.partition(e.body,i=>i instanceof k);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.flatMap(n=>{const s=[];return n.callee&&!W(n.callee).isOk()&&s.push(new u(o.INVALID_TABLEGROUP_FIELD,"A TableGroup field must be of the form <table> or <schema>.<table>",n.callee)),this.registerField(n),n.args.length>0&&s.push(...n.args.map(i=>new u(o.INVALID_TABLEGROUP_FIELD,"A TableGroup field should only have a single Table name",i))),s})}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ie(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}registerField(e){if(e.callee&&M(e.callee)){const n=V(e.callee).unwrap(),s=qe(n),i=this.symbolFactory.create(en,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(s)){const a=r.get(s);return[new u(o.DUPLICATE_TABLEGROUP_FIELD_NAME,`${n} already exists in the group`,e),new u(o.DUPLICATE_TABLEGROUP_FIELD_NAME,`${n} already exists in the group`,a.declaration)]}r.set(s,i)}return[]}}const vt=["-","+"];function ie(t){switch(t.type.value.toLowerCase()){case b.Enum:return bn;case b.Table:return vn;case b.TableGroup:return kn;case b.Project:return gn;case b.Ref:return _n;case b.Note:return Ln;case b.Indexes:return In;default:return Tn}}function Je(t){return!!W(t).unwrap_or(!1)}function xn(t){return Pe(t)}function Pe(t){return t instanceof D&&t.expression instanceof X}function Ze(t,e,n){var i;t[0]==="public"&&(t=t.slice(1));let s=e;for(const r of t){let a;const l=$e(r);if(s.has(l)){if(a=(i=s.get(l))==null?void 0:i.symbolTable,!a)throw new Error("Expect a symbol table in a schema symbol")}else{a=new _e;const p=n.create(gt,{symbolTable:a});s.set(l,p)}s=a}return s}function wt(t){return t==="-"||t==="<>"||t===">"||t==="<"}function On(t){var n;if(!(t instanceof D)||!(t.expression instanceof Ee)||((n=t.expression.literal)==null?void 0:n.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 s=1;s<e.length;s+=1)if(!qt(e[s]))return!1;return!0}function oe(t){return t===void 0}function Sn(t){var e;return!!($(t)||ce(t)||de(t)&&["true","false","null"].includes(t.expression.variable.value.toLowerCase())||t instanceof q&&vt.includes((e=t.op)==null?void 0:e.value)&&ce(t.expression)||t instanceof ee)}function ce(t){var e;return t instanceof D&&t.expression instanceof Ee&&((e=t.expression.literal)==null?void 0:e.kind)===c.NUMERIC_LITERAL}function Rn(t){var n;if(!(t instanceof q)||!wt((n=t.op)==null?void 0:n.value))return!1;const e=W(t.expression).unwrap_or(void 0);return e!==void 0&&e.length>0}function yt(t){return t instanceof J&&t.elementList.every(M)}function z(t){var s;const e={},n=[];if(!t)return new F({});for(const i of t.elementList){if(!i.name)continue;if(i.name instanceof D){n.push(new u(o.INVALID_SETTINGS,"A setting name must be a stream of identifiers",i.name));continue}const r=(s=De(i.name).unwrap_or(void 0))==null?void 0:s.toLowerCase();r&&(e[r]===void 0?e[r]=[i]:e[r].push(i))}return new F(e,n)}class ht{constructor(e,n){this.ast=e,this.symbolFactory=n,this.publicSchemaSymbol=this.symbolFactory.create(gt,{symbolTable:new _e}),this.ast.symbol=this.publicSchemaSymbol,this.ast.symbol.declaration=this.ast}validate(){const e=[];this.ast.body.forEach(s=>{if(s.parent=this.ast,s.type===void 0)return;const i=ie(s),r=new i(s,this.publicSchemaSymbol.symbolTable,this.symbolFactory);e.push(...r.validate())});const n=this.ast.body.filter(s=>ge(s).unwrap_or(void 0)===b.Project);return n.length>1&&n.forEach(s=>e.push(new u(o.PROJECT_REDEFINED,"Only one project can exist",s))),new F(this.ast,e)}}class re{constructor(e,n){this.declarationNode=e,this.errors=n}bind(){this.bindSettingList(this.declarationNode.attributeList,this.settingList),this.bindBody()}bindSettingList(e,n){if(e)for(const s of e.elementList){if(s.name instanceof D)continue;const i=De(s.name).unwrap_or(void 0);if(!i)continue;const r=n[i.toLowerCase()];r!=null&&r.shouldBind&&this.scanAndBind(s.value,r)}}bindBody(){const e=this.declarationNode;if(!e.body)return;const{body:n}=e;if(n instanceof te)for(const s of n.body)if(s instanceof _){if(!s.type)continue;const i=kt(s);new i(s,this.errors).bind()}else this.bindSubfield(s);else this.bindSubfield(n)}bindSubfield(e){const n=[e.callee,...e.args],s=I.last(n);s instanceof P&&(n.pop(),this.bindSettingList(s,this.subfield.settingList));const{argBinderRules:i}=this.subfield.arg;for(let r=0;r<Math.min(n.length,i.length);r+=1)i[r].shouldBind&&this.scanAndBind(n[r],i[r])}scanAndBind(e,n){var s,i;if(e)if(e instanceof D){if(e.expression instanceof X&&((i=n.keywords)!=null&&i.includes((s=e.expression.variable)==null?void 0:s.value.toLowerCase())))return;this.bindFragments([e],n)}else e instanceof Q?He(e)?this.bindFragments(ue(e).unwrap_or([]),n):(this.scanAndBind(e.leftExpression,n),this.scanAndBind(e.rightExpression,n)):e instanceof q?this.scanAndBind(e.expression,n):e instanceof Re?this.scanAndBind(e.expression,n):e instanceof J&&e.elementList.forEach(r=>this.scanAndBind(r,n))}bindFragments(e,n){if(e.length===0)return;const s=[...n.topSubnamesSymbolKind],{remainingSubnamesSymbolKind:i}=n,r=e.findIndex(f=>!M(f)),l=r!==-1&&yt(e[r])?e[r]:void 0,p=r>=0?s.pop():void 0,h=e.slice(0,r===-1?void 0:r);if(h.length===0)return;const T=[];for(;s.length&&h.length;){const f=s.pop(),N=h.pop(),g=V(N).unwrap();T.unshift({index:Fe(g,f),referrer:N})}for(;h.length;){const f=h.pop(),N=V(f).unwrap();T.unshift({index:Fe(N,i),referrer:f})}return l?l.elementList.forEach(f=>this.resolveIndexStack([...T,{index:Fe(V(f).unwrap(),p),referrer:f}],n.ignoreNameNotFound)):this.resolveIndexStack(T,n.ignoreNameNotFound)}resolveIndexStack(e,n){if(e.length===0)throw new Error("Unreachable - An unresolved name must have at least one name component");const[s,...i]=e,r=mn(s.index,this.declarationNode);if(r===void 0){const{kind:h,name:T}=se(s.index).unwrap();this.logError(s.referrer,`Can not find ${h} '${T}'`,n);return}r.references.push(s.referrer),s.referrer.referee=r;let a=r.symbolTable,{kind:l,name:p}=se(s.index).unwrap();for(const h of i){const{kind:T,name:f}=se(h.index).unwrap(),N=a.get(h.index);if(!N){this.logError(h.referrer,`${l} '${p}' does not have ${T} '${f}'`,n);return}if(l=T,p=f,h.referrer.referee=N,N.references.push(h.referrer),!N.symbolTable)break;a=N.symbolTable}}logError(e,n,s){s||this.errors.push(new u(o.BINDING_ERROR,n,e))}}class Dn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Pn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Un extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class Mn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Fn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Bn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class Vn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Enum],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!0}]},settingList:{ref:{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},default:{shouldBind:!1}}},this.settingList={}}}class Gn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}function kt(t){switch(t.type.value.toLowerCase()){case b.Enum:return Pn;case b.Table:return Vn;case b.TableGroup:return Gn;case b.Project:return Fn;case b.Ref:return Bn;case b.Note:return Mn;case b.Indexes:return Un;default:return Dn}}class Cn{constructor(e){this.ast=e,this.errors=[]}resolve(){for(const e of this.ast.body)if(e.type){const n=kt(e);new n(e,this.errors).bind()}return new F(this.ast,this.errors)}}class Xn{constructor(e){this.generator=e}create(e,n){return new e(n,this.generator.nextId())}}class $n{constructor(e,n){this.ast=e,this.symbolFactory=new Xn(n)}analyze(){return new ht(this.ast,this.symbolFactory).validate().chain(n=>new Cn(n).resolve())}validate(){return new ht(this.ast,this.symbolFactory).validate().chain(n=>new F(n,[]))}}function ft(t,e){const{variables:n,tupleElements:s}=Ie(t).unwrap();return s?n.length===0?{schemaName:e.schemaName,tableName:e.name,fieldNames:s}:{tableName:n.pop(),schemaName:n.pop()||null,fieldNames:s}:n.length===1?{schemaName:e.schemaName,tableName:e.name,fieldNames:[n[0]]}:{fieldNames:[n.pop()],tableName:n.pop(),schemaName:n.pop()||null}}function xt(t){switch(t){case"<":return["1","*"];case"<>":return["*","*"];case">":return["*","1"];case"-":return["1","1"]}throw new Error("Invalid relation op")}function x(t){return{start:{offset:t.startPos.offset,line:t.startPos.line+1,column:t.startPos.column+1},end:{offset:t.endPos.offset,line:t.endPos.line+1,column:t.endPos.column+1}}}function Ce(t){var n;const e=(n=ue(t).unwrap_or(void 0))==null?void 0:n.pop();return e instanceof J?e.elementList.map(s=>s.referee):[e.referee]}function Ae(t){const e=W(t).unwrap();return{name:e.pop(),schemaName:e}}function Wn(t){return t.expression.literal.value}function Ot(t,e){if(Array.isArray(t)){const i=t.map(({id:a})=>a).sort().join(","),r=e.map(({id:a})=>a).sort().join(",");return i<r?`${i}-${r}`:`${r}-${i}`}const n=t.id,s=e.id;return n<s?`${n}-${s}`:`${s}-${n}`}function St(t,e){if(Array.isArray(t)){const i=t.map(({id:a})=>a).sort(),r=e.map(({id:a})=>a).sort();return I.zip(i,r).every(([a,l])=>a===l)}const n=t.id,s=e.id;return n===s}class Rt{constructor(e,n){this.declarationNode=e,this.env=n,this.table={name:void 0,schemaName:void 0,alias:null,fields:[],token:void 0,indexes:[]},this.pkColumns=[]}interpret(){this.table.token=x(this.declarationNode),this.env.tables.set(this.declarationNode,this.table);const e=[...this.interpretName(this.declarationNode.name),...this.interpretAlias(this.declarationNode.alias),...this.interpretSettingList(this.declarationNode.attributeList),...this.interpretBody(this.declarationNode.body)];return this.pkColumns.length>=2&&(this.table.indexes.push({columns:this.pkColumns.map(({name:n})=>({value:n,type:"column"})),token:{start:{offset:-1,line:-1,column:-1},end:{offset:-1,line:-1,column:-1}},pk:!0}),this.pkColumns.forEach(n=>n.pk=!1)),e}interpretName(e){const{name:n,schemaName:s}=Ae(e);return s.length>1?(this.table.name=n,this.table.schemaName=s.join("."),[new u(o.UNSUPPORTED,"Nested schema is not supported",e)]):(this.table.name=n,this.table.schemaName=s.length?s[0]:null,[])}interpretAlias(e){if(!e)return[];const n=V(e).unwrap_or(null);return n&&(this.env.aliases.push({name:n,kind:"table",value:{tableName:this.table.name,schemaName:this.table.schemaName}}),this.table.alias=n),[]}interpretSettingList(e){var r,a,l;const n=z(e).getValue();this.table.headerColor=(r=n.headercolor)!=null&&r.length?Wn((l=(a=n.headercolor)==null?void 0:a.at(0))==null?void 0:l.value):void 0;const[s]=n.note||[],i=Y(s==null?void 0:s.value).unwrap_or(void 0);return this.table.note=s&&{value:i,token:x(s)},[]}interpretBody(e){const[n,s]=I.partition(e.body,i=>i instanceof k);return[...this.interpretFields(n),...this.interpretSubElements(s)]}interpretSubElements(e){return e.flatMap(n=>{var s;switch((s=n.type)==null?void 0:s.value.toLowerCase()){case"note":return this.table.note={value:Y(n.body instanceof te?n.body.body[0].callee:n.body.callee).unwrap(),token:x(n)},[];case"indexes":return this.interpretIndexes(n)}return[]})}interpretFields(e){return e.flatMap(n=>this.interpretColumn(n))}interpretColumn(e){var a,l,p,h,T,f,N,g;const n=[],s={};s.name=V(e.callee).unwrap();const i=jn(e.args[0]);s.type=i.getValue(),n.push(...i.getErrors()),s.token=x(e),s.inline_refs=[];const r=e.args.slice(1);if(I.last(r)instanceof P){const v=z(r.pop()).getValue();s.pk=!!((a=v.pk)!=null&&a.length)||!!((l=v["primary key"])!=null&&l.length),s.increment=!!((p=v.increment)!=null&&p.length),s.unique=!!((h=v.unique)!=null&&h.length),s.not_null=!!((T=v["not null"])!=null&&T.length)&&!0,s.dbdefault=Yn((N=(f=v.default)==null?void 0:f.at(0))==null?void 0:N.value);const Ne=(g=v.note)==null?void 0:g.at(0);s.note=Ne&&{value:Y(Ne.value).unwrap(),token:x(Ne)};const me=v.ref||[];s.inline_refs=me.flatMap(j=>{const[tt]=Ce(j.value.expression);if(St(tt,e.symbol))return n.push(new u(o.SAME_ENDPOINT,"Two endpoints are the same",j)),[];const ve=j.value.op,Z=W(j.value.expression).unwrap();let he;if(Z.length===1){const[ae]=Z;he={schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[ae],relation:ve.value,token:x(j)}}else if(Z.length===2){const[ae,Te]=Z;he={schemaName:null,tableName:ae,fieldNames:[Te],relation:ve.value,token:x(j)}}else if(Z.length===3){const[ae,Te,st]=Z;he={schemaName:ae,tableName:Te,fieldNames:[st],relation:ve.value,token:x(j)}}else{n.push(new u(o.UNSUPPORTED,"Nested schema is not supported",j));const ae=Z.pop(),Te=Z.pop();he={schemaName:Z.join("."),tableName:Te,fieldNames:[ae],relation:ve.value,token:x(j)}}const nt=this.registerInlineRefToEnv(e,tt,he,j);return n.push(...nt),nt.length===0?he:[]})}return s.pk||(s.pk=r.some(v=>G(v).unwrap().toLowerCase()==="pk")),s.unique||(s.unique=r.some(v=>G(v).unwrap().toLowerCase()==="unique")),this.table.fields.push(s),s.pk&&this.pkColumns.push(s),n}interpretIndexes(e){return this.table.indexes.push(...e.body.body.map(n=>{var a,l,p,h,T,f,N;const s={columns:[]},i=n;s.token=x(e);const r=[i.callee,...i.args];if(I.last(r)instanceof P){const g=z(r.pop()).getValue();s.pk=!!((a=g.pk)!=null&&a.length),s.unique=!!((l=g.unique)!=null&&l.length),s.name=Y((h=(p=g.name)==null?void 0:p.at(0))==null?void 0:h.value).unwrap_or(void 0);const v=(T=g.note)==null?void 0:T.at(0);s.note=v&&{value:Y(v.value).unwrap(),token:x(v)},s.type=G((N=(f=g.type)==null?void 0:f.at(0))==null?void 0:N.value).unwrap_or(void 0)}return r.flatMap(g=>{if(!(g instanceof H))return g;const v=[];for(;g instanceof H;)v.push(g.argumentList),g=g.callee;return v.push(g),v}).forEach(g=>{const{functional:v,nonFunctional:Ne}=Ge(g).unwrap();s.columns.push(...v.map(me=>({value:me.value.value,type:"expression"})),...Ne.map(me=>({value:V(me).unwrap(),type:"column"})))}),s})),[]}registerInlineRefToEnv(e,n,s,i){const r=Ot(e.symbol,n);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=xt(s.relation);return this.env.refIds[r]=i,this.env.ref.set(i,{name:null,schemaName:null,token:s.token,endpoints:[{...s,relation:a[1]},{schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[G(e.callee).unwrap()],token:x(e),relation:a[0]}]}),[]}}function jn(t){let e=null;t instanceof H&&(e=t.argumentList.elementList.map(r=>ce(r)?r.expression.literal.value:$(r)?Y(r).unwrap():G(r).unwrap()).join(","),t=t.callee);let n="";for(;t instanceof le;)n=`[${t.indexer.elementList.map(r=>r.name.expression.literal.value).join(",")}]${n}`,t=t.array;const{name:s,schemaName:i}=Ae(t);return i.length>1?new F({schemaName:i.length===0?null:i[0],type_name:`${s}${n}${e?`(${e})`:""}`,args:e},[new u(o.UNSUPPORTED,"Nested schema is not supported",t)]):new F({schemaName:i.length===0?null:i[0],type_name:`${s}${n}${e?`(${e})`:""}`,args:e})}function Yn(t){var e,n,s;if(t){if($(t))return{value:Y(t).unwrap(),type:"string"};if(ce(t))return{type:"number",value:Number.parseFloat(t.expression.literal.value)};if(de(t))return{value:t.expression.variable.value.toLowerCase(),type:"boolean"};if(t instanceof q&&vt.includes((e=t.op)==null?void 0:e.value)&&ce(t.expression)){const i=Number.parseFloat(t.expression.expression.literal.value);return{value:((n=t.op)==null?void 0:n.value)==="-"?0-i:i,type:"number"}}if(t instanceof ee)return{value:(s=t.value)==null?void 0:s.value,type:"expression"};throw new Error("Unreachable")}}class Dt{constructor(e,n){this.declarationNode=e,this.env=n,this.container=this.declarationNode.parent instanceof _?this.env.tables.get(this.declarationNode.parent):void 0,this.ref={}}interpret(){return this.ref.token=x(this.declarationNode),this.env.ref.set(this.declarationNode,this.ref),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(e){const n=[],s=W(this.declarationNode.name).unwrap_or([]);return this.ref.name=s.pop()||null,s.length>1&&n.push(new u(o.UNSUPPORTED,"Nested schema is not supported",this.declarationNode.name)),this.ref.schemaName=s.join(".")||null,n}interpretBody(e){return e instanceof k?this.interpretField(e):this.interpretField(e.body[0])}interpretField(e){var h,T,f,N;const n=e.callee.op.value,{leftExpression:s,rightExpression:i}=e.callee,r=Ce(s),a=Ce(i);if(St(r,a))return[new u(o.SAME_ENDPOINT,"Two endpoints are the same",e)];const l=Ot(r,a);if(this.env.refIds[l])return[new u(o.CIRCULAR_REF,"References with same endpoints exist",this.declarationNode),new u(o.CIRCULAR_REF,"References with same endpoints exist",this.env.refIds[l])];if(e.args[0]){const g=z(e.args[0]).getValue();this.ref.onDelete=G((T=(h=g.delete)==null?void 0:h.at(0))==null?void 0:T.value).unwrap_or(void 0),this.ref.onDelete=G((N=(f=g.delete)==null?void 0:f.at(0))==null?void 0:N.value).unwrap_or(void 0)}const p=xt(n);return this.ref.endpoints=[{...ft(s,this.container),relation:p[0],token:x(s)},{...ft(i,this.container),relation:p[1],token:x(i)}],this.env.refIds[l]=this.declarationNode,[]}}class Pt{constructor(e,n){this.declarationNode=e,this.env=n,this.tableGroup={tables:[]}}interpret(){const e=[];return this.tableGroup.token=x(this.declarationNode),this.env.tableGroups.set(this.declarationNode,this.tableGroup),e.push(...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)),e}interpretName(e){const n=[],{name:s,schemaName:i}=Ae(e);return i.length>=2&&(this.tableGroup.name=s,this.tableGroup.schemaName=i.join("."),n.push(new u(o.UNSUPPORTED,"Nested schema is not supported",this.declarationNode.name))),this.tableGroup.name=s,this.tableGroup.schemaName=i[0]||null,n}interpretBody(e){const n=[];return this.tableGroup.tables=this.declarationNode.body.body.map(s=>{const i=W(s.callee).unwrap();i.length>2&&n.push(new u(o.UNSUPPORTED,"Nested schema is not supported",s));const r=ue(s.callee).unwrap().pop().referee.id;if(this.env.groupOfTable[r]){const a=this.env.groupOfTable[r],{schemaName:l,name:p}=this.env.tableGroups.get(a),h=l?`${l}.${p}`:p;n.push(new u(o.TABLE_REAPPEAR_IN_TABLEGROUP,`Table "${i.join(".")}" already appears in group "${h}"`,s))}else this.env.groupOfTable[r]=this.declarationNode;return{name:i.pop(),schemaName:i.join(".")}}),n}}class Ut{constructor(e,n){this.declarationNode=e,this.env=n,this.enum={values:[]}}interpret(){return this.enum.token=x(this.declarationNode),this.env.enums.set(this.declarationNode,this.enum),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(e){const{name:n,schemaName:s}=Ae(e);return s.length>1?(this.enum.name=n,this.enum.schemaName=s.join("."),[new u(o.UNSUPPORTED,"Nested schema is not supported",e)]):(this.enum.name=n,this.enum.schemaName=s.length?s[0]:null,[])}interpretBody(e){return e.body.flatMap(n=>{var l;const s=n,i={};i.token=x(s),i.name=G(s.callee).unwrap();const a=(l=z(s.args[0]).getValue().note)==null?void 0:l.at(0);return i.note=a&&{value:Y(a.value).unwrap(),token:x(a)},this.enum.values.push(i),[]})}}class zn{constructor(e,n){this.declarationNode=e,this.env=n,this.project={enums:[],refs:[],tableGroups:[],tables:[]}}interpret(){return this.env.project.set(this.declarationNode,this.project),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(e){if(!e)return this.project.name=null,[];const{name:n}=Ae(e);return this.project.name=n,[]}interpretBody(e){return e.body.flatMap(n=>{var i;const s=n;switch((i=s.type)==null?void 0:i.value.toLowerCase()){case"table":{const r=new Rt(s,this.env).interpret();return this.project.tables.push(this.env.tables.get(s)),r}case"ref":{const r=new Dt(s,this.env).interpret();return this.project.refs.push(this.env.ref.get(s)),r}case"tablegroup":{const r=new Pt(s,this.env).interpret();return this.project.tableGroups.push(this.env.tableGroups.get(s)),r}case"enum":{const r=new Ut(s,this.env).interpret();return this.project.enums.push(this.env.enums.get(s)),r}case"note":return this.project.note={value:Y(s.body instanceof te?s.body.body[0].callee:s.body.callee).unwrap(),token:x(s)},[];default:return this.project[s.type.value.toLowerCase()]=Y(s.body.callee).unwrap(),[]}})}}class qn{constructor(e){this.ast=e,this.env={schema:[],tables:new Map,refIds:{},ref:new Map,enums:new Map,tableGroups:new Map,groupOfTable:{},aliases:[],project:new Map}}interpret(){const e=this.ast.body.flatMap(n=>{switch(ge(n).unwrap_or(void 0)){case b.Table:return new Rt(n,this.env).interpret();case b.Ref:return new Dt(n,this.env).interpret();case b.TableGroup:return new Pt(n,this.env).interpret();case b.Enum:return new Ut(n,this.env).interpret();case b.Project:return new zn(n,this.env).interpret();default:return[]}});return new F(Qn(this.env),e)}}function Qn(t){return{schemas:[],tables:Array.from(t.tables.values()),refs:Array.from(t.ref.values()),enums:Array.from(t.enums.values()),tableGroups:Array.from(t.tableGroups.values()),aliases:t.aliases,project:Array.from(t.project.values())[0]||{}}}var L=(t=>(t[t.Function=1]="Function",t[t.Constructor=2]="Constructor",t[t.Field=3]="Field",t[t.Variable=4]="Variable",t[t.Class=5]="Class",t[t.Struct=6]="Struct",t[t.Interface=7]="Interface",t[t.Module=8]="Module",t[t.Property=9]="Property",t[t.Event=10]="Event",t[t.Operator=11]="Operator",t[t.Unit=12]="Unit",t[t.Value=13]="Value",t[t.Constant=14]="Constant",t[t.Enum=15]="Enum",t[t.EnumMember=16]="EnumMember",t[t.Keyword=17]="Keyword",t[t.Text=18]="Text",t[t.Color=19]="Color",t[t.File=20]="File",t[t.Reference=21]="Reference",t[t.Customcolor=22]="Customcolor",t[t.Folder=23]="Folder",t[t.TypeParameter=24]="TypeParameter",t[t.User=25]="User",t[t.Issue=26]="Issue",t[t.Snippet=27]="Snippet",t))(L||{}),w=(t=>(t[t.None=0]="None",t[t.KeepWhitespace=1]="KeepWhitespace",t[t.InsertAsSnippet=4]="InsertAsSnippet",t))(w||{});function Le(t){switch(t){case m.Schema:return L.Module;case m.Table:return L.Class;case m.Column:return L.Field;case m.Enum:return L.Enum;case m.EnumField:return L.EnumMember;case m.TableGroup:return L.Struct;case m.TableGroupField:return L.Field;default:return L.Text}}function Oe(t,e){if(!t||Ve(t))return!1;for(const n of t.trailingTrivia){if(n.start>e)break;if(n.kind===c.NEWLINE&&n.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 Ue(t){return{...t,suggestions:t.suggestions.map(e=>({...e,insertText:e.insertText.search(/[^a-zA-Z\d_]/)!==-1||e.insertText[0].match(/\d/)?`"${e.insertText}"`:e.insertText}))}}function Ke(t,e){return t.getOffsetAt(e)}class Mt{constructor(e,n=[]){this.compiler=e,this.triggerCharacters=n}provideCompletionItems(e,n){var T,f;const s=Ke(e,n),i=this.compiler.token.flatStream(),{token:r,index:a}=this.compiler.container.token(s),l=a===void 0?i[0]:i[a+1];if([...(r==null?void 0:r.trailingTrivia)||[],...(r==null?void 0:r.leadingTrivia)||[],...(l==null?void 0:l.leadingTrivia)||[]].find(N=>$t(N)&&be(s,N)))return S();if(a===void 0)return mt();if([c.STRING_LITERAL,c.QUOTED_STRING].includes(r.kind)&&be(s,r))return S();const p=this.compiler.container.element(s);if(this.compiler.container.scopeKind(s)===R.TOPLEVEL||p instanceof _&&p.type&&p.type.start<=s&&p.type.end>=s)return mt();const h=[...this.compiler.container.stack(s)].reverse();for(const N of h)if(N instanceof q)switch((T=N.op)==null?void 0:T.value){case">":case"<":case"<>":case"-":return pt(this.compiler,s,N)}else if(N instanceof Q)switch((f=N.op)==null?void 0:f.value){case">":case"<":case"<>":case"-":return pt(this.compiler,s,N);case".":return Ft(this.compiler,s,N)}else{if(N instanceof ne)return dt(this.compiler,s,N);if(N instanceof P)return dt(this.compiler,s,N);if(N instanceof J)return Hn(this.compiler,s);if(N instanceof k)return Nt(this.compiler,s,N);if(N instanceof _&&(N.bodyColon&&s>=N.bodyColon.end||N.body&&be(s,N.body)))return Nt(this.compiler,s,void 0)}return S()}}function pt(t,e,n){const s=t.container.scopeKind(e);if([R.REF,R.TABLE].includes(s)){const i=Me(t,e,t.container.element(e),[m.Table,m.Schema,m.Column]);return Oe(n.op,e)?Se(i):i}return S()}function Me(t,e,n,s){var a;if(n===void 0)return S();let i=n;const r={suggestions:[]};for(;i;){if((a=i==null?void 0:i.symbol)!=null&&a.symbolTable){const{symbol:l}=i;r.suggestions.push(...t.symbol.members(l).filter(({kind:p})=>s.includes(p)).map(({name:p,kind:h})=>({label:p,insertText:p,insertTextRules:w.KeepWhitespace,kind:Le(h),sortText:Le(h).toString().padStart(2,"0"),range:void 0})))}i=i instanceof _?i.parent:void 0}return Ue(r)}function Hn(t,e){var s;switch(t.container.scopeKind(e)){case R.INDEXES:return Vt(t,e);case R.REF:{const i=[...t.container.stack(e)];for(;i.length>0;){const r=i.pop();if(r instanceof Q&&((s=r.op)==null?void 0:s.value)===".")return Ft(t,e,r)}}return Bt(t,e)}return S()}function dt(t,e,n){const{token:s}=t.container.token(e);if([c.COMMA,c.LBRACKET].includes(s==null?void 0:s.kind)){const i=Et(t,e);return(s==null?void 0:s.kind)===c.COMMA&&Oe(s,e)?Se(i):i}if(n.name&&n.name.start<=e&&n.name.end>=e)return Et(t,e);if(n.name instanceof K){const i=Jn(t,e,De(n.name).unwrap());return(s==null?void 0:s.kind)===c.COLON&&Oe(s,e)?Se(i):i}return S()}function Et(t,e){const n=t.container.element(e),s=t.container.scopeKind(e);if(n instanceof C)return S();if(n.body&&!be(e,n.body))switch(s){case R.TABLE:return{suggestions:[{label:"headercolor",insertText:"headercolor: ",kind:L.Field,insertTextRules:w.KeepWhitespace,range:void 0},{label:"note",insertText:"note: ",kind:L.Field,insertTextRules:w.KeepWhitespace,range:void 0}]};default:return S()}switch(s){case R.TABLE:return{suggestions:[...["primary key","null","not null","increment","pk","unique"].map(i=>({label:i,insertText:i,kind:L.Property,insertTextRules:w.KeepWhitespace,range:void 0})),...["ref","default"].map(i=>({label:i,insertText:`${i}: `,kind:L.Property,insertTextRules:w.KeepWhitespace,range:void 0})),{label:"note",insertText:"note: ",kind:L.Property,insertTextRules:w.KeepWhitespace,range:void 0}]};case R.ENUM:return{suggestions:[{label:"note",insertText:"note: ",kind:L.Property,insertTextRules:w.KeepWhitespace,range:void 0}]};case R.INDEXES:return{suggestions:[...["unique","pk"].map(i=>({label:i,insertText:i,insertTextRules:w.KeepWhitespace,kind:L.Property,range:void 0})),...["note","name","type"].map(i=>({label:i,insertText:`${i}: `,kind:L.Property,insertTextRules:w.KeepWhitespace,range:void 0}))]};case R.REF:return{suggestions:["update","delete"].map(i=>({label:i,insertText:`${i}: `,kind:L.Property,insertTextRules:w.KeepWhitespace,range:void 0}))}}return S()}function Jn(t,e,n){switch(n==null?void 0:n.toLowerCase()){case"update":case"delete":return{suggestions:["cascade","set default","set null","restrict"].map(s=>({label:s,insertText:s,kind:L.Value,insertTextRules:w.KeepWhitespace,range:void 0}))};case"type":return{suggestions:["btree","hash"].map(s=>({label:s,insertText:`${s}`,kind:L.Value,insertTextRules:w.KeepWhitespace,range:void 0}))}}return S()}function Ft(t,e,n){const s=ue(n).unwrap_or([]);if(s.pop(),s.some(r=>!M(r)))return S();const i=s.map(r=>G(r).unwrap());return Ue({suggestions:t.symbol.ofName({nameStack:i,owner:t.container.element(e)}).flatMap(({symbol:r})=>t.symbol.members(r)).map(({kind:r,name:a})=>({label:a,insertText:a,kind:Le(r),range:void 0}))})}function Nt(t,e,n){var i;switch(t.container.scopeKind(e)){case R.TABLE:return Kn(t,e,n);case R.PROJECT:return es(t,e,n);case R.INDEXES:return ns(t,e);case R.ENUM:return Zn(t,e,n);case R.REF:{const r=Bt(t,e);return((i=t.container.token(e).token)==null?void 0:i.kind)===c.COLON&&Oe(t.container.token(e).token,e)?Se(r):r}case R.TABLEGROUP:return ts(t);default:return S()}}function mt(){return{suggestions:["Table","TableGroup","Enum","Project","Ref"].map(t=>({label:t,insertText:t,insertTextRules:w.KeepWhitespace,kind:L.Keyword,range:void 0}))}}function Zn(t,e,n){return n!=null&&n.callee&&et(e,n)===1?Me(t,e,t.container.element(e),[m.Schema,m.Table,m.Column]):S()}function Kn(t,e,n){if(!(n!=null&&n.callee))return{suggestions:["Note","indexes"].map(i=>({label:i,insertText:i,insertTextRules:w.KeepWhitespace,kind:L.Keyword,range:void 0}))};const s=et(e,n);return s===0?{suggestions:["Note","indexes"].map(i=>({label:i,insertText:i,insertTextRules:w.KeepWhitespace,kind:L.Keyword,range:void 0}))}:s===1?ss(t,e):S()}function es(t,e,n){return n!=null&&n.callee?et(e,n)===0?{suggestions:["Table","TableGroup","Enum","Note","Ref"].map(i=>({label:i,insertText:i,insertTextRules:w.KeepWhitespace,kind:L.Keyword,range:void 0}))}:S():{suggestions:["Table","TableGroup","Enum","Note","Ref"].map(i=>({label:i,insertText:i,insertTextRules:w.KeepWhitespace,kind:L.Keyword,range:void 0}))}}function Bt(t,e){return Me(t,e,t.container.element(e),[m.Schema,m.Table,m.Column])}function ts(t){return Ue({suggestions:[...t.parse.publicSymbolTable().entries()].flatMap(([e])=>{const n=se(e).unwrap_or(void 0);if(n===void 0)return[];const{kind:s,name:i}=n;return s!==m.Table&&s!==m.Schema?[]:{label:i,insertText:i,insertTextRules:w.KeepWhitespace,kind:Le(s),range:void 0}})})}function ns(t,e){return Vt(t,e)}function ss(t,e){return{suggestions:[...["integer","int","tinyint","smallint","mediumint","bigint","bit","bool","binary","varbinary","logical","char","nchar","varchar","varchar2","nvarchar","nvarchar2","binary_float","binary_double","float","double","decimal","dec","real","money","smallmoney","enum","tinyblob","tinytext","blob","text","mediumblob","mediumtext","longblob","longtext","ntext","set","inet6","uuid","image","date","time","datetime","datetime2","timestamp","year","smalldatetime","datetimeoffset","XML","sql_variant","uniqueidentifier","CURSOR","BFILE","CLOB","NCLOB","RAW"].map(n=>({label:n,insertText:n,insertTextRules:w.KeepWhitespace,kind:L.TypeParameter,sortText:L.TypeParameter.toString().padStart(2,"0"),range:void 0})),...Me(t,e,t.container.element(e),[m.Enum,m.Schema]).suggestions]}}function Vt(t,e){const n=t.container.element(e),s=n==null?void 0:n.parent;if(!((s==null?void 0:s.symbol)instanceof _t))return S();const{symbolTable:i}=s.symbol;return Ue({suggestions:[...i.entries()].flatMap(([r])=>{const a=se(r).unwrap_or(void 0);if(a===void 0)return[];const{name:l}=a;return{label:l,insertText:l,insertTextRules:w.KeepWhitespace,kind:Le(m.Column),range:void 0}})})}function et(t,e){if(!e.callee)return-1;const n=[e.callee,...e.args],s=n.findIndex(i=>t<=i.end);return s===-1?n.length:s}class Gt{constructor(e){this.compiler=e}provideDefinition(e,n){var a;const{uri:s}=e,i=Ke(e,n),r=[...this.compiler.container.stack(i)];for(;r.length!==0;){const l=r.pop();if((a=l==null?void 0:l.referee)!=null&&a.declaration&&[pe.PRIMARY_EXPRESSION,pe.VARIABLE].includes(l==null?void 0:l.kind)){const{startPos:p,endPos:h}=l.referee.declaration;return[{range:{startColumn:p.column+1,startLineNumber:p.line+1,endColumn:h.column+1,endLineNumber:h.line+1},uri:s}]}}return[]}}class Ct{constructor(e){this.compiler=e}provideReferences(e,n){const{uri:s}=e,i=Ke(e,n),r=[...this.compiler.container.stack(i)];for(;r.length!==0;){const a=r.pop();if(a&&[pe.ELEMENT_DECLARATION,pe.FUNCTION_APPLICATION,pe.PRIMARY_EXPRESSION].includes(a==null?void 0:a.kind)){const{symbol:l}=a;if(l!=null&&l.references.length)return l.references.map(({startPos:p,endPos:h})=>({range:{startColumn:p.column+1,startLineNumber:p.line+1,endColumn:h.column+1,endLineNumber:h.line+1},uri:s}))}}return[]}}const is=Object.freeze(Object.defineProperty({__proto__:null,CompletionItemInsertTextRule:w,CompletionItemKind:L,DBMLCompletionItemProvider:Mt,DBMLDefinitionProvider:Gt,DBMLReferencesProvider:Ct},Symbol.toStringTag,{value:"Module"}));var R=(t=>(t[t.TABLE=0]="TABLE",t[t.ENUM=1]="ENUM",t[t.TABLEGROUP=2]="TABLEGROUP",t[t.INDEXES=3]="INDEXES",t[t.NOTE=4]="NOTE",t[t.REF=5]="REF",t[t.PROJECT=6]="PROJECT",t[t.CUSTOM=7]="CUSTOM",t[t.TOPLEVEL=8]="TOPLEVEL",t))(R||{});class rs{constructor(){this.source="",this.cache=new Array(16).fill(null),this.nodeIdGenerator=new Wt,this.symbolIdGenerator=new Qt,this.token={invalidStream:this.createQuery(6,()=>this.parse.tokens().filter(At)),flatStream:this.createQuery(7,()=>this.parse.tokens().flatMap(e=>[...e.leadingInvalid,e,...e.trailingInvalid]))},this.parse={source:()=>this.source,_:this.createQuery(0,()=>{const e=new an(this.source).lex().chain(n=>new cn(n,this.nodeIdGenerator).parse()).chain(({ast:n,tokens:s})=>new $n(n,this.symbolIdGenerator).analyze().map(()=>({ast:n,tokens:s})));return e.getErrors().length>0?e:e.chain(({ast:n,tokens:s})=>new qn(n).interpret().map(r=>({ast:n,tokens:s,rawDb:r})))}),ast:this.createQuery(1,()=>this.parse._().getValue().ast),errors:this.createQuery(2,()=>this.parse._().getErrors()),tokens:this.createQuery(4,()=>this.parse._().getValue().tokens),rawDb:this.createQuery(3,()=>this.parse._().getValue().rawDb),publicSymbolTable:this.createQuery(5,()=>this.parse._().getValue().ast.symbol.symbolTable)},this.container={stack:this.createQuery(10,e=>{const n=this.parse.tokens();let{index:s}=this.container.token(e);const{token:i}=this.container.token(e);if(s===void 0)return[this.parse.ast()];for(;n[s].isInvalid&&s>=0;)s-=1;if(s===-1)return[this.parse.ast()];const r=n[s].start;let a=this.parse.ast();const l=[a];for(;;){const h=rn(a).find(T=>be(r,T));if(h===void 0||h instanceof B)break;l.push(h),a=h}if((i==null?void 0:i.kind)===c.COLON)return l;for(;l.length>0;){let p=!1;const h=I.last(l);if(h instanceof k){const T=this.parse.source();for(let f=h.end;f<e;f+=1)T[f]===`
7
+ `;case"\\":return"\\";case"r":return"\r";case"'":return"'";case'"':return'"';case"0":return"\0";case"b":return"\b";case"v":return"\v";case"f":return"\f";case"u":{let e="";for(let n=0;n<=3;n+=1){if(this.isAtEnd()||!fe(this.peek()))return`\\u${e}`;e+=this.advance()}return String.fromCharCode(parseInt(e,16))}default:return`\\${this.tokens[this.current.offset-1]}`}}}var ye=(t=>(t[t.ListExpression=0]="ListExpression",t[t.GroupExpression=1]="GroupExpression",t[t.BlockExpression=2]="BlockExpression",t))(ye||{});class on{constructor(){this.stack=[],this.numberOfNestedLParens=0,this.numberOfNestedLBrackets=0,this.numberOfNestedLBraces=0}push(e){this.stack.push(e),e===0&&(this.numberOfNestedLBrackets+=1),e===1&&(this.numberOfNestedLParens+=1),e===2&&(this.numberOfNestedLBraces+=1)}pop(){const e=this.stack.pop();return e===0&&(this.numberOfNestedLBrackets-=1),e===1&&(this.numberOfNestedLParens-=1),e===2&&(this.numberOfNestedLBraces-=1),e}top(){return I.last(this.stack)}isWithinGroupExpressionContext(){return this.numberOfNestedLParens>0}isWithinListExpressionContext(){return this.numberOfNestedLBrackets>0}isWithinBlockExpressionContext(){return this.numberOfNestedLBraces>0}withContextDo(e,n){return()=>{this.push(e);try{return n()}finally{this.pop()}}}findHandlerContext(e,n){if(!(this.numberOfNestedLBraces<=0&&this.numberOfNestedLBrackets<=0&&this.numberOfNestedLParens<=0))for(let s=n;s<e.length-1;s+=1)switch(e[s].kind){case 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,n){return new e(n,this.generator.nextId())}}class d{constructor(e,n,s){this.token=e,this.partialNode=n,this.handlerContext=s}}class cn{constructor(e,n){this.current=0,this.errors=[],this.contextStack=new on,this.synchronizeProgram=()=>{const s=this.peek();s.kind!==c.EOF?E(this.advance()):(E(this.peek()),this.logError(s,o.UNEXPECTED_EOF,"Unexpected EOF"))},this.synchronizeElementDeclarationName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(lt(s)||this.check(c.COLON,c.LBRACE,c.LBRACKET))break;E(s),this.advance()}},this.synchronizeElementDeclarationAlias=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(c.COLON,c.LBRACE,c.LBRACKET))break;E(s),this.advance()}},this.blockExpression=this.contextStack.withContextDo(ye.BlockExpression,()=>{const s={body:[]},i=()=>this.nodeFactory.create(te,s);try{this.consume("Expect an opening brace '{'",c.LBRACE),s.blockOpenBrace=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.blockOpenBrace=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}for(;!this.isAtEnd()&&!this.check(c.RBRACE);)try{s.body.push(this.canBeField()?this.fieldDeclaration():this.expression())}catch(r){if(!(r instanceof d))throw r;if(s.body.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}try{this.consume("Expect a closing brace '}'",c.RBRACE),s.blockCloseBrace=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.blockCloseBrace=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}return i()}),this.synchronizeBlock=()=>{if(!this.check(c.RBRACE))for(E(this.advance());!this.isAtEnd();){const s=this.peek();if(this.check(c.RBRACE)||at(this.previous(),s))break;E(s),this.advance()}},this.tupleExpression=this.contextStack.withContextDo(ye.GroupExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(Xe,{groupOpenParen:s.tupleOpenParen,groupCloseParen:s.tupleCloseParen,expression:s.elementList[0]}),r=()=>this.nodeFactory.create(J,s);try{this.consume("Expect an opening parenthesis '('",c.LPAREN),s.tupleOpenParen=this.previous()}catch(a){if(!(a instanceof d))throw a;if(s.tupleOpenParen=a.partialNode,!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}if(!this.isAtEnd()&&!this.check(c.RPAREN))try{s.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof d))throw a;if(s.elementList.push(a.partialNode),!this.canHandle(a))throw new d(a.token,i(),a.handlerContext);this.synchronizeTuple()}for(;!this.isAtEnd()&&!this.check(c.RPAREN);)try{this.consume("Expect a comma ','",c.COMMA),s.commaList.push(this.previous()),s.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof d))throw a;if(a.partialNode instanceof y&&s.elementList.push(a.partialNode),!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}try{this.consume("Expect a closing parenthesis ')'",c.RPAREN),s.tupleCloseParen=this.previous()}catch(a){if(!(a instanceof d))throw a;if(s.tupleCloseParen=a.partialNode,!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}return s.elementList.length===1?i():r()}),this.synchronizeTuple=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(c.RPAREN,c.COMMA))break;E(s),this.advance()}},this.listExpression=this.contextStack.withContextDo(ye.ListExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(P,s);try{this.consume("Expect an opening bracket '['",c.LBRACKET),s.listOpenBracket=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.listOpenBracket=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}if(!this.isAtEnd()&&!this.check(c.RBRACKET))try{s.elementList.push(this.attribute())}catch(r){if(!(r instanceof d))throw r;if(s.elementList.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}for(;!this.isAtEnd()&&!this.check(c.RBRACKET);)try{this.consume("Expect a comma ','",c.COMMA),s.commaList.push(this.previous()),s.elementList.push(this.attribute())}catch(r){if(!(r instanceof d))throw r;if(r.partialNode instanceof y&&s.elementList.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}try{this.consume("Expect a closing bracket ']'",c.RBRACKET),s.listCloseBracket=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.listCloseBracket=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}return i()}),this.synchronizeList=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(c.COMMA,c.RBRACKET))break;E(s),this.advance()}},this.synchronizeAttributeName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(c.COMMA,c.RBRACKET,c.COLON))break;E(s),this.advance()}},this.synchronizeAttributeValue=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(c.COMMA,c.RBRACKET))break;E(s),this.advance()}},this.tokens=e,this.nodeFactory=new ln(n)}isAtEnd(){return this.current>=this.tokens.length||this.tokens[this.current].kind===c.EOF}advance(){return this.isAtEnd()?I.last(this.tokens):this.tokens[this.current++]}peek(e=0){return e+this.current>=this.tokens.length?I.last(this.tokens):this.tokens[this.current+e]}match(...e){const n=this.check(...e);return n&&this.advance(),n}check(...e){const n=this.peek();return e.includes(n.kind)}previous(){return this.tokens[this.current-1]}canHandle(e){return e.handlerContext===void 0||e.handlerContext===this.contextStack.top()}consume(e,...n){if(!this.match(...n))throw this.logError(this.peek(),o.UNEXPECTED_TOKEN,e),new d(this.peek(),void 0,this.contextStack.findHandlerContext(this.tokens,this.current))}discardUntil(e,...n){if(this.isAtEnd()||!this.check(...n)){for(E(this.peek()),this.logError(this.advance(),o.UNEXPECTED_TOKEN,e);!this.isAtEnd()&&!this.check(...n);)E(this.advance());return!this.isAtEnd()}return!0}gatherInvalid(){const e=[],n=[];let s,i=0;for(;i<this.tokens.length&&this.tokens[i].isInvalid;i+=1)n.push(this.tokens[i]);for(s=this.tokens[i],s.leadingInvalid=n,e.push(s),i+=1;i<this.tokens.length;i+=1){const r=this.tokens[i];r.isInvalid?s.trailingInvalid.push(r):(s=r,e.push(s))}this.tokens=e}parse(){const e=this.program(),n=this.advance(),s=this.nodeFactory.create(C,{body:e,eof:n});return this.gatherInvalid(),new F({ast:s,tokens:this.tokens},this.errors)}program(){const e=[];for(;!this.isAtEnd();)try{const n=this.elementDeclaration();e.push(n)}catch(n){if(!(n instanceof d))throw n;e.push(n.partialNode),this.synchronizeProgram()}return e}elementDeclaration(){const e={},n=()=>this.nodeFactory.create(_,e);try{this.consume("Expect an identifier",c.IDENTIFIER),e.type=this.previous()}catch(s){throw s instanceof d?(e.type=s.partialNode,new d(s.token,n(),s.handlerContext)):s}if(!this.check(c.COLON,c.LBRACE,c.LBRACKET))try{e.name=this.normalExpression()}catch(s){if(!(s instanceof d))throw s;if(e.name=s.partialNode,!this.canHandle(s))throw new d(s.token,n(),s.handlerContext);this.synchronizeElementDeclarationName()}if(lt(this.peek()))if(e.as=this.advance(),this.check(c.COLON,c.LBRACE,c.LBRACKET))this.logError(this.peek(),o.UNEXPECTED_TOKEN,"Expect an alias");else try{e.alias=this.normalExpression()}catch(s){if(!(s instanceof d))throw s;if(e.alias=s.partialNode,!this.canHandle(s))throw new d(s.token,n(),s.handlerContext);this.synchronizeElementDeclarationAlias()}try{e.attributeList=this.check(c.LBRACKET)?this.listExpression():void 0}catch(s){throw s instanceof d?(e.attributeList=s.partialNode,new d(s.token,n(),s.handlerContext)):s}if(!this.discardUntil("Expect an opening brace '{' or a colon ':'",c.LBRACE,c.COLON))return n();try{if(this.match(c.COLON)){e.bodyColon=this.previous();const s=this.expression();s instanceof _?(E(s),this.logError(s,o.UNEXPECTED_ELEMENT_DECLARATION,"An element's simple body must not be an element declaration")):e.body=s}else e.body=this.blockExpression()}catch(s){throw s instanceof d?(e.body=s.partialNode,new d(s.token,n(),s.handlerContext)):s}return this.nodeFactory.create(_,e)}fieldDeclaration(){const e={},n=()=>this.nodeFactory.create(_,e);try{this.consume("Expect an identifier",c.IDENTIFIER),e.type=this.previous()}catch(s){throw s instanceof d?(e.type=s.partialNode,new d(s.token,n(),s.handlerContext)):s}try{this.consume("Expect a colon ':'",c.COLON),e.bodyColon=this.previous()}catch(s){throw s instanceof d?(e.bodyColon=s.partialNode,new d(s.token,n(),s.handlerContext)):s}try{const s=this.expression();s instanceof _?this.errors.push(new u(o.INVALID_ELEMENT_IN_SIMPLE_BODY,"Simple body cannot be an element declaration",s)):e.body=s}catch(s){throw s instanceof d?(e.body=s.partialNode,new d(s.token,n(),s.handlerContext)):s}return this.nodeFactory.create(_,e)}expression(){const e={args:[]},n=()=>tn(e.callee,e.args,this.nodeFactory).unwrap_or(this.nodeFactory.create(k,e));try{e.callee=this.normalExpression()}catch(i){throw i instanceof d?(e.callee=i.partialNode,new d(i.token,n(),i.handlerContext)):i}if(this.shouldStopExpression())return n();let s=e.callee;for(;!this.shouldStopExpression();){Ve(this.previous())||this.logError(s,o.MISSING_SPACES,"Expect a following space");try{s=this.normalExpression(),e.args.push(s)}catch(i){throw i instanceof d?(s=i.partialNode,e.args.push(s),new d(i.token,n(),i.handlerContext)):i}}return n()}shouldStopExpression(){if(this.isAtEnd()||Tt(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 n=this.leftExpression_bp();for(;!this.isAtEnd();){const s=this.peek();if(s.kind===c.LPAREN){const{left:i}=ct(s);if(i<e||at(this.previous(),s)&&!this.contextStack.isWithinGroupExpressionContext()&&!this.contextStack.isWithinListExpressionContext())break;try{n=this.nodeFactory.create(H,{callee:n,argumentList:this.tupleExpression()})}catch(r){throw r instanceof d?(n=this.nodeFactory.create(H,{callee:n,argumentList:r.partialNode}),new d(r.token,n,r.handlerContext)):r}}else if(s.kind===c.LBRACKET){if(Ve(this.previous()))break;try{n=this.nodeFactory.create(le,{expression:n,indexer:this.listExpression()})}catch(i){throw i instanceof d?(n=this.nodeFactory.create(le,{expression:n,indexer:i.partialNode}),new d(i.token,n,i.handlerContext)):i}}else if(rt(s)){const i=s,r=ct(i);if(r.left!==null){if(r.left<=e)break;this.advance(),n=this.nodeFactory.create(Re,{expression:n,op:i})}else{const a=hn(i);if(a.left===null||a.left<=e)break;this.advance();try{n=this.nodeFactory.create(Q,{leftExpression:n,op:i,rightExpression:i.value==="."?this.extractOperand():this.expression_bp(a.right)})}catch(l){throw l instanceof d?(n=this.nodeFactory.create(Q,{leftExpression:n,op:i,rightExpression:l.partialNode}),new d(l.token,n,l.handlerContext)):l}}}else break}return n}leftExpression_bp(){let e;if(rt(this.peek())){const n={};n.op=this.peek();const s=pn(n.op);if(s.right===null)throw this.logError(n.op,o.UNKNOWN_PREFIX_OP,`Unexpected '${n.op.value}' in an expression`),new d(n.op,this.nodeFactory.create(we,{pre:n.op}),this.contextStack.findHandlerContext(this.tokens,this.current));this.advance();try{n.expression=this.expression_bp(s.right)}catch(i){throw i instanceof d?(n.expression=i.partialNode,new d(i.token,this.nodeFactory.create(q,n),i.handlerContext)):i}e=this.nodeFactory.create(q,n)}else if(e=this.extractOperand(),e instanceof we)throw new d(this.peek(),this.nodeFactory.create(we,{pre:this.peek()}),this.contextStack.findHandlerContext(this.tokens,this.current));return e}extractOperand(){return this.check(c.NUMERIC_LITERAL,c.STRING_LITERAL,c.COLOR_LITERAL,c.QUOTED_STRING,c.IDENTIFIER)?this.primaryExpression():this.check(c.FUNCTION_EXPRESSION)?this.functionExpression():this.check(c.LBRACKET)?this.listExpression():this.check(c.LBRACE)?this.blockExpression():this.check(c.LPAREN)?this.tupleExpression():(this.peek().kind===c.EOF?this.logError(this.peek(),o.UNEXPECTED_EOF,"Unexpected EOF"):this.logError(this.peek(),o.INVALID_OPERAND,`Invalid start of operand "${this.peek().value}"`),this.nodeFactory.create(we,{pre:this.previous()}))}functionExpression(){const e={};try{this.consume("Expect a function expression",c.FUNCTION_EXPRESSION),e.value=this.previous()}catch(n){throw n instanceof d?(e.value=n.partialNode,new d(n.token,this.nodeFactory.create(ee,e),n.handlerContext)):n}return this.nodeFactory.create(ee,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(Ee,{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 n=this.peek();this.logError(n,o.EMPTY_ATTRIBUTE_NAME,"Expect a non-empty attribute name"),e.name=this.nodeFactory.create(K,{identifiers:[]})}else try{e.name=this.attributeName()}catch(n){if(!(n instanceof d))throw n;if(e.name=n.partialNode,!this.canHandle(n))throw new d(n.token,this.nodeFactory.create(ne,e),n.handlerContext);this.synchronizeAttributeName()}return this.match(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(n){if(!(n instanceof d)||!this.canHandle(n))throw n;e=n.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(n){throw n instanceof d?new d(n.token,this.nodeFactory.create(K,{identifiers:e}),n.handlerContext):n}return this.nodeFactory.create(K,{identifiers:e})}logError(e,n,s){this.errors.push(new u(n,s,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 ct(t){return dn[t.value]||{left:null,right:null}}var b=(t=>(t.Table="table",t.Enum="enum",t.Ref="ref",t.Note="note",t.Project="project",t.Indexes="indexes",t.TableGroup="tablegroup",t))(b||{});function ge(t){var n;const e=(n=t==null?void 0:t.type)==null?void 0:n.value.toLowerCase();switch(e){case b.Enum:case b.Table:case b.Indexes:case b.Note:case b.Project:case b.Ref:case b.TableGroup:return new O(e);default:return new A}}function ue(t){if(!He(t))return new O([t]);const e=ue(t.leftExpression).unwrap_or(void 0);return e?(e.push(t.rightExpression),new O(e)):new A}function W(t){if(t===void 0)return new A;const e=ue(t).unwrap_or(void 0);if(!e)return new A;const n=[];for(const s of e){const i=G(s).unwrap_or(void 0);if(!i)return new A;n.push(i)}return new O(n)}function Ie(t){if(t===void 0)return new A;const e=ue(t).unwrap_or(void 0);if(!e||e.length===0)return new A;const n=[];let s;if(!M(I.last(e))){const i=e.pop();if(yt(i))s=i.elementList.map(r=>V(r).unwrap());else return new A}for(const i of e){const r=G(i).unwrap_or(void 0);if(!r)return new A;n.push(r)}return new O({variables:n,tupleElements:s})}function G(t){return M(t)?new O(t.expression.variable.value):new A}function Ge(t){if(ut(t))return t instanceof ee?new O({functional:[t],nonFunctional:[]}):new O({functional:[],nonFunctional:[t]});if(t instanceof J&&t.elementList.every(ut)){const e=t.elementList.filter(s=>s instanceof ee),n=t.elementList.filter(M);return new O({functional:e,nonFunctional:n})}return new A}function V(t){var n;const e=(n=t==null?void 0:t.expression.variable)==null?void 0:n.value;return e===void 0?new A:new O(e)}function Y(t){return $(t)?t.expression instanceof X?new O(t.expression.variable.value):new O(t.expression.literal.value):new A}function En(t){var e;return!(t instanceof Q)||!wt((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),n=Ie(t.rightExpression);if(!e.isOk()||!n.isOk())return!1;const{tupleElements:s}=e.unwrap(),{tupleElements:i}=n.unwrap();return(s==null?void 0:s.length)===(i==null?void 0:i.length)}function ut(t){return t instanceof D&&t.expression instanceof X||t instanceof ee}function mn(t,e){var i,r,a,l;let n=e;const s=Yt(t);for(;n;){if((r=(i=n.symbol)==null?void 0:i.symbolTable)!=null&&r.has(t))return(a=n.symbol.symbolTable)==null?void 0:a.get(t);if(((l=n.symbol)==null?void 0:l.declaration)instanceof C&&s)return n.symbol;if(n instanceof C)return;n=n.parent}}class Tn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof C||ge(this.declarationNode.parent).unwrap_or(void 0)!==b.Project?[new u(o.INVALID_CUSTOM_CONTEXT,"A custom element can only appear in a Project",this.declarationNode)]:[]}validateName(e){return e?[new u(o.UNEXPECTED_NAME,"A Custom element shouldn't have a name",e)]:[]}validateAlias(e){return e?[new u(o.UNEXPECTED_NAME,"A Custom element shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new u(o.UNEXPECTED_SETTINGS,"A Custom element shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof te)return[new u(o.UNEXPECTED_COMPLEX_BODY,"A Custom element can only have an inline field",e)];const n=[];return $(e.callee)||n.push(new u(o.INVALID_CUSTOM_ELEMENT_VALUE,"A Custom element value can only be a string",e)),e.args.length>0&&n.push(...e.args.map(s=>new u(o.INVALID_CUSTOM_ELEMENT_VALUE,"A Custom element value can only be a string",s))),n}}class _e{constructor(){this.table=new Map}has(e){return this.table.has(e)}set(e,n){this.table.set(e,n)}get(e,n){return this.table.get(e)||n!==void 0&&this.set(e,n)||n}entries(){return this.table.entries()}}class bn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof _?[new u(o.INVALID_PROJECT_CONTEXT,"An Enum can only appear top-level",this.declarationNode)]:[]}validateName(e){return e?Je(e)?[]:[new u(o.INVALID_NAME,"An Enum name must be of the form <enum> or <schema>.<enum>",e)]:[new u(o.NAME_NOT_FOUND,"An Enum must have a name",this.declarationNode)]}validateAlias(e){return e?[new u(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}registerElement(){const e=[];this.declarationNode.symbol=this.symbolFactory.create(Ht,{declaration:this.declarationNode,symbolTable:new _e});const{name:n}=this.declarationNode,s=W(n);if(s.isOk()){const i=s.unwrap(),r=i.pop(),a=Ze(i,this.publicSymbolTable,this.symbolFactory),l=je(r);a.has(l)&&e.push(new u(o.DUPLICATE_NAME,`Enum name ${r} already exists in schema '${i.join(".")||"public"}'`,n)),a.set(l,this.declarationNode.symbol)}return e}validateSettingList(e){return e?[new u(o.UNEXPECTED_SETTINGS,"An Enum shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof k)return this.validateFields([e]);const[n,s]=I.partition(e.body,i=>i instanceof k);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.length===0?[new u(o.EMPTY_ENUM,"An Enum must have at least one element",this.declarationNode)]:e.flatMap(n=>{const s=[];n.callee&&!M(n.callee)&&s.push(new u(o.INVALID_ENUM_ELEMENT_NAME,"An enum field must be an identifier or a quoted identifier",n.callee));const i=[...n.args];return I.last(i)instanceof P?(s.push(...this.validateFieldSettings(I.last(i))),i.pop()):i[0]instanceof P&&(s.push(...this.validateFieldSettings(i[0])),i.shift()),i.length>0&&s.push(...i.map(r=>new u(o.INVALID_ENUM_ELEMENT,"An Enum must have only a field and optionally a setting list",r))),s.push(...this.registerField(n)),s})}validateFieldSettings(e){const n=z(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"note":a.length>1&&a.forEach(l=>s.push(new u(o.DUPLICATE_ENUM_ELEMENT_SETTING,"'note' can only appear once",l))),a.forEach(l=>{$(l.value)||s.push(new u(o.INVALID_ENUM_ELEMENT_SETTING,"'note' must be a string",l))});break;default:a.forEach(l=>s.push(new u(o.UNKNOWN_ENUM_ELEMENT_SETTING,`Unknown enum field setting '${r}'`,l)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ie(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}registerField(e){if(e.callee&&M(e.callee)){const n=V(e.callee).unwrap(),s=Ye(n),i=this.symbolFactory.create(Jt,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(s)){const a=r.get(s);return[new u(o.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,e),new u(o.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,a.declaration)]}r.set(s,i)}return[]}}class In{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof C||ge(this.declarationNode.parent).unwrap_or(void 0)!==b.Table?[new u(o.INVALID_NOTE_CONTEXT,"An Indexes can only appear inside a Table",this.declarationNode)]:[]}validateName(e){return e?[new u(o.UNEXPECTED_NAME,"An Indexes shouldn't have a name",e)]:[]}validateAlias(e){return e?[new u(o.UNEXPECTED_ALIAS,"An Indexes shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new u(o.UNEXPECTED_SETTINGS,"An Indexes shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof k)return[new u(o.UNEXPECTED_SIMPLE_BODY,"An Indexes must have a complex body",e)];const[n,s]=I.partition(e.body,i=>i instanceof k);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.flatMap(n=>{if(!n.callee)return[];const s=[],i=[n.callee,...n.args];return I.last(i)instanceof P&&s.push(...this.validateFieldSetting(i.pop())),i.forEach(r=>{for(;r instanceof H;)r.argumentList&&!Ge(r.argumentList).isOk()&&s.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()||s.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))}),s})}validateFieldSetting(e){const n=z(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"note":case"name":a.length>1&&a.forEach(l=>s.push(new u(o.DUPLICATE_INDEX_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{$(l.value)||s.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=>s.push(new u(o.DUPLICATE_INDEX_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{oe(l.value)||s.push(new u(o.INVALID_INDEX_SETTING_VALUE,`'${r}' must not have a value`,l))});break;case"type":a.length>1&&a.forEach(l=>s.push(new u(o.DUPLICATE_INDEX_SETTING,"'type' can only appear once",l))),a.forEach(l=>{M(l.value)||s.push(new u(o.INVALID_INDEX_SETTING_VALUE,`'type' must be "btree" or "hash"`,l))});break;default:a.forEach(l=>s.push(new u(o.UNKNOWN_INDEX_SETTING,`Unknown index setting '${r}'`,l)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ie(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class Ln{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof C||![b.Table,b.Project].includes(ge(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 k)return this.validateFields([e]);const[n,s]=I.partition(e.body,i=>i instanceof k);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){const n=[];return e.length===0?[new u(o.EMPTY_NOTE,"A Note must have a content",this.declarationNode)]:(e.length>1&&e.slice(1).forEach(s=>n.push(new u(o.NOTE_CONTENT_REDEFINED,"A Note can only contain one string",s))),$(e[0].callee)||n.push(new u(o.INVALID_NOTE,"A Note content must be a quoted string",e[0])),e[0].args.length>0&&n.push(...e[0].args.map(s=>new u(o.INVALID_NOTE,"A Note can only contain one quoted string",s))),n)}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ie(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class gn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof _?[new u(o.INVALID_PROJECT_CONTEXT,"A Project can only appear top-level",this.declarationNode)]:[]}validateName(e){return e?Pe(e)?[]:[new u(o.INVALID_NAME,"A Project's name is optional or must be an identifier or a quoted identifer",e)]:[]}validateAlias(e){return e?[new u(o.UNEXPECTED_ALIAS,"A Project shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new u(o.UNEXPECTED_SETTINGS,"A Project shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof k)return[new u(o.UNEXPECTED_SIMPLE_BODY,"A Project's body must be a block",e)];const[n,s]=I.partition(e.body,i=>i instanceof k);return[...n.map(i=>new u(o.INVALID_PROJECT_FIELD,"A Project can not have inline fields",i)),...this.validateSubElements(s)]}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ie(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class _n{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof C?[]:[new u(o.INVALID_REF_CONTEXT,"A Ref must appear top-level",this.declarationNode)]}validateName(e){return e?Pe(e)?[]:[new u(o.INVALID_NAME,"A Ref's name is optional or must be an identifier or a quoted identifer",e)]:[]}validateAlias(e){return e?[new u(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new u(o.UNEXPECTED_SETTINGS,"A Ref shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof k)return this.validateFields([e]);const[n,s]=I.partition(e.body,i=>i instanceof k);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){if(e.length===0)return[new u(o.EMPTY_REF,"A Ref must have at least one field",this.declarationNode)];const n=[];return e.length>1&&n.push(...e.slice(1).map(s=>new u(o.REF_REDEFINED,"A Ref can only contain one binary relationship",s))),e.forEach(s=>{s.callee&&!En(s.callee)&&n.push(new u(o.INVALID_REF_FIELD,"A Ref field must be a binary relationship",s.callee)),s.callee&&!Nn(s.callee)&&n.push(new u(o.UNEQUAL_FIELDS_BINARY_REF,"Unequal fields in ref endpoints",s.callee));const i=[...s.args];I.last(i)instanceof P?(this.validateFieldSettings(I.last(i)),i.pop()):i[0]instanceof P&&(n.push(...this.validateFieldSettings(i[0])),i.shift()),i.length>0&&n.push(...i.map(r=>new u(o.INVALID_REF_FIELD,"A Ref field should only have a single binary relationship",r)))}),n}validateFieldSettings(e){const n=z(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"delete":case"update":a.length>1&&a.forEach(l=>s.push(new u(o.DUPLICATE_REF_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{An(l.value)||s.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=>s.push(new u(o.UNKNOWN_REF_SETTING,`Unknown ref setting '${r}'`,l)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ie(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}function An(t){if(!(M(t)&&t.expression.variable.kind!==c.QUOTED_STRING)&&!(t instanceof K))return!1;let e;if(t instanceof K?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,n,s){this.declarationNode=e,this.symbolFactory=s,this.publicSymbolTable=n}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof _?[new u(o.INVALID_TABLE_CONTEXT,"Table must appear top-level",this.declarationNode)]:[]}validateName(e){return e?e instanceof le?[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,"Table aliases can only contains alphanumeric and underscore unless surrounded by double quotes",e)]:[]}validateSettingList(e){const n=z(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"headercolor":a.length>1&&s.push(...a.map(l=>new u(o.DUPLICATE_TABLE_SETTING,"'headercolor' can only appear once",l))),a.forEach(l=>{On(l.value)||s.push(new u(o.INVALID_TABLE_SETTING,"'headercolor' must be a color literal",l.value||l.name))});break;case"note":a.length>1&&s.push(...a.map(l=>new u(o.DUPLICATE_TABLE_SETTING,"'note' can only appear once",l))),a.forEach(l=>{$(l.value)||s.push(new u(o.INVALID_TABLE_SETTING,"'note' must be a string literal",l.value||l.name))});break;default:s.push(...a.map(l=>new u(o.INVALID_TABLE_SETTING,`Unknown '${r}' setting`,l)))}}return s}registerElement(){const e=[];this.declarationNode.symbol=this.symbolFactory.create(_t,{declaration:this.declarationNode,symbolTable:new _e});const{name:n,alias:s}=this.declarationNode,i=W(n);if(i.isOk()){const r=[...i.unwrap()],a=r.pop(),l=Ze(r,this.publicSymbolTable,this.symbolFactory),p=ke(a);l.has(p)&&e.push(new u(o.DUPLICATE_NAME,`Table name '${a}' already exists in schema '${r.join(".")||"public"}'`,n)),l.set(p,this.declarationNode.symbol)}if(s&&Pe(s)&&!yn(s.expression.variable.value,i.unwrap_or([]))){const r=V(s).unwrap(),a=ke(r);this.publicSymbolTable.has(a)&&e.push(new u(o.DUPLICATE_NAME,`Table name '${r}' already exists`,n)),this.publicSymbolTable.set(a,this.declarationNode.symbol)}return e}validateBody(e){if(!e)return[];if(e instanceof k)return[new u(o.UNEXPECTED_SIMPLE_BODY,"A Table's body must be a block",e)];const[n,s]=I.partition(e.body,i=>i instanceof k);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.length===0?[new u(o.EMPTY_TABLE,"A Table must have at least one column",this.declarationNode)]:e.flatMap(n=>{if(!n.callee)return[];const s=[];n.args.length===0&&s.push(new u(o.INVALID_COLUMN,"A column must have a type",n.callee)),M(n.callee)||s.push(new u(o.INVALID_COLUMN_NAME,"A column name must be an identifier or a quoted identifier",n.callee)),n.args[0]&&!wn(n.args[0])&&s.push(new u(o.INVALID_COLUMN_TYPE,"Invalid column type",n.args[0]));const i=n.args.slice(1);return s.push(...this.validateFieldSetting(i)),s.push(...this.registerField(n)),s})}registerField(e){if(e.callee&&M(e.callee)){const n=V(e.callee).unwrap(),s=We(n),i=this.symbolFactory.create(Zt,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(s)){const a=r.get(s);return[new u(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,e),new u(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,a.declaration)]}r.set(s,i)}return[]}validateFieldSetting(e){if(!e.slice(0,-1).every(de)||!e.slice(-1).every(p=>de(p)||p instanceof P))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 n;I.last(e)instanceof P&&(n=e.pop());const s=z(n),i=s.getErrors(),r=s.getValue();for(const p of e){const h=V(p).unwrap_or("").toLowerCase();if(h!=="pk"&&h!=="unique"){i.push(new u(o.INVALID_SETTINGS,"Inline column settings can only be `pk` or `unique`",p));continue}r[h]===void 0?r[h]=[p]:r[h].push(p)}const a=r.pk||[],l=r["primary key"]||[];a.length>=1&&l.length>=1&&i.push(...[...a,...l].map(p=>new u(o.DUPLICATE_COLUMN_SETTING,"Either one of 'primary key' and 'pk' can appear",p)));for(const p in r){const h=r[p];switch(p){case"note":h.length>1&&i.push(...h.map(f=>new u(o.DUPLICATE_COLUMN_SETTING,"note can only appear once",f))),h.forEach(f=>{$(f.value)||i.push(new u(o.INVALID_COLUMN_SETTING_VALUE,"'note' must be a quoted string",f.value||f.name))});break;case"ref":h.forEach(f=>{Rn(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 n=e.flatMap(i=>{if(i.parent=this.declarationNode,!i.type)return[];const r=ie(i);return new r(i,this.publicSymbolTable,this.symbolFactory).validate()}),s=e.filter(i=>{var r;return((r=i.type)==null?void 0:r.value.toLowerCase())==="note"});return s.length>1&&(n.push(...s.map(i=>new u(o.NOTE_REDEFINED,"Duplicate notes are defined",i))),n.push()),n}}function wn(t){if(!(t instanceof H||He(t)||t instanceof D||t instanceof le))return!1;if(t instanceof H){if(t.callee===void 0||t.argumentList===void 0||!t.argumentList.elementList.every(n=>ce(n)||$(n)||de(n)))return!1;t=t.callee}for(;t instanceof le;){if(t.array===void 0||t.indexer===void 0||!t.indexer.elementList.every(n=>!n.colon&&!n.value&&ce(n.name)))return!1;t=t.array}const e=W(t).unwrap_or(void 0);return e!==void 0&&e.length>0}function yn(t,e){return e.length===1&&t===e[0]}class kn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof _?[new u(o.INVALID_TABLEGROUP_CONTEXT,"TableGroup must appear top-level",this.declarationNode)]:[]}validateName(e){return e?Je(e)?[]:[new u(o.INVALID_NAME,"A TableGroup name must be of the form <tablegroup> or <schema>.<tablegroup>",e)]:[new u(o.NAME_NOT_FOUND,"A TableGroup must have a name",this.declarationNode)]}validateAlias(e){return e?[new u(o.UNEXPECTED_ALIAS,"A TableGroup shouldn't have an alias",e)]:[]}registerElement(){const{name:e}=this.declarationNode;this.declarationNode.symbol=this.symbolFactory.create(Kt,{declaration:this.declarationNode,symbolTable:new _e});const n=W(e);if(n.isOk()){const s=n.unwrap(),i=s.pop(),r=Ze(s,this.publicSymbolTable,this.symbolFactory),a=ze(i);if(r.has(a))return[new u(o.DUPLICATE_NAME,`TableGroup name '${i}' already exists in schema '${s.join(".")||"public"}'`,e)];r.set(a,this.declarationNode.symbol)}return[]}validateSettingList(e){return e?[new u(o.UNEXPECTED_SETTINGS,"A TableGroup shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof k)return[new u(o.UNEXPECTED_SIMPLE_BODY,"A TableGroup's body must be a block",e)];const[n,s]=I.partition(e.body,i=>i instanceof k);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.flatMap(n=>{const s=[];return n.callee&&!W(n.callee).isOk()&&s.push(new u(o.INVALID_TABLEGROUP_FIELD,"A TableGroup field must be of the form <table> or <schema>.<table>",n.callee)),this.registerField(n),n.args.length>0&&s.push(...n.args.map(i=>new u(o.INVALID_TABLEGROUP_FIELD,"A TableGroup field should only have a single Table name",i))),s})}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ie(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}registerField(e){if(e.callee&&M(e.callee)){const n=V(e.callee).unwrap(),s=qe(n),i=this.symbolFactory.create(en,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(s)){const a=r.get(s);return[new u(o.DUPLICATE_TABLEGROUP_FIELD_NAME,`${n} already exists in the group`,e),new u(o.DUPLICATE_TABLEGROUP_FIELD_NAME,`${n} already exists in the group`,a.declaration)]}r.set(s,i)}return[]}}const vt=["-","+"];function ie(t){switch(t.type.value.toLowerCase()){case b.Enum:return bn;case b.Table:return vn;case b.TableGroup:return kn;case b.Project:return gn;case b.Ref:return _n;case b.Note:return Ln;case b.Indexes:return In;default:return Tn}}function Je(t){return!!W(t).unwrap_or(!1)}function xn(t){return Pe(t)}function Pe(t){return t instanceof D&&t.expression instanceof X}function Ze(t,e,n){var i;t[0]==="public"&&(t=t.slice(1));let s=e;for(const r of t){let a;const l=$e(r);if(s.has(l)){if(a=(i=s.get(l))==null?void 0:i.symbolTable,!a)throw new Error("Expect a symbol table in a schema symbol")}else{a=new _e;const p=n.create(gt,{symbolTable:a});s.set(l,p)}s=a}return s}function wt(t){return t==="-"||t==="<>"||t===">"||t==="<"}function On(t){var n;if(!(t instanceof D)||!(t.expression instanceof Ee)||((n=t.expression.literal)==null?void 0:n.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 s=1;s<e.length;s+=1)if(!qt(e[s]))return!1;return!0}function oe(t){return t===void 0}function Sn(t){var e;return!!($(t)||ce(t)||de(t)&&["true","false","null"].includes(t.expression.variable.value.toLowerCase())||t instanceof q&&vt.includes((e=t.op)==null?void 0:e.value)&&ce(t.expression)||t instanceof ee)}function ce(t){var e;return t instanceof D&&t.expression instanceof Ee&&((e=t.expression.literal)==null?void 0:e.kind)===c.NUMERIC_LITERAL}function Rn(t){var n;if(!(t instanceof q)||!wt((n=t.op)==null?void 0:n.value))return!1;const e=W(t.expression).unwrap_or(void 0);return e!==void 0&&e.length>0}function yt(t){return t instanceof J&&t.elementList.every(M)}function z(t){var s;const e={},n=[];if(!t)return new F({});for(const i of t.elementList){if(!i.name)continue;if(i.name instanceof D){n.push(new u(o.INVALID_SETTINGS,"A setting name must be a stream of identifiers",i.name));continue}const r=(s=De(i.name).unwrap_or(void 0))==null?void 0:s.toLowerCase();r&&(e[r]===void 0?e[r]=[i]:e[r].push(i))}return new F(e,n)}class ht{constructor(e,n){this.ast=e,this.symbolFactory=n,this.publicSchemaSymbol=this.symbolFactory.create(gt,{symbolTable:new _e}),this.ast.symbol=this.publicSchemaSymbol,this.ast.symbol.declaration=this.ast}validate(){const e=[];this.ast.body.forEach(s=>{if(s.parent=this.ast,s.type===void 0)return;const i=ie(s),r=new i(s,this.publicSchemaSymbol.symbolTable,this.symbolFactory);e.push(...r.validate())});const n=this.ast.body.filter(s=>ge(s).unwrap_or(void 0)===b.Project);return n.length>1&&n.forEach(s=>e.push(new u(o.PROJECT_REDEFINED,"Only one project can exist",s))),new F(this.ast,e)}}class re{constructor(e,n){this.declarationNode=e,this.errors=n}bind(){this.bindSettingList(this.declarationNode.attributeList,this.settingList),this.bindBody()}bindSettingList(e,n){if(e)for(const s of e.elementList){if(s.name instanceof D)continue;const i=De(s.name).unwrap_or(void 0);if(!i)continue;const r=n[i.toLowerCase()];r!=null&&r.shouldBind&&this.scanAndBind(s.value,r)}}bindBody(){const e=this.declarationNode;if(!e.body)return;const{body:n}=e;if(n instanceof te)for(const s of n.body)if(s instanceof _){if(!s.type)continue;const i=kt(s);new i(s,this.errors).bind()}else this.bindSubfield(s);else this.bindSubfield(n)}bindSubfield(e){const n=[e.callee,...e.args],s=I.last(n);s instanceof P&&(n.pop(),this.bindSettingList(s,this.subfield.settingList));const{argBinderRules:i}=this.subfield.arg;for(let r=0;r<Math.min(n.length,i.length);r+=1)i[r].shouldBind&&this.scanAndBind(n[r],i[r])}scanAndBind(e,n){var s,i;if(e)if(e instanceof D){if(e.expression instanceof X&&((i=n.keywords)!=null&&i.includes((s=e.expression.variable)==null?void 0:s.value.toLowerCase())))return;this.bindFragments([e],n)}else e instanceof Q?He(e)?this.bindFragments(ue(e).unwrap_or([]),n):(this.scanAndBind(e.leftExpression,n),this.scanAndBind(e.rightExpression,n)):e instanceof q?this.scanAndBind(e.expression,n):e instanceof Re?this.scanAndBind(e.expression,n):e instanceof J&&e.elementList.forEach(r=>this.scanAndBind(r,n))}bindFragments(e,n){if(e.length===0)return;const s=[...n.topSubnamesSymbolKind],{remainingSubnamesSymbolKind:i}=n,r=e.findIndex(f=>!M(f)),l=r!==-1&&yt(e[r])?e[r]:void 0,p=r>=0?s.pop():void 0,h=e.slice(0,r===-1?void 0:r);if(h.length===0)return;const T=[];for(;s.length&&h.length;){const f=s.pop(),N=h.pop(),g=V(N).unwrap();T.unshift({index:Fe(g,f),referrer:N})}for(;h.length;){const f=h.pop(),N=V(f).unwrap();T.unshift({index:Fe(N,i),referrer:f})}return l?l.elementList.forEach(f=>this.resolveIndexStack([...T,{index:Fe(V(f).unwrap(),p),referrer:f}],n.ignoreNameNotFound)):this.resolveIndexStack(T,n.ignoreNameNotFound)}resolveIndexStack(e,n){if(e.length===0)throw new Error("Unreachable - An unresolved name must have at least one name component");const[s,...i]=e,r=mn(s.index,this.declarationNode);if(r===void 0){const{kind:h,name:T}=se(s.index).unwrap();this.logError(s.referrer,`Can not find ${h} '${T}'`,n);return}r.references.push(s.referrer),s.referrer.referee=r;let a=r.symbolTable,{kind:l,name:p}=se(s.index).unwrap();for(const h of i){const{kind:T,name:f}=se(h.index).unwrap(),N=a.get(h.index);if(!N){this.logError(h.referrer,`${l} '${p}' does not have ${T} '${f}'`,n);return}if(l=T,p=f,h.referrer.referee=N,N.references.push(h.referrer),!N.symbolTable)break;a=N.symbolTable}}logError(e,n,s){s||this.errors.push(new u(o.BINDING_ERROR,n,e))}}class Dn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Pn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Un extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class Mn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Fn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Bn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class Vn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Enum],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!0}]},settingList:{ref:{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},default:{shouldBind:!1}}},this.settingList={}}}class Gn extends re{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}function kt(t){switch(t.type.value.toLowerCase()){case b.Enum:return Pn;case b.Table:return Vn;case b.TableGroup:return Gn;case b.Project:return Fn;case b.Ref:return Bn;case b.Note:return Mn;case b.Indexes:return Un;default:return Dn}}class Cn{constructor(e){this.ast=e,this.errors=[]}resolve(){for(const e of this.ast.body)if(e.type){const n=kt(e);new n(e,this.errors).bind()}return new F(this.ast,this.errors)}}class Xn{constructor(e){this.generator=e}create(e,n){return new e(n,this.generator.nextId())}}class $n{constructor(e,n){this.ast=e,this.symbolFactory=new Xn(n)}analyze(){return new ht(this.ast,this.symbolFactory).validate().chain(n=>new Cn(n).resolve())}validate(){return new ht(this.ast,this.symbolFactory).validate().chain(n=>new F(n,[]))}}function ft(t,e){const{variables:n,tupleElements:s}=Ie(t).unwrap();return s?n.length===0?{schemaName:e.schemaName,tableName:e.name,fieldNames:s}:{tableName:n.pop(),schemaName:n.pop()||null,fieldNames:s}:n.length===1?{schemaName:e.schemaName,tableName:e.name,fieldNames:[n[0]]}:{fieldNames:[n.pop()],tableName:n.pop(),schemaName:n.pop()||null}}function xt(t){switch(t){case"<":return["1","*"];case"<>":return["*","*"];case">":return["*","1"];case"-":return["1","1"]}throw new Error("Invalid relation op")}function x(t){return{start:{offset:t.startPos.offset,line:t.startPos.line+1,column:t.startPos.column+1},end:{offset:t.endPos.offset,line:t.endPos.line+1,column:t.endPos.column+1}}}function Ce(t){var n;const e=(n=ue(t).unwrap_or(void 0))==null?void 0:n.pop();return e instanceof J?e.elementList.map(s=>s.referee):[e.referee]}function Ae(t){const e=W(t).unwrap();return{name:e.pop(),schemaName:e}}function Wn(t){return t.expression.literal.value}function Ot(t,e){if(Array.isArray(t)){const i=t.map(({id:a})=>a).sort().join(","),r=e.map(({id:a})=>a).sort().join(",");return i<r?`${i}-${r}`:`${r}-${i}`}const n=t.id,s=e.id;return n<s?`${n}-${s}`:`${s}-${n}`}function St(t,e){if(Array.isArray(t)){const i=t.map(({id:a})=>a).sort(),r=e.map(({id:a})=>a).sort();return I.zip(i,r).every(([a,l])=>a===l)}const n=t.id,s=e.id;return n===s}class Rt{constructor(e,n){this.declarationNode=e,this.env=n,this.table={name:void 0,schemaName:void 0,alias:null,fields:[],token:void 0,indexes:[]},this.pkColumns=[]}interpret(){this.table.token=x(this.declarationNode),this.env.tables.set(this.declarationNode,this.table);const e=[...this.interpretName(this.declarationNode.name),...this.interpretAlias(this.declarationNode.alias),...this.interpretSettingList(this.declarationNode.attributeList),...this.interpretBody(this.declarationNode.body)];return this.pkColumns.length>=2&&(this.table.indexes.push({columns:this.pkColumns.map(({name:n})=>({value:n,type:"column"})),token:{start:{offset:-1,line:-1,column:-1},end:{offset:-1,line:-1,column:-1}},pk:!0}),this.pkColumns.forEach(n=>n.pk=!1)),e}interpretName(e){const{name:n,schemaName:s}=Ae(e);return s.length>1?(this.table.name=n,this.table.schemaName=s.join("."),[new u(o.UNSUPPORTED,"Nested schema is not supported",e)]):(this.table.name=n,this.table.schemaName=s.length?s[0]:null,[])}interpretAlias(e){if(!e)return[];const n=V(e).unwrap_or(null);return n&&(this.env.aliases.push({name:n,kind:"table",value:{tableName:this.table.name,schemaName:this.table.schemaName}}),this.table.alias=n),[]}interpretSettingList(e){var r,a,l;const n=z(e).getValue();this.table.headerColor=(r=n.headercolor)!=null&&r.length?Wn((l=(a=n.headercolor)==null?void 0:a.at(0))==null?void 0:l.value):void 0;const[s]=n.note||[],i=Y(s==null?void 0:s.value).unwrap_or(void 0);return this.table.note=s&&{value:i,token:x(s)},[]}interpretBody(e){const[n,s]=I.partition(e.body,i=>i instanceof k);return[...this.interpretFields(n),...this.interpretSubElements(s)]}interpretSubElements(e){return e.flatMap(n=>{var s;switch((s=n.type)==null?void 0:s.value.toLowerCase()){case"note":return this.table.note={value:Y(n.body instanceof te?n.body.body[0].callee:n.body.callee).unwrap(),token:x(n)},[];case"indexes":return this.interpretIndexes(n)}return[]})}interpretFields(e){return e.flatMap(n=>this.interpretColumn(n))}interpretColumn(e){var a,l,p,h,T,f,N,g;const n=[],s={};s.name=V(e.callee).unwrap();const i=jn(e.args[0]);s.type=i.getValue(),n.push(...i.getErrors()),s.token=x(e),s.inline_refs=[];const r=e.args.slice(1);if(I.last(r)instanceof P){const v=z(r.pop()).getValue();s.pk=!!((a=v.pk)!=null&&a.length)||!!((l=v["primary key"])!=null&&l.length),s.increment=!!((p=v.increment)!=null&&p.length),s.unique=!!((h=v.unique)!=null&&h.length),s.not_null=!!((T=v["not null"])!=null&&T.length)&&!0,s.dbdefault=Yn((N=(f=v.default)==null?void 0:f.at(0))==null?void 0:N.value);const Ne=(g=v.note)==null?void 0:g.at(0);s.note=Ne&&{value:Y(Ne.value).unwrap(),token:x(Ne)};const me=v.ref||[];s.inline_refs=me.flatMap(j=>{const[tt]=Ce(j.value.expression);if(St(tt,e.symbol))return n.push(new u(o.SAME_ENDPOINT,"Two endpoints are the same",j)),[];const ve=j.value.op,Z=W(j.value.expression).unwrap();let he;if(Z.length===1){const[ae]=Z;he={schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[ae],relation:ve.value,token:x(j)}}else if(Z.length===2){const[ae,Te]=Z;he={schemaName:null,tableName:ae,fieldNames:[Te],relation:ve.value,token:x(j)}}else if(Z.length===3){const[ae,Te,st]=Z;he={schemaName:ae,tableName:Te,fieldNames:[st],relation:ve.value,token:x(j)}}else{n.push(new u(o.UNSUPPORTED,"Nested schema is not supported",j));const ae=Z.pop(),Te=Z.pop();he={schemaName:Z.join("."),tableName:Te,fieldNames:[ae],relation:ve.value,token:x(j)}}const nt=this.registerInlineRefToEnv(e,tt,he,j);return n.push(...nt),nt.length===0?he:[]})}return s.pk||(s.pk=r.some(v=>G(v).unwrap().toLowerCase()==="pk")),s.unique||(s.unique=r.some(v=>G(v).unwrap().toLowerCase()==="unique")),this.table.fields.push(s),s.pk&&this.pkColumns.push(s),n}interpretIndexes(e){return this.table.indexes.push(...e.body.body.map(n=>{var a,l,p,h,T,f,N;const s={columns:[]},i=n;s.token=x(e);const r=[i.callee,...i.args];if(I.last(r)instanceof P){const g=z(r.pop()).getValue();s.pk=!!((a=g.pk)!=null&&a.length),s.unique=!!((l=g.unique)!=null&&l.length),s.name=Y((h=(p=g.name)==null?void 0:p.at(0))==null?void 0:h.value).unwrap_or(void 0);const v=(T=g.note)==null?void 0:T.at(0);s.note=v&&{value:Y(v.value).unwrap(),token:x(v)},s.type=G((N=(f=g.type)==null?void 0:f.at(0))==null?void 0:N.value).unwrap_or(void 0)}return r.flatMap(g=>{if(!(g instanceof H))return g;const v=[];for(;g instanceof H;)v.push(g.argumentList),g=g.callee;return v.push(g),v}).forEach(g=>{const{functional:v,nonFunctional:Ne}=Ge(g).unwrap();s.columns.push(...v.map(me=>({value:me.value.value,type:"expression"})),...Ne.map(me=>({value:V(me).unwrap(),type:"column"})))}),s})),[]}registerInlineRefToEnv(e,n,s,i){const r=Ot(e.symbol,n);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=xt(s.relation);return this.env.refIds[r]=i,this.env.ref.set(i,{name:null,schemaName:null,token:s.token,endpoints:[{...s,relation:a[1]},{schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[G(e.callee).unwrap()],token:x(e),relation:a[0]}]}),[]}}function jn(t){let e=null;t instanceof H&&(e=t.argumentList.elementList.map(r=>ce(r)?r.expression.literal.value:$(r)?Y(r).unwrap():G(r).unwrap()).join(","),t=t.callee);let n="";for(;t instanceof le;)n=`[${t.indexer.elementList.map(r=>r.name.expression.literal.value).join(",")}]${n}`,t=t.array;const{name:s,schemaName:i}=Ae(t);return i.length>1?new F({schemaName:i.length===0?null:i[0],type_name:`${s}${n}${e?`(${e})`:""}`,args:e},[new u(o.UNSUPPORTED,"Nested schema is not supported",t)]):new F({schemaName:i.length===0?null:i[0],type_name:`${s}${n}${e?`(${e})`:""}`,args:e})}function Yn(t){var e,n,s;if(t){if($(t))return{value:Y(t).unwrap(),type:"string"};if(ce(t))return{type:"number",value:Number.parseFloat(t.expression.literal.value)};if(de(t))return{value:t.expression.variable.value.toLowerCase(),type:"boolean"};if(t instanceof q&&vt.includes((e=t.op)==null?void 0:e.value)&&ce(t.expression)){const i=Number.parseFloat(t.expression.expression.literal.value);return{value:((n=t.op)==null?void 0:n.value)==="-"?0-i:i,type:"number"}}if(t instanceof ee)return{value:(s=t.value)==null?void 0:s.value,type:"expression"};throw new Error("Unreachable")}}class Dt{constructor(e,n){this.declarationNode=e,this.env=n,this.container=this.declarationNode.parent instanceof _?this.env.tables.get(this.declarationNode.parent):void 0,this.ref={}}interpret(){return this.ref.token=x(this.declarationNode),this.env.ref.set(this.declarationNode,this.ref),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(e){const n=[],s=W(this.declarationNode.name).unwrap_or([]);return this.ref.name=s.pop()||null,s.length>1&&n.push(new u(o.UNSUPPORTED,"Nested schema is not supported",this.declarationNode.name)),this.ref.schemaName=s.join(".")||null,n}interpretBody(e){return e instanceof k?this.interpretField(e):this.interpretField(e.body[0])}interpretField(e){var h,T,f,N;const n=e.callee.op.value,{leftExpression:s,rightExpression:i}=e.callee,r=Ce(s),a=Ce(i);if(St(r,a))return[new u(o.SAME_ENDPOINT,"Two endpoints are the same",e)];const l=Ot(r,a);if(this.env.refIds[l])return[new u(o.CIRCULAR_REF,"References with same endpoints exist",this.declarationNode),new u(o.CIRCULAR_REF,"References with same endpoints exist",this.env.refIds[l])];if(e.args[0]){const g=z(e.args[0]).getValue();this.ref.onDelete=G((T=(h=g.delete)==null?void 0:h.at(0))==null?void 0:T.value).unwrap_or(void 0),this.ref.onUpdate=G((N=(f=g.update)==null?void 0:f.at(0))==null?void 0:N.value).unwrap_or(void 0)}const p=xt(n);return this.ref.endpoints=[{...ft(s,this.container),relation:p[0],token:x(s)},{...ft(i,this.container),relation:p[1],token:x(i)}],this.env.refIds[l]=this.declarationNode,[]}}class Pt{constructor(e,n){this.declarationNode=e,this.env=n,this.tableGroup={tables:[]}}interpret(){const e=[];return this.tableGroup.token=x(this.declarationNode),this.env.tableGroups.set(this.declarationNode,this.tableGroup),e.push(...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)),e}interpretName(e){const n=[],{name:s,schemaName:i}=Ae(e);return i.length>=2&&(this.tableGroup.name=s,this.tableGroup.schemaName=i.join("."),n.push(new u(o.UNSUPPORTED,"Nested schema is not supported",this.declarationNode.name))),this.tableGroup.name=s,this.tableGroup.schemaName=i[0]||null,n}interpretBody(e){const n=[];return this.tableGroup.tables=this.declarationNode.body.body.map(s=>{const i=W(s.callee).unwrap();i.length>2&&n.push(new u(o.UNSUPPORTED,"Nested schema is not supported",s));const r=ue(s.callee).unwrap().pop().referee.id;if(this.env.groupOfTable[r]){const a=this.env.groupOfTable[r],{schemaName:l,name:p}=this.env.tableGroups.get(a),h=l?`${l}.${p}`:p;n.push(new u(o.TABLE_REAPPEAR_IN_TABLEGROUP,`Table "${i.join(".")}" already appears in group "${h}"`,s))}else this.env.groupOfTable[r]=this.declarationNode;return{name:i.pop(),schemaName:i.join(".")}}),n}}class Ut{constructor(e,n){this.declarationNode=e,this.env=n,this.enum={values:[]}}interpret(){return this.enum.token=x(this.declarationNode),this.env.enums.set(this.declarationNode,this.enum),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(e){const{name:n,schemaName:s}=Ae(e);return s.length>1?(this.enum.name=n,this.enum.schemaName=s.join("."),[new u(o.UNSUPPORTED,"Nested schema is not supported",e)]):(this.enum.name=n,this.enum.schemaName=s.length?s[0]:null,[])}interpretBody(e){return e.body.flatMap(n=>{var l;const s=n,i={};i.token=x(s),i.name=G(s.callee).unwrap();const a=(l=z(s.args[0]).getValue().note)==null?void 0:l.at(0);return i.note=a&&{value:Y(a.value).unwrap(),token:x(a)},this.enum.values.push(i),[]})}}class zn{constructor(e,n){this.declarationNode=e,this.env=n,this.project={enums:[],refs:[],tableGroups:[],tables:[]}}interpret(){return this.env.project.set(this.declarationNode,this.project),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(e){if(!e)return this.project.name=null,[];const{name:n}=Ae(e);return this.project.name=n,[]}interpretBody(e){return e.body.flatMap(n=>{var i;const s=n;switch((i=s.type)==null?void 0:i.value.toLowerCase()){case"table":{const r=new Rt(s,this.env).interpret();return this.project.tables.push(this.env.tables.get(s)),r}case"ref":{const r=new Dt(s,this.env).interpret();return this.project.refs.push(this.env.ref.get(s)),r}case"tablegroup":{const r=new Pt(s,this.env).interpret();return this.project.tableGroups.push(this.env.tableGroups.get(s)),r}case"enum":{const r=new Ut(s,this.env).interpret();return this.project.enums.push(this.env.enums.get(s)),r}case"note":return this.project.note={value:Y(s.body instanceof te?s.body.body[0].callee:s.body.callee).unwrap(),token:x(s)},[];default:return this.project[s.type.value.toLowerCase()]=Y(s.body.callee).unwrap(),[]}})}}class qn{constructor(e){this.ast=e,this.env={schema:[],tables:new Map,refIds:{},ref:new Map,enums:new Map,tableGroups:new Map,groupOfTable:{},aliases:[],project:new Map}}interpret(){const e=this.ast.body.flatMap(n=>{switch(ge(n).unwrap_or(void 0)){case b.Table:return new Rt(n,this.env).interpret();case b.Ref:return new Dt(n,this.env).interpret();case b.TableGroup:return new Pt(n,this.env).interpret();case b.Enum:return new Ut(n,this.env).interpret();case b.Project:return new zn(n,this.env).interpret();default:return[]}});return new F(Qn(this.env),e)}}function Qn(t){return{schemas:[],tables:Array.from(t.tables.values()),refs:Array.from(t.ref.values()),enums:Array.from(t.enums.values()),tableGroups:Array.from(t.tableGroups.values()),aliases:t.aliases,project:Array.from(t.project.values())[0]||{}}}var L=(t=>(t[t.Function=1]="Function",t[t.Constructor=2]="Constructor",t[t.Field=3]="Field",t[t.Variable=4]="Variable",t[t.Class=5]="Class",t[t.Struct=6]="Struct",t[t.Interface=7]="Interface",t[t.Module=8]="Module",t[t.Property=9]="Property",t[t.Event=10]="Event",t[t.Operator=11]="Operator",t[t.Unit=12]="Unit",t[t.Value=13]="Value",t[t.Constant=14]="Constant",t[t.Enum=15]="Enum",t[t.EnumMember=16]="EnumMember",t[t.Keyword=17]="Keyword",t[t.Text=18]="Text",t[t.Color=19]="Color",t[t.File=20]="File",t[t.Reference=21]="Reference",t[t.Customcolor=22]="Customcolor",t[t.Folder=23]="Folder",t[t.TypeParameter=24]="TypeParameter",t[t.User=25]="User",t[t.Issue=26]="Issue",t[t.Snippet=27]="Snippet",t))(L||{}),w=(t=>(t[t.None=0]="None",t[t.KeepWhitespace=1]="KeepWhitespace",t[t.InsertAsSnippet=4]="InsertAsSnippet",t))(w||{});function Le(t){switch(t){case m.Schema:return L.Module;case m.Table:return L.Class;case m.Column:return L.Field;case m.Enum:return L.Enum;case m.EnumField:return L.EnumMember;case m.TableGroup:return L.Struct;case m.TableGroupField:return L.Field;default:return L.Text}}function Oe(t,e){if(!t||Ve(t))return!1;for(const n of t.trailingTrivia){if(n.start>e)break;if(n.kind===c.NEWLINE&&n.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 Ue(t){return{...t,suggestions:t.suggestions.map(e=>({...e,insertText:e.insertText.search(/[^a-zA-Z\d_]/)!==-1||e.insertText[0].match(/\d/)?`"${e.insertText}"`:e.insertText}))}}function Ke(t,e){return t.getOffsetAt(e)}class Mt{constructor(e,n=[]){this.compiler=e,this.triggerCharacters=n}provideCompletionItems(e,n){var T,f;const s=Ke(e,n),i=this.compiler.token.flatStream(),{token:r,index:a}=this.compiler.container.token(s),l=a===void 0?i[0]:i[a+1];if([...(r==null?void 0:r.trailingTrivia)||[],...(r==null?void 0:r.leadingTrivia)||[],...(l==null?void 0:l.leadingTrivia)||[]].find(N=>$t(N)&&be(s,N)))return S();if(a===void 0)return mt();if([c.STRING_LITERAL,c.QUOTED_STRING].includes(r.kind)&&be(s,r))return S();const p=this.compiler.container.element(s);if(this.compiler.container.scopeKind(s)===R.TOPLEVEL||p instanceof _&&p.type&&p.type.start<=s&&p.type.end>=s)return mt();const h=[...this.compiler.container.stack(s)].reverse();for(const N of h)if(N instanceof q)switch((T=N.op)==null?void 0:T.value){case">":case"<":case"<>":case"-":return pt(this.compiler,s,N)}else if(N instanceof Q)switch((f=N.op)==null?void 0:f.value){case">":case"<":case"<>":case"-":return pt(this.compiler,s,N);case".":return Ft(this.compiler,s,N)}else{if(N instanceof ne)return dt(this.compiler,s,N);if(N instanceof P)return dt(this.compiler,s,N);if(N instanceof J)return Hn(this.compiler,s);if(N instanceof k)return Nt(this.compiler,s,N);if(N instanceof _&&(N.bodyColon&&s>=N.bodyColon.end||N.body&&be(s,N.body)))return Nt(this.compiler,s,void 0)}return S()}}function pt(t,e,n){const s=t.container.scopeKind(e);if([R.REF,R.TABLE].includes(s)){const i=Me(t,e,t.container.element(e),[m.Table,m.Schema,m.Column]);return Oe(n.op,e)?Se(i):i}return S()}function Me(t,e,n,s){var a;if(n===void 0)return S();let i=n;const r={suggestions:[]};for(;i;){if((a=i==null?void 0:i.symbol)!=null&&a.symbolTable){const{symbol:l}=i;r.suggestions.push(...t.symbol.members(l).filter(({kind:p})=>s.includes(p)).map(({name:p,kind:h})=>({label:p,insertText:p,insertTextRules:w.KeepWhitespace,kind:Le(h),sortText:Le(h).toString().padStart(2,"0"),range:void 0})))}i=i instanceof _?i.parent:void 0}return Ue(r)}function Hn(t,e){var s;switch(t.container.scopeKind(e)){case R.INDEXES:return Vt(t,e);case R.REF:{const i=[...t.container.stack(e)];for(;i.length>0;){const r=i.pop();if(r instanceof Q&&((s=r.op)==null?void 0:s.value)===".")return Ft(t,e,r)}}return Bt(t,e)}return S()}function dt(t,e,n){const{token:s}=t.container.token(e);if([c.COMMA,c.LBRACKET].includes(s==null?void 0:s.kind)){const i=Et(t,e);return(s==null?void 0:s.kind)===c.COMMA&&Oe(s,e)?Se(i):i}if(n.name&&n.name.start<=e&&n.name.end>=e)return Et(t,e);if(n.name instanceof K){const i=Jn(t,e,De(n.name).unwrap());return(s==null?void 0:s.kind)===c.COLON&&Oe(s,e)?Se(i):i}return S()}function Et(t,e){const n=t.container.element(e),s=t.container.scopeKind(e);if(n instanceof C)return S();if(n.body&&!be(e,n.body))switch(s){case R.TABLE:return{suggestions:[{label:"headercolor",insertText:"headercolor: ",kind:L.Field,insertTextRules:w.KeepWhitespace,range:void 0},{label:"note",insertText:"note: ",kind:L.Field,insertTextRules:w.KeepWhitespace,range:void 0}]};default:return S()}switch(s){case R.TABLE:return{suggestions:[...["primary key","null","not null","increment","pk","unique"].map(i=>({label:i,insertText:i,kind:L.Property,insertTextRules:w.KeepWhitespace,range:void 0})),...["ref","default"].map(i=>({label:i,insertText:`${i}: `,kind:L.Property,insertTextRules:w.KeepWhitespace,range:void 0})),{label:"note",insertText:"note: ",kind:L.Property,insertTextRules:w.KeepWhitespace,range:void 0}]};case R.ENUM:return{suggestions:[{label:"note",insertText:"note: ",kind:L.Property,insertTextRules:w.KeepWhitespace,range:void 0}]};case R.INDEXES:return{suggestions:[...["unique","pk"].map(i=>({label:i,insertText:i,insertTextRules:w.KeepWhitespace,kind:L.Property,range:void 0})),...["note","name","type"].map(i=>({label:i,insertText:`${i}: `,kind:L.Property,insertTextRules:w.KeepWhitespace,range:void 0}))]};case R.REF:return{suggestions:["update","delete"].map(i=>({label:i,insertText:`${i}: `,kind:L.Property,insertTextRules:w.KeepWhitespace,range:void 0}))}}return S()}function Jn(t,e,n){switch(n==null?void 0:n.toLowerCase()){case"update":case"delete":return{suggestions:["cascade","set default","set null","restrict"].map(s=>({label:s,insertText:s,kind:L.Value,insertTextRules:w.KeepWhitespace,range:void 0}))};case"type":return{suggestions:["btree","hash"].map(s=>({label:s,insertText:`${s}`,kind:L.Value,insertTextRules:w.KeepWhitespace,range:void 0}))}}return S()}function Ft(t,e,n){const s=ue(n).unwrap_or([]);if(s.pop(),s.some(r=>!M(r)))return S();const i=s.map(r=>G(r).unwrap());return Ue({suggestions:t.symbol.ofName({nameStack:i,owner:t.container.element(e)}).flatMap(({symbol:r})=>t.symbol.members(r)).map(({kind:r,name:a})=>({label:a,insertText:a,kind:Le(r),range:void 0}))})}function Nt(t,e,n){var i;switch(t.container.scopeKind(e)){case R.TABLE:return Kn(t,e,n);case R.PROJECT:return es(t,e,n);case R.INDEXES:return ns(t,e);case R.ENUM:return Zn(t,e,n);case R.REF:{const r=Bt(t,e);return((i=t.container.token(e).token)==null?void 0:i.kind)===c.COLON&&Oe(t.container.token(e).token,e)?Se(r):r}case R.TABLEGROUP:return ts(t);default:return S()}}function mt(){return{suggestions:["Table","TableGroup","Enum","Project","Ref"].map(t=>({label:t,insertText:t,insertTextRules:w.KeepWhitespace,kind:L.Keyword,range:void 0}))}}function Zn(t,e,n){return n!=null&&n.callee&&et(e,n)===1?Me(t,e,t.container.element(e),[m.Schema,m.Table,m.Column]):S()}function Kn(t,e,n){if(!(n!=null&&n.callee))return{suggestions:["Note","indexes"].map(i=>({label:i,insertText:i,insertTextRules:w.KeepWhitespace,kind:L.Keyword,range:void 0}))};const s=et(e,n);return s===0?{suggestions:["Note","indexes"].map(i=>({label:i,insertText:i,insertTextRules:w.KeepWhitespace,kind:L.Keyword,range:void 0}))}:s===1?ss(t,e):S()}function es(t,e,n){return n!=null&&n.callee?et(e,n)===0?{suggestions:["Table","TableGroup","Enum","Note","Ref"].map(i=>({label:i,insertText:i,insertTextRules:w.KeepWhitespace,kind:L.Keyword,range:void 0}))}:S():{suggestions:["Table","TableGroup","Enum","Note","Ref"].map(i=>({label:i,insertText:i,insertTextRules:w.KeepWhitespace,kind:L.Keyword,range:void 0}))}}function Bt(t,e){return Me(t,e,t.container.element(e),[m.Schema,m.Table,m.Column])}function ts(t){return Ue({suggestions:[...t.parse.publicSymbolTable().entries()].flatMap(([e])=>{const n=se(e).unwrap_or(void 0);if(n===void 0)return[];const{kind:s,name:i}=n;return s!==m.Table&&s!==m.Schema?[]:{label:i,insertText:i,insertTextRules:w.KeepWhitespace,kind:Le(s),range:void 0}})})}function ns(t,e){return Vt(t,e)}function ss(t,e){return{suggestions:[...["integer","int","tinyint","smallint","mediumint","bigint","bit","bool","binary","varbinary","logical","char","nchar","varchar","varchar2","nvarchar","nvarchar2","binary_float","binary_double","float","double","decimal","dec","real","money","smallmoney","enum","tinyblob","tinytext","blob","text","mediumblob","mediumtext","longblob","longtext","ntext","set","inet6","uuid","image","date","time","datetime","datetime2","timestamp","year","smalldatetime","datetimeoffset","XML","sql_variant","uniqueidentifier","CURSOR","BFILE","CLOB","NCLOB","RAW"].map(n=>({label:n,insertText:n,insertTextRules:w.KeepWhitespace,kind:L.TypeParameter,sortText:L.TypeParameter.toString().padStart(2,"0"),range:void 0})),...Me(t,e,t.container.element(e),[m.Enum,m.Schema]).suggestions]}}function Vt(t,e){const n=t.container.element(e),s=n==null?void 0:n.parent;if(!((s==null?void 0:s.symbol)instanceof _t))return S();const{symbolTable:i}=s.symbol;return Ue({suggestions:[...i.entries()].flatMap(([r])=>{const a=se(r).unwrap_or(void 0);if(a===void 0)return[];const{name:l}=a;return{label:l,insertText:l,insertTextRules:w.KeepWhitespace,kind:Le(m.Column),range:void 0}})})}function et(t,e){if(!e.callee)return-1;const n=[e.callee,...e.args],s=n.findIndex(i=>t<=i.end);return s===-1?n.length:s}class Gt{constructor(e){this.compiler=e}provideDefinition(e,n){var a;const{uri:s}=e,i=Ke(e,n),r=[...this.compiler.container.stack(i)];for(;r.length!==0;){const l=r.pop();if((a=l==null?void 0:l.referee)!=null&&a.declaration&&[pe.PRIMARY_EXPRESSION,pe.VARIABLE].includes(l==null?void 0:l.kind)){const{startPos:p,endPos:h}=l.referee.declaration;return[{range:{startColumn:p.column+1,startLineNumber:p.line+1,endColumn:h.column+1,endLineNumber:h.line+1},uri:s}]}}return[]}}class Ct{constructor(e){this.compiler=e}provideReferences(e,n){const{uri:s}=e,i=Ke(e,n),r=[...this.compiler.container.stack(i)];for(;r.length!==0;){const a=r.pop();if(a&&[pe.ELEMENT_DECLARATION,pe.FUNCTION_APPLICATION,pe.PRIMARY_EXPRESSION].includes(a==null?void 0:a.kind)){const{symbol:l}=a;if(l!=null&&l.references.length)return l.references.map(({startPos:p,endPos:h})=>({range:{startColumn:p.column+1,startLineNumber:p.line+1,endColumn:h.column+1,endLineNumber:h.line+1},uri:s}))}}return[]}}const is=Object.freeze(Object.defineProperty({__proto__:null,CompletionItemInsertTextRule:w,CompletionItemKind:L,DBMLCompletionItemProvider:Mt,DBMLDefinitionProvider:Gt,DBMLReferencesProvider:Ct},Symbol.toStringTag,{value:"Module"}));var R=(t=>(t[t.TABLE=0]="TABLE",t[t.ENUM=1]="ENUM",t[t.TABLEGROUP=2]="TABLEGROUP",t[t.INDEXES=3]="INDEXES",t[t.NOTE=4]="NOTE",t[t.REF=5]="REF",t[t.PROJECT=6]="PROJECT",t[t.CUSTOM=7]="CUSTOM",t[t.TOPLEVEL=8]="TOPLEVEL",t))(R||{});class rs{constructor(){this.source="",this.cache=new Array(16).fill(null),this.nodeIdGenerator=new Wt,this.symbolIdGenerator=new Qt,this.token={invalidStream:this.createQuery(6,()=>this.parse.tokens().filter(At)),flatStream:this.createQuery(7,()=>this.parse.tokens().flatMap(e=>[...e.leadingInvalid,e,...e.trailingInvalid]))},this.parse={source:()=>this.source,_:this.createQuery(0,()=>{const e=new an(this.source).lex().chain(n=>new cn(n,this.nodeIdGenerator).parse()).chain(({ast:n,tokens:s})=>new $n(n,this.symbolIdGenerator).analyze().map(()=>({ast:n,tokens:s})));return e.getErrors().length>0?e:e.chain(({ast:n,tokens:s})=>new qn(n).interpret().map(r=>({ast:n,tokens:s,rawDb:r})))}),ast:this.createQuery(1,()=>this.parse._().getValue().ast),errors:this.createQuery(2,()=>this.parse._().getErrors()),tokens:this.createQuery(4,()=>this.parse._().getValue().tokens),rawDb:this.createQuery(3,()=>this.parse._().getValue().rawDb),publicSymbolTable:this.createQuery(5,()=>this.parse._().getValue().ast.symbol.symbolTable)},this.container={stack:this.createQuery(10,e=>{const n=this.parse.tokens();let{index:s}=this.container.token(e);const{token:i}=this.container.token(e);if(s===void 0)return[this.parse.ast()];for(;n[s].isInvalid&&s>=0;)s-=1;if(s===-1)return[this.parse.ast()];const r=n[s].start;let a=this.parse.ast();const l=[a];for(;;){const h=rn(a).find(T=>be(r,T));if(h===void 0||h instanceof B)break;l.push(h),a=h}if((i==null?void 0:i.kind)===c.COLON)return l;for(;l.length>0;){let p=!1;const h=I.last(l);if(h instanceof k){const T=this.parse.source();for(let f=h.end;f<e;f+=1)T[f]===`
8
8
  `&&(l.pop(),p=!0)}else h instanceof q||h instanceof Q?this.container.token(e).token!==h.op&&(l.pop(),p=!0):h instanceof P?h.listCloseBracket&&h.end<=e&&(l.pop(),p=!0):h instanceof J?h.tupleCloseParen&&h.end<=e&&(l.pop(),p=!0):h instanceof te?h.blockCloseBrace&&h.end<=e&&(l.pop(),p=!0):h instanceof K||h.end<e&&(l.pop(),p=!0);if(p){const T=I.last(l);T instanceof _&&T.end<=e&&l.pop()}if(!p)break}return l}),token:this.createQuery(11,e=>{const n=this.token.flatStream().findIndex(s=>s.start>=e);return n===void 0?{token:void 0,index:void 0}:n<=0?{token:void 0,index:void 0}:{token:this.token.flatStream()[n-1],index:n-1}}),element:this.createQuery(12,e=>{const n=this.container.stack(e);for(let s=n.length-1;s>=0;s-=1)if(n[s]instanceof _)return n[s];return this.parse.ast()}),scope:this.createQuery(14,e=>{var n,s;return(s=(n=this.container.element(e))==null?void 0:n.symbol)==null?void 0:s.symbolTable}),scopeKind:this.createQuery(15,e=>{var s;if(this.container.element(e)instanceof C)return 8;switch((s=this.container.element(e).type)==null?void 0:s.value.toLowerCase()){case"table":return 0;case"enum":return 1;case"ref":return 5;case"tablegroup":return 2;case"indexes":return 3;case"note":return 4;case"project":return 6;default:return 7}})},this.symbol={ofName:this.createQuery(8,({nameStack:e,owner:n=this.parse.ast()})=>{var i;if(e.length===0)return[];const s=[];for(let r=n;r;r=r instanceof _?r.parent:void 0){if(!((i=r.symbol)!=null&&i.symbolTable))continue;const{symbolTable:a}=r.symbol;let l=[a],p=[];for(const h of e)p=l.flatMap(T=>zt(h).flatMap(f=>{const N=T.get(f),g=se(f).unwrap_or(void 0);return!N||!g?[]:{...g,symbol:N}})),l=p.flatMap(T=>T.symbol.symbolTable?T.symbol.symbolTable:[]);s.push(...p)}return s},({nameStack:e,owner:n})=>`${e.join(".")}@${n.id}`),members:this.createQuery(9,e=>e.symbolTable?[...e.symbolTable.entries()].map(([n,s])=>({...se(n).unwrap(),symbol:s})):[])}}createQuery(e,n,s){return i=>{const r=this.cache[e],a=i&&s?s(i):i;if(r!==null){if(!(r instanceof Map))return r;if(r.has(a))return r.get(a)}const l=n(i);return i!==void 0?r instanceof Map?r.set(a,l):(this.cache[e]=new Map,this.cache[e].set(a,l)):this.cache[e]=l,l}}setSource(e){this.source=e,this.cache=new Array(16).fill(null),this.nodeIdGenerator.reset(),this.symbolIdGenerator.reset()}initMonacoServices(){return{definitionProvider:new Gt(this),referenceProvider:new Ct(this),autocompletionProvider:new Mt(this)}}}exports.Compiler=rs;exports.serialize=jt;exports.services=is;
@@ -3210,7 +3210,7 @@ class Dt {
3210
3210
  ];
3211
3211
  if (e.args[0]) {
3212
3212
  const g = z(e.args[0]).getValue();
3213
- this.ref.onDelete = G((T = (h = g.delete) == null ? void 0 : h.at(0)) == null ? void 0 : T.value).unwrap_or(void 0), this.ref.onDelete = G((N = (f = g.delete) == null ? void 0 : f.at(0)) == null ? void 0 : N.value).unwrap_or(void 0);
3213
+ this.ref.onDelete = G((T = (h = g.delete) == null ? void 0 : h.at(0)) == null ? void 0 : T.value).unwrap_or(void 0), this.ref.onUpdate = G((N = (f = g.update) == null ? void 0 : f.at(0)) == null ? void 0 : N.value).unwrap_or(void 0);
3214
3214
  }
3215
3215
  const p = xt(n);
3216
3216
  return this.ref.endpoints = [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dbml/parse",
3
- "version": "3.1.6",
3
+ "version": "3.1.7",
4
4
  "description": "> TODO: description",
5
5
  "author": "Holistics <dev@holistics.io>",
6
6
  "license": "Apache-2.0",
@@ -45,5 +45,5 @@
45
45
  "peerDependencies": {
46
46
  "lodash": "^4.17.21"
47
47
  },
48
- "gitHead": "f82965d9636209e22f31794111f37e05c5da79ce"
48
+ "gitHead": "b6e3cf786827e6c71950ab4c6a150a9f16da7aa2"
49
49
  }