@dbml/parse 3.8.1 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/compiler.d.ts +0 -1
  2. package/dist/dbml-parse.js +1 -1
  3. package/dist/dbml-parse.mjs +1 -1
  4. package/dist/index.d.ts +0 -1
  5. package/dist/lib/analyzer/analyzer.d.ts +0 -1
  6. package/dist/lib/analyzer/binder/binder.d.ts +0 -1
  7. package/dist/lib/analyzer/binder/elementBinder/custom.d.ts +0 -1
  8. package/dist/lib/analyzer/binder/elementBinder/elementBinder.d.ts +0 -1
  9. package/dist/lib/analyzer/binder/elementBinder/enum.d.ts +0 -1
  10. package/dist/lib/analyzer/binder/elementBinder/indexes.d.ts +0 -1
  11. package/dist/lib/analyzer/binder/elementBinder/note.d.ts +0 -1
  12. package/dist/lib/analyzer/binder/elementBinder/project.d.ts +0 -1
  13. package/dist/lib/analyzer/binder/elementBinder/ref.d.ts +0 -1
  14. package/dist/lib/analyzer/binder/elementBinder/table.d.ts +0 -1
  15. package/dist/lib/analyzer/binder/elementBinder/tableGroup.d.ts +0 -1
  16. package/dist/lib/analyzer/binder/types.d.ts +16 -0
  17. package/dist/lib/analyzer/binder/utils.d.ts +0 -1
  18. package/dist/lib/analyzer/symbol/factory.d.ts +0 -1
  19. package/dist/lib/analyzer/symbol/symbolIndex.d.ts +0 -1
  20. package/dist/lib/analyzer/symbol/symbolTable.d.ts +0 -1
  21. package/dist/lib/analyzer/symbol/symbols.d.ts +0 -1
  22. package/dist/lib/analyzer/symbol/utils.d.ts +0 -1
  23. package/dist/lib/analyzer/utils.d.ts +0 -1
  24. package/dist/lib/analyzer/validator/elementValidators/custom.d.ts +0 -1
  25. package/dist/lib/analyzer/validator/elementValidators/enum.d.ts +0 -1
  26. package/dist/lib/analyzer/validator/elementValidators/indexes.d.ts +0 -1
  27. package/dist/lib/analyzer/validator/elementValidators/note.d.ts +0 -1
  28. package/dist/lib/analyzer/validator/elementValidators/project.d.ts +0 -1
  29. package/dist/lib/analyzer/validator/elementValidators/ref.d.ts +0 -1
  30. package/dist/lib/analyzer/validator/elementValidators/table.d.ts +0 -1
  31. package/dist/lib/analyzer/validator/elementValidators/tableGroup.d.ts +0 -1
  32. package/dist/lib/analyzer/validator/types.d.ts +4 -0
  33. package/dist/lib/analyzer/validator/utils.d.ts +0 -1
  34. package/dist/lib/analyzer/validator/validator.d.ts +0 -1
  35. package/dist/lib/errors.d.ts +0 -1
  36. package/dist/lib/interpreter/elementInterpreter/enum.d.ts +0 -1
  37. package/dist/lib/interpreter/elementInterpreter/project.d.ts +0 -1
  38. package/dist/lib/interpreter/elementInterpreter/ref.d.ts +0 -1
  39. package/dist/lib/interpreter/elementInterpreter/sticky_note.d.ts +0 -1
  40. package/dist/lib/interpreter/elementInterpreter/table.d.ts +0 -1
  41. package/dist/lib/interpreter/elementInterpreter/tableGroup.d.ts +0 -1
  42. package/dist/lib/interpreter/interpreter.d.ts +0 -1
  43. package/dist/lib/interpreter/types.d.ts +168 -0
  44. package/dist/lib/interpreter/utils.d.ts +0 -1
  45. package/dist/lib/lexer/lexer.d.ts +0 -1
  46. package/dist/lib/lexer/tokens.d.ts +0 -1
  47. package/dist/lib/lexer/utils.d.ts +0 -1
  48. package/dist/lib/parser/contextStack.d.ts +0 -1
  49. package/dist/lib/parser/factory.d.ts +0 -1
  50. package/dist/lib/parser/nodes.d.ts +0 -1
  51. package/dist/lib/parser/parser.d.ts +0 -1
  52. package/dist/lib/parser/utils.d.ts +0 -1
  53. package/dist/lib/serialization/serialize.d.ts +0 -1
  54. package/dist/lib/types.d.ts +5 -0
  55. package/dist/lib/utils.d.ts +0 -1
  56. package/dist/services/definition/provider.d.ts +0 -1
  57. package/dist/services/index.d.ts +0 -1
  58. package/dist/services/references/provider.d.ts +0 -1
  59. package/dist/services/suggestions/provider.d.ts +0 -1
  60. package/dist/services/suggestions/utils.d.ts +0 -1
  61. package/dist/services/types.d.ts +0 -1
  62. package/dist/services/utils.d.ts +0 -1
  63. package/package.json +3 -4
@@ -7,7 +7,6 @@ import { default as Report } from './lib/report';
7
7
  import { SyntaxToken } from './lib/lexer/tokens';
8
8
  import { Database } from './lib/interpreter/types';
9
9
  import { DBMLCompletionItemProvider, DBMLDefinitionProvider, DBMLReferencesProvider } from './services/index';
10
-
11
10
  export declare const enum ScopeKind {
12
11
  TABLE = 0,
13
12
  ENUM = 1,
@@ -6,7 +6,7 @@
6
6
  `,{allowNewline:!0,allowEof:!0,raw:!0,consumeStopSequence:!1})}multilineComment(){this.consumeUntil(u.MULTILINE_COMMENT,"*/",{allowNewline:!0,allowEof:!1,raw:!0})}identifier(){for(;!this.isAtEnd()&&Ee(this.peek());)this.advance();this.addToken(u.IDENTIFIER)}operator(){for(;rt(this.peek());)this.advance();this.addToken(u.OP)}numericLiteralOrIdentifier(){let e=0;if(this.isAtEnd())return this.addToken(u.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(u.NUMERIC_LITERAL);if(!n&&!Ee(this.peek()))return this.addToken(u.NUMERIC_LITERAL);if(!n&&!De(this.peek()))break;this.advance()}if(e>0){for(;!this.isAtEnd()&&(this.check(".")||Ee(this.peek()));)this.advance();const n=this.createToken(u.NUMERIC_LITERAL,!0);this.tokens.push(n),this.errors.push(new c(o.UNKNOWN_TOKEN,"Invalid number",n))}else{for(;!this.isAtEnd()&&Ee(this.peek());)this.advance();const n=this.createToken(u.IDENTIFIER,!1);this.tokens.push(n)}}colorLiteral(){for(;!this.isAtEnd()&&Ee(this.peek());)this.advance();this.addToken(u.COLOR_LITERAL)}escapedString(){const e={column:this.current.column-1,offset:this.current.offset-1,line:this.current.line};if(this.isAtEnd())return"\\";switch(this.advance()){case"\r":return this.check(`
7
7
  `)&&this.advance(),"";case`
8
8
  `:return"";case"t":return" ";case"n":return`
9
- `;case"\\":return"\\";case"r":return"\r";case"'":return this.peek()==="'"&&this.peek(1)==="'"?(this.advance(),this.advance(),"'''"):"'";case'"':return'"';case"0":return"\0";case"b":return"\b";case"v":return"\v";case"f":return"\f";case" ":return"\\ ";case"u":{let n="";for(let s=0;s<=3;s+=1){if(this.isAtEnd()||!Ee(this.peek()))return this.errors.push(new c(o.INVALID_ESCAPE_SEQUENCE,`Invalid unicode escape sequence '\\u${n}', only unicode escape sequences of the form '\\uHHHH' where H is a hexadecimal number are allowed`,F.create(u.STRING_LITERAL,e,this.current,`\\u${n}`,!0))),`\\u${n}`;n+=this.advance()}return String.fromCharCode(parseInt(n,16))}default:return this.text[this.current.offset-1]}}}var Se=(t=>(t[t.ListExpression=0]="ListExpression",t[t.GroupExpression=1]="GroupExpression",t[t.BlockExpression=2]="BlockExpression",t))(Se||{});class hn{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 b.last(this.stack)}isWithinGroupExpressionContext(){return this.numberOfNestedLParens>0}isWithinListExpressionContext(){return this.numberOfNestedLBrackets>0}isWithinBlockExpressionContext(){return this.numberOfNestedLBraces>0}withContextDo(e,n){return()=>{this.push(e);try{return n()}finally{this.pop()}}}findHandlerContext(e,n){if(!(this.numberOfNestedLBraces<=0&&this.numberOfNestedLBrackets<=0&&this.numberOfNestedLParens<=0))for(let s=n;s<e.length-1;s+=1)switch(e[s].kind){case u.COMMA:if(this.isWithinGroupExpressionContext()||this.isWithinListExpressionContext())return[...this.stack].reverse().find(r=>[1,0].includes(r));break;case u.RPAREN:if(this.isWithinGroupExpressionContext())return 1;break;case u.RBRACE:if(this.isWithinBlockExpressionContext())return 2;break;case u.RBRACKET:if(this.isWithinListExpressionContext())return 0;break}}}class fn{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 pn{constructor(e,n){this.current=0,this.errors=[],this.contextStack=new hn,this.synchronizeProgram=()=>{const s=this.peek();s.kind!==u.EOF?N(this.advance()):(N(this.peek()),this.logError(s,o.UNEXPECTED_EOF,"Unexpected EOF"))},this.synchronizeElementDeclarationName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(ct(s)||this.check(u.COLON,u.LBRACE,u.LBRACKET))break;N(s),this.advance()}},this.synchronizeElementDeclarationAlias=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.COLON,u.LBRACE,u.LBRACKET))break;N(s),this.advance()}},this.blockExpression=this.contextStack.withContextDo(Se.BlockExpression,()=>{const s={body:[]},i=()=>this.nodeFactory.create(J,s);try{this.consume("Expect an opening brace '{'",u.LBRACE),s.blockOpenBrace=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.blockOpenBrace=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}for(;!this.isAtEnd()&&!this.check(u.RBRACE);)try{s.body.push(this.canBeField()?this.fieldDeclaration():this.expression())}catch(r){if(!(r instanceof d))throw r;if(s.body.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}try{this.consume("Expect a closing brace '}'",u.RBRACE),s.blockCloseBrace=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.blockCloseBrace=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}return i()}),this.synchronizeBlock=()=>{if(!this.check(u.RBRACE))for(N(this.advance());!this.isAtEnd();){const s=this.peek();if(this.check(u.RBRACE)||ot(this.previous(),s))break;N(s),this.advance()}},this.tupleExpression=this.contextStack.withContextDo(Se.GroupExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(We,{groupOpenParen:s.tupleOpenParen,groupCloseParen:s.tupleCloseParen,expression:s.elementList[0]}),r=()=>this.nodeFactory.create(Z,s);try{this.consume("Expect an opening parenthesis '('",u.LPAREN),s.tupleOpenParen=this.previous()}catch(a){if(!(a instanceof d))throw a;if(s.tupleOpenParen=a.partialNode,!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}if(!this.isAtEnd()&&!this.check(u.RPAREN))try{s.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof d))throw a;if(s.elementList.push(a.partialNode),!this.canHandle(a))throw new d(a.token,i(),a.handlerContext);this.synchronizeTuple()}for(;!this.isAtEnd()&&!this.check(u.RPAREN);)try{this.consume("Expect a comma ','",u.COMMA),s.commaList.push(this.previous()),s.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof d))throw a;if(a.partialNode instanceof x&&s.elementList.push(a.partialNode),!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}try{this.consume("Expect a closing parenthesis ')'",u.RPAREN),s.tupleCloseParen=this.previous()}catch(a){if(!(a instanceof d))throw a;if(s.tupleCloseParen=a.partialNode,!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}return s.elementList.length===1?i():r()}),this.synchronizeTuple=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.RPAREN,u.COMMA))break;N(s),this.advance()}},this.listExpression=this.contextStack.withContextDo(Se.ListExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(R,s);try{this.consume("Expect an opening bracket '['",u.LBRACKET),s.listOpenBracket=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.listOpenBracket=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}if(!this.isAtEnd()&&!this.check(u.RBRACKET))try{s.elementList.push(this.attribute())}catch(r){if(!(r instanceof d))throw r;if(s.elementList.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}for(;!this.isAtEnd()&&!this.check(u.RBRACKET);)try{this.consume("Expect a comma ','",u.COMMA),s.commaList.push(this.previous()),s.elementList.push(this.attribute())}catch(r){if(!(r instanceof d))throw r;if(r.partialNode instanceof x&&s.elementList.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}try{this.consume("Expect a closing bracket ']'",u.RBRACKET),s.listCloseBracket=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.listCloseBracket=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}return i()}),this.synchronizeList=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.COMMA,u.RBRACKET))break;N(s),this.advance()}},this.synchronizeAttributeName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.COMMA,u.RBRACKET,u.COLON))break;N(s),this.advance()}},this.synchronizeAttributeValue=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.COMMA,u.RBRACKET))break;N(s),this.advance()}},this.tokens=e,this.nodeFactory=new fn(n)}isAtEnd(){return this.current>=this.tokens.length||this.tokens[this.current].kind===u.EOF}advance(){return this.isAtEnd()?b.last(this.tokens):this.tokens[this.current++]}peek(e=0){return e+this.current>=this.tokens.length?b.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(N(this.peek()),this.logError(this.advance(),o.UNEXPECTED_TOKEN,e);!this.isAtEnd()&&!this.check(...n);)N(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(X,{body:e,eof:n});return this.gatherInvalid(),new V({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(v,e);try{this.consume("Expect an identifier",u.IDENTIFIER),e.type=this.previous()}catch(s){throw s instanceof d?(e.type=s.partialNode,new d(s.token,n(),s.handlerContext)):s}if(!this.check(u.COLON,u.LBRACE,u.LBRACKET))try{e.name=this.normalExpression()}catch(s){if(!(s instanceof d))throw s;if(e.name=s.partialNode,!this.canHandle(s))throw new d(s.token,n(),s.handlerContext);this.synchronizeElementDeclarationName()}if(ct(this.peek()))if(e.as=this.advance(),this.check(u.COLON,u.LBRACE,u.LBRACKET))this.logError(this.peek(),o.UNEXPECTED_TOKEN,"Expect an alias");else try{e.alias=this.normalExpression()}catch(s){if(!(s instanceof d))throw s;if(e.alias=s.partialNode,!this.canHandle(s))throw new d(s.token,n(),s.handlerContext);this.synchronizeElementDeclarationAlias()}try{e.attributeList=this.check(u.LBRACKET)?this.listExpression():void 0}catch(s){throw s instanceof d?(e.attributeList=s.partialNode,new d(s.token,n(),s.handlerContext)):s}if(!this.discardUntil("Expect an opening brace '{' or a colon ':'",u.LBRACE,u.COLON))return n();try{if(this.match(u.COLON)){e.bodyColon=this.previous();const s=this.expression();s instanceof v?(N(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(v,e)}fieldDeclaration(){const e={},n=()=>this.nodeFactory.create(v,e);try{this.consume("Expect an identifier",u.IDENTIFIER),e.type=this.previous()}catch(s){throw s instanceof d?(e.type=s.partialNode,new d(s.token,n(),s.handlerContext)):s}try{this.consume("Expect a colon ':'",u.COLON),e.bodyColon=this.previous()}catch(s){throw s instanceof d?(e.bodyColon=s.partialNode,new d(s.token,n(),s.handlerContext)):s}try{const s=this.expression();s instanceof v?this.errors.push(new c(o.INVALID_ELEMENT_IN_SIMPLE_BODY,"Simple body cannot be an element declaration",s)):e.body=s}catch(s){throw s instanceof d?(e.body=s.partialNode,new d(s.token,n(),s.handlerContext)):s}return this.nodeFactory.create(v,e)}expression(){const e={args:[]},n=()=>an(e.callee,e.args,this.nodeFactory).unwrap_or(this.nodeFactory.create(w,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();){Ce(this.previous())||this.logError(s,o.MISSING_SPACES,"Expect a following space");try{s=this.normalExpression(),e.args.push(s)}catch(i){throw i instanceof d?(s=i.partialNode,e.args.push(s),new d(i.token,n(),i.handlerContext)):i}}return n()}shouldStopExpression(){if(this.isAtEnd()||bt(this.previous()))return!0;const e=this.peek().kind;return e===u.RBRACE||e===u.RBRACKET||e===u.RPAREN||e===u.COMMA||e===u.COLON}normalExpression(){return this.expression_bp(0)}expression_bp(e){let n=this.leftExpression_bp();for(;!this.isAtEnd();){const s=this.peek();if(s.kind===u.LPAREN){const{left:i}=ut(s);if(i<e||ot(this.previous(),s)&&!this.contextStack.isWithinGroupExpressionContext()&&!this.contextStack.isWithinListExpressionContext())break;try{n=this.nodeFactory.create(H,{callee:n,argumentList:this.tupleExpression()})}catch(r){throw r instanceof d?(n=this.nodeFactory.create(H,{callee:n,argumentList:r.partialNode}),new d(r.token,n,r.handlerContext)):r}}else if(s.kind===u.LBRACKET){if(Ce(this.previous()))break;try{n=this.nodeFactory.create(he,{expression:n,indexer:this.listExpression()})}catch(i){throw i instanceof d?(n=this.nodeFactory.create(he,{expression:n,indexer:i.partialNode}),new d(i.token,n,i.handlerContext)):i}}else if(at(s)){const i=s,r=ut(i);if(r.left!==null){if(r.left<=e)break;this.advance(),n=this.nodeFactory.create(Ue,{expression:n,op:i})}else{const a=En(i);if(a.left===null||a.left<=e)break;this.advance();try{n=this.nodeFactory.create(q,{leftExpression:n,op:i,rightExpression:i.value==="."?this.extractOperand():this.expression_bp(a.right)})}catch(l){throw l instanceof d?(n=this.nodeFactory.create(q,{leftExpression:n,op:i,rightExpression:l.partialNode}),new d(l.token,n,l.handlerContext)):l}}}else break}return n}leftExpression_bp(){let e;if(at(this.peek())){const n={};n.op=this.peek();const s=mn(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(xe,{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 xe)throw new d(this.peek(),this.nodeFactory.create(xe,{pre:this.peek()}),this.contextStack.findHandlerContext(this.tokens,this.current));return e}extractOperand(){return this.check(u.NUMERIC_LITERAL,u.STRING_LITERAL,u.COLOR_LITERAL,u.QUOTED_STRING,u.IDENTIFIER)?this.primaryExpression():this.check(u.FUNCTION_EXPRESSION)?this.functionExpression():this.check(u.LBRACKET)?this.listExpression():this.check(u.LBRACE)?this.blockExpression():this.check(u.LPAREN)?this.tupleExpression():(this.peek().kind===u.EOF?this.logError(this.peek(),o.UNEXPECTED_EOF,"Unexpected EOF"):this.logError(this.peek(),o.INVALID_OPERAND,`Invalid start of operand "${this.peek().value}"`),this.nodeFactory.create(xe,{pre:this.previous()}))}functionExpression(){const e={};try{this.consume("Expect a function expression",u.FUNCTION_EXPRESSION),e.value=this.previous()}catch(n){throw n instanceof d?(e.value=n.partialNode,new d(n.token,this.nodeFactory.create(ne,e),n.handlerContext)):n}return this.nodeFactory.create(ne,e)}canBeField(){return this.peek().kind===u.IDENTIFIER&&this.peek(1).kind===u.COLON}primaryExpression(){if(this.match(u.COLOR_LITERAL,u.STRING_LITERAL,u.NUMERIC_LITERAL))return this.nodeFactory.create(U,{expression:this.nodeFactory.create(be,{literal:this.previous()})});if(this.match(u.QUOTED_STRING,u.IDENTIFIER))return this.nodeFactory.create(U,{expression:this.nodeFactory.create(K,{variable:this.previous()})});throw this.logError(this.peek(),o.UNEXPECTED_TOKEN,"Expect a variable or literal"),new d(this.peek(),void 0,this.contextStack.findHandlerContext(this.tokens,this.current))}attribute(){const e={};if(this.check(u.COLON,u.RBRACKET,u.COMMA)){const n=this.peek();this.logError(n,o.EMPTY_ATTRIBUTE_NAME,"Expect a non-empty attribute name"),e.name=this.nodeFactory.create(Y,{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(se,e),n.handlerContext);this.synchronizeAttributeName()}return this.match(u.COLON)&&(e.colon=this.previous(),e.value=this.attributeValue()),this.nodeFactory.create(se,e)}attributeValue(){let e;try{e=this.peek().kind===u.IDENTIFIER&&this.peek(1).kind===u.IDENTIFIER?this.attributeName():this.normalExpression()}catch(n){if(!(n instanceof d)||!this.canHandle(n))throw n;e=n.partialNode,this.synchronizeAttributeValue()}return e}attributeName(){const e=[];if(this.peek().kind!==u.IDENTIFIER)return this.primaryExpression();for(;!this.isAtEnd()&&!this.check(u.COLON,u.COMMA,u.RBRACKET);)try{this.consume("Expect an identifier",u.IDENTIFIER),e.push(this.previous())}catch(n){throw n instanceof d?new d(n.token,this.nodeFactory.create(Y,{identifiers:e}),n.handlerContext):n}return this.nodeFactory.create(Y,{identifiers:e})}logError(e,n,s){this.errors.push(new c(n,s,e))}}const dn={"+":{left:9,right:10},"*":{left:11,right:12},"-":{left:9,right:10},"/":{left:11,right:12},"%":{left:11,right:12},"<":{left:7,right:8},"<=":{left:7,right:8},">":{left:7,right:8},">=":{left:7,right:8},"<>":{left:7,right:8},"=":{left:2,right:3},"==":{left:4,right:5},"!=":{left:4,right:5},".":{left:16,right:17}};function En(t){return dn[t.value]||{left:null,right:null}}const Nn={"+":{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 mn(t){return Nn[t.value]||{left:null,right:null}}const Tn={"(":{left:14,right:null}};function ut(t){return Tn[t.value]||{left:null,right:null}}var I=(t=>(t.Table="table",t.Enum="enum",t.Ref="ref",t.Note="note",t.Project="project",t.Indexes="indexes",t.TableGroup="tablegroup",t))(I||{});function ve(t){var n;const e=(n=t==null?void 0:t.type)==null?void 0:n.value.toLowerCase();switch(e){case I.Enum:case I.Table:case I.Indexes:case I.Note:case I.Project:case I.Ref:case I.TableGroup:return new S(e);default:return new k}}function pe(t){if(!Je(t))return new S([t]);const e=pe(t.leftExpression).unwrap_or(void 0);return e?(e.push(t.rightExpression),new S(e)):new k}function W(t){if(t===void 0)return new k;const e=pe(t).unwrap_or(void 0);if(!e)return new k;const n=[];for(const s of e){const i=j(s).unwrap_or(void 0);if(!i)return new k;n.push(i)}return new S(n)}function _e(t){if(t===void 0)return new k;const e=pe(t).unwrap_or(void 0);if(!e||e.length===0)return new k;const n=[];let s;if(!M(b.last(e))){const i=e.pop();if(St(i))s=i.elementList.map(r=>C(r).unwrap());else return new k}for(const i of e){const r=j(i).unwrap_or(void 0);if(!r)return new k;n.push(r)}return new S({variables:n,tupleElements:s})}function j(t){return M(t)?new S(t.expression.variable.value):new k}function Xe(t){if(ht(t))return t instanceof ne?new S({functional:[t],nonFunctional:[]}):new S({functional:[],nonFunctional:[t]});if(t instanceof Z&&t.elementList.every(ht)){const e=t.elementList.filter(s=>s instanceof ne),n=t.elementList.filter(M);return new S({functional:e,nonFunctional:n})}return new k}function C(t){var n;const e=(n=t==null?void 0:t.expression.variable)==null?void 0:n.value;return e===void 0?new k:new S(e)}function G(t){return $(t)?t.expression instanceof K?new S(t.expression.variable.value):new S(t.expression.literal.value):new k}function bn(t){var e;return!(t instanceof q)||!kt((e=t.op)==null?void 0:e.value)?!1:_e(t.leftExpression).and_then(()=>_e(t.rightExpression)).unwrap_or(void 0)!==void 0}function In(t){const e=_e(t.leftExpression),n=_e(t.rightExpression);if(!e.isOk()||!n.isOk())return!1;const{tupleElements:s}=e.unwrap(),{tupleElements:i}=n.unwrap();return(s==null?void 0:s.length)===(i==null?void 0:i.length)}function ht(t){return t instanceof U&&t.expression instanceof K||t instanceof ne}function Ln(t,e){var i,r,a,l;let n=e;const s=Ht(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 X&&s)return n.symbol;if(n instanceof X)return;n=n.parent}}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 X||ve(this.declarationNode.parent).unwrap_or(void 0)!==I.Project?[new c(o.INVALID_CUSTOM_CONTEXT,"A custom element can only appear in a Project",this.declarationNode)]:[]}validateName(e){return e?[new c(o.UNEXPECTED_NAME,"A Custom element shouldn't have a name",e)]:[]}validateAlias(e){return e?[new c(o.UNEXPECTED_NAME,"A Custom element shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"A Custom element shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof J)return[new c(o.UNEXPECTED_COMPLEX_BODY,"A Custom element can only have an inline field",e)];const n=[];return $(e.callee)||n.push(new c(o.INVALID_CUSTOM_ELEMENT_VALUE,"A Custom element value can only be a string",e)),e.args.length>0&&n.push(...e.args.map(s=>new c(o.INVALID_CUSTOM_ELEMENT_VALUE,"A Custom element value can only be a string",s))),n}}class we{constructor(){this.table=new Map}has(e){return this.table.has(e)}set(e,n){this.table.set(e,n)}get(e,n){return this.table.get(e)||n!==void 0&&this.set(e,n)||n}entries(){return this.table.entries()}}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.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof v?[new c(o.INVALID_PROJECT_CONTEXT,"An Enum can only appear top-level",this.declarationNode)]:[]}validateName(e){return e?yt(e)?[]:[new c(o.INVALID_NAME,"An Enum name must be of the form <enum> or <schema>.<enum>",e)]:[new c(o.NAME_NOT_FOUND,"An Enum must have a name",this.declarationNode)]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}registerElement(){const e=[];this.declarationNode.symbol=this.symbolFactory.create(en,{declaration:this.declarationNode,symbolTable:new we});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=ze(r);a.has(l)&&e.push(new c(o.DUPLICATE_NAME,`Enum name ${r} already exists in schema '${i.join(".")||"public"}'`,n)),a.set(l,this.declarationNode.symbol)}return e}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"An Enum shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return this.validateFields([e]);const[n,s]=b.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.length===0?[new c(o.EMPTY_ENUM,"An Enum must have at least one element",this.declarationNode)]:e.flatMap(n=>{const s=[];n.callee&&!M(n.callee)&&s.push(new c(o.INVALID_ENUM_ELEMENT_NAME,"An enum field must be an identifier or a quoted identifier",n.callee));const i=[...n.args];return b.last(i)instanceof R?(s.push(...this.validateFieldSettings(b.last(i))),i.pop()):i[0]instanceof R&&(s.push(...this.validateFieldSettings(i[0])),i.shift()),i.length>0&&s.push(...i.map(r=>new c(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=B(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"note":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_ENUM_ELEMENT_SETTING,"'note' can only appear once",l))),a.forEach(l=>{$(l.value)||s.push(new c(o.INVALID_ENUM_ELEMENT_SETTING,"'note' must be a string",l))});break;default:a.forEach(l=>s.push(new c(o.UNKNOWN_ENUM_ELEMENT_SETTING,`Unknown enum field setting '${r}'`,l)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ae(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}registerField(e){if(e.callee&&M(e.callee)){const n=C(e.callee).unwrap(),s=Qe(n),i=this.symbolFactory.create(tn,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(s)){const a=r.get(s);return[new c(o.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,e),new c(o.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,a.declaration)]}r.set(s,i)}return[]}}class An{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof X||ve(this.declarationNode.parent).unwrap_or(void 0)!==I.Table?[new c(o.INVALID_NOTE_CONTEXT,"An Indexes can only appear inside a Table",this.declarationNode)]:[]}validateName(e){return e?[new c(o.UNEXPECTED_NAME,"An Indexes shouldn't have a name",e)]:[]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"An Indexes shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"An Indexes shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return[new c(o.UNEXPECTED_SIMPLE_BODY,"An Indexes must have a complex body",e)];const[n,s]=b.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.flatMap(n=>{if(!n.callee)return[];const s=[],i=[n.callee,...n.args];return b.last(i)instanceof R&&s.push(...this.validateFieldSetting(i.pop())),i.forEach(r=>{for(;r instanceof H;)r.argumentList&&!Xe(r.argumentList).isOk()&&s.push(new c(o.INVALID_INDEXES_FIELD,"An index field must be an identifier, a quoted identifier, a functional expression or a tuple of such",r.argumentList)),r=r.callee;Xe(r).isOk()||s.push(new c(o.INVALID_INDEXES_FIELD,"An index field must be an identifier, a quoted identifier, a functional expression or a tuple of such",r))}),s})}validateFieldSetting(e){const n=B(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"note":case"name":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_INDEX_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{$(l.value)||s.push(new c(o.INVALID_INDEX_SETTING_VALUE,`'${r}' must be a string`,l))});break;case"unique":case"pk":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_INDEX_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{ue(l.value)||s.push(new c(o.INVALID_INDEX_SETTING_VALUE,`'${r}' must not have a value`,l))});break;case"type":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_INDEX_SETTING,"'type' can only appear once",l))),a.forEach(l=>{M(l.value)||s.push(new c(o.INVALID_INDEX_SETTING_VALUE,`'type' must be "btree" or "hash"`,l))});break;default:a.forEach(l=>s.push(new c(o.UNKNOWN_INDEX_SETTING,`Unknown index setting '${r}'`,l)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ae(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class vn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return!(this.declarationNode.parent instanceof X)&&![I.Table,I.TableGroup,I.Project].includes(ve(this.declarationNode.parent).unwrap_or(void 0))?[new c(o.INVALID_NOTE_CONTEXT,"A Note can only appear inside a Table, a Table Group or a Project. Sticky note can only appear at the global scope.",this.declarationNode)]:[]}validateName(e){if(!(this.declarationNode.parent instanceof X))return e?[new c(o.UNEXPECTED_NAME,"A Note shouldn't have a name",e)]:[];if(!e)return[new c(o.INVALID_NAME,"Sticky note must have a name",this.declarationNode)];const n=W(e);if(!n.isOk())return[new c(o.INVALID_NAME,"Invalid name for sticky note ",this.declarationNode)];const i=n.unwrap().join("."),r=qt(i);return this.publicSymbolTable.has(r)?[new c(o.DUPLICATE_NAME,`Sticky note "${i}" has already been defined`,e)]:(this.publicSymbolTable.set(r,this.declarationNode.symbol),[])}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"A Note shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return this.validateFields([e]);const[n,s]=b.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){const n=[];return e.length===0?[new c(o.EMPTY_NOTE,"A Note must have a content",this.declarationNode)]:(e.length>1&&e.slice(1).forEach(s=>n.push(new c(o.NOTE_CONTENT_REDEFINED,"A Note can only contain one string",s))),$(e[0].callee)||n.push(new c(o.INVALID_NOTE,"A Note content must be a quoted string",e[0])),e[0].args.length>0&&n.push(...e[0].args.map(s=>new c(o.INVALID_NOTE,"A Note can only contain one quoted string",s))),n)}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ae(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class wn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof v?[new c(o.INVALID_PROJECT_CONTEXT,"A Project can only appear top-level",this.declarationNode)]:[]}validateName(e){return e?ye(e)?[]:[new c(o.INVALID_NAME,"A Project's name is optional or must be an identifier or a quoted identifer",e)]:[]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A Project shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"A Project shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return[new c(o.UNEXPECTED_SIMPLE_BODY,"A Project's body must be a block",e)];const[n,s]=b.partition(e.body,i=>i instanceof w);return[...n.map(i=>new c(o.INVALID_PROJECT_FIELD,"A Project can not have inline fields",i)),...this.validateSubElements(s)]}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ae(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class yn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof X?[]:[new c(o.INVALID_REF_CONTEXT,"A Ref must appear top-level",this.declarationNode)]}validateName(e){return e?ye(e)?[]:[new c(o.INVALID_NAME,"A Ref's name is optional or must be an identifier or a quoted identifer",e)]:[]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"A Ref shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return this.validateFields([e]);const[n,s]=b.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){if(e.length===0)return[new c(o.EMPTY_REF,"A Ref must have at least one field",this.declarationNode)];const n=[];return e.length>1&&n.push(...e.slice(1).map(s=>new c(o.REF_REDEFINED,"A Ref can only contain one binary relationship",s))),e.forEach(s=>{s.callee&&!bn(s.callee)&&n.push(new c(o.INVALID_REF_FIELD,"A Ref field must be a binary relationship",s.callee)),s.callee&&!In(s.callee)&&n.push(new c(o.UNEQUAL_FIELDS_BINARY_REF,"Unequal fields in ref endpoints",s.callee));const i=[...s.args];b.last(i)instanceof R?(this.validateFieldSettings(b.last(i)),i.pop()):i[0]instanceof R&&(n.push(...this.validateFieldSettings(i[0])),i.shift()),i.length>0&&n.push(...i.map(r=>new c(o.INVALID_REF_FIELD,"A Ref field should only have a single binary relationship",r)))}),n}validateFieldSettings(e){const n=B(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"delete":case"update":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_REF_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{kn(l.value)||s.push(new c(o.INVALID_REF_SETTING_VALUE,`'${r}' can only have values "cascade", "no action", "set null", "set default" or "restrict"`,l))});break;default:a.forEach(l=>s.push(new c(o.UNKNOWN_REF_SETTING,`Unknown ref setting '${r}'`,l)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ae(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}function kn(t){if(!(M(t)&&t.expression.variable.kind!==u.QUOTED_STRING)&&!(t instanceof Y))return!1;let e;if(t instanceof Y?e=Te(t).unwrap_or(""):e=t.expression.variable.value,e)switch(e.toLowerCase()){case"cascade":case"no action":case"set null":case"set default":case"restrict":return!0;default:return!1}return!1}class xn{constructor(e,n,s){this.declarationNode=e,this.symbolFactory=s,this.publicSymbolTable=n}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof v?[new c(o.INVALID_TABLE_CONTEXT,"Table must appear top-level",this.declarationNode)]:[]}validateName(e){return e?e instanceof he?[new c(o.INVALID_NAME,"Invalid array as Table name, maybe you forget to add a space between the name and the setting list?",e)]:yt(e)?[]:[new c(o.INVALID_NAME,"A Table name must be of the form <table> or <schema>.<table>",e)]:[new c(o.NAME_NOT_FOUND,"A Table must have a name",this.declarationNode)]}validateAlias(e){return e?Rn(e)?[]:[new c(o.INVALID_ALIAS,"Table aliases can only contains alphanumeric and underscore unless surrounded by double quotes",e)]:[]}validateSettingList(e){const n=B(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"headercolor":a.length>1&&s.push(...a.map(l=>new c(o.DUPLICATE_TABLE_SETTING,"'headercolor' can only appear once",l))),a.forEach(l=>{xt(l.value)||s.push(new c(o.INVALID_TABLE_SETTING,"'headercolor' must be a color literal",l.value||l.name))});break;case"note":a.length>1&&s.push(...a.map(l=>new c(o.DUPLICATE_TABLE_SETTING,"'note' can only appear once",l))),a.forEach(l=>{$(l.value)||s.push(new c(o.INVALID_TABLE_SETTING,"'note' must be a string literal",l.value||l.name))});break;default:s.push(...a.map(l=>new c(o.INVALID_TABLE_SETTING,`Unknown '${r}' setting`,l)))}}return s}registerElement(){const e=[];this.declarationNode.symbol=this.symbolFactory.create(At,{declaration:this.declarationNode,symbolTable:new we});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=Oe(a);l.has(p)&&e.push(new c(o.DUPLICATE_NAME,`Table name '${a}' already exists in schema '${r.join(".")||"public"}'`,n)),l.set(p,this.declarationNode.symbol)}if(s&&ye(s)&&!On(s.expression.variable.value,i.unwrap_or([]))){const r=C(s).unwrap(),a=Oe(r);this.publicSymbolTable.has(a)&&e.push(new c(o.DUPLICATE_NAME,`Table name '${r}' already exists`,n)),this.publicSymbolTable.set(a,this.declarationNode.symbol)}return e}validateBody(e){if(!e)return[];if(e instanceof w)return[new c(o.UNEXPECTED_SIMPLE_BODY,"A Table's body must be a block",e)];const[n,s]=b.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.length===0?[new c(o.EMPTY_TABLE,"A Table must have at least one column",this.declarationNode)]:e.flatMap(n=>{if(!n.callee)return[];const s=[];n.args.length===0&&s.push(new c(o.INVALID_COLUMN,"A column must have a type",n.callee)),M(n.callee)||s.push(new c(o.INVALID_COLUMN_NAME,"A column name must be an identifier or a quoted identifier",n.callee)),n.args[0]&&!Sn(n.args[0])&&s.push(new c(o.INVALID_COLUMN_TYPE,"Invalid column type",n.args[0]));const i=n.args.slice(1);return s.push(...this.validateFieldSetting(i)),s.push(...this.registerField(n)),s})}registerField(e){if(e.callee&&M(e.callee)){const n=C(e.callee).unwrap(),s=Ye(n),i=this.symbolFactory.create(nn,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(s)){const a=r.get(s);return[new c(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,e),new c(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,a.declaration)]}r.set(s,i)}return[]}validateFieldSetting(e){if(!e.slice(0,-1).every(me)||!e.slice(-1).every(p=>me(p)||p instanceof R))return[...e.map(p=>new c(o.INVALID_COLUMN,"These fields must be some inline settings optionally ended with a setting list",p))];if(e.length===0)return[];let n;b.last(e)instanceof R&&(n=e.pop());const s=B(n),i=s.getErrors(),r=s.getValue();for(const p of e){const f=C(p).unwrap_or("").toLowerCase();if(f!=="pk"&&f!=="unique"){i.push(new c(o.INVALID_SETTINGS,"Inline column settings can only be `pk` or `unique`",p));continue}r[f]===void 0?r[f]=[p]:r[f].push(p)}const a=r.pk||[],l=r["primary key"]||[];a.length>=1&&l.length>=1&&i.push(...[...a,...l].map(p=>new c(o.DUPLICATE_COLUMN_SETTING,"Either one of 'primary key' and 'pk' can appear",p)));for(const p in r){const f=r[p];switch(p){case"note":f.length>1&&i.push(...f.map(h=>new c(o.DUPLICATE_COLUMN_SETTING,"note can only appear once",h))),f.forEach(h=>{$(h.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'note' must be a quoted string",h.value||h.name))});break;case"ref":f.forEach(h=>{Un(h.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'ref' must be a valid unary relationship",h.value||h.name))});break;case"primary key":f.length>1&&i.push(...f.map(h=>new c(o.DUPLICATE_COLUMN_SETTING,"primary key can only appear once",h))),f.forEach(h=>{ue(h.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'primary key' must not have a value",h.value||h.name))});break;case"pk":f.length>1&&i.push(...f.map(h=>new c(o.DUPLICATE_COLUMN_SETTING,"'pk' can only appear once",h))),f.forEach(h=>{h instanceof se&&!ue(h.value)&&i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'pk' must not have a value",h.value||h.name))});break;case"not null":f.length>1&&i.push(...f.map(h=>new c(o.DUPLICATE_COLUMN_SETTING,"'not null' can only appear once",h)));const E=r.null||[];f.length>=1&&E.length>=1&&i.push(...[...f,...E].map(h=>new c(o.CONFLICTING_SETTING,"'not null' and 'null' can not be set at the same time",h))),f.forEach(h=>{ue(h.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'not null' must not have a value",h.value||h.name))});break;case"null":f.length>1&&i.push(...f.map(h=>new c(o.DUPLICATE_COLUMN_SETTING,"'null' can only appear once",h))),f.forEach(h=>{ue(h.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'null' must not have a value",h.value||h.name))});break;case"unique":f.length>1&&i.push(...f.map(h=>new c(o.DUPLICATE_COLUMN_SETTING,"'unique' can only appear once",h))),f.forEach(h=>{h instanceof se&&!ue(h.value)&&i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'unique' must not have a value",h.value||h.name))});break;case"increment":f.length>1&&i.push(...f.map(h=>new c(o.DUPLICATE_COLUMN_SETTING,"'increment' can only appear once",h))),f.forEach(h=>{h instanceof se&&!ue(h.value)&&i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'increment' must not have a value",h.value||h.name))});break;case"default":f.length>1&&i.push(...f.map(h=>new c(o.DUPLICATE_TABLE_SETTING,"'default' can only appear once",h))),f.forEach(h=>{Pn(h.value)||i.push(new c(o.INVALID_TABLE_SETTING,"'default' must be a string literal, number literal, function expression, true, false or null",h.value||h.name))});break;default:f.forEach(h=>i.push(new c(o.UNKNOWN_COLUMN_SETTING,`Unknown column setting '${p}'`,h)))}}return i}validateSubElements(e){const n=e.flatMap(i=>{if(i.parent=this.declarationNode,!i.type)return[];const r=ae(i);return new r(i,this.publicSymbolTable,this.symbolFactory).validate()}),s=e.filter(i=>{var r;return((r=i.type)==null?void 0:r.value.toLowerCase())==="note"});return s.length>1&&n.push(...s.map(i=>new c(o.NOTE_REDEFINED,"Duplicate notes are defined",i))),n}}function Sn(t){if(!(t instanceof H||Je(t)||t instanceof U||t instanceof he))return!1;if(t instanceof H){if(t.callee===void 0||t.argumentList===void 0||!t.argumentList.elementList.every(n=>fe(n)||$(n)||me(n)))return!1;t=t.callee}for(;t instanceof he;){if(t.array===void 0||t.indexer===void 0||!t.indexer.elementList.every(n=>!n.colon&&!n.value&&fe(n.name)))return!1;t=t.array}const e=W(t).unwrap_or(void 0);return e!==void 0&&e.length>0}function On(t,e){return e.length===1&&t===e[0]}class Dn{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 v?[new c(o.INVALID_TABLEGROUP_CONTEXT,"TableGroup must appear top-level",this.declarationNode)]:[]}validateName(e){return e?ye(e)?[]:[new c(o.INVALID_NAME,"A TableGroup name must be a single identifier",e)]:[new c(o.NAME_NOT_FOUND,"A TableGroup must have a name",this.declarationNode)]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A TableGroup shouldn't have an alias",e)]:[]}registerElement(){const{name:e}=this.declarationNode;this.declarationNode.symbol=this.symbolFactory.create(sn,{declaration:this.declarationNode,symbolTable:new we});const n=W(e);if(n.isOk()){const s=n.unwrap(),i=s.pop(),r=Ze(s,this.publicSymbolTable,this.symbolFactory),a=qe(i);if(r.has(a))return[new c(o.DUPLICATE_NAME,`TableGroup name '${i}' already exists`,e)];r.set(a,this.declarationNode.symbol)}return[]}validateSettingList(e){const n=B(e),s=n.getErrors(),i=n.getValue();return b.forIn(i,(r,a)=>{switch(a){case"color":r.length>1&&s.push(...r.map(l=>new c(o.DUPLICATE_TABLE_SETTING,"'color' can only appear once",l))),r.forEach(l=>{xt(l.value)||s.push(new c(o.INVALID_TABLE_SETTING,"'color' must be a color literal",l.value||l.name))});break;case"note":r.length>1&&s.push(...r.map(l=>new c(o.DUPLICATE_TABLE_SETTING,"'note' can only appear once",l))),r.filter(l=>!$(l.value)).forEach(l=>{s.push(new c(o.INVALID_TABLE_SETTING,"'note' must be a string literal",l.value||l.name))});break;default:s.push(...r.map(l=>new c(o.INVALID_TABLE_SETTING,`Unknown '${a}' setting`,l)));break}}),s}validateBody(e){if(!e)return[];if(e instanceof w)return[new c(o.UNEXPECTED_SIMPLE_BODY,"A TableGroup's body must be a block",e)];const[n,s]=b.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.flatMap(n=>{const s=[];return n.callee&&!W(n.callee).isOk()&&s.push(new c(o.INVALID_TABLEGROUP_FIELD,"A TableGroup field must be of the form <table> or <schema>.<table>",n.callee)),this.registerField(n),n.args.length>0&&s.push(...n.args.map(i=>new c(o.INVALID_TABLEGROUP_FIELD,"A TableGroup field should only have a single Table name",i))),s})}validateSubElements(e){const n=e.flatMap(i=>{if(i.parent=this.declarationNode,!i.type)return[];const r=ae(i);return new r(i,this.publicSymbolTable,this.symbolFactory).validate()}),s=e.filter(i=>{var r;return((r=i.type)==null?void 0:r.value.toLowerCase())==="note"});return s.length>1&&n.push(...s.map(i=>new c(o.NOTE_REDEFINED,"Duplicate notes are defined",i))),n}registerField(e){if(e.callee&&M(e.callee)){const n=C(e.callee).unwrap(),s=He(n),i=this.symbolFactory.create(rn,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(s)){const a=r.get(s);return[new c(o.DUPLICATE_TABLEGROUP_FIELD_NAME,`${n} already exists in the group`,e),new c(o.DUPLICATE_TABLEGROUP_FIELD_NAME,`${n} already exists in the group`,a.declaration)]}r.set(s,i)}return[]}}const wt=["-","+"];function ae(t){switch(t.type.value.toLowerCase()){case I.Enum:return _n;case I.Table:return xn;case I.TableGroup:return Dn;case I.Project:return wn;case I.Ref:return yn;case I.Note:return vn;case I.Indexes:return An;default:return gn}}function yt(t){return!!W(t).unwrap_or(!1)}function Rn(t){return ye(t)}function ye(t){return t instanceof U&&t.expression instanceof K}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=je(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 we;const p=n.create(_t,{symbolTable:a});s.set(l,p)}s=a}return s}function kt(t){return t==="-"||t==="<>"||t===">"||t==="<"}function xt(t){var n;if(!(t instanceof U)||!(t.expression instanceof be)||((n=t.expression.literal)==null?void 0:n.kind)!==u.COLOR_LITERAL)return!1;const e=t.expression.literal.value;if(e.length!==4&&e.length!==7||e[0]!=="#")return!1;for(let s=1;s<e.length;s+=1)if(!Zt(e[s]))return!1;return!0}function ue(t){return t===void 0}function Pn(t){var e;return!!($(t)||fe(t)||me(t)&&["true","false","null"].includes(t.expression.variable.value.toLowerCase())||t instanceof Q&&wt.includes((e=t.op)==null?void 0:e.value)&&fe(t.expression)||t instanceof ne)}function fe(t){var e;return t instanceof U&&t.expression instanceof be&&((e=t.expression.literal)==null?void 0:e.kind)===u.NUMERIC_LITERAL}function Un(t){var n;if(!(t instanceof Q)||!kt((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 St(t){return t instanceof Z&&t.elementList.every(M)}function B(t){var s;const e={},n=[];if(!t)return new V({});for(const i of t.elementList){if(!i.name)continue;if(i.name instanceof U){n.push(new c(o.INVALID_SETTINGS,"A setting name must be a stream of identifiers",i.name));continue}const r=(s=Te(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 V(e,n)}class ft{constructor(e,n){this.ast=e,this.symbolFactory=n,this.publicSchemaSymbol=this.symbolFactory.create(_t,{symbolTable:new we}),this.ast.symbol=this.publicSchemaSymbol,this.ast.symbol.declaration=this.ast}validate(){const e=[];this.ast.body.forEach(s=>{if(s.parent=this.ast,s.type===void 0)return;const i=ae(s),r=new i(s,this.publicSchemaSymbol.symbolTable,this.symbolFactory);e.push(...r.validate())});const n=this.ast.body.filter(s=>ve(s).unwrap_or(void 0)===I.Project);return n.length>1&&n.forEach(s=>e.push(new c(o.PROJECT_REDEFINED,"Only one project can exist",s))),new V(this.ast,e)}}class oe{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 U)continue;const i=Te(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 J)for(const s of n.body)if(s instanceof v){if(!s.type)continue;const i=Ot(s);new i(s,this.errors).bind()}else this.bindSubfield(s);else this.bindSubfield(n)}bindSubfield(e){const n=[e.callee,...e.args],s=b.last(n);s instanceof R&&(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 U){if(e.expression instanceof K&&((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?Je(e)?this.bindFragments(pe(e).unwrap_or([]),n):(this.scanAndBind(e.leftExpression,n),this.scanAndBind(e.rightExpression,n)):e instanceof Q?this.scanAndBind(e.expression,n):e instanceof Ue?this.scanAndBind(e.expression,n):e instanceof Z&&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(h=>!M(h)),l=r!==-1&&St(e[r])?e[r]:void 0,p=r>=0?s.pop():void 0,f=e.slice(0,r===-1?void 0:r);if(f.length===0)return;const E=[];for(;s.length&&f.length;){const h=s.pop(),m=f.pop(),g=C(m).unwrap();E.unshift({index:Ve(g,h),referrer:m})}for(;f.length;){const h=f.pop(),m=C(h).unwrap();E.unshift({index:Ve(m,i),referrer:h})}return l?l.elementList.forEach(h=>this.resolveIndexStack([...E,{index:Ve(C(h).unwrap(),p),referrer:h}],n.ignoreNameNotFound)):this.resolveIndexStack(E,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=Ln(s.index,this.declarationNode);if(r===void 0){const{kind:f,name:E}=ie(s.index).unwrap();this.logError(s.referrer,`Can not find ${f} '${E}'`,n);return}r.references.push(s.referrer),s.referrer.referee=r;let a=r.symbolTable,{kind:l,name:p}=ie(s.index).unwrap();for(const f of i){const{kind:E,name:h}=ie(f.index).unwrap(),m=a.get(f.index);if(!m){this.logError(f.referrer,`${l} '${p}' does not have ${E} '${h}'`,n);return}if(l=E,p=h,f.referrer.referee=m,m.references.push(f.referrer),!m.symbolTable)break;a=m.symbolTable}}logError(e,n,s){s||this.errors.push(new c(o.BINDING_ERROR,n,e))}}class Mn extends oe{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Fn extends oe{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Bn extends oe{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[T.Table,T.Column],remainingSubnamesSymbolKind:T.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[T.Table,T.Column],remainingSubnamesSymbolKind:T.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[T.Table,T.Column],remainingSubnamesSymbolKind:T.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[T.Table,T.Column],remainingSubnamesSymbolKind:T.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class Vn extends oe{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Gn extends oe{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Cn extends oe{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[T.Table,T.Column],remainingSubnamesSymbolKind:T.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class Xn extends oe{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1},{shouldBind:!0,topSubnamesSymbolKind:[T.Enum],remainingSubnamesSymbolKind:T.Schema,ignoreNameNotFound:!0}]},settingList:{ref:{shouldBind:!0,topSubnamesSymbolKind:[T.Table,T.Column],remainingSubnamesSymbolKind:T.Schema,ignoreNameNotFound:!1},default:{shouldBind:!1}}},this.settingList={}}}class $n extends oe{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[T.Table],remainingSubnamesSymbolKind:T.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}function Ot(t){switch(t.type.value.toLowerCase()){case I.Enum:return Fn;case I.Table:return Xn;case I.TableGroup:return $n;case I.Project:return Gn;case I.Ref:return Cn;case I.Note:return Vn;case I.Indexes:return Bn;default:return Mn}}class Wn{constructor(e){this.ast=e,this.errors=[]}resolve(){for(const e of this.ast.body)if(e.type){const n=Ot(e);new n(e,this.errors).bind()}return new V(this.ast,this.errors)}}class jn{constructor(e){this.generator=e}create(e,n){return new e(n,this.generator.nextId())}}class Yn{constructor(e,n){this.ast=e,this.symbolFactory=new jn(n)}analyze(){return new ft(this.ast,this.symbolFactory).validate().chain(n=>new Wn(n).resolve())}validate(){return new ft(this.ast,this.symbolFactory).validate().chain(n=>new V(n,[]))}}function pt(t,e){const{variables:n,tupleElements:s}=_e(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 Dt(t){switch(t){case"<":return["1","*"];case"<>":return["*","*"];case">":return["*","1"];case"-":return["1","1"]}throw new Error("Invalid relation op")}function A(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 $e(t){var n;const e=(n=pe(t).unwrap_or(void 0))==null?void 0:n.pop();return e instanceof Z?e.elementList.map(s=>s.referee):[e.referee]}function Ie(t){const e=W(t).unwrap();return{name:e.pop(),schemaName:e}}function Ke(t){return t.expression.literal.value}function Rt(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.toString(),s=e.id.toString();return n<s?`${n}-${s}`:`${s}-${n}`}function Pt(t,e){if(Array.isArray(t)){const i=t.map(({id:a})=>a).sort(),r=e.map(({id:a})=>a).sort();return b.zip(i,r).every(([a,l])=>a===l)}const n=t.id,s=e.id;return n===s}function re(t){const e=t.split(`
9
+ `;case"\\":return"\\";case"r":return"\r";case"'":return"'";case'"':return'"';case"0":return"\0";case"b":return"\b";case"v":return"\v";case"f":return"\f";case" ":return"\\ ";case"u":{let n="";for(let s=0;s<=3;s+=1){if(this.isAtEnd()||!Ee(this.peek()))return this.errors.push(new c(o.INVALID_ESCAPE_SEQUENCE,`Invalid unicode escape sequence '\\u${n}', only unicode escape sequences of the form '\\uHHHH' where H is a hexadecimal number are allowed`,F.create(u.STRING_LITERAL,e,this.current,`\\u${n}`,!0))),`\\u${n}`;n+=this.advance()}return String.fromCharCode(parseInt(n,16))}default:return this.text[this.current.offset-1]}}}var Se=(t=>(t[t.ListExpression=0]="ListExpression",t[t.GroupExpression=1]="GroupExpression",t[t.BlockExpression=2]="BlockExpression",t))(Se||{});class hn{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 b.last(this.stack)}isWithinGroupExpressionContext(){return this.numberOfNestedLParens>0}isWithinListExpressionContext(){return this.numberOfNestedLBrackets>0}isWithinBlockExpressionContext(){return this.numberOfNestedLBraces>0}withContextDo(e,n){return()=>{this.push(e);try{return n()}finally{this.pop()}}}findHandlerContext(e,n){if(!(this.numberOfNestedLBraces<=0&&this.numberOfNestedLBrackets<=0&&this.numberOfNestedLParens<=0))for(let s=n;s<e.length-1;s+=1)switch(e[s].kind){case u.COMMA:if(this.isWithinGroupExpressionContext()||this.isWithinListExpressionContext())return[...this.stack].reverse().find(r=>[1,0].includes(r));break;case u.RPAREN:if(this.isWithinGroupExpressionContext())return 1;break;case u.RBRACE:if(this.isWithinBlockExpressionContext())return 2;break;case u.RBRACKET:if(this.isWithinListExpressionContext())return 0;break}}}class fn{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 pn{constructor(e,n){this.current=0,this.errors=[],this.contextStack=new hn,this.synchronizeProgram=()=>{const s=this.peek();s.kind!==u.EOF?N(this.advance()):(N(this.peek()),this.logError(s,o.UNEXPECTED_EOF,"Unexpected EOF"))},this.synchronizeElementDeclarationName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(ct(s)||this.check(u.COLON,u.LBRACE,u.LBRACKET))break;N(s),this.advance()}},this.synchronizeElementDeclarationAlias=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.COLON,u.LBRACE,u.LBRACKET))break;N(s),this.advance()}},this.blockExpression=this.contextStack.withContextDo(Se.BlockExpression,()=>{const s={body:[]},i=()=>this.nodeFactory.create(J,s);try{this.consume("Expect an opening brace '{'",u.LBRACE),s.blockOpenBrace=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.blockOpenBrace=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}for(;!this.isAtEnd()&&!this.check(u.RBRACE);)try{s.body.push(this.canBeField()?this.fieldDeclaration():this.expression())}catch(r){if(!(r instanceof d))throw r;if(s.body.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}try{this.consume("Expect a closing brace '}'",u.RBRACE),s.blockCloseBrace=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.blockCloseBrace=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeBlock()}return i()}),this.synchronizeBlock=()=>{if(!this.check(u.RBRACE))for(N(this.advance());!this.isAtEnd();){const s=this.peek();if(this.check(u.RBRACE)||ot(this.previous(),s))break;N(s),this.advance()}},this.tupleExpression=this.contextStack.withContextDo(Se.GroupExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(We,{groupOpenParen:s.tupleOpenParen,groupCloseParen:s.tupleCloseParen,expression:s.elementList[0]}),r=()=>this.nodeFactory.create(Z,s);try{this.consume("Expect an opening parenthesis '('",u.LPAREN),s.tupleOpenParen=this.previous()}catch(a){if(!(a instanceof d))throw a;if(s.tupleOpenParen=a.partialNode,!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}if(!this.isAtEnd()&&!this.check(u.RPAREN))try{s.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof d))throw a;if(s.elementList.push(a.partialNode),!this.canHandle(a))throw new d(a.token,i(),a.handlerContext);this.synchronizeTuple()}for(;!this.isAtEnd()&&!this.check(u.RPAREN);)try{this.consume("Expect a comma ','",u.COMMA),s.commaList.push(this.previous()),s.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof d))throw a;if(a.partialNode instanceof x&&s.elementList.push(a.partialNode),!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}try{this.consume("Expect a closing parenthesis ')'",u.RPAREN),s.tupleCloseParen=this.previous()}catch(a){if(!(a instanceof d))throw a;if(s.tupleCloseParen=a.partialNode,!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}return s.elementList.length===1?i():r()}),this.synchronizeTuple=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.RPAREN,u.COMMA))break;N(s),this.advance()}},this.listExpression=this.contextStack.withContextDo(Se.ListExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(R,s);try{this.consume("Expect an opening bracket '['",u.LBRACKET),s.listOpenBracket=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.listOpenBracket=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}if(!this.isAtEnd()&&!this.check(u.RBRACKET))try{s.elementList.push(this.attribute())}catch(r){if(!(r instanceof d))throw r;if(s.elementList.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}for(;!this.isAtEnd()&&!this.check(u.RBRACKET);)try{this.consume("Expect a comma ','",u.COMMA),s.commaList.push(this.previous()),s.elementList.push(this.attribute())}catch(r){if(!(r instanceof d))throw r;if(r.partialNode instanceof x&&s.elementList.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}try{this.consume("Expect a closing bracket ']'",u.RBRACKET),s.listCloseBracket=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.listCloseBracket=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}return i()}),this.synchronizeList=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.COMMA,u.RBRACKET))break;N(s),this.advance()}},this.synchronizeAttributeName=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.COMMA,u.RBRACKET,u.COLON))break;N(s),this.advance()}},this.synchronizeAttributeValue=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.COMMA,u.RBRACKET))break;N(s),this.advance()}},this.tokens=e,this.nodeFactory=new fn(n)}isAtEnd(){return this.current>=this.tokens.length||this.tokens[this.current].kind===u.EOF}advance(){return this.isAtEnd()?b.last(this.tokens):this.tokens[this.current++]}peek(e=0){return e+this.current>=this.tokens.length?b.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(N(this.peek()),this.logError(this.advance(),o.UNEXPECTED_TOKEN,e);!this.isAtEnd()&&!this.check(...n);)N(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(X,{body:e,eof:n});return this.gatherInvalid(),new V({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(v,e);try{this.consume("Expect an identifier",u.IDENTIFIER),e.type=this.previous()}catch(s){throw s instanceof d?(e.type=s.partialNode,new d(s.token,n(),s.handlerContext)):s}if(!this.check(u.COLON,u.LBRACE,u.LBRACKET))try{e.name=this.normalExpression()}catch(s){if(!(s instanceof d))throw s;if(e.name=s.partialNode,!this.canHandle(s))throw new d(s.token,n(),s.handlerContext);this.synchronizeElementDeclarationName()}if(ct(this.peek()))if(e.as=this.advance(),this.check(u.COLON,u.LBRACE,u.LBRACKET))this.logError(this.peek(),o.UNEXPECTED_TOKEN,"Expect an alias");else try{e.alias=this.normalExpression()}catch(s){if(!(s instanceof d))throw s;if(e.alias=s.partialNode,!this.canHandle(s))throw new d(s.token,n(),s.handlerContext);this.synchronizeElementDeclarationAlias()}try{e.attributeList=this.check(u.LBRACKET)?this.listExpression():void 0}catch(s){throw s instanceof d?(e.attributeList=s.partialNode,new d(s.token,n(),s.handlerContext)):s}if(!this.discardUntil("Expect an opening brace '{' or a colon ':'",u.LBRACE,u.COLON))return n();try{if(this.match(u.COLON)){e.bodyColon=this.previous();const s=this.expression();s instanceof v?(N(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(v,e)}fieldDeclaration(){const e={},n=()=>this.nodeFactory.create(v,e);try{this.consume("Expect an identifier",u.IDENTIFIER),e.type=this.previous()}catch(s){throw s instanceof d?(e.type=s.partialNode,new d(s.token,n(),s.handlerContext)):s}try{this.consume("Expect a colon ':'",u.COLON),e.bodyColon=this.previous()}catch(s){throw s instanceof d?(e.bodyColon=s.partialNode,new d(s.token,n(),s.handlerContext)):s}try{const s=this.expression();s instanceof v?this.errors.push(new c(o.INVALID_ELEMENT_IN_SIMPLE_BODY,"Simple body cannot be an element declaration",s)):e.body=s}catch(s){throw s instanceof d?(e.body=s.partialNode,new d(s.token,n(),s.handlerContext)):s}return this.nodeFactory.create(v,e)}expression(){const e={args:[]},n=()=>an(e.callee,e.args,this.nodeFactory).unwrap_or(this.nodeFactory.create(w,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();){Ce(this.previous())||this.logError(s,o.MISSING_SPACES,"Expect a following space");try{s=this.normalExpression(),e.args.push(s)}catch(i){throw i instanceof d?(s=i.partialNode,e.args.push(s),new d(i.token,n(),i.handlerContext)):i}}return n()}shouldStopExpression(){if(this.isAtEnd()||bt(this.previous()))return!0;const e=this.peek().kind;return e===u.RBRACE||e===u.RBRACKET||e===u.RPAREN||e===u.COMMA||e===u.COLON}normalExpression(){return this.expression_bp(0)}expression_bp(e){let n=this.leftExpression_bp();for(;!this.isAtEnd();){const s=this.peek();if(s.kind===u.LPAREN){const{left:i}=ut(s);if(i<e||ot(this.previous(),s)&&!this.contextStack.isWithinGroupExpressionContext()&&!this.contextStack.isWithinListExpressionContext())break;try{n=this.nodeFactory.create(H,{callee:n,argumentList:this.tupleExpression()})}catch(r){throw r instanceof d?(n=this.nodeFactory.create(H,{callee:n,argumentList:r.partialNode}),new d(r.token,n,r.handlerContext)):r}}else if(s.kind===u.LBRACKET){if(Ce(this.previous()))break;try{n=this.nodeFactory.create(he,{expression:n,indexer:this.listExpression()})}catch(i){throw i instanceof d?(n=this.nodeFactory.create(he,{expression:n,indexer:i.partialNode}),new d(i.token,n,i.handlerContext)):i}}else if(at(s)){const i=s,r=ut(i);if(r.left!==null){if(r.left<=e)break;this.advance(),n=this.nodeFactory.create(Ue,{expression:n,op:i})}else{const a=En(i);if(a.left===null||a.left<=e)break;this.advance();try{n=this.nodeFactory.create(q,{leftExpression:n,op:i,rightExpression:i.value==="."?this.extractOperand():this.expression_bp(a.right)})}catch(l){throw l instanceof d?(n=this.nodeFactory.create(q,{leftExpression:n,op:i,rightExpression:l.partialNode}),new d(l.token,n,l.handlerContext)):l}}}else break}return n}leftExpression_bp(){let e;if(at(this.peek())){const n={};n.op=this.peek();const s=mn(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(xe,{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 xe)throw new d(this.peek(),this.nodeFactory.create(xe,{pre:this.peek()}),this.contextStack.findHandlerContext(this.tokens,this.current));return e}extractOperand(){return this.check(u.NUMERIC_LITERAL,u.STRING_LITERAL,u.COLOR_LITERAL,u.QUOTED_STRING,u.IDENTIFIER)?this.primaryExpression():this.check(u.FUNCTION_EXPRESSION)?this.functionExpression():this.check(u.LBRACKET)?this.listExpression():this.check(u.LBRACE)?this.blockExpression():this.check(u.LPAREN)?this.tupleExpression():(this.peek().kind===u.EOF?this.logError(this.peek(),o.UNEXPECTED_EOF,"Unexpected EOF"):this.logError(this.peek(),o.INVALID_OPERAND,`Invalid start of operand "${this.peek().value}"`),this.nodeFactory.create(xe,{pre:this.previous()}))}functionExpression(){const e={};try{this.consume("Expect a function expression",u.FUNCTION_EXPRESSION),e.value=this.previous()}catch(n){throw n instanceof d?(e.value=n.partialNode,new d(n.token,this.nodeFactory.create(ne,e),n.handlerContext)):n}return this.nodeFactory.create(ne,e)}canBeField(){return this.peek().kind===u.IDENTIFIER&&this.peek(1).kind===u.COLON}primaryExpression(){if(this.match(u.COLOR_LITERAL,u.STRING_LITERAL,u.NUMERIC_LITERAL))return this.nodeFactory.create(U,{expression:this.nodeFactory.create(be,{literal:this.previous()})});if(this.match(u.QUOTED_STRING,u.IDENTIFIER))return this.nodeFactory.create(U,{expression:this.nodeFactory.create(K,{variable:this.previous()})});throw this.logError(this.peek(),o.UNEXPECTED_TOKEN,"Expect a variable or literal"),new d(this.peek(),void 0,this.contextStack.findHandlerContext(this.tokens,this.current))}attribute(){const e={};if(this.check(u.COLON,u.RBRACKET,u.COMMA)){const n=this.peek();this.logError(n,o.EMPTY_ATTRIBUTE_NAME,"Expect a non-empty attribute name"),e.name=this.nodeFactory.create(Y,{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(se,e),n.handlerContext);this.synchronizeAttributeName()}return this.match(u.COLON)&&(e.colon=this.previous(),e.value=this.attributeValue()),this.nodeFactory.create(se,e)}attributeValue(){let e;try{e=this.peek().kind===u.IDENTIFIER&&this.peek(1).kind===u.IDENTIFIER?this.attributeName():this.normalExpression()}catch(n){if(!(n instanceof d)||!this.canHandle(n))throw n;e=n.partialNode,this.synchronizeAttributeValue()}return e}attributeName(){const e=[];if(this.peek().kind!==u.IDENTIFIER)return this.primaryExpression();for(;!this.isAtEnd()&&!this.check(u.COLON,u.COMMA,u.RBRACKET);)try{this.consume("Expect an identifier",u.IDENTIFIER),e.push(this.previous())}catch(n){throw n instanceof d?new d(n.token,this.nodeFactory.create(Y,{identifiers:e}),n.handlerContext):n}return this.nodeFactory.create(Y,{identifiers:e})}logError(e,n,s){this.errors.push(new c(n,s,e))}}const dn={"+":{left:9,right:10},"*":{left:11,right:12},"-":{left:9,right:10},"/":{left:11,right:12},"%":{left:11,right:12},"<":{left:7,right:8},"<=":{left:7,right:8},">":{left:7,right:8},">=":{left:7,right:8},"<>":{left:7,right:8},"=":{left:2,right:3},"==":{left:4,right:5},"!=":{left:4,right:5},".":{left:16,right:17}};function En(t){return dn[t.value]||{left:null,right:null}}const Nn={"+":{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 mn(t){return Nn[t.value]||{left:null,right:null}}const Tn={"(":{left:14,right:null}};function ut(t){return Tn[t.value]||{left:null,right:null}}var I=(t=>(t.Table="table",t.Enum="enum",t.Ref="ref",t.Note="note",t.Project="project",t.Indexes="indexes",t.TableGroup="tablegroup",t))(I||{});function ve(t){var n;const e=(n=t==null?void 0:t.type)==null?void 0:n.value.toLowerCase();switch(e){case I.Enum:case I.Table:case I.Indexes:case I.Note:case I.Project:case I.Ref:case I.TableGroup:return new S(e);default:return new k}}function pe(t){if(!Je(t))return new S([t]);const e=pe(t.leftExpression).unwrap_or(void 0);return e?(e.push(t.rightExpression),new S(e)):new k}function W(t){if(t===void 0)return new k;const e=pe(t).unwrap_or(void 0);if(!e)return new k;const n=[];for(const s of e){const i=j(s).unwrap_or(void 0);if(!i)return new k;n.push(i)}return new S(n)}function _e(t){if(t===void 0)return new k;const e=pe(t).unwrap_or(void 0);if(!e||e.length===0)return new k;const n=[];let s;if(!M(b.last(e))){const i=e.pop();if(St(i))s=i.elementList.map(r=>C(r).unwrap());else return new k}for(const i of e){const r=j(i).unwrap_or(void 0);if(!r)return new k;n.push(r)}return new S({variables:n,tupleElements:s})}function j(t){return M(t)?new S(t.expression.variable.value):new k}function Xe(t){if(ht(t))return t instanceof ne?new S({functional:[t],nonFunctional:[]}):new S({functional:[],nonFunctional:[t]});if(t instanceof Z&&t.elementList.every(ht)){const e=t.elementList.filter(s=>s instanceof ne),n=t.elementList.filter(M);return new S({functional:e,nonFunctional:n})}return new k}function C(t){var n;const e=(n=t==null?void 0:t.expression.variable)==null?void 0:n.value;return e===void 0?new k:new S(e)}function G(t){return $(t)?t.expression instanceof K?new S(t.expression.variable.value):new S(t.expression.literal.value):new k}function bn(t){var e;return!(t instanceof q)||!kt((e=t.op)==null?void 0:e.value)?!1:_e(t.leftExpression).and_then(()=>_e(t.rightExpression)).unwrap_or(void 0)!==void 0}function In(t){const e=_e(t.leftExpression),n=_e(t.rightExpression);if(!e.isOk()||!n.isOk())return!1;const{tupleElements:s}=e.unwrap(),{tupleElements:i}=n.unwrap();return(s==null?void 0:s.length)===(i==null?void 0:i.length)}function ht(t){return t instanceof U&&t.expression instanceof K||t instanceof ne}function Ln(t,e){var i,r,a,l;let n=e;const s=Ht(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 X&&s)return n.symbol;if(n instanceof X)return;n=n.parent}}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 X||ve(this.declarationNode.parent).unwrap_or(void 0)!==I.Project?[new c(o.INVALID_CUSTOM_CONTEXT,"A custom element can only appear in a Project",this.declarationNode)]:[]}validateName(e){return e?[new c(o.UNEXPECTED_NAME,"A Custom element shouldn't have a name",e)]:[]}validateAlias(e){return e?[new c(o.UNEXPECTED_NAME,"A Custom element shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"A Custom element shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof J)return[new c(o.UNEXPECTED_COMPLEX_BODY,"A Custom element can only have an inline field",e)];const n=[];return $(e.callee)||n.push(new c(o.INVALID_CUSTOM_ELEMENT_VALUE,"A Custom element value can only be a string",e)),e.args.length>0&&n.push(...e.args.map(s=>new c(o.INVALID_CUSTOM_ELEMENT_VALUE,"A Custom element value can only be a string",s))),n}}class we{constructor(){this.table=new Map}has(e){return this.table.has(e)}set(e,n){this.table.set(e,n)}get(e,n){return this.table.get(e)||n!==void 0&&this.set(e,n)||n}entries(){return this.table.entries()}}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.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof v?[new c(o.INVALID_PROJECT_CONTEXT,"An Enum can only appear top-level",this.declarationNode)]:[]}validateName(e){return e?yt(e)?[]:[new c(o.INVALID_NAME,"An Enum name must be of the form <enum> or <schema>.<enum>",e)]:[new c(o.NAME_NOT_FOUND,"An Enum must have a name",this.declarationNode)]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}registerElement(){const e=[];this.declarationNode.symbol=this.symbolFactory.create(en,{declaration:this.declarationNode,symbolTable:new we});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=ze(r);a.has(l)&&e.push(new c(o.DUPLICATE_NAME,`Enum name ${r} already exists in schema '${i.join(".")||"public"}'`,n)),a.set(l,this.declarationNode.symbol)}return e}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"An Enum shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return this.validateFields([e]);const[n,s]=b.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.length===0?[new c(o.EMPTY_ENUM,"An Enum must have at least one element",this.declarationNode)]:e.flatMap(n=>{const s=[];n.callee&&!M(n.callee)&&s.push(new c(o.INVALID_ENUM_ELEMENT_NAME,"An enum field must be an identifier or a quoted identifier",n.callee));const i=[...n.args];return b.last(i)instanceof R?(s.push(...this.validateFieldSettings(b.last(i))),i.pop()):i[0]instanceof R&&(s.push(...this.validateFieldSettings(i[0])),i.shift()),i.length>0&&s.push(...i.map(r=>new c(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=B(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"note":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_ENUM_ELEMENT_SETTING,"'note' can only appear once",l))),a.forEach(l=>{$(l.value)||s.push(new c(o.INVALID_ENUM_ELEMENT_SETTING,"'note' must be a string",l))});break;default:a.forEach(l=>s.push(new c(o.UNKNOWN_ENUM_ELEMENT_SETTING,`Unknown enum field setting '${r}'`,l)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ae(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}registerField(e){if(e.callee&&M(e.callee)){const n=C(e.callee).unwrap(),s=Qe(n),i=this.symbolFactory.create(tn,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(s)){const a=r.get(s);return[new c(o.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,e),new c(o.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,a.declaration)]}r.set(s,i)}return[]}}class An{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof X||ve(this.declarationNode.parent).unwrap_or(void 0)!==I.Table?[new c(o.INVALID_NOTE_CONTEXT,"An Indexes can only appear inside a Table",this.declarationNode)]:[]}validateName(e){return e?[new c(o.UNEXPECTED_NAME,"An Indexes shouldn't have a name",e)]:[]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"An Indexes shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"An Indexes shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return[new c(o.UNEXPECTED_SIMPLE_BODY,"An Indexes must have a complex body",e)];const[n,s]=b.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.flatMap(n=>{if(!n.callee)return[];const s=[],i=[n.callee,...n.args];return b.last(i)instanceof R&&s.push(...this.validateFieldSetting(i.pop())),i.forEach(r=>{for(;r instanceof H;)r.argumentList&&!Xe(r.argumentList).isOk()&&s.push(new c(o.INVALID_INDEXES_FIELD,"An index field must be an identifier, a quoted identifier, a functional expression or a tuple of such",r.argumentList)),r=r.callee;Xe(r).isOk()||s.push(new c(o.INVALID_INDEXES_FIELD,"An index field must be an identifier, a quoted identifier, a functional expression or a tuple of such",r))}),s})}validateFieldSetting(e){const n=B(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"note":case"name":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_INDEX_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{$(l.value)||s.push(new c(o.INVALID_INDEX_SETTING_VALUE,`'${r}' must be a string`,l))});break;case"unique":case"pk":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_INDEX_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{ue(l.value)||s.push(new c(o.INVALID_INDEX_SETTING_VALUE,`'${r}' must not have a value`,l))});break;case"type":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_INDEX_SETTING,"'type' can only appear once",l))),a.forEach(l=>{M(l.value)||s.push(new c(o.INVALID_INDEX_SETTING_VALUE,`'type' must be "btree" or "hash"`,l))});break;default:a.forEach(l=>s.push(new c(o.UNKNOWN_INDEX_SETTING,`Unknown index setting '${r}'`,l)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ae(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class vn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return!(this.declarationNode.parent instanceof X)&&![I.Table,I.TableGroup,I.Project].includes(ve(this.declarationNode.parent).unwrap_or(void 0))?[new c(o.INVALID_NOTE_CONTEXT,"A Note can only appear inside a Table, a Table Group or a Project. Sticky note can only appear at the global scope.",this.declarationNode)]:[]}validateName(e){if(!(this.declarationNode.parent instanceof X))return e?[new c(o.UNEXPECTED_NAME,"A Note shouldn't have a name",e)]:[];if(!e)return[new c(o.INVALID_NAME,"Sticky note must have a name",this.declarationNode)];const n=W(e);if(!n.isOk())return[new c(o.INVALID_NAME,"Invalid name for sticky note ",this.declarationNode)];const i=n.unwrap().join("."),r=qt(i);return this.publicSymbolTable.has(r)?[new c(o.DUPLICATE_NAME,`Sticky note "${i}" has already been defined`,e)]:(this.publicSymbolTable.set(r,this.declarationNode.symbol),[])}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"A Note shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return this.validateFields([e]);const[n,s]=b.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){const n=[];return e.length===0?[new c(o.EMPTY_NOTE,"A Note must have a content",this.declarationNode)]:(e.length>1&&e.slice(1).forEach(s=>n.push(new c(o.NOTE_CONTENT_REDEFINED,"A Note can only contain one string",s))),$(e[0].callee)||n.push(new c(o.INVALID_NOTE,"A Note content must be a quoted string",e[0])),e[0].args.length>0&&n.push(...e[0].args.map(s=>new c(o.INVALID_NOTE,"A Note can only contain one quoted string",s))),n)}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ae(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class wn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof v?[new c(o.INVALID_PROJECT_CONTEXT,"A Project can only appear top-level",this.declarationNode)]:[]}validateName(e){return e?ye(e)?[]:[new c(o.INVALID_NAME,"A Project's name is optional or must be an identifier or a quoted identifer",e)]:[]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A Project shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"A Project shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return[new c(o.UNEXPECTED_SIMPLE_BODY,"A Project's body must be a block",e)];const[n,s]=b.partition(e.body,i=>i instanceof w);return[...n.map(i=>new c(o.INVALID_PROJECT_FIELD,"A Project can not have inline fields",i)),...this.validateSubElements(s)]}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ae(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class yn{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof X?[]:[new c(o.INVALID_REF_CONTEXT,"A Ref must appear top-level",this.declarationNode)]}validateName(e){return e?ye(e)?[]:[new c(o.INVALID_NAME,"A Ref's name is optional or must be an identifier or a quoted identifer",e)]:[]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",e)]:[]}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"A Ref shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof w)return this.validateFields([e]);const[n,s]=b.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){if(e.length===0)return[new c(o.EMPTY_REF,"A Ref must have at least one field",this.declarationNode)];const n=[];return e.length>1&&n.push(...e.slice(1).map(s=>new c(o.REF_REDEFINED,"A Ref can only contain one binary relationship",s))),e.forEach(s=>{s.callee&&!bn(s.callee)&&n.push(new c(o.INVALID_REF_FIELD,"A Ref field must be a binary relationship",s.callee)),s.callee&&!In(s.callee)&&n.push(new c(o.UNEQUAL_FIELDS_BINARY_REF,"Unequal fields in ref endpoints",s.callee));const i=[...s.args];b.last(i)instanceof R?(this.validateFieldSettings(b.last(i)),i.pop()):i[0]instanceof R&&(n.push(...this.validateFieldSettings(i[0])),i.shift()),i.length>0&&n.push(...i.map(r=>new c(o.INVALID_REF_FIELD,"A Ref field should only have a single binary relationship",r)))}),n}validateFieldSettings(e){const n=B(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"delete":case"update":a.length>1&&a.forEach(l=>s.push(new c(o.DUPLICATE_REF_SETTING,`'${r}' can only appear once`,l))),a.forEach(l=>{kn(l.value)||s.push(new c(o.INVALID_REF_SETTING_VALUE,`'${r}' can only have values "cascade", "no action", "set null", "set default" or "restrict"`,l))});break;default:a.forEach(l=>s.push(new c(o.UNKNOWN_REF_SETTING,`Unknown ref setting '${r}'`,l)))}}return s}validateSubElements(e){return e.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const s=ae(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}}function kn(t){if(!(M(t)&&t.expression.variable.kind!==u.QUOTED_STRING)&&!(t instanceof Y))return!1;let e;if(t instanceof Y?e=Te(t).unwrap_or(""):e=t.expression.variable.value,e)switch(e.toLowerCase()){case"cascade":case"no action":case"set null":case"set default":case"restrict":return!0;default:return!1}return!1}class xn{constructor(e,n,s){this.declarationNode=e,this.symbolFactory=s,this.publicSymbolTable=n}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof v?[new c(o.INVALID_TABLE_CONTEXT,"Table must appear top-level",this.declarationNode)]:[]}validateName(e){return e?e instanceof he?[new c(o.INVALID_NAME,"Invalid array as Table name, maybe you forget to add a space between the name and the setting list?",e)]:yt(e)?[]:[new c(o.INVALID_NAME,"A Table name must be of the form <table> or <schema>.<table>",e)]:[new c(o.NAME_NOT_FOUND,"A Table must have a name",this.declarationNode)]}validateAlias(e){return e?Rn(e)?[]:[new c(o.INVALID_ALIAS,"Table aliases can only contains alphanumeric and underscore unless surrounded by double quotes",e)]:[]}validateSettingList(e){const n=B(e),s=n.getErrors(),i=n.getValue();for(const r in i){const a=i[r];switch(r){case"headercolor":a.length>1&&s.push(...a.map(l=>new c(o.DUPLICATE_TABLE_SETTING,"'headercolor' can only appear once",l))),a.forEach(l=>{xt(l.value)||s.push(new c(o.INVALID_TABLE_SETTING,"'headercolor' must be a color literal",l.value||l.name))});break;case"note":a.length>1&&s.push(...a.map(l=>new c(o.DUPLICATE_TABLE_SETTING,"'note' can only appear once",l))),a.forEach(l=>{$(l.value)||s.push(new c(o.INVALID_TABLE_SETTING,"'note' must be a string literal",l.value||l.name))});break;default:s.push(...a.map(l=>new c(o.INVALID_TABLE_SETTING,`Unknown '${r}' setting`,l)))}}return s}registerElement(){const e=[];this.declarationNode.symbol=this.symbolFactory.create(At,{declaration:this.declarationNode,symbolTable:new we});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=Oe(a);l.has(p)&&e.push(new c(o.DUPLICATE_NAME,`Table name '${a}' already exists in schema '${r.join(".")||"public"}'`,n)),l.set(p,this.declarationNode.symbol)}if(s&&ye(s)&&!On(s.expression.variable.value,i.unwrap_or([]))){const r=C(s).unwrap(),a=Oe(r);this.publicSymbolTable.has(a)&&e.push(new c(o.DUPLICATE_NAME,`Table name '${r}' already exists`,n)),this.publicSymbolTable.set(a,this.declarationNode.symbol)}return e}validateBody(e){if(!e)return[];if(e instanceof w)return[new c(o.UNEXPECTED_SIMPLE_BODY,"A Table's body must be a block",e)];const[n,s]=b.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.length===0?[new c(o.EMPTY_TABLE,"A Table must have at least one column",this.declarationNode)]:e.flatMap(n=>{if(!n.callee)return[];const s=[];n.args.length===0&&s.push(new c(o.INVALID_COLUMN,"A column must have a type",n.callee)),M(n.callee)||s.push(new c(o.INVALID_COLUMN_NAME,"A column name must be an identifier or a quoted identifier",n.callee)),n.args[0]&&!Sn(n.args[0])&&s.push(new c(o.INVALID_COLUMN_TYPE,"Invalid column type",n.args[0]));const i=n.args.slice(1);return s.push(...this.validateFieldSetting(i)),s.push(...this.registerField(n)),s})}registerField(e){if(e.callee&&M(e.callee)){const n=C(e.callee).unwrap(),s=Ye(n),i=this.symbolFactory.create(nn,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(s)){const a=r.get(s);return[new c(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,e),new c(o.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,a.declaration)]}r.set(s,i)}return[]}validateFieldSetting(e){if(!e.slice(0,-1).every(me)||!e.slice(-1).every(p=>me(p)||p instanceof R))return[...e.map(p=>new c(o.INVALID_COLUMN,"These fields must be some inline settings optionally ended with a setting list",p))];if(e.length===0)return[];let n;b.last(e)instanceof R&&(n=e.pop());const s=B(n),i=s.getErrors(),r=s.getValue();for(const p of e){const f=C(p).unwrap_or("").toLowerCase();if(f!=="pk"&&f!=="unique"){i.push(new c(o.INVALID_SETTINGS,"Inline column settings can only be `pk` or `unique`",p));continue}r[f]===void 0?r[f]=[p]:r[f].push(p)}const a=r.pk||[],l=r["primary key"]||[];a.length>=1&&l.length>=1&&i.push(...[...a,...l].map(p=>new c(o.DUPLICATE_COLUMN_SETTING,"Either one of 'primary key' and 'pk' can appear",p)));for(const p in r){const f=r[p];switch(p){case"note":f.length>1&&i.push(...f.map(h=>new c(o.DUPLICATE_COLUMN_SETTING,"note can only appear once",h))),f.forEach(h=>{$(h.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'note' must be a quoted string",h.value||h.name))});break;case"ref":f.forEach(h=>{Un(h.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'ref' must be a valid unary relationship",h.value||h.name))});break;case"primary key":f.length>1&&i.push(...f.map(h=>new c(o.DUPLICATE_COLUMN_SETTING,"primary key can only appear once",h))),f.forEach(h=>{ue(h.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'primary key' must not have a value",h.value||h.name))});break;case"pk":f.length>1&&i.push(...f.map(h=>new c(o.DUPLICATE_COLUMN_SETTING,"'pk' can only appear once",h))),f.forEach(h=>{h instanceof se&&!ue(h.value)&&i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'pk' must not have a value",h.value||h.name))});break;case"not null":f.length>1&&i.push(...f.map(h=>new c(o.DUPLICATE_COLUMN_SETTING,"'not null' can only appear once",h)));const E=r.null||[];f.length>=1&&E.length>=1&&i.push(...[...f,...E].map(h=>new c(o.CONFLICTING_SETTING,"'not null' and 'null' can not be set at the same time",h))),f.forEach(h=>{ue(h.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'not null' must not have a value",h.value||h.name))});break;case"null":f.length>1&&i.push(...f.map(h=>new c(o.DUPLICATE_COLUMN_SETTING,"'null' can only appear once",h))),f.forEach(h=>{ue(h.value)||i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'null' must not have a value",h.value||h.name))});break;case"unique":f.length>1&&i.push(...f.map(h=>new c(o.DUPLICATE_COLUMN_SETTING,"'unique' can only appear once",h))),f.forEach(h=>{h instanceof se&&!ue(h.value)&&i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'unique' must not have a value",h.value||h.name))});break;case"increment":f.length>1&&i.push(...f.map(h=>new c(o.DUPLICATE_COLUMN_SETTING,"'increment' can only appear once",h))),f.forEach(h=>{h instanceof se&&!ue(h.value)&&i.push(new c(o.INVALID_COLUMN_SETTING_VALUE,"'increment' must not have a value",h.value||h.name))});break;case"default":f.length>1&&i.push(...f.map(h=>new c(o.DUPLICATE_TABLE_SETTING,"'default' can only appear once",h))),f.forEach(h=>{Pn(h.value)||i.push(new c(o.INVALID_TABLE_SETTING,"'default' must be a string literal, number literal, function expression, true, false or null",h.value||h.name))});break;default:f.forEach(h=>i.push(new c(o.UNKNOWN_COLUMN_SETTING,`Unknown column setting '${p}'`,h)))}}return i}validateSubElements(e){const n=e.flatMap(i=>{if(i.parent=this.declarationNode,!i.type)return[];const r=ae(i);return new r(i,this.publicSymbolTable,this.symbolFactory).validate()}),s=e.filter(i=>{var r;return((r=i.type)==null?void 0:r.value.toLowerCase())==="note"});return s.length>1&&n.push(...s.map(i=>new c(o.NOTE_REDEFINED,"Duplicate notes are defined",i))),n}}function Sn(t){if(!(t instanceof H||Je(t)||t instanceof U||t instanceof he))return!1;if(t instanceof H){if(t.callee===void 0||t.argumentList===void 0||!t.argumentList.elementList.every(n=>fe(n)||$(n)||me(n)))return!1;t=t.callee}for(;t instanceof he;){if(t.array===void 0||t.indexer===void 0||!t.indexer.elementList.every(n=>!n.colon&&!n.value&&fe(n.name)))return!1;t=t.array}const e=W(t).unwrap_or(void 0);return e!==void 0&&e.length>0}function On(t,e){return e.length===1&&t===e[0]}class Dn{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 v?[new c(o.INVALID_TABLEGROUP_CONTEXT,"TableGroup must appear top-level",this.declarationNode)]:[]}validateName(e){return e?ye(e)?[]:[new c(o.INVALID_NAME,"A TableGroup name must be a single identifier",e)]:[new c(o.NAME_NOT_FOUND,"A TableGroup must have a name",this.declarationNode)]}validateAlias(e){return e?[new c(o.UNEXPECTED_ALIAS,"A TableGroup shouldn't have an alias",e)]:[]}registerElement(){const{name:e}=this.declarationNode;this.declarationNode.symbol=this.symbolFactory.create(sn,{declaration:this.declarationNode,symbolTable:new we});const n=W(e);if(n.isOk()){const s=n.unwrap(),i=s.pop(),r=Ze(s,this.publicSymbolTable,this.symbolFactory),a=qe(i);if(r.has(a))return[new c(o.DUPLICATE_NAME,`TableGroup name '${i}' already exists`,e)];r.set(a,this.declarationNode.symbol)}return[]}validateSettingList(e){const n=B(e),s=n.getErrors(),i=n.getValue();return b.forIn(i,(r,a)=>{switch(a){case"color":r.length>1&&s.push(...r.map(l=>new c(o.DUPLICATE_TABLE_SETTING,"'color' can only appear once",l))),r.forEach(l=>{xt(l.value)||s.push(new c(o.INVALID_TABLE_SETTING,"'color' must be a color literal",l.value||l.name))});break;case"note":r.length>1&&s.push(...r.map(l=>new c(o.DUPLICATE_TABLE_SETTING,"'note' can only appear once",l))),r.filter(l=>!$(l.value)).forEach(l=>{s.push(new c(o.INVALID_TABLE_SETTING,"'note' must be a string literal",l.value||l.name))});break;default:s.push(...r.map(l=>new c(o.INVALID_TABLE_SETTING,`Unknown '${a}' setting`,l)));break}}),s}validateBody(e){if(!e)return[];if(e instanceof w)return[new c(o.UNEXPECTED_SIMPLE_BODY,"A TableGroup's body must be a block",e)];const[n,s]=b.partition(e.body,i=>i instanceof w);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.flatMap(n=>{const s=[];return n.callee&&!W(n.callee).isOk()&&s.push(new c(o.INVALID_TABLEGROUP_FIELD,"A TableGroup field must be of the form <table> or <schema>.<table>",n.callee)),this.registerField(n),n.args.length>0&&s.push(...n.args.map(i=>new c(o.INVALID_TABLEGROUP_FIELD,"A TableGroup field should only have a single Table name",i))),s})}validateSubElements(e){const n=e.flatMap(i=>{if(i.parent=this.declarationNode,!i.type)return[];const r=ae(i);return new r(i,this.publicSymbolTable,this.symbolFactory).validate()}),s=e.filter(i=>{var r;return((r=i.type)==null?void 0:r.value.toLowerCase())==="note"});return s.length>1&&n.push(...s.map(i=>new c(o.NOTE_REDEFINED,"Duplicate notes are defined",i))),n}registerField(e){if(e.callee&&M(e.callee)){const n=C(e.callee).unwrap(),s=He(n),i=this.symbolFactory.create(rn,{declaration:e});e.symbol=i;const r=this.declarationNode.symbol.symbolTable;if(r.has(s)){const a=r.get(s);return[new c(o.DUPLICATE_TABLEGROUP_FIELD_NAME,`${n} already exists in the group`,e),new c(o.DUPLICATE_TABLEGROUP_FIELD_NAME,`${n} already exists in the group`,a.declaration)]}r.set(s,i)}return[]}}const wt=["-","+"];function ae(t){switch(t.type.value.toLowerCase()){case I.Enum:return _n;case I.Table:return xn;case I.TableGroup:return Dn;case I.Project:return wn;case I.Ref:return yn;case I.Note:return vn;case I.Indexes:return An;default:return gn}}function yt(t){return!!W(t).unwrap_or(!1)}function Rn(t){return ye(t)}function ye(t){return t instanceof U&&t.expression instanceof K}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=je(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 we;const p=n.create(_t,{symbolTable:a});s.set(l,p)}s=a}return s}function kt(t){return t==="-"||t==="<>"||t===">"||t==="<"}function xt(t){var n;if(!(t instanceof U)||!(t.expression instanceof be)||((n=t.expression.literal)==null?void 0:n.kind)!==u.COLOR_LITERAL)return!1;const e=t.expression.literal.value;if(e.length!==4&&e.length!==7||e[0]!=="#")return!1;for(let s=1;s<e.length;s+=1)if(!Zt(e[s]))return!1;return!0}function ue(t){return t===void 0}function Pn(t){var e;return!!($(t)||fe(t)||me(t)&&["true","false","null"].includes(t.expression.variable.value.toLowerCase())||t instanceof Q&&wt.includes((e=t.op)==null?void 0:e.value)&&fe(t.expression)||t instanceof ne)}function fe(t){var e;return t instanceof U&&t.expression instanceof be&&((e=t.expression.literal)==null?void 0:e.kind)===u.NUMERIC_LITERAL}function Un(t){var n;if(!(t instanceof Q)||!kt((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 St(t){return t instanceof Z&&t.elementList.every(M)}function B(t){var s;const e={},n=[];if(!t)return new V({});for(const i of t.elementList){if(!i.name)continue;if(i.name instanceof U){n.push(new c(o.INVALID_SETTINGS,"A setting name must be a stream of identifiers",i.name));continue}const r=(s=Te(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 V(e,n)}class ft{constructor(e,n){this.ast=e,this.symbolFactory=n,this.publicSchemaSymbol=this.symbolFactory.create(_t,{symbolTable:new we}),this.ast.symbol=this.publicSchemaSymbol,this.ast.symbol.declaration=this.ast}validate(){const e=[];this.ast.body.forEach(s=>{if(s.parent=this.ast,s.type===void 0)return;const i=ae(s),r=new i(s,this.publicSchemaSymbol.symbolTable,this.symbolFactory);e.push(...r.validate())});const n=this.ast.body.filter(s=>ve(s).unwrap_or(void 0)===I.Project);return n.length>1&&n.forEach(s=>e.push(new c(o.PROJECT_REDEFINED,"Only one project can exist",s))),new V(this.ast,e)}}class oe{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 U)continue;const i=Te(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 J)for(const s of n.body)if(s instanceof v){if(!s.type)continue;const i=Ot(s);new i(s,this.errors).bind()}else this.bindSubfield(s);else this.bindSubfield(n)}bindSubfield(e){const n=[e.callee,...e.args],s=b.last(n);s instanceof R&&(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 U){if(e.expression instanceof K&&((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?Je(e)?this.bindFragments(pe(e).unwrap_or([]),n):(this.scanAndBind(e.leftExpression,n),this.scanAndBind(e.rightExpression,n)):e instanceof Q?this.scanAndBind(e.expression,n):e instanceof Ue?this.scanAndBind(e.expression,n):e instanceof Z&&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(h=>!M(h)),l=r!==-1&&St(e[r])?e[r]:void 0,p=r>=0?s.pop():void 0,f=e.slice(0,r===-1?void 0:r);if(f.length===0)return;const E=[];for(;s.length&&f.length;){const h=s.pop(),m=f.pop(),g=C(m).unwrap();E.unshift({index:Ve(g,h),referrer:m})}for(;f.length;){const h=f.pop(),m=C(h).unwrap();E.unshift({index:Ve(m,i),referrer:h})}return l?l.elementList.forEach(h=>this.resolveIndexStack([...E,{index:Ve(C(h).unwrap(),p),referrer:h}],n.ignoreNameNotFound)):this.resolveIndexStack(E,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=Ln(s.index,this.declarationNode);if(r===void 0){const{kind:f,name:E}=ie(s.index).unwrap();this.logError(s.referrer,`Can not find ${f} '${E}'`,n);return}r.references.push(s.referrer),s.referrer.referee=r;let a=r.symbolTable,{kind:l,name:p}=ie(s.index).unwrap();for(const f of i){const{kind:E,name:h}=ie(f.index).unwrap(),m=a.get(f.index);if(!m){this.logError(f.referrer,`${l} '${p}' does not have ${E} '${h}'`,n);return}if(l=E,p=h,f.referrer.referee=m,m.references.push(f.referrer),!m.symbolTable)break;a=m.symbolTable}}logError(e,n,s){s||this.errors.push(new c(o.BINDING_ERROR,n,e))}}class Mn extends oe{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Fn extends oe{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Bn extends oe{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[T.Table,T.Column],remainingSubnamesSymbolKind:T.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[T.Table,T.Column],remainingSubnamesSymbolKind:T.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[T.Table,T.Column],remainingSubnamesSymbolKind:T.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[T.Table,T.Column],remainingSubnamesSymbolKind:T.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class Vn extends oe{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Gn extends oe{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Cn extends oe{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[T.Table,T.Column],remainingSubnamesSymbolKind:T.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class Xn extends oe{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1},{shouldBind:!0,topSubnamesSymbolKind:[T.Enum],remainingSubnamesSymbolKind:T.Schema,ignoreNameNotFound:!0}]},settingList:{ref:{shouldBind:!0,topSubnamesSymbolKind:[T.Table,T.Column],remainingSubnamesSymbolKind:T.Schema,ignoreNameNotFound:!1},default:{shouldBind:!1}}},this.settingList={}}}class $n extends oe{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[T.Table],remainingSubnamesSymbolKind:T.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}function Ot(t){switch(t.type.value.toLowerCase()){case I.Enum:return Fn;case I.Table:return Xn;case I.TableGroup:return $n;case I.Project:return Gn;case I.Ref:return Cn;case I.Note:return Vn;case I.Indexes:return Bn;default:return Mn}}class Wn{constructor(e){this.ast=e,this.errors=[]}resolve(){for(const e of this.ast.body)if(e.type){const n=Ot(e);new n(e,this.errors).bind()}return new V(this.ast,this.errors)}}class jn{constructor(e){this.generator=e}create(e,n){return new e(n,this.generator.nextId())}}class Yn{constructor(e,n){this.ast=e,this.symbolFactory=new jn(n)}analyze(){return new ft(this.ast,this.symbolFactory).validate().chain(n=>new Wn(n).resolve())}validate(){return new ft(this.ast,this.symbolFactory).validate().chain(n=>new V(n,[]))}}function pt(t,e){const{variables:n,tupleElements:s}=_e(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 Dt(t){switch(t){case"<":return["1","*"];case"<>":return["*","*"];case">":return["*","1"];case"-":return["1","1"]}throw new Error("Invalid relation op")}function A(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 $e(t){var n;const e=(n=pe(t).unwrap_or(void 0))==null?void 0:n.pop();return e instanceof Z?e.elementList.map(s=>s.referee):[e.referee]}function Ie(t){const e=W(t).unwrap();return{name:e.pop(),schemaName:e}}function Ke(t){return t.expression.literal.value}function Rt(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.toString(),s=e.id.toString();return n<s?`${n}-${s}`:`${s}-${n}`}function Pt(t,e){if(Array.isArray(t)){const i=t.map(({id:a})=>a).sort(),r=e.map(({id:a})=>a).sort();return b.zip(i,r).every(([a,l])=>a===l)}const n=t.id,s=e.id;return n===s}function re(t){const e=t.split(`
10
10
  `),n=e.slice(e.findIndex(r=>r.trimStart()!=="")),s=n.filter(r=>r.trimStart()),i=Math.min(...s.map(r=>r.length-r.trimStart().length));return n.map(r=>r.slice(i)).join(`
11
11
  `)}class Ut{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=A(this.declarationNode),this.env.tables.set(this.declarationNode,this.table);const e=[...this.interpretName(this.declarationNode.name),...this.interpretAlias(this.declarationNode.alias),...this.interpretSettingList(this.declarationNode.attributeList),...this.interpretBody(this.declarationNode.body)];return this.pkColumns.length>=2&&(this.table.indexes.push({columns:this.pkColumns.map(({name:n,token:s})=>({value:n,type:"column",token:s})),token:{start:{offset:-1,line:-1,column:-1},end:{offset:-1,line:-1,column:-1}},pk:!0}),this.pkColumns.forEach(n=>n.pk=!1)),e}interpretName(e){const{name:n,schemaName:s}=Ie(e);return s.length>1?(this.table.name=n,this.table.schemaName=s.join("."),[new c(o.UNSUPPORTED,"Nested schema is not supported",e)]):(this.table.name=n,this.table.schemaName=s.length?s[0]:null,[])}interpretAlias(e){if(!e)return[];const n=C(e).unwrap_or(null);return n&&(this.env.aliases.push({name:n,kind:"table",value:{tableName:this.table.name,schemaName:this.table.schemaName}}),this.table.alias=n),[]}interpretSettingList(e){var i,r,a;const n=B(e).getValue();this.table.headerColor=(i=n.headercolor)!=null&&i.length?Ke((a=(r=n.headercolor)==null?void 0:r.at(0))==null?void 0:a.value):void 0;const[s]=n.note||[];return this.table.note=s&&{value:G(s==null?void 0:s.value).map(re).unwrap(),token:A(s)},[]}interpretBody(e){const[n,s]=b.partition(e.body,i=>i instanceof w);return[...this.interpretFields(n),...this.interpretSubElements(s)]}interpretSubElements(e){return e.flatMap(n=>{var s;switch((s=n.type)==null?void 0:s.value.toLowerCase()){case"note":return this.table.note={value:G(n.body instanceof J?n.body.body[0].callee:n.body.callee).map(re).unwrap(),token:A(n)},[];case"indexes":return this.interpretIndexes(n)}return[]})}interpretFields(e){return e.flatMap(n=>this.interpretColumn(n))}interpretColumn(e){var a,l,p,f,E,h,m,g;const n=[],s={};s.name=C(e.callee).unwrap();const i=zn(e.args[0]);s.type=i.getValue(),n.push(...i.getErrors()),s.token=A(e),s.inline_refs=[];const r=e.args.slice(1);if(b.last(r)instanceof R){const _=B(r.pop()).getValue();s.pk=!!((a=_.pk)!=null&&a.length)||!!((l=_["primary key"])!=null&&l.length),s.increment=!!((p=_.increment)!=null&&p.length),s.unique=!!((f=_.unique)!=null&&f.length),s.not_null=!!((E=_["not null"])!=null&&E.length)&&!0,s.dbdefault=Qn((m=(h=_.default)==null?void 0:h.at(0))==null?void 0:m.value);const ee=(g=_.note)==null?void 0:g.at(0);s.note=ee&&{value:G(ee.value).map(re).unwrap(),token:A(ee)};const le=_.ref||[];s.inline_refs=le.flatMap(z=>{const[nt]=$e(z.value.expression);if(Pt(nt,e.symbol))return n.push(new c(o.SAME_ENDPOINT,"Two endpoints are the same",z)),[];const ke=z.value.op,te=W(z.value.expression).unwrap();let de;if(te.length===1){const[ce]=te;de={schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[ce],relation:ke.value,token:A(z)}}else if(te.length===2){const[ce,Le]=te;de={schemaName:null,tableName:ce,fieldNames:[Le],relation:ke.value,token:A(z)}}else if(te.length===3){const[ce,Le,it]=te;de={schemaName:ce,tableName:Le,fieldNames:[it],relation:ke.value,token:A(z)}}else{n.push(new c(o.UNSUPPORTED,"Nested schema is not supported",z));const ce=te.pop(),Le=te.pop();de={schemaName:te.join("."),tableName:Le,fieldNames:[ce],relation:ke.value,token:A(z)}}const st=this.registerInlineRefToEnv(e,nt,de,z);return n.push(...st),st.length===0?de:[]})}return s.pk||(s.pk=r.some(_=>j(_).unwrap().toLowerCase()==="pk")),s.unique||(s.unique=r.some(_=>j(_).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,f,E,h,m;const s={columns:[]},i=n;s.token=A(i);const r=[i.callee,...i.args];if(b.last(r)instanceof R){const g=B(r.pop()).getValue();s.pk=!!((a=g.pk)!=null&&a.length),s.unique=!!((l=g.unique)!=null&&l.length),s.name=G((f=(p=g.name)==null?void 0:p.at(0))==null?void 0:f.value).unwrap_or(void 0);const _=(E=g.note)==null?void 0:E.at(0);s.note=_&&{value:G(_.value).unwrap(),token:A(_)},s.type=j((m=(h=g.type)==null?void 0:h.at(0))==null?void 0:m.value).unwrap_or(void 0)}return r.flatMap(g=>{if(!(g instanceof H))return g;const _=[];for(;g instanceof H;)_.push(g.argumentList),g=g.callee;return _.push(g),_}).forEach(g=>{const{functional:_,nonFunctional:ee}=Xe(g).unwrap();s.columns.push(..._.map(le=>({value:le.value.value,type:"expression",token:A(le)})),...ee.map(le=>({value:C(le).unwrap(),type:"column",token:A(le)})))}),s})),[]}registerInlineRefToEnv(e,n,s,i){const r=Rt(e.symbol,n);if(this.env.refIds[r])return[new c(o.CIRCULAR_REF,"References with same endpoints exist",i),new c(o.CIRCULAR_REF,"References with same endpoints exist",this.env.refIds[r])];const a=Dt(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:[j(e.callee).unwrap()],token:A(e),relation:a[0]}]}),[]}}function zn(t){let e=null;t instanceof H&&(e=t.argumentList.elementList.map(r=>fe(r)?r.expression.literal.value:$(r)?G(r).unwrap():j(r).unwrap()).join(","),t=t.callee);let n="";for(;t instanceof he;)n=`[${t.indexer.elementList.map(r=>r.name.expression.literal.value).join(",")}]${n}`,t=t.array;const{name:s,schemaName:i}=Ie(t);return i.length>1?new V({schemaName:i.length===0?null:i[0],type_name:`${s}${n}${e?`(${e})`:""}`,args:e},[new c(o.UNSUPPORTED,"Nested schema is not supported",t)]):new V({schemaName:i.length===0?null:i[0],type_name:`${s}${n}${e?`(${e})`:""}`,args:e})}function Qn(t){var e,n,s;if(t){if($(t))return{value:G(t).unwrap(),type:"string"};if(fe(t))return{type:"number",value:Number.parseFloat(t.expression.literal.value)};if(me(t))return{value:t.expression.variable.value.toLowerCase(),type:"boolean"};if(t instanceof Q&&wt.includes((e=t.op)==null?void 0:e.value)&&fe(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 ne)return{value:(s=t.value)==null?void 0:s.value,type:"expression"};throw new Error("Unreachable")}}class qn{constructor(e,n){this.declarationNode=e,this.env=n,this.note={name:void 0,content:void 0,token:void 0}}interpret(){return this.note.token=A(this.declarationNode),this.env.notes.set(this.declarationNode,this.note),[...this.interpretName(this.declarationNode.name),...this.interpretSettingList(this.declarationNode.attributeList),...this.interpretBody(this.declarationNode.body)]}interpretName(e){const{name:n}=Ie(e);return this.note.name=n,[]}interpretSettingList(e){var s,i,r;const n=B(e).getValue();return this.note.headerColor=(s=n.headercolor)!=null&&s.length?Ke((r=(i=n.headercolor)==null?void 0:i.at(0))==null?void 0:r.value):void 0,[]}interpretBody(e){const[n,s]=b.partition(e.body,i=>i instanceof w);return n.length!==1||s.length>0?[new c(o.INVALID_NOTE,"Invalid note syntax",e)]:[...this.interpretNote(n[0])]}interpretNote(e){const n=b.get(e,"callee.expression.literal.value","");return this.note.content=re(n),[]}}class Mt{constructor(e,n){this.declarationNode=e,this.env=n,this.container=this.declarationNode.parent instanceof v?this.env.tables.get(this.declarationNode.parent):void 0,this.ref={}}interpret(){return this.ref.token=A(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 c(o.UNSUPPORTED,"Nested schema is not supported",this.declarationNode.name)),this.ref.schemaName=s.join(".")||null,n}interpretBody(e){return e instanceof w?this.interpretField(e):this.interpretField(e.body[0])}interpretField(e){var f,E,h,m;const n=e.callee.op.value,{leftExpression:s,rightExpression:i}=e.callee,r=$e(s),a=$e(i);if(Pt(r,a))return[new c(o.SAME_ENDPOINT,"Two endpoints are the same",e)];const l=Rt(r,a);if(this.env.refIds[l])return[new c(o.CIRCULAR_REF,"References with same endpoints exist",this.declarationNode),new c(o.CIRCULAR_REF,"References with same endpoints exist",this.env.refIds[l])];if(e.args[0]){const g=B(e.args[0]).getValue(),_=(E=(f=g.delete)==null?void 0:f.at(0))==null?void 0:E.value;this.ref.onDelete=_ instanceof Y?Te(_).unwrap_or(void 0):j(_).unwrap_or(void 0);const ee=(m=(h=g.update)==null?void 0:h.at(0))==null?void 0:m.value;this.ref.onUpdate=ee instanceof Y?Te(ee).unwrap_or(void 0):j(ee).unwrap_or(void 0)}const p=Dt(n);return this.ref.endpoints=[{...pt(s,this.container),relation:p[0],token:A(s)},{...pt(i,this.container),relation:p[1],token:A(i)}],this.env.refIds[l]=this.declarationNode,[]}}class Ft{constructor(e,n){this.declarationNode=e,this.env=n,this.tableGroup={tables:[]}}interpret(){const e=[];return this.tableGroup.token=A(this.declarationNode),this.env.tableGroups.set(this.declarationNode,this.tableGroup),e.push(...this.interpretName(this.declarationNode.name),...this.interpretSettingList(this.declarationNode.attributeList),...this.interpretBody(this.declarationNode.body)),e}interpretName(e){const n=[],{name:s,schemaName:i}=Ie(e);return i.length>=2&&(this.tableGroup.name=s,this.tableGroup.schemaName=i.join("."),n.push(new c(o.UNSUPPORTED,"Nested schema is not supported",this.declarationNode.name))),this.tableGroup.name=s,this.tableGroup.schemaName=i[0]||null,n}interpretBody(e){const[n,s]=b.partition(e.body,i=>i instanceof w);return[...this.interpretFields(n),...this.interpretSubElements(s)]}interpretSubElements(e){return e.flatMap(n=>{var s;switch((s=n.type)==null?void 0:s.value.toLowerCase()){case"note":this.tableGroup.note={value:G(n.body instanceof J?n.body.body[0].callee:n.body.callee).map(re).unwrap(),token:A(n)};break}return[]})}interpretFields(e){const n=[];return this.tableGroup.tables=e.map(s=>{const i=W(s.callee).unwrap();i.length>2&&n.push(new c(o.UNSUPPORTED,"Nested schema is not supported",s));const r=pe(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),f=l?`${l}.${p}`:p;n.push(new c(o.TABLE_REAPPEAR_IN_TABLEGROUP,`Table "${i.join(".")}" already appears in group "${f}"`,s))}else this.env.groupOfTable[r]=this.declarationNode;return{name:i.pop(),schemaName:i.join(".")}}),n}interpretSettingList(e){var i,r,a;const n=B(e).getValue();this.tableGroup.color=(i=n.color)!=null&&i.length?Ke((a=(r=n.color)==null?void 0:r.at(0))==null?void 0:a.value):void 0;const[s]=n.note||[];return this.tableGroup.note=s&&{value:G(s==null?void 0:s.value).map(re).unwrap(),token:A(s)},[]}}class Bt{constructor(e,n){this.declarationNode=e,this.env=n,this.enum={values:[]}}interpret(){return this.enum.token=A(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}=Ie(e);return s.length>1?(this.enum.name=n,this.enum.schemaName=s.join("."),[new c(o.UNSUPPORTED,"Nested schema is not supported",e)]):(this.enum.name=n,this.enum.schemaName=s.length?s[0]:null,[])}interpretBody(e){return e.body.flatMap(n=>{var l;const s=n,i={};i.token=A(s),i.name=j(s.callee).unwrap();const a=(l=B(s.args[0]).getValue().note)==null?void 0:l.at(0);return i.note=a&&{value:G(a.value).map(re).unwrap(),token:A(a)},this.enum.values.push(i),[]})}}class Hn{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.project.token=A(this.declarationNode),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(e){if(!e)return this.project.name=null,[];const{name:n}=Ie(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 Ut(s,this.env).interpret();return this.project.tables.push(this.env.tables.get(s)),r}case"ref":{const r=new Mt(s,this.env).interpret();return this.project.refs.push(this.env.ref.get(s)),r}case"tablegroup":{const r=new Ft(s,this.env).interpret();return this.project.tableGroups.push(this.env.tableGroups.get(s)),r}case"enum":{const r=new Bt(s,this.env).interpret();return this.project.enums.push(this.env.enums.get(s)),r}case"note":return this.project.note={value:G(s.body instanceof J?s.body.body[0].callee:s.body.callee).map(re).unwrap(),token:A(s)},[];default:return this.project[s.type.value.toLowerCase()]=G(s.body.callee).unwrap(),[]}})}}class Jn{constructor(e){this.ast=e,this.env={schema:[],tables:new Map,notes:new Map,refIds:{},ref:new Map,enums:new Map,tableGroups:new Map,groupOfTable:{},aliases:[],project:new Map}}interpret(){const e=this.ast.body.flatMap(n=>{switch(ve(n).unwrap_or(void 0)){case I.Table:return new Ut(n,this.env).interpret();case I.Note:return new qn(n,this.env).interpret();case I.Ref:return new Mt(n,this.env).interpret();case I.TableGroup:return new Ft(n,this.env).interpret();case I.Enum:return new Bt(n,this.env).interpret();case I.Project:return new Hn(n,this.env).interpret();default:return[]}});return new V(Zn(this.env),e)}}function Zn(t){return{schemas:[],tables:Array.from(t.tables.values()),notes:Array.from(t.notes.values()),refs:Array.from(t.ref.values()),enums:Array.from(t.enums.values()),tableGroups:Array.from(t.tableGroups.values()),aliases:t.aliases,project:Array.from(t.project.values())[0]||{}}}var L=(t=>(t[t.Function=1]="Function",t[t.Constructor=2]="Constructor",t[t.Field=3]="Field",t[t.Variable=4]="Variable",t[t.Class=5]="Class",t[t.Struct=6]="Struct",t[t.Interface=7]="Interface",t[t.Module=8]="Module",t[t.Property=9]="Property",t[t.Event=10]="Event",t[t.Operator=11]="Operator",t[t.Unit=12]="Unit",t[t.Value=13]="Value",t[t.Constant=14]="Constant",t[t.Enum=15]="Enum",t[t.EnumMember=16]="EnumMember",t[t.Keyword=17]="Keyword",t[t.Text=18]="Text",t[t.Color=19]="Color",t[t.File=20]="File",t[t.Reference=21]="Reference",t[t.Customcolor=22]="Customcolor",t[t.Folder=23]="Folder",t[t.TypeParameter=24]="TypeParameter",t[t.User=25]="User",t[t.Issue=26]="Issue",t[t.Snippet=27]="Snippet",t))(L||{}),y=(t=>(t[t.None=0]="None",t[t.KeepWhitespace=1]="KeepWhitespace",t[t.InsertAsSnippet=4]="InsertAsSnippet",t))(y||{});function Ae(t){switch(t){case T.Schema:return L.Module;case T.Table:return L.Class;case T.Column:return L.Field;case T.Enum:return L.Enum;case T.EnumField:return L.EnumMember;case T.TableGroup:return L.Struct;case T.TableGroupField:return L.Field;default:return L.Text}}function Re(t,e){if(!t||Ce(t))return!1;for(const n of t.trailingTrivia){if(n.start>e)break;if(n.kind===u.NEWLINE&&n.end<=e)return!1}return!0}function D(){return{suggestions:[]}}function Pe(t){return{...t,suggestions:t.suggestions.map(e=>({...e,insertText:` ${e.insertText}`}))}}function Fe(t){return{...t,suggestions:t.suggestions.map(e=>({...e,insertText:e.insertText.split("").every(Me)?e.insertText:`"${e.insertText}"`}))}}function et(t,e){return t.getOffsetAt(e)}class Vt{constructor(e,n=[]){this.compiler=e,this.triggerCharacters=n}provideCompletionItems(e,n){var E,h;const s=et(e,n),i=this.compiler.token.flatStream(),{token:r,index:a}=this.compiler.container.token(s),l=a===void 0?i[0]:i[a+1];if([...(r==null?void 0:r.trailingTrivia)||[],...(r==null?void 0:r.leadingTrivia)||[],...(l==null?void 0:l.leadingTrivia)||[]].find(m=>Yt(m)&&ge(s,m)))return D();if(a===void 0)return Tt();if([u.STRING_LITERAL,u.QUOTED_STRING].includes(r.kind)&&ge(s,r))return D();const p=this.compiler.container.element(s);if(this.compiler.container.scopeKind(s)===O.TOPLEVEL||p instanceof v&&p.type&&p.type.start<=s&&p.type.end>=s)return Tt();const f=[...this.compiler.container.stack(s)].reverse();for(const m of f)if(m instanceof Q)switch((E=m.op)==null?void 0:E.value){case">":case"<":case"<>":case"-":return dt(this.compiler,s,m)}else if(m instanceof q)switch((h=m.op)==null?void 0:h.value){case">":case"<":case"<>":case"-":return dt(this.compiler,s,m);case".":return Gt(this.compiler,s,m)}else{if(m instanceof se)return Et(this.compiler,s,m);if(m instanceof R)return Et(this.compiler,s,m);if(m instanceof Z)return Kn(this.compiler,s);if(m instanceof w)return mt(this.compiler,s,m);if(m instanceof v&&(m.bodyColon&&s>=m.bodyColon.end||m.body&&ge(s,m.body)))return mt(this.compiler,s,void 0)}return D()}}function dt(t,e,n){const s=t.container.scopeKind(e);if([O.REF,O.TABLE].includes(s)){const i=Be(t,e,t.container.element(e),[T.Table,T.Schema,T.Column]);return Re(n.op,e)?Pe(i):i}return D()}function Be(t,e,n,s){var a;if(n===void 0)return D();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:f})=>({label:p,insertText:p,insertTextRules:y.KeepWhitespace,kind:Ae(f),sortText:Ae(f).toString().padStart(2,"0"),range:void 0})))}i=i instanceof v?i.parent:void 0}return Fe(r)}function Kn(t,e){var s;switch(t.container.scopeKind(e)){case O.INDEXES:return Xt(t,e);case O.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 Gt(t,e,r)}}return Ct(t,e)}return D()}function Et(t,e,n){const{token:s}=t.container.token(e);if([u.COMMA,u.LBRACKET].includes(s==null?void 0:s.kind)){const i=Nt(t,e);return(s==null?void 0:s.kind)===u.COMMA&&Re(s,e)?Pe(i):i}if(n.name&&n.name.start<=e&&n.name.end>=e)return Nt(t,e);if(n.name instanceof Y){const i=es(t,e,Te(n.name).unwrap_or(""));return(s==null?void 0:s.kind)===u.COLON&&Re(s,e)?Pe(i):i}return D()}function Nt(t,e){const n=t.container.element(e),s=t.container.scopeKind(e);if(n instanceof X)return D();if(n.body&&!ge(e,n.body))switch(s){case O.TABLE:return{suggestions:["headercolor","note"].map(i=>({label:i,insertText:`${i}: `,kind:L.Field,insertTextRules:y.KeepWhitespace,range:void 0}))};case O.TABLEGROUP:return{suggestions:["color","note"].map(i=>({label:i,insertText:`${i}: `,kind:L.Field,insertTextRules:y.KeepWhitespace,range:void 0}))};default:return D()}switch(s){case O.TABLE:return{suggestions:[...["primary key","null","not null","increment","pk","unique"].map(i=>({label:i,insertText:i,kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0})),...["ref","default"].map(i=>({label:i,insertText:`${i}: `,kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0})),{label:"note",insertText:"note: ",kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0}]};case O.ENUM:return{suggestions:[{label:"note",insertText:"note: ",kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0}]};case O.INDEXES:return{suggestions:[...["unique","pk"].map(i=>({label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:L.Property,range:void 0})),...["note","name","type"].map(i=>({label:i,insertText:`${i}: `,kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0}))]};case O.REF:return{suggestions:["update","delete"].map(i=>({label:i,insertText:`${i}: `,kind:L.Property,insertTextRules:y.KeepWhitespace,range:void 0}))}}return D()}function es(t,e,n){switch(n==null?void 0:n.toLowerCase()){case"update":case"delete":return{suggestions:["cascade","set default","set null","restrict"].map(s=>({label:s,insertText:s,kind:L.Value,insertTextRules:y.KeepWhitespace,range:void 0}))};case"type":return{suggestions:["btree","hash"].map(s=>({label:s,insertText:`${s}`,kind:L.Value,insertTextRules:y.KeepWhitespace,range:void 0}))}}return D()}function Gt(t,e,n){const s=pe(n).unwrap_or([]);if(s.pop(),s.some(r=>!M(r)))return D();const i=s.map(r=>j(r).unwrap());return Fe({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:Ae(r),range:void 0}))})}function mt(t,e,n){var i;switch(t.container.scopeKind(e)){case O.TABLE:return ns(t,e,n);case O.PROJECT:return ss(t,e,n);case O.INDEXES:return rs(t,e);case O.ENUM:return ts(t,e,n);case O.REF:{const r=Ct(t,e);return((i=t.container.token(e).token)==null?void 0:i.kind)===u.COLON&&Re(t.container.token(e).token,e)?Pe(r):r}case O.TABLEGROUP:return is(t);default:return D()}}function Tt(){return{suggestions:["Table","TableGroup","Enum","Project","Ref"].map(t=>({label:t,insertText:t,insertTextRules:y.KeepWhitespace,kind:L.Keyword,range:void 0}))}}function ts(t,e,n){return n!=null&&n.callee&&tt(e,n)===1?Be(t,e,t.container.element(e),[T.Schema,T.Table,T.Column]):D()}function ns(t,e,n){if(!(n!=null&&n.callee))return{suggestions:["Note","indexes"].map(i=>({label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:L.Keyword,range:void 0}))};const s=tt(e,n);return s===0?{suggestions:["Note","indexes"].map(i=>({label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:L.Keyword,range:void 0}))}:s===1?as(t,e):D()}function ss(t,e,n){return n!=null&&n.callee?tt(e,n)===0?{suggestions:["Table","TableGroup","Enum","Note","Ref"].map(i=>({label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:L.Keyword,range:void 0}))}:D():{suggestions:["Table","TableGroup","Enum","Note","Ref"].map(i=>({label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:L.Keyword,range:void 0}))}}function Ct(t,e){return Be(t,e,t.container.element(e),[T.Schema,T.Table,T.Column])}function is(t){return{suggestions:[...Fe({suggestions:[...t.parse.publicSymbolTable().entries()].flatMap(([e])=>{const n=ie(e).unwrap_or(void 0);if(n===void 0)return[];const{kind:s,name:i}=n;return s!==T.Table&&s!==T.Schema?[]:{label:i,insertText:i,insertTextRules:y.KeepWhitespace,kind:Ae(s),range:void 0}})}).suggestions,...["Note"].map(e=>({label:e,insertText:e,insertTextRules:y.KeepWhitespace,kind:L.Keyword,range:void 0}))]}}function rs(t,e){return Xt(t,e)}function as(t,e){return{suggestions:[...["integer","int","tinyint","smallint","mediumint","bigint","bit","bool","binary","varbinary","logical","char","nchar","varchar","varchar2","nvarchar","nvarchar2","binary_float","binary_double","float","double","decimal","dec","real","money","smallmoney","enum","tinyblob","tinytext","blob","text","mediumblob","mediumtext","longblob","longtext","ntext","set","inet6","uuid","image","date","time","datetime","datetime2","timestamp","year","smalldatetime","datetimeoffset","XML","sql_variant","uniqueidentifier","CURSOR","BFILE","CLOB","NCLOB","RAW"].map(n=>({label:n,insertText:n,insertTextRules:y.KeepWhitespace,kind:L.TypeParameter,sortText:L.TypeParameter.toString().padStart(2,"0"),range:void 0})),...Be(t,e,t.container.element(e),[T.Enum,T.Schema]).suggestions]}}function Xt(t,e){const n=t.container.element(e),s=n==null?void 0:n.parent;if(!((s==null?void 0:s.symbol)instanceof At))return D();const{symbolTable:i}=s.symbol;return Fe({suggestions:[...i.entries()].flatMap(([r])=>{const a=ie(r).unwrap_or(void 0);if(a===void 0)return[];const{name:l}=a;return{label:l,insertText:l,insertTextRules:y.KeepWhitespace,kind:Ae(T.Column),range:void 0}})})}function tt(t,e){if(!e.callee)return-1;const n=[e.callee,...e.args],s=n.findIndex(i=>t<=i.end);return s===-1?n.length:s}class $t{constructor(e){this.compiler=e}provideDefinition(e,n){var a;const{uri:s}=e,i=et(e,n),r=[...this.compiler.container.stack(i)];for(;r.length!==0;){const l=r.pop();if((a=l==null?void 0:l.referee)!=null&&a.declaration&&[Ne.PRIMARY_EXPRESSION,Ne.VARIABLE].includes(l==null?void 0:l.kind)){const{startPos:p,endPos:f}=l.referee.declaration;return[{range:{startColumn:p.column+1,startLineNumber:p.line+1,endColumn:f.column+1,endLineNumber:f.line+1},uri:s}]}}return[]}}class Wt{constructor(e){this.compiler=e}provideReferences(e,n){const{uri:s}=e,i=et(e,n),r=[...this.compiler.container.stack(i)];for(;r.length!==0;){const a=r.pop();if(a&&[Ne.ELEMENT_DECLARATION,Ne.FUNCTION_APPLICATION,Ne.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:f})=>({range:{startColumn:p.column+1,startLineNumber:p.line+1,endColumn:f.column+1,endLineNumber:f.line+1},uri:s}))}}return[]}}const os=Object.freeze(Object.defineProperty({__proto__:null,CompletionItemInsertTextRule:y,CompletionItemKind:L,DBMLCompletionItemProvider:Vt,DBMLDefinitionProvider:$t,DBMLReferencesProvider:Wt},Symbol.toStringTag,{value:"Module"}));var O=(t=>(t[t.TABLE=0]="TABLE",t[t.ENUM=1]="ENUM",t[t.TABLEGROUP=2]="TABLEGROUP",t[t.INDEXES=3]="INDEXES",t[t.NOTE=4]="NOTE",t[t.REF=5]="REF",t[t.PROJECT=6]="PROJECT",t[t.CUSTOM=7]="CUSTOM",t[t.TOPLEVEL=8]="TOPLEVEL",t))(O||{});class ls{constructor(){this.source="",this.cache=new Array(16).fill(null),this.nodeIdGenerator=new zt,this.symbolIdGenerator=new Kt,this.token={invalidStream:this.createQuery(6,()=>this.parse.tokens().filter(vt)),flatStream:this.createQuery(7,()=>this.parse.tokens().flatMap(e=>[...e.leadingInvalid,e,...e.trailingInvalid]))},this.parse={source:()=>this.source,_:this.createQuery(0,()=>{const e=new un(this.source).lex().chain(n=>new pn(n,this.nodeIdGenerator).parse()).chain(({ast:n,tokens:s})=>new Yn(n,this.symbolIdGenerator).analyze().map(()=>({ast:n,tokens:s})));return e.getErrors().length>0?e:e.chain(({ast:n,tokens:s})=>new Jn(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.token.flatStream(),{index:s,token:i}=this.container.token(e),r=s===void 0?-1:b.findLastIndex(n,f=>!f.isInvalid,s);if(r===-1)return[this.parse.ast()];const a=n[r].start;let l=this.parse.ast();const p=[l];for(;;){const E=cn(l).find(h=>ge(a,h));if(E===void 0||E instanceof F)break;p.push(E),l=E}if((i==null?void 0:i.kind)===u.COLON)return p;for(;p.length>0;){let f=!1;const E=b.last(p);if(E instanceof w){const h=this.parse.source();for(let m=E.end;m<e;m+=1)h[m]===`
12
12
  `&&(p.pop(),f=!0)}else E instanceof Q||E instanceof q?this.container.token(e).token!==E.op&&(p.pop(),f=!0):E instanceof R?E.listCloseBracket&&E.end<=e&&(p.pop(),f=!0):E instanceof Z?E.tupleCloseParen&&E.end<=e&&(p.pop(),f=!0):E instanceof J?E.blockCloseBrace&&E.end<=e&&(p.pop(),f=!0):E instanceof Y||E.end<e&&(p.pop(),f=!0);if(f){const h=b.last(p);h instanceof v&&h.end<=e&&p.pop()}if(!f)break}return p}),token:this.createQuery(11,e=>{const n=this.token.flatStream().findIndex(s=>s.start>=e);return n===void 0?{token:void 0,index:void 0}:n<=0?{token:void 0,index:void 0}:{token:this.token.flatStream()[n-1],index:n-1}}),element:this.createQuery(12,e=>{const n=this.container.stack(e);for(let s=n.length-1;s>=0;s-=1)if(n[s]instanceof v)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 X)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 v?r.parent:void 0){if(!((i=r.symbol)!=null&&i.symbolTable))continue;const{symbolTable:a}=r.symbol;let l=[a],p=[];for(const f of e)p=l.flatMap(E=>Jt(f).flatMap(h=>{const m=E.get(h),g=ie(h).unwrap_or(void 0);return!m||!g?[]:{...g,symbol:m}})),l=p.flatMap(E=>E.symbol.symbolTable?E.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])=>({...ie(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 $t(this),referenceProvider:new Wt(this),autocompletionProvider:new Vt(this)}}}exports.Compiler=ls;exports.serialize=Qt;exports.services=os;
@@ -954,7 +954,7 @@ class fn {
954
954
  case "r":
955
955
  return "\r";
956
956
  case "'":
957
- return this.peek() === "'" && this.peek(1) === "'" ? (this.advance(), this.advance(), "'''") : "'";
957
+ return "'";
958
958
  case '"':
959
959
  return '"';
960
960
  case "0":
package/dist/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import { serialize } from './lib/serialization/serialize';
2
2
  import { default as Compiler } from './compiler';
3
-
4
3
  import * as services from './services/index';
5
4
  export { serialize, Compiler, services };
@@ -2,7 +2,6 @@ import { ProgramNode } from '../parser/nodes';
2
2
  import { default as Report } from '../report';
3
3
  import { CompileError } from '../errors';
4
4
  import { NodeSymbolIdGenerator } from './symbol/symbols';
5
-
6
5
  export default class Analyzer {
7
6
  private ast;
8
7
  private symbolFactory;
@@ -1,7 +1,6 @@
1
1
  import { CompileError } from '../../errors';
2
2
  import { ProgramNode } from '../../parser/nodes';
3
3
  import { default as Report } from '../../report';
4
-
5
4
  export default class Binder {
6
5
  private ast;
7
6
  private errors;
@@ -1,5 +1,4 @@
1
1
  import { default as ElementBinder } from './elementBinder';
2
-
3
2
  export default class CustomBinder extends ElementBinder {
4
3
  protected subfield: {
5
4
  arg: {
@@ -1,7 +1,6 @@
1
1
  import { ElementDeclarationNode, SyntaxNode } from '../../../parser/nodes';
2
2
  import { ArgumentBinderRule, SettingListBinderRule } from '../types';
3
3
  import { CompileError } from '../../../errors';
4
-
5
4
  export default abstract class ElementBinder {
6
5
  protected abstract subfield: {
7
6
  arg: ArgumentBinderRule;
@@ -1,5 +1,4 @@
1
1
  import { default as ElementBinder } from './elementBinder';
2
-
3
2
  export default class EnumBinder extends ElementBinder {
4
3
  protected subfield: {
5
4
  arg: {
@@ -1,6 +1,5 @@
1
1
  import { SymbolKind } from '../../symbol/symbolIndex';
2
2
  import { default as ElementBinder } from './elementBinder';
3
-
4
3
  export default class IndexesBinder extends ElementBinder {
5
4
  protected subfield: {
6
5
  arg: {
@@ -1,5 +1,4 @@
1
1
  import { default as ElementBinder } from './elementBinder';
2
-
3
2
  export default class NoteBinder extends ElementBinder {
4
3
  protected subfield: {
5
4
  arg: {
@@ -1,5 +1,4 @@
1
1
  import { default as ElementBinder } from './elementBinder';
2
-
3
2
  export default class ProjectBinder extends ElementBinder {
4
3
  protected subfield: {
5
4
  arg: {
@@ -1,6 +1,5 @@
1
1
  import { SymbolKind } from '../../symbol/symbolIndex';
2
2
  import { default as ElementBinder } from './elementBinder';
3
-
4
3
  export default class RefBinder extends ElementBinder {
5
4
  protected subfield: {
6
5
  arg: {
@@ -1,6 +1,5 @@
1
1
  import { SymbolKind } from '../../symbol/symbolIndex';
2
2
  import { default as ElementBinder } from './elementBinder';
3
-
4
3
  export default class TableBinder extends ElementBinder {
5
4
  protected subfield: {
6
5
  arg: {
@@ -1,6 +1,5 @@
1
1
  import { SymbolKind } from '../../symbol/symbolIndex';
2
2
  import { default as ElementBinder } from './elementBinder';
3
-
4
3
  export default class TableGroupBinder extends ElementBinder {
5
4
  protected subfield: {
6
5
  arg: {
@@ -0,0 +1,16 @@
1
+ import { SymbolKind } from '../symbol/symbolIndex';
2
+ export type BinderRule = {
3
+ shouldBind: true;
4
+ topSubnamesSymbolKind: SymbolKind[];
5
+ remainingSubnamesSymbolKind: SymbolKind;
6
+ ignoreNameNotFound: boolean;
7
+ keywords?: readonly string[];
8
+ } | {
9
+ shouldBind: false;
10
+ };
11
+ export interface ArgumentBinderRule {
12
+ argBinderRules: BinderRule[];
13
+ }
14
+ export interface SettingListBinderRule {
15
+ [index: string]: BinderRule;
16
+ }
@@ -8,7 +8,6 @@ import { default as ProjectBinder } from './elementBinder/project';
8
8
  import { default as RefBinder } from './elementBinder/ref';
9
9
  import { default as TableBinder } from './elementBinder/table';
10
10
  import { default as TableGroupBinder } from './elementBinder/tableGroup';
11
-
12
11
  export declare function pickBinder(element: ElementDeclarationNode & {
13
12
  type: SyntaxToken;
14
13
  }): typeof EnumBinder | typeof TableBinder | typeof TableGroupBinder | typeof ProjectBinder | typeof RefBinder | typeof NoteBinder | typeof IndexesBinder | typeof CustomBinder;
@@ -1,5 +1,4 @@
1
1
  import { NodeSymbol, NodeSymbolId, NodeSymbolIdGenerator } from './symbols';
2
-
3
2
  export default class SymbolFactory {
4
3
  private generator;
5
4
  constructor(generator: NodeSymbolIdGenerator);
@@ -1,5 +1,4 @@
1
1
  import { Option } from '../../option';
2
-
3
2
  export type NodeSymbolIndex = string;
4
3
  export declare enum SymbolKind {
5
4
  Schema = "Schema",
@@ -1,6 +1,5 @@
1
1
  import { NodeSymbolIndex } from './symbolIndex';
2
2
  import { NodeSymbol } from './symbols';
3
-
4
3
  export default class SymbolTable {
5
4
  private table;
6
5
  constructor();
@@ -1,6 +1,5 @@
1
1
  import { default as SymbolTable } from './symbolTable';
2
2
  import { SyntaxNode } from '../../parser/nodes';
3
-
4
3
  export type NodeSymbolId = number;
5
4
  export declare class NodeSymbolIdGenerator {
6
5
  private id;
@@ -1,3 +1,2 @@
1
1
  import { NodeSymbolIndex } from './symbolIndex';
2
-
3
2
  export declare function generatePossibleIndexes(name: string): NodeSymbolIndex[];
@@ -4,7 +4,6 @@ import { NodeSymbolIndex } from './symbol/symbolIndex';
4
4
  import { NodeSymbol } from './symbol/symbols';
5
5
  import { SyntaxToken } from '../lexer/tokens';
6
6
  import { ElementKind } from './types';
7
-
8
7
  export declare function getElementKind(node?: ElementDeclarationNode): Option<ElementKind>;
9
8
  export declare function destructureMemberAccessExpression(node: SyntaxNode): Option<SyntaxNode[]>;
10
9
  export declare function destructureComplexVariable(node?: SyntaxNode): Option<string[]>;
@@ -4,7 +4,6 @@ import { default as SymbolFactory } from '../../symbol/factory';
4
4
  import { SyntaxToken } from '../../../lexer/tokens';
5
5
  import { ElementValidator } from '../types';
6
6
  import { default as SymbolTable } from '../../../analyzer/symbol/symbolTable';
7
-
8
7
  export default class CustomValidator implements ElementValidator {
9
8
  private declarationNode;
10
9
  private publicSymbolTable;
@@ -4,7 +4,6 @@ import { BlockExpressionNode, ElementDeclarationNode, FunctionApplicationNode, L
4
4
  import { SyntaxToken } from '../../../lexer/tokens';
5
5
  import { ElementValidator } from '../types';
6
6
  import { default as SymbolTable } from '../../../analyzer/symbol/symbolTable';
7
-
8
7
  export default class EnumValidator implements ElementValidator {
9
8
  private declarationNode;
10
9
  private publicSymbolTable;
@@ -4,7 +4,6 @@ import { ElementDeclarationNode, SyntaxNode } from '../../../parser/nodes';
4
4
  import { SyntaxToken } from '../../../lexer/tokens';
5
5
  import { ElementValidator } from '../types';
6
6
  import { default as SymbolTable } from '../../../analyzer/symbol/symbolTable';
7
-
8
7
  export default class IndexesValidator implements ElementValidator {
9
8
  private declarationNode;
10
9
  private publicSymbolTable;
@@ -4,7 +4,6 @@ import { BlockExpressionNode, ElementDeclarationNode, FunctionApplicationNode }
4
4
  import { SyntaxToken } from '../../../lexer/tokens';
5
5
  import { ElementValidator } from '../types';
6
6
  import { default as SymbolTable } from '../../symbol/symbolTable';
7
-
8
7
  export default class NoteValidator implements ElementValidator {
9
8
  private declarationNode;
10
9
  private publicSymbolTable;
@@ -4,7 +4,6 @@ import { BlockExpressionNode, ElementDeclarationNode, FunctionApplicationNode }
4
4
  import { SyntaxToken } from '../../../lexer/tokens';
5
5
  import { ElementValidator } from '../types';
6
6
  import { default as SymbolTable } from '../../../analyzer/symbol/symbolTable';
7
-
8
7
  export default class ProjectValidator implements ElementValidator {
9
8
  private declarationNode;
10
9
  private publicSymbolTable;
@@ -4,7 +4,6 @@ import { CompileError } from '../../../errors';
4
4
  import { BlockExpressionNode, ElementDeclarationNode, FunctionApplicationNode, ListExpressionNode } from '../../../parser/nodes';
5
5
  import { ElementValidator } from '../types';
6
6
  import { default as SymbolTable } from '../../../analyzer/symbol/symbolTable';
7
-
8
7
  export default class RefValidator implements ElementValidator {
9
8
  private declarationNode;
10
9
  private publicSymbolTable;
@@ -4,7 +4,6 @@ import { BlockExpressionNode, ElementDeclarationNode, ExpressionNode, FunctionAp
4
4
  import { ElementValidator } from '../types';
5
5
  import { SyntaxToken } from '../../../lexer/tokens';
6
6
  import { default as SymbolTable } from '../../../analyzer/symbol/symbolTable';
7
-
8
7
  export default class TableValidator implements ElementValidator {
9
8
  private declarationNode;
10
9
  private symbolFactory;
@@ -4,7 +4,6 @@ import { default as SymbolTable } from '../../symbol/symbolTable';
4
4
  import { SyntaxToken } from '../../../lexer/tokens';
5
5
  import { BlockExpressionNode, ElementDeclarationNode, FunctionApplicationNode } from '../../../parser/nodes';
6
6
  import { default as SymbolFactory } from '../../symbol/factory';
7
-
8
7
  export default class TableGroupValidator implements ElementValidator {
9
8
  private declarationNode;
10
9
  private publicSymbolTable;
@@ -0,0 +1,4 @@
1
+ import { CompileError } from '../../errors';
2
+ export interface ElementValidator {
3
+ validate(): CompileError[];
4
+ }
@@ -12,7 +12,6 @@ import { default as SymbolTable } from '../symbol/symbolTable';
12
12
  import { default as SymbolFactory } from '../symbol/factory';
13
13
  import { default as Report } from '../../report';
14
14
  import { CompileError } from '../../errors';
15
-
16
15
  export declare function pickValidator(element: ElementDeclarationNode & {
17
16
  type: SyntaxToken;
18
17
  }): typeof CustomValidator | typeof EnumValidator | typeof TableValidator | typeof TableGroupValidator | typeof ProjectValidator | typeof RefValidator | typeof NoteValidator | typeof IndexesValidator;
@@ -2,7 +2,6 @@ import { default as Report } from '../../report';
2
2
  import { CompileError } from '../../errors';
3
3
  import { ProgramNode } from '../../parser/nodes';
4
4
  import { default as SymbolFactory } from '../symbol/factory';
5
-
6
5
  export default class Validator {
7
6
  private ast;
8
7
  private publicSchemaSymbol;
@@ -1,6 +1,5 @@
1
1
  import { SyntaxToken } from './lexer/tokens';
2
2
  import { SyntaxNode } from './parser/nodes';
3
-
4
3
  export declare enum CompileErrorCode {
5
4
  UNKNOWN_SYMBOL = 1000,
6
5
  UNEXPECTED_SYMBOL = 1001,
@@ -1,7 +1,6 @@
1
1
  import { CompileError } from '../../errors';
2
2
  import { ElementDeclarationNode } from '../../parser/nodes';
3
3
  import { ElementInterpreter, InterpreterDatabase } from '../types';
4
-
5
4
  export declare class EnumInterpreter implements ElementInterpreter {
6
5
  private declarationNode;
7
6
  private env;
@@ -1,7 +1,6 @@
1
1
  import { CompileError } from '../../errors';
2
2
  import { ElementDeclarationNode } from '../../parser/nodes';
3
3
  import { ElementInterpreter, InterpreterDatabase } from '../types';
4
-
5
4
  export declare class ProjectInterpreter implements ElementInterpreter {
6
5
  private declarationNode;
7
6
  private env;
@@ -1,7 +1,6 @@
1
1
  import { CompileError } from '../../errors';
2
2
  import { ElementDeclarationNode } from '../../parser/nodes';
3
3
  import { ElementInterpreter, InterpreterDatabase } from '../types';
4
-
5
4
  export declare class RefInterpreter implements ElementInterpreter {
6
5
  private declarationNode;
7
6
  private env;
@@ -1,7 +1,6 @@
1
1
  import { ElementInterpreter, InterpreterDatabase } from '../types';
2
2
  import { ElementDeclarationNode } from '../../parser/nodes';
3
3
  import { CompileError } from '../../errors';
4
-
5
4
  export declare class StickyNoteInterpreter implements ElementInterpreter {
6
5
  private declarationNode;
7
6
  private env;
@@ -1,7 +1,6 @@
1
1
  import { ElementInterpreter, InterpreterDatabase } from '../types';
2
2
  import { ElementDeclarationNode } from '../../parser/nodes';
3
3
  import { CompileError } from '../../errors';
4
-
5
4
  export declare class TableInterpreter implements ElementInterpreter {
6
5
  private declarationNode;
7
6
  private env;
@@ -1,7 +1,6 @@
1
1
  import { CompileError } from '../../errors';
2
2
  import { ElementDeclarationNode } from '../../parser/nodes';
3
3
  import { ElementInterpreter, InterpreterDatabase } from '../types';
4
-
5
4
  export declare class TableGroupInterpreter implements ElementInterpreter {
6
5
  private declarationNode;
7
6
  private env;
@@ -2,7 +2,6 @@ import { ProgramNode } from '../parser/nodes';
2
2
  import { CompileError } from '../errors';
3
3
  import { Database, InterpreterDatabase } from './types';
4
4
  import { default as Report } from '../report';
5
-
6
5
  export default class Interpreter {
7
6
  ast: ProgramNode;
8
7
  env: InterpreterDatabase;
@@ -0,0 +1,168 @@
1
+ import { ElementDeclarationNode } from '../parser/nodes';
2
+ import { Position } from '../types';
3
+ import { CompileError } from '../errors';
4
+ export interface TokenPosition {
5
+ start: Position;
6
+ end: Position;
7
+ }
8
+ export interface ElementInterpreter {
9
+ interpret(): CompileError[];
10
+ }
11
+ export interface InterpreterDatabase {
12
+ schema: [];
13
+ tables: Map<ElementDeclarationNode, Table>;
14
+ notes: Map<ElementDeclarationNode, Note>;
15
+ refIds: {
16
+ [refid: string]: ElementDeclarationNode;
17
+ };
18
+ ref: Map<ElementDeclarationNode, Ref>;
19
+ enums: Map<ElementDeclarationNode, Enum>;
20
+ groupOfTable: {
21
+ [tableid: string]: ElementDeclarationNode;
22
+ };
23
+ tableGroups: Map<ElementDeclarationNode, TableGroup>;
24
+ aliases: Alias[];
25
+ project: Map<ElementDeclarationNode, Project>;
26
+ }
27
+ export interface Database {
28
+ schemas: [];
29
+ tables: Table[];
30
+ notes: Note[];
31
+ refs: Ref[];
32
+ enums: Enum[];
33
+ tableGroups: TableGroup[];
34
+ aliases: Alias[];
35
+ project: Project;
36
+ }
37
+ export interface Table {
38
+ name: string;
39
+ schemaName: null | string;
40
+ alias: string | null;
41
+ fields: Column[];
42
+ token: TokenPosition;
43
+ indexes: Index[];
44
+ headerColor?: string;
45
+ note?: {
46
+ value: string;
47
+ token: TokenPosition;
48
+ };
49
+ }
50
+ export interface Note {
51
+ name: string;
52
+ content: string;
53
+ token: TokenPosition;
54
+ headerColor?: string;
55
+ }
56
+ export interface ColumnType {
57
+ schemaName: string | null;
58
+ type_name: string;
59
+ args: string | null;
60
+ }
61
+ export interface Column {
62
+ name: string;
63
+ type: ColumnType;
64
+ token: TokenPosition;
65
+ inline_refs: InlineRef[];
66
+ pk?: boolean;
67
+ dbdefault?: {
68
+ type: 'number' | 'string' | 'boolean' | 'expression';
69
+ value: number | string;
70
+ };
71
+ increment?: boolean;
72
+ unique?: boolean;
73
+ not_null?: boolean;
74
+ note?: {
75
+ value: string;
76
+ token: TokenPosition;
77
+ };
78
+ }
79
+ export interface Index {
80
+ columns: {
81
+ value: string;
82
+ type: string;
83
+ token: TokenPosition;
84
+ }[];
85
+ token: TokenPosition;
86
+ unique?: boolean;
87
+ pk?: boolean;
88
+ name?: string;
89
+ note?: {
90
+ value: string;
91
+ token: TokenPosition;
92
+ };
93
+ type?: string;
94
+ }
95
+ export interface InlineRef {
96
+ schemaName: string | null;
97
+ tableName: string;
98
+ fieldNames: string[];
99
+ relation: '>' | '<' | '-' | '<>';
100
+ token: TokenPosition;
101
+ }
102
+ export interface Ref {
103
+ schemaName: string | null;
104
+ name: string | null;
105
+ endpoints: RefEndpointPair;
106
+ onDelete?: string;
107
+ onUpdate?: string;
108
+ token: TokenPosition;
109
+ }
110
+ export type RefEndpointPair = [RefEndpoint, RefEndpoint];
111
+ export interface RefEndpoint {
112
+ schemaName: string | null;
113
+ tableName: string;
114
+ fieldNames: string[];
115
+ relation: RelationCardinality;
116
+ token: TokenPosition;
117
+ }
118
+ export type RelationCardinality = '1' | '*';
119
+ export interface Enum {
120
+ name: string;
121
+ schemaName: string | null;
122
+ token: TokenPosition;
123
+ values: EnumField[];
124
+ }
125
+ export interface EnumField {
126
+ name: string;
127
+ token: TokenPosition;
128
+ note?: {
129
+ value: string;
130
+ token: TokenPosition;
131
+ };
132
+ }
133
+ export interface TableGroup {
134
+ name: string | null;
135
+ schemaName: string | null;
136
+ tables: TableGroupField[];
137
+ token: TokenPosition;
138
+ color?: string;
139
+ note?: {
140
+ value: string;
141
+ token: TokenPosition;
142
+ };
143
+ }
144
+ export interface TableGroupField {
145
+ name: string;
146
+ schemaName: string | null;
147
+ }
148
+ export interface Alias {
149
+ name: string;
150
+ kind: 'table';
151
+ value: {
152
+ tableName: string;
153
+ schemaName: string | null;
154
+ };
155
+ }
156
+ export type Project = Record<string, never> | {
157
+ name: string | null;
158
+ tables: Table[];
159
+ refs: Ref[];
160
+ enums: Enum[];
161
+ tableGroups: TableGroup[];
162
+ note?: {
163
+ value: string;
164
+ token: TokenPosition;
165
+ };
166
+ token: TokenPosition;
167
+ [index: string & Omit<any, 'name' | 'tables' | 'refs' | 'enums' | 'tableGroups' | 'note'>]: string;
168
+ };
@@ -2,7 +2,6 @@ import { ColumnSymbol } from '../analyzer/symbol/symbols';
2
2
  import { LiteralNode, PrimaryExpressionNode, SyntaxNode } from '../parser/nodes';
3
3
  import { RelationCardinality, Table, TokenPosition } from './types';
4
4
  import { SyntaxTokenKind } from '../lexer/tokens';
5
-
6
5
  export declare function extractNamesFromRefOperand(operand: SyntaxNode, owner?: Table): {
7
6
  schemaName: string | null;
8
7
  tableName: string;
@@ -1,7 +1,6 @@
1
1
  import { CompileError } from '../errors';
2
2
  import { default as Report } from '../report';
3
3
  import { SyntaxToken, SyntaxTokenKind } from './tokens';
4
-
5
4
  export default class Lexer {
6
5
  private start;
7
6
  private current;
@@ -1,5 +1,4 @@
1
1
  import { Position } from '../types';
2
-
3
2
  export declare enum SyntaxTokenKind {
4
3
  SPACE = "<space>",
5
4
  TAB = "<tab>",
@@ -1,5 +1,4 @@
1
1
  import { SyntaxToken } from './tokens';
2
-
3
2
  export declare function hasTrailingNewLines(token: SyntaxToken): boolean;
4
3
  export declare function isAtStartOfLine(previous: SyntaxToken, token: SyntaxToken): boolean;
5
4
  export declare function hasTrailingSpaces(token: SyntaxToken): boolean;
@@ -1,5 +1,4 @@
1
1
  import { SyntaxToken } from '../lexer/tokens';
2
-
3
2
  export declare const enum ParsingContext {
4
3
  ListExpression = 0,
5
4
  GroupExpression = 1,
@@ -1,5 +1,4 @@
1
1
  import { SyntaxNode, SyntaxNodeId, SyntaxNodeIdGenerator } from './nodes';
2
-
3
2
  export default class NodeFactory {
4
3
  private generator;
5
4
  constructor(generator: SyntaxNodeIdGenerator);
@@ -1,7 +1,6 @@
1
1
  import { SyntaxToken } from '../lexer/tokens';
2
2
  import { NodeSymbol } from '../analyzer/symbol/symbols';
3
3
  import { Position } from '../types';
4
-
5
4
  export type SyntaxNodeId = number;
6
5
  export declare class SyntaxNodeIdGenerator {
7
6
  private id;
@@ -2,7 +2,6 @@ import { CompileError } from '../errors';
2
2
  import { SyntaxToken } from '../lexer/tokens';
3
3
  import { default as Report } from '../report';
4
4
  import { ProgramNode, SyntaxNodeIdGenerator } from './nodes';
5
-
6
5
  export default class Parser {
7
6
  private tokens;
8
7
  private current;
@@ -2,7 +2,6 @@ import { SyntaxToken, SyntaxTokenKind } from '../lexer/tokens';
2
2
  import { Option } from '../option';
3
3
  import { default as NodeFactory } from './factory';
4
4
  import { ElementDeclarationNode, ExpressionNode, IdentiferStreamNode, InfixExpressionNode, LiteralNode, NormalExpressionNode, PrimaryExpressionNode, SyntaxNode, VariableNode } from './nodes';
5
-
6
5
  export declare function convertFuncAppToElem(callee: ExpressionNode | undefined, args: NormalExpressionNode[], factory: NodeFactory): Option<ElementDeclarationNode>;
7
6
  export declare function isAsKeyword(token: SyntaxToken): token is SyntaxToken & {
8
7
  kind: SyntaxTokenKind.IDENTIFIER;
@@ -1,5 +1,4 @@
1
1
  import { ProgramNode } from '../parser/nodes';
2
2
  import { default as Report } from '../report';
3
3
  import { CompileError } from '../errors';
4
-
5
4
  export declare function serialize(report: Readonly<Report<ProgramNode, CompileError>>, pretty?: boolean): string;
@@ -0,0 +1,5 @@
1
+ export interface Position {
2
+ offset: number;
3
+ line: number;
4
+ column: number;
5
+ }
@@ -1,6 +1,5 @@
1
1
  import { SyntaxToken } from './lexer/tokens';
2
2
  import { SyntaxNode } from './parser/nodes';
3
-
4
3
  export declare function isAlphaOrUnderscore(char: string): boolean;
5
4
  export declare function isDigit(char: string): boolean;
6
5
  export declare function isHexChar(char: string): boolean;
@@ -1,6 +1,5 @@
1
1
  import { Definition, DefinitionProvider, TextModel, Position } from '../types';
2
2
  import { default as Compiler } from '../../compiler';
3
-
4
3
  export default class DBMLDefinitionProvider implements DefinitionProvider {
5
4
  private compiler;
6
5
  constructor(compiler: Compiler);
@@ -1,6 +1,5 @@
1
1
  import { default as DBMLCompletionItemProvider } from './suggestions/provider';
2
2
  import { default as DBMLDefinitionProvider } from './definition/provider';
3
3
  import { default as DBMLReferencesProvider } from './references/provider';
4
-
5
4
  export * from './types';
6
5
  export { DBMLCompletionItemProvider, DBMLDefinitionProvider, DBMLReferencesProvider, };
@@ -1,6 +1,5 @@
1
1
  import { default as Compiler } from '../../compiler';
2
2
  import { Location, ReferenceProvider, TextModel, Position } from '../types';
3
-
4
3
  export default class DBMLReferencesProvider implements ReferenceProvider {
5
4
  private compiler;
6
5
  constructor(compiler: Compiler);
@@ -1,6 +1,5 @@
1
1
  import { default as Compiler } from '../../compiler';
2
2
  import { CompletionList, TextModel, CompletionItemProvider, Position } from '../types';
3
-
4
3
  export default class DBMLCompletionItemProvider implements CompletionItemProvider {
5
4
  private compiler;
6
5
  triggerCharacters: string[];
@@ -1,7 +1,6 @@
1
1
  import { SymbolKind } from '../../lib/analyzer/symbol/symbolIndex';
2
2
  import { CompletionItemKind, CompletionList } from '../types';
3
3
  import { SyntaxToken } from '../../lib/lexer/tokens';
4
-
5
4
  export declare function pickCompletionItemKind(symbolKind: SymbolKind): CompletionItemKind;
6
5
  export declare function shouldPrependSpace(token: SyntaxToken | undefined, offset: number): boolean;
7
6
  export declare function noSuggestions(): CompletionList;
@@ -1,5 +1,4 @@
1
1
  import { Position as IPosition, editor, languages, IRange, IDisposable, CancellationToken as ICancellationToken } from 'monaco-editor-core';
2
-
3
2
  export type Position = IPosition;
4
3
  export type TextModel = editor.ITextModel;
5
4
  export type ProviderResult<T> = languages.ProviderResult<T>;
@@ -1,3 +1,2 @@
1
1
  import { TextModel, Position } from './types';
2
-
3
2
  export declare function getOffsetFromMonacoPosition(model: TextModel, position: Position): number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dbml/parse",
3
- "version": "3.8.1",
3
+ "version": "3.9.0",
4
4
  "description": "> TODO: description",
5
5
  "author": "Holistics <dev@holistics.io>",
6
6
  "license": "Apache-2.0",
@@ -37,8 +37,7 @@
37
37
  "monaco-editor-core": "^0.44.0",
38
38
  "typescript": "^5.2.2",
39
39
  "vite": "^4.5.0",
40
- "vite-dts": "^1.0.4",
41
- "vite-plugin-dts": "^3.9.1",
40
+ "vite-plugin-dts": "^4.1.1",
42
41
  "vitest": "^0.34.6"
43
42
  },
44
43
  "dependencies": {
@@ -47,5 +46,5 @@
47
46
  "peerDependencies": {
48
47
  "lodash": "^4.17.21"
49
48
  },
50
- "gitHead": "40a25ded1488372f082739f6d43e45f2ad918e7e"
49
+ "gitHead": "d40aaa3827853d17fa385aa27ae1e099c9234e4b"
51
50
  }