@dbml/parse
Version:
> TODO: description
9 lines • 106 kB
JavaScript
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const b=require("lodash");var u=(t=>(t.SPACE="<space>",t.TAB="<tab>",t.NEWLINE="<newline>",t.COMMA="<comma>",t.LPAREN="<lparen>",t.RPAREN="<rparen>",t.LBRACE="<lbrace>",t.RBRACE="<rbrace>",t.LBRACKET="<lbracket>",t.RBRACKET="<rbracket>",t.LANGLE="<langle>",t.RANGLE="<rangle>",t.OP="<op>",t.EOF="<eof>",t.NUMERIC_LITERAL="<number>",t.STRING_LITERAL="<string>",t.COLOR_LITERAL="<color>",t.FUNCTION_EXPRESSION="<function-expression>",t.QUOTED_STRING="<variable>",t.IDENTIFIER="<identifier>",t.SEMICOLON="<semicolon>",t.COLON="<colon>",t.SINGLE_LINE_COMMENT="<single-line-comment>",t.MULTILINE_COMMENT="<multiline-comment>",t))(u||{});function Yt(t){switch(t.kind){case"<newline>":case"<space>":case"<tab>":case"<single-line-comment>":case"<multiline-comment>":return!0;default:return!1}}function ot(t){if(!t)return!1;switch(t){case"+":case"-":case"*":case"/":case"%":case"<":case">":case"=":case"!":case".":case"&":case"|":return!0;default:return!1}}function lt(t){return t!==void 0&&t.kind==="<op>"}class G{constructor(e,n,s,i,r){this.kind=e,this.startPos=n,this.endPos=s,this.value=i,this.leadingTrivia=[],this.trailingTrivia=[],this.leadingInvalid=[],this.trailingInvalid=[],this.isInvalid=r,this.start=n.offset,this.end=s.offset}static create(e,n,s,i,r){return new G(e,n,s,i,r)}}function Lt(t){return t.trailingTrivia.find(({kind:e})=>e===u.NEWLINE)!==void 0}function ct(t,e){return e.leadingTrivia.find(({kind:s})=>s===u.NEWLINE)!==void 0||Lt(t)}function $e(t){return t.trailingTrivia.find(({kind:e})=>[u.SPACE,u.TAB].includes(e))!==void 0}function gt(t){return t.trailingTrivia.length===0?t.end:gt(b.last(t.trailingTrivia))}function _t(t){return t.leadingTrivia.length===0?t.start:_t(t.leadingTrivia[0])}function zt(t){return[u.SINGLE_LINE_COMMENT,u.MULTILINE_COMMENT].includes(t.kind)}class Qt{constructor(){this.id=0}reset(){this.id=0}nextId(){return this.id++}}class k{constructor(e,n,s){this.id=e,this.kind=n;const i=s.find(a=>a!==void 0&&!Number.isNaN(a.start));i?(this.startPos=i.startPos,this.fullStart=i instanceof G?_t(i):i.fullStart):(this.startPos={offset:NaN,column:NaN,line:NaN},this.fullStart=NaN);const r=[...s].reverse().find(a=>a!==void 0&&!Number.isNaN(a.end));r?(this.endPos=r.endPos,this.fullEnd=r instanceof G?gt(r):r.fullEnd):(this.endPos={offset:NaN,column:NaN,line:NaN},this.fullEnd=NaN),this.start=this.startPos.offset,this.end=this.endPos.offset}}var Ne=(t=>(t.PROGRAM="<program>",t.ELEMENT_DECLARATION="<element-declaration>",t.ATTRIBUTE="<attribute>",t.IDENTIFIER_STREAM="<identifer-stream>",t.LITERAL="<literal>",t.VARIABLE="<variable>",t.PREFIX_EXPRESSION="<prefix-expression>",t.INFIX_EXPRESSION="<infix-expression>",t.POSTFIX_EXPRESSION="<postfix-expression>",t.FUNCTION_EXPRESSION="<function-expression>",t.FUNCTION_APPLICATION="<function-application>",t.BLOCK_EXPRESSION="<block-expression>",t.LIST_EXPRESSION="<list-expression>",t.TUPLE_EXPRESSION="<tuple-expression>",t.CALL_EXPRESSION="<call-expression>",t.PRIMARY_EXPRESSION="<primary-expression>",t.GROUP_EXPRESSION="<group-expression>",t.DUMMY="<dummy>",t.ARRAY="<array>",t))(Ne||{});class j extends k{constructor({body:e=[],eof:n},s){super(s,"<program>",[...e,n]),this.body=e,this.eof=n}}class A extends k{constructor({type:e,name:n,as:s,alias:i,attributeList:r,bodyColon:a,body:l},p){if(super(p,"<element-declaration>",[e,n,s,i,r,a,l]),l&&a&&!(l instanceof v||l instanceof A))throw new Error("If an element has a simple body, it must be a function application node");this.type=e,this.name=n,this.as=s,this.alias=i,this.attributeList=r,this.bodyColon=a,this.body=l}}class q extends k{constructor({identifiers:e=[]},n){super(n,"<identifer-stream>",e||[]),this.identifiers=e}}class ie extends k{constructor({name:e,colon:n,value:s},i){super(i,"<attribute>",[e,n,s]),this.name=e,this.value=s,this.colon=n}}class H extends k{constructor({op:e,expression:n},s){super(s,"<prefix-expression>",[e,n]),this.op=e,this.expression=n}}class J extends k{constructor({op:e,leftExpression:n,rightExpression:s},i){super(i,"<infix-expression>",[n,e,s]),this.op=e,this.leftExpression=n,this.rightExpression=s}}class Me extends k{constructor({op:e,expression:n},s){super(s,"<postfix-expression>",[n,e]),this.op=e,this.expression=n}}class se extends k{constructor({value:e},n){super(n,"<function-expression>",[e]),this.value=e}}class v extends k{constructor({callee:e,args:n=[]},s){super(s,"<function-application>",[e,...n]),this.callee=e,this.args=n}}class K extends k{constructor({blockOpenBrace:e,body:n=[],blockCloseBrace:s},i){super(i,"<block-expression>",[e,...n,s]),this.blockOpenBrace=e,this.body=n,this.blockCloseBrace=s}}class R extends k{constructor({listOpenBracket:e,elementList:n=[],commaList:s=[],listCloseBracket:i},r){super(r,"<list-expression>",[e,...At(n,s),i]),this.listOpenBracket=e,this.elementList=n,this.commaList=s,this.listCloseBracket=i}}class ee extends k{constructor({tupleOpenParen:e,elementList:n=[],commaList:s=[],tupleCloseParen:i},r){super(r,"<tuple-expression>",[e,...At(n,s),i]),this.tupleOpenParen=e,this.elementList=n,this.commaList=s,this.tupleCloseParen=i}}class Ye extends ee{constructor({groupOpenParen:e,expression:n,groupCloseParen:s},i){super({tupleOpenParen:e,elementList:n&&[n],commaList:[],tupleCloseParen:s},i),this.kind="<group-expression>"}}class Z extends k{constructor({callee:e,argumentList:n},s){super(s,"<call-expression>",[e,n]),this.callee=e,this.argumentList=n}}class be extends k{constructor({literal:e},n){super(n,"<literal>",[e]),this.literal=e}}class te extends k{constructor({variable:e},n){super(n,"<variable>",[e]),this.variable=e}}class M extends k{constructor({expression:e},n){super(n,"<primary-expression>",[e]),this.expression=e}}class Se extends k{constructor({pre:e},n){const s=G.create(u.SPACE,e.endPos,e.endPos," ",!1);super(n,"<dummy>",[s])}}class he extends k{constructor({expression:e,indexer:n},s){super(s,"<array>",[e,n]),this.array=e,this.indexer=n}}function At(t,e){if(!t||t.length===0)return e||[];if(!e||e.length===0)return t||[];const[n]=t,[s]=e;return(n.start<s.start?b.flatten(b.zip(t,e)):b.flatten(b.zip(e,t))).filter(i=>i!==null)}function qt(t,e=!1){return JSON.stringify(t,function(n,s){var i;return!(this instanceof j)&&n==="symbol"?s==null?void 0:s.id:n==="symbol"?{symbolTable:s==null?void 0:s.symbolTable,id:s==null?void 0:s.id,references:s==null?void 0:s.references.map(r=>r.id),declaration:(i=s==null?void 0:s.declaration)==null?void 0:i.id}:n==="referee"||n==="parent"||n==="declaration"?s==null?void 0:s.id:n==="symbolTable"?Object.fromEntries(s.table):s},e?2:0)}class x{constructor(e){this.value=e}unwrap(){return this.value}unwrap_or(e){return this.value}and_then(e){return e(this.value)}map(e){return new x(e(this.value))}isOk(){return!0}}class y{unwrap(){throw new Error("Trying to unwrap a None value")}unwrap_or(e){return e}and_then(e){return new y}map(e){return new y}isOk(){return!1}}var T=(t=>(t.Schema="Schema",t.Table="Table",t.Column="Column",t.TableGroup="TableGroup",t.TableGroupField="TableGroup field",t.Enum="Enum",t.EnumField="Enum field",t.Note="Note",t))(T||{});function ze(t){return`Schema:${t}`}function De(t){return`Table:${t}`}function Qe(t){return`Column:${t}`}function qe(t){return`Enum:${t}`}function He(t){return`Enum field:${t}`}function Je(t){return`TableGroup:${t}`}function Ze(t){return`TableGroup field:${t}`}function Ht(t){return`Note:${t}`}function Ce(t,e){switch(e){case"Column":return Qe(t);case"Enum":return qe(t);case"Enum field":return He(t);case"Schema":return ze(t);case"Table":return De(t);case"TableGroup":return Je(t);case"TableGroup field":return Ze(t);default:throw new Error("Unreachable")}}function re(t){const[e,n]=t.split(":");return Object.values(T).includes(e)?new x({name:n,kind:e}):new y}function Jt(t){const e=re(t).unwrap_or(void 0);if(!e)return!1;const{kind:n,name:s}=e;return n==="Schema"&&s==="public"}function Zt(t){return[ze,De,qe,Je,Qe,He,Ze].map(e=>e(t))}function Fe(t){return!!t.match(/(\p{L}|_|\p{M})/gu)}function Re(t){const[e]=t;return e>="0"&&e<="9"}function Kt(t){const[e]=t;return Re(e)||Fe(e)&&e.toLowerCase()>="a"&&e.toLowerCase()<="f"}function Ee(t){return Fe(t)||Re(t)}function ut(t,e){const n=[],s=Math.min(t.length,e.length);for(let i=0;i<s;i+=1)n.push(t[i],e[i]);return n.push(...t.slice(s),...e.slice(s)),n}function _e(t,e){return t>=e.start&&t<e.end}class en{constructor(){this.id=0}reset(){this.id=0}nextId(){return this.id++}}class vt{constructor({symbolTable:e},n){this.references=[],this.id=n,this.symbolTable=e}}class tn{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class nn{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}class wt{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class sn{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}class rn{constructor({symbolTable:e,declaration:n},s){this.references=[],this.id=s,this.symbolTable=e,this.declaration=n}}class an{constructor({declaration:e},n){this.references=[],this.id=n,this.declaration=e}}var o=(t=>(t[t.UNKNOWN_SYMBOL=1e3]="UNKNOWN_SYMBOL",t[t.UNEXPECTED_SYMBOL=1001]="UNEXPECTED_SYMBOL",t[t.UNEXPECTED_EOF=1002]="UNEXPECTED_EOF",t[t.UNEXPECTED_NEWLINE=1003]="UNEXPECTED_NEWLINE",t[t.UNKNOWN_TOKEN=1004]="UNKNOWN_TOKEN",t[t.UNEXPECTED_TOKEN=1005]="UNEXPECTED_TOKEN",t[t.UNEXPECTED_ELEMENT_DECLARATION=1006]="UNEXPECTED_ELEMENT_DECLARATION",t[t.MISSING_SPACES=1007]="MISSING_SPACES",t[t.UNKNOWN_PREFIX_OP=1008]="UNKNOWN_PREFIX_OP",t[t.INVALID_OPERAND=1009]="INVALID_OPERAND",t[t.EMPTY_ATTRIBUTE_NAME=1010]="EMPTY_ATTRIBUTE_NAME",t[t.INVALID_ESCAPE_SEQUENCE=1011]="INVALID_ESCAPE_SEQUENCE",t[t.INVALID_NAME=3e3]="INVALID_NAME",t[t.UNEXPECTED_NAME=3001]="UNEXPECTED_NAME",t[t.NAME_NOT_FOUND=3002]="NAME_NOT_FOUND",t[t.DUPLICATE_NAME=3003]="DUPLICATE_NAME",t[t.INVALID_ALIAS=3004]="INVALID_ALIAS",t[t.UNEXPECTED_ALIAS=3005]="UNEXPECTED_ALIAS",t[t.UNEXPECTED_SETTINGS=3006]="UNEXPECTED_SETTINGS",t[t.INVALID_SETTINGS=3007]="INVALID_SETTINGS",t[t.UNEXPECTED_SIMPLE_BODY=3008]="UNEXPECTED_SIMPLE_BODY",t[t.UNEXPECTED_COMPLEX_BODY=3009]="UNEXPECTED_COMPLEX_BODY",t[t.INVALID_TABLE_CONTEXT=3010]="INVALID_TABLE_CONTEXT",t[t.INVALID_TABLE_SETTING=3011]="INVALID_TABLE_SETTING",t[t.DUPLICATE_TABLE_SETTING=3012]="DUPLICATE_TABLE_SETTING",t[t.INVALID_TABLEGROUP_CONTEXT=3013]="INVALID_TABLEGROUP_CONTEXT",t[t.INVALID_TABLEGROUP_ELEMENT_NAME=3014]="INVALID_TABLEGROUP_ELEMENT_NAME",t[t.DUPLICATE_TABLEGROUP_ELEMENT_NAME=3015]="DUPLICATE_TABLEGROUP_ELEMENT_NAME",t[t.DUPLICATE_TABLEGROUP_FIELD_NAME=3016]="DUPLICATE_TABLEGROUP_FIELD_NAME",t[t.INVALID_TABLEGROUP_FIELD=3017]="INVALID_TABLEGROUP_FIELD",t[t.EMPTY_TABLE=3018]="EMPTY_TABLE",t[t.INVALID_COLUMN=3019]="INVALID_COLUMN",t[t.INVALID_COLUMN_NAME=3020]="INVALID_COLUMN_NAME",t[t.UNKNOWN_COLUMN_SETTING=3021]="UNKNOWN_COLUMN_SETTING",t[t.INVALID_COLUMN_TYPE=3022]="INVALID_COLUMN_TYPE",t[t.DUPLICATE_COLUMN_NAME=3023]="DUPLICATE_COLUMN_NAME",t[t.DUPLICATE_COLUMN_SETTING=3024]="DUPLICATE_COLUMN_SETTING",t[t.INVALID_COLUMN_SETTING_VALUE=3025]="INVALID_COLUMN_SETTING_VALUE",t[t.INVALID_ENUM_CONTEXT=3026]="INVALID_ENUM_CONTEXT",t[t.INVALID_ENUM_ELEMENT_NAME=3027]="INVALID_ENUM_ELEMENT_NAME",t[t.INVALID_ENUM_ELEMENT=3028]="INVALID_ENUM_ELEMENT",t[t.DUPLICATE_ENUM_ELEMENT_NAME=3029]="DUPLICATE_ENUM_ELEMENT_NAME",t[t.UNKNOWN_ENUM_ELEMENT_SETTING=3030]="UNKNOWN_ENUM_ELEMENT_SETTING",t[t.DUPLICATE_ENUM_ELEMENT_SETTING=3031]="DUPLICATE_ENUM_ELEMENT_SETTING",t[t.INVALID_ENUM_ELEMENT_SETTING=3032]="INVALID_ENUM_ELEMENT_SETTING",t[t.EMPTY_ENUM=3033]="EMPTY_ENUM",t[t.INVALID_REF_CONTEXT=3034]="INVALID_REF_CONTEXT",t[t.UNKNOWN_REF_SETTING=3035]="UNKNOWN_REF_SETTING",t[t.DUPLICATE_REF_SETTING=3036]="DUPLICATE_REF_SETTING",t[t.INVALID_REF_SETTING_VALUE=3037]="INVALID_REF_SETTING_VALUE",t[t.INVALID_REF_RELATIONSHIP=3038]="INVALID_REF_RELATIONSHIP",t[t.INVALID_REF_FIELD=3039]="INVALID_REF_FIELD",t[t.EMPTY_REF=3040]="EMPTY_REF",t[t.REF_REDEFINED=3041]="REF_REDEFINED",t[t.INVALID_NOTE_CONTEXT=3042]="INVALID_NOTE_CONTEXT",t[t.INVALID_NOTE=3043]="INVALID_NOTE",t[t.NOTE_REDEFINED=3044]="NOTE_REDEFINED",t[t.NOTE_CONTENT_REDEFINED=3045]="NOTE_CONTENT_REDEFINED",t[t.EMPTY_NOTE=3046]="EMPTY_NOTE",t[t.INVALID_INDEXES_CONTEXT=3047]="INVALID_INDEXES_CONTEXT",t[t.INVALID_INDEXES_FIELD=3048]="INVALID_INDEXES_FIELD",t[t.INVALID_INDEX=3049]="INVALID_INDEX",t[t.UNKNOWN_INDEX_SETTING=3050]="UNKNOWN_INDEX_SETTING",t[t.DUPLICATE_INDEX_SETTING=3051]="DUPLICATE_INDEX_SETTING",t[t.UNEXPECTED_INDEX_SETTING_VALUE=3052]="UNEXPECTED_INDEX_SETTING_VALUE",t[t.INVALID_INDEX_SETTING_VALUE=3053]="INVALID_INDEX_SETTING_VALUE",t[t.INVALID_PROJECT_CONTEXT=3054]="INVALID_PROJECT_CONTEXT",t[t.PROJECT_REDEFINED=3055]="PROJECT_REDEFINED",t[t.INVALID_PROJECT_FIELD=3056]="INVALID_PROJECT_FIELD",t[t.INVALID_CUSTOM_CONTEXT=3057]="INVALID_CUSTOM_CONTEXT",t[t.INVALID_CUSTOM_ELEMENT_VALUE=3058]="INVALID_CUSTOM_ELEMENT_VALUE",t[t.INVALID_ELEMENT_IN_SIMPLE_BODY=3059]="INVALID_ELEMENT_IN_SIMPLE_BODY",t[t.BINDING_ERROR=4e3]="BINDING_ERROR",t[t.UNSUPPORTED=5e3]="UNSUPPORTED",t[t.CIRCULAR_REF=5001]="CIRCULAR_REF",t[t.SAME_ENDPOINT=5002]="SAME_ENDPOINT",t[t.UNEQUAL_FIELDS_BINARY_REF=5003]="UNEQUAL_FIELDS_BINARY_REF",t[t.CONFLICTING_SETTING=5004]="CONFLICTING_SETTING",t[t.TABLE_REAPPEAR_IN_TABLEGROUP=5005]="TABLE_REAPPEAR_IN_TABLEGROUP",t))(o||{});class c extends Error{constructor(e,n,s){super(n),this.code=e,this.diagnostic=n,this.nodeOrToken=s,this.start=s.start,this.end=s.end,this.name=this.constructor.name,Object.setPrototypeOf(this,c.prototype)}}class X{constructor(e,n){this.value=e,this.errors=n===void 0?[]:n}getValue(){return this.value}getErrors(){return this.errors}chain(e){const n=e(this.value),s=[...this.errors,...n.errors];return new X(n.value,s)}map(e){return new X(e(this.value),this.errors)}}function on(t,e,n){if(!t||!me(t)||e.length===0)return new y;const s=[...e],i=Xe(t).unwrap(),r=s.pop();if(!(r instanceof K))return new y;const a=b.last(s)instanceof R?s.pop():void 0;return s.length===3&&Xe(s[1]).unwrap().value==="as"?new x(n.create(A,{type:i,name:s[0],as:Xe(s[1]).unwrap(),alias:s[2],attributeList:a,body:r})):s.length===1?new x(n.create(A,{type:i,name:s[0],attributeList:a,body:r})):s.length===0?new x(n.create(A,{type:i,attributeList:a,body:r})):new y}function ht(t){return t.kind===u.IDENTIFIER&&t.value==="as"}function N(t){t&&(t instanceof G?ln(t):cn(t))}function ln(t){t.kind!==u.EOF&&(t.isInvalid=!0)}function cn(t){if(t instanceof A)N(t.type),N(t.name),N(t.as),N(t.alias),N(t.bodyColon),N(t.attributeList),N(t.body);else if(t instanceof q)t.identifiers.forEach(N);else if(t instanceof ie)N(t.name),N(t.colon),N(t.value);else if(t instanceof H)N(t.op),N(t.expression);else if(t instanceof J)N(t.leftExpression),N(t.op),N(t.rightExpression);else if(t instanceof Me)N(t.op),N(t.expression);else if(t instanceof K)N(t.blockOpenBrace),t.body.forEach(N),N(t.blockCloseBrace);else if(t instanceof R)N(t.listOpenBracket),t.commaList.forEach(N),t.elementList.forEach(N),N(t.listCloseBracket);else if(t instanceof ee)N(t.tupleOpenParen),t.commaList.forEach(N),t.elementList.forEach(N),N(t.tupleCloseParen);else if(t instanceof Z)N(t.callee),N(t.argumentList);else if(t instanceof v)N(t.callee),t.args.forEach(N);else if(t instanceof M)N(t.expression);else if(t instanceof se)N(t.value);else if(t instanceof te)N(t.variable);else if(t instanceof be)N(t.literal);else throw t instanceof Ye?new Error("This case is handled by the TupleExpressionNode case"):new Error("Unreachable case in markInvalidNode")}function yt(t){return!!(t!=null&&t.isInvalid)}function U(...t){return t.filter(e=>e!==void 0)}function un(t){if(t instanceof j)return U(...t.body,t.eof);if(t instanceof A)return U(t.type,t.name,t.as,t.alias,t.attributeList,t.bodyColon,t.body);if(t instanceof ie)return U(t.name,t.colon,t.value);if(t instanceof q)return t.identifiers;if(t instanceof be)return t.literal?[t.literal]:[];if(t instanceof te)return U(t.variable);if(t instanceof H)return U(t.op,t.expression);if(t instanceof J)return U(t.leftExpression,t.op,t.rightExpression);if(t instanceof Me)return U(t.expression,t.op);if(t instanceof se)return U(t.value);if(t instanceof v)return U(t.callee,...t.args);if(t instanceof K)return U(t.blockOpenBrace,...t.body,t.blockCloseBrace);if(t instanceof R)return U(t.listOpenBracket,...ut(t.elementList,t.commaList),t.listCloseBracket);if(t instanceof ee)return U(t.tupleOpenParen,...ut(t.elementList,t.commaList),t.tupleCloseParen);if(t instanceof Z)return U(t.callee,t.argumentList);if(t instanceof M)return U(t.expression);if(t instanceof he)return U(t.array,t.indexer);throw t instanceof Ye?new Error("This case is already handled by TupleExpressionNode"):new Error("Unreachable - no other possible cases")}function Xe(t){return V(t)?new x(t.expression.variable):new y}function Y(t){var e;return t instanceof M&&(t.expression instanceof te&&t.expression.variable instanceof G&&t.expression.variable.kind===u.QUOTED_STRING||t.expression instanceof be&&((e=t.expression.literal)==null?void 0:e.kind)===u.STRING_LITERAL)}function V(t){return t instanceof M&&t.expression instanceof te&&t.expression.variable instanceof G}function me(t){var e;return t instanceof M&&t.expression instanceof te&&((e=t.expression.variable)==null?void 0:e.kind)===u.IDENTIFIER}function Ke(t){var e;return t instanceof J&&t.leftExpression instanceof k&&t.rightExpression instanceof k&&((e=t.op)==null?void 0:e.value)==="."}function Te(t){if(t===void 0)return new y;const e=t.identifiers.map(n=>n.value).join(" ");return e===""?new y:new x(e)}class hn{constructor(e){this.start={offset:0,line:0,column:0},this.current={offset:0,line:0,column:0},this.tokens=[],this.errors=[],this.text=e}isAtEnd(){return this.current.offset>=this.text.length}advance(){const e=this.peek();return this.current={...this.current},e===`
`?(this.current.line+=1,this.current.column=0):this.current.column+=1,this.current.offset+=1,e}peek(e=0){if(!(this.current.offset+e>=this.text.length))return this.text[this.current.offset+e]}check(e){for(let n=0;n<e.length;n+=1)if(e[n]!==this.peek(n))return!1;return!0}match(e){return this.check(e)?(e.split("").forEach(()=>this.advance()),!0):!1}addToken(e,n=!1){this.tokens.push(this.createToken(e,n))}createToken(e,n=!1){return G.create(e,this.start,this.current,this.text.substring(this.start.offset,this.current.offset),n)}lex(){return this.scanTokens(),this.tokens.push(G.create(u.EOF,this.start,this.current,"",!1)),this.gatherTrivia(),this.gatherInvalid(),new X(this.tokens,this.errors)}scanTokens(){for(;!this.isAtEnd();){const e=this.advance();switch(e){case" ":this.addToken(u.SPACE);break;case"\r":break;case`
`:this.addToken(u.NEWLINE);break;case" ":this.addToken(u.TAB);break;case",":this.addToken(u.COMMA);break;case"(":this.addToken(u.LPAREN);break;case")":this.addToken(u.RPAREN);break;case"[":this.addToken(u.LBRACKET);break;case"]":this.addToken(u.RBRACKET);break;case"{":this.addToken(u.LBRACE);break;case"}":this.addToken(u.RBRACE);break;case";":this.addToken(u.SEMICOLON);break;case":":this.addToken(u.COLON);break;case"'":this.match("''")?this.multilineStringLiteral():this.singleLineStringLiteral();break;case'"':this.quotedVariable();break;case"`":this.functionExpression();break;case"#":this.colorLiteral();break;case"/":this.match("/")?this.singleLineComment():this.match("*")?this.multilineComment():this.operator();break;default:if(ot(e)){this.operator();break}if(Fe(e)){this.identifier();break}if(Re(e)){this.numericLiteralOrIdentifier();break}this.addToken(u.OP,!0),this.errors.push(new c(o.UNKNOWN_SYMBOL,`Unexpected token '${e}'`,this.createToken(u.OP,!0)));break}this.start={...this.current}}}gatherTrivia(){let e=!0,n=[],s;const i=[];for(const r of this.tokens)Yt(r)?(n.push(r),r.kind===u.NEWLINE&&s&&(s.trailingTrivia=n,e=!0,s=void 0,n=[])):(e?r.leadingTrivia=n:s.trailingTrivia=n,i.push(r),n=[],s=r,e=!1);this.tokens=i}gatherInvalid(){let e;const n=[],s=[];for(e=0;e<this.tokens.length&&yt(this.tokens[e]);e+=1)s.push(this.tokens[e]);let i=this.tokens[e];for(i.leadingInvalid=[...s,...i.leadingInvalid];e<this.tokens.length;e+=1){const r=this.tokens[e];r.isInvalid?i.trailingInvalid.push(r):(i=r,n.push(r))}this.tokens=n}consumeUntil(e,n,{allowNewline:s,allowEof:i,raw:r,consumeStopSequence:a=!0}){let l="";for(;!this.isAtEnd()&&(s||!this.check(`
`))&&!this.check(n);)this.peek()==="\\"&&!r?(this.advance(),l+=this.escapedString()):l+=this.advance();if(this.isAtEnd()&&!i){const p=this.createToken(e,!0);this.tokens.push(p),this.errors.push(new c(o.UNEXPECTED_EOF,"EOF reached while parsing",p));return}if(this.check(`
`)&&!s){const p=this.createToken(e,!0);this.tokens.push(p),this.errors.push(new c(o.UNEXPECTED_NEWLINE,"Invalid newline encountered while parsing",p));return}a&&this.match(n),this.tokens.push(G.create(e,this.start,this.current,l,!1))}singleLineStringLiteral(){this.consumeUntil(u.STRING_LITERAL,"'",{allowNewline:!1,allowEof:!1,raw:!1})}multilineStringLiteral(){this.consumeUntil(u.STRING_LITERAL,"'''",{allowNewline:!0,allowEof:!1,raw:!1})}functionExpression(){this.consumeUntil(u.FUNCTION_EXPRESSION,"`",{allowNewline:!1,allowEof:!1,raw:!0})}quotedVariable(){this.consumeUntil(u.QUOTED_STRING,'"',{allowNewline:!1,allowEof:!1,raw:!1})}singleLineComment(){this.consumeUntil(u.SINGLE_LINE_COMMENT,`
`,{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(;ot(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&&!Re(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(`
`)&&this.advance(),"";case`
`:return"";case"t":return" ";case"n":return`
`;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`,G.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 Oe=(t=>(t[t.ListExpression=0]="ListExpression",t[t.GroupExpression=1]="GroupExpression",t[t.BlockExpression=2]="BlockExpression",t))(Oe||{});class fn{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 pn{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 dn{constructor(e,n){this.current=0,this.errors=[],this.contextStack=new fn,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(ht(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(Oe.BlockExpression,()=>{const s={body:[]},i=()=>this.nodeFactory.create(K,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)||ct(this.previous(),s))break;N(s),this.advance()}},this.tupleExpression=this.contextStack.withContextDo(Oe.GroupExpression,()=>{const s={elementList:[],commaList:[]},i=()=>this.nodeFactory.create(Ye,{groupOpenParen:s.tupleOpenParen,groupCloseParen:s.tupleCloseParen,expression:s.elementList[0]}),r=()=>this.nodeFactory.create(ee,s);try{this.consume("Expect an opening parenthesis '('",u.LPAREN),s.tupleOpenParen=this.previous()}catch(a){if(!(a instanceof d))throw a;if(s.tupleOpenParen=a.partialNode,!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}if(!this.isAtEnd()&&!this.check(u.RPAREN))try{s.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof d))throw a;if(s.elementList.push(a.partialNode),!this.canHandle(a))throw new d(a.token,i(),a.handlerContext);this.synchronizeTuple()}for(;!this.isAtEnd()&&!this.check(u.RPAREN);)try{this.consume("Expect a comma ','",u.COMMA),s.commaList.push(this.previous()),s.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof d))throw a;if(a.partialNode instanceof k&&s.elementList.push(a.partialNode),!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}try{this.consume("Expect a closing parenthesis ')'",u.RPAREN),s.tupleCloseParen=this.previous()}catch(a){if(!(a instanceof d))throw a;if(s.tupleCloseParen=a.partialNode,!this.canHandle(a))throw new d(a.token,r(),a.handlerContext);this.synchronizeTuple()}return s.elementList.length===1?i():r()}),this.synchronizeTuple=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.RPAREN,u.COMMA))break;N(s),this.advance()}},this.listExpression=this.contextStack.withContextDo(Oe.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 k&&s.elementList.push(r.partialNode),!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}try{this.consume("Expect a closing bracket ']'",u.RBRACKET),s.listCloseBracket=this.previous()}catch(r){if(!(r instanceof d))throw r;if(s.listCloseBracket=r.partialNode,!this.canHandle(r))throw new d(r.token,i(),r.handlerContext);this.synchronizeList()}return i()}),this.synchronizeList=()=>{for(;!this.isAtEnd();){const s=this.peek();if(this.check(u.COMMA,u.RBRACKET))break;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 pn(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(j,{body:e,eof:n});return this.gatherInvalid(),new X({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(A,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(ht(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 A?(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(A,e)}fieldDeclaration(){const e={},n=()=>this.nodeFactory.create(A,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 A?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(A,e)}expression(){const e={args:[]},n=()=>on(e.callee,e.args,this.nodeFactory).unwrap_or(this.nodeFactory.create(v,e));try{e.callee=this.normalExpression()}catch(i){throw i instanceof d?(e.callee=i.partialNode,new d(i.token,n(),i.handlerContext)):i}if(this.shouldStopExpression())return n();let s=e.callee;for(;!this.shouldStopExpression();){$e(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()||Lt(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}=ft(s);if(i<e||ct(this.previous(),s)&&!this.contextStack.isWithinGroupExpressionContext()&&!this.contextStack.isWithinListExpressionContext())break;try{n=this.nodeFactory.create(Z,{callee:n,argumentList:this.tupleExpression()})}catch(r){throw r instanceof d?(n=this.nodeFactory.create(Z,{callee:n,argumentList:r.partialNode}),new d(r.token,n,r.handlerContext)):r}}else if(s.kind===u.LBRACKET){if($e(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(lt(s)){const i=s,r=ft(i);if(r.left!==null){if(r.left<=e)break;this.advance(),n=this.nodeFactory.create(Me,{expression:n,op:i})}else{const a=Nn(i);if(a.left===null||a.left<=e)break;this.advance();try{n=this.nodeFactory.create(J,{leftExpression:n,op:i,rightExpression:i.value==="."?this.extractOperand():this.expression_bp(a.right)})}catch(l){throw l instanceof d?(n=this.nodeFactory.create(J,{leftExpression:n,op:i,rightExpression:l.partialNode}),new d(l.token,n,l.handlerContext)):l}}}else break}return n}leftExpression_bp(){let e;if(lt(this.peek())){const n={};n.op=this.peek();const s=Tn(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(Se,{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(H,n),i.handlerContext)):i}e=this.nodeFactory.create(H,n)}else if(e=this.extractOperand(),e instanceof Se)throw new d(this.peek(),this.nodeFactory.create(Se,{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(Se,{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(se,e),n.handlerContext)):n}return this.nodeFactory.create(se,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(M,{expression:this.nodeFactory.create(be,{literal:this.previous()})});if(this.match(u.QUOTED_STRING,u.IDENTIFIER))return this.nodeFactory.create(M,{expression:this.nodeFactory.create(te,{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(q,{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(ie,e),n.handlerContext);this.synchronizeAttributeName()}return this.match(u.COLON)&&(e.colon=this.previous(),e.value=this.attributeValue()),this.nodeFactory.create(ie,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(q,{identifiers:e}),n.handlerContext):n}return this.nodeFactory.create(q,{identifiers:e})}logError(e,n,s){this.errors.push(new c(n,s,e))}}const En={"+":{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 Nn(t){return En[t.value]||{left:null,right:null}}const mn={"+":{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 Tn(t){return mn[t.value]||{left:null,right:null}}const bn={"(":{left:14,right:null}};function ft(t){return bn[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 we(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 x(e);default:return new y}}function pe(t){if(!Ke(t))return new x([t]);const e=pe(t.leftExpression).unwrap_or(void 0);return e?(e.push(t.rightExpression),new x(e)):new y}function z(t){if(t===void 0)return new y;const e=pe(t).unwrap_or(void 0);if(!e)return new y;const n=[];for(const s of e){const i=Q(s).unwrap_or(void 0);if(!i)return new y;n.push(i)}return new x(n)}function Ae(t){if(t===void 0)return new y;const e=pe(t).unwrap_or(void 0);if(!e||e.length===0)return new y;const n=[];let s;if(!V(b.last(e))){const i=e.pop();if(Ot(i))s=i.elementList.map(r=>W(r).unwrap());else return new y}for(const i of e){const r=Q(i).unwrap_or(void 0);if(!r)return new y;n.push(r)}return new x({variables:n,tupleElements:s})}function Q(t){return V(t)?new x(t.expression.variable.value):new y}function We(t){if(pt(t))return t instanceof se?new x({functional:[t],nonFunctional:[]}):new x({functional:[],nonFunctional:[t]});if(t instanceof ee&&t.elementList.every(pt)){const e=t.elementList.filter(s=>s instanceof se),n=t.elementList.filter(V);return new x({functional:e,nonFunctional:n})}return new y}function W(t){var n;const e=(n=t==null?void 0:t.expression.variable)==null?void 0:n.value;return e===void 0?new y:new x(e)}function $(t){return Y(t)?t.expression instanceof te?new x(t.expression.variable.value):new x(t.expression.literal.value):new y}function In(t){var e;return!(t instanceof J)||!St((e=t.op)==null?void 0:e.value)?!1:Ae(t.leftExpression).and_then(()=>Ae(t.rightExpression)).unwrap_or(void 0)!==void 0}function Ln(t){const e=Ae(t.leftExpression),n=Ae(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 pt(t){return t instanceof M&&t.expression instanceof te||t instanceof se}function gn(t,e){var i,r,a,l;let n=e;const s=Jt(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 j&&s)return n.symbol;if(n instanceof j)return;n=n.parent}}class _n{constructor(e,n,s){this.declarationNode=e,this.publicSymbolTable=n,this.symbolFactory=s}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof j||we(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 K)return[new c(o.UNEXPECTED_COMPLEX_BODY,"A Custom element can only have an inline field",e)];const n=[];return Y(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 ye{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 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.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof A?[new c(o.INVALID_PROJECT_CONTEXT,"An Enum can only appear top-level",this.declarationNode)]:[]}validateName(e){return e?xt(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(tn,{declaration:this.declarationNode,symbolTable:new ye});const{name:n}=this.declarationNode,s=z(n);if(s.isOk()){const i=s.unwrap(),r=i.pop(),a=et(i,this.publicSymbolTable,this.symbolFactory),l=qe(r);a.has(l)&&e.push(new c(o.DUPLICATE_NAME,`Enum name ${r} already exists in schema '${i.join(".")||"public"}'`,n)),a.set(l,this.declarationNode.symbol)}return e}validateSettingList(e){return e?[new c(o.UNEXPECTED_SETTINGS,"An Enum shouldn't have a setting list",e)]:[]}validateBody(e){if(!e)return[];if(e instanceof v)return this.validateFields([e]);const[n,s]=b.partition(e.body,i=>i instanceof v);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.length===0?[new c(o.EMPTY_ENUM,"An Enum must have at least one element",this.declarationNode)]:e.flatMap(n=>{const s=[];n.callee&&!V(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=C(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=>{Y(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=oe(n);return new s(n,this.publicSymbolTable,this.symbolFactory).validate()})}registerField(e){if(e.callee&&V(e.callee)){const n=W(e.callee).unwrap(),s=He(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 enum field ${n}`,e),new c(o.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,a.declaration)]}r.set(s,i)}return[]}}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 j||we(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 v)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 v);return[...this.validateFields(n),...this.validateSubElements(s)]}validateFields(e){return e.flatMap(n=>{if(!n.callee)return[];const s=[],i=[n.callee,...n.args];return b.last(i)instanceof R&&s.push(...this.validateFieldSetting(i.pop())),i.forEach(r=>{for(;r instanceof Z;)r.argumentList&&!We(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;We(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=C(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=>{Y(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=>{V(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=oe(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