| 193 | |
| 194 | export class SyntaxTreeNode { |
| 195 | public static create(code: string) { |
| 196 | const parentNode = new SyntaxTreeNode(SyntaxTreeNodeType.SQL); |
| 197 | let currentNode = parentNode; |
| 198 | const nodeStack = [currentNode]; |
| 199 | lexer.reset(code); |
| 200 | for (const token of lexer) { |
| 201 | if (!token.type) { |
| 202 | throw new Error("Undefined token type encountered."); |
| 203 | } |
| 204 | if (START_TOKEN_NODE_MAPPINGS.has(token.type)) { |
| 205 | const childType = START_TOKEN_NODE_MAPPINGS.get(token.type)!; |
| 206 | if (childType === SyntaxTreeNodeType.SQL && currentNode.type !== SyntaxTreeNodeType.SQL) { |
| 207 | throw new Error("SQL syntax tree nodes may only be children of other SQL nodes."); |
| 208 | } |
| 209 | const newCurrentNode = new SyntaxTreeNode(childType, [token.value]); |
| 210 | nodeStack.push(newCurrentNode); |
| 211 | currentNode.push(newCurrentNode); |
| 212 | currentNode = newCurrentNode; |
| 213 | } else if (CLOSE_TOKEN_TYPES.has(token.type)) { |
| 214 | currentNode.push(token.value); |
| 215 | nodeStack.pop(); |
| 216 | currentNode = nodeStack[nodeStack.length - 1]; |
| 217 | } else if (WHOLE_TOKEN_NODE_MAPPINGS.has(token.type)) { |
| 218 | currentNode.push( |
| 219 | new SyntaxTreeNode(WHOLE_TOKEN_NODE_MAPPINGS.get(token.type)!).push(token.value) |
| 220 | ); |
| 221 | } else { |
| 222 | currentNode.push(token.value); |
| 223 | } |
| 224 | } |
| 225 | return parentNode; |
| 226 | } |
| 227 | |
| 228 | public static isSyntaxTreeNode(node: string | SyntaxTreeNode): node is SyntaxTreeNode { |
| 229 | return typeof node !== "string"; |