parseTokens is the core parsing routine. It takes a preprocessed []models.TokenWithSpan (already normalised by preprocessTokens) and returns the parsed AST.
(tokens []models.TokenWithSpan)
| 265 | // []models.TokenWithSpan (already normalised by preprocessTokens) and returns |
| 266 | // the parsed AST. |
| 267 | func (p *Parser) parseTokens(tokens []models.TokenWithSpan) (*ast.AST, error) { |
| 268 | p.tokens = tokens |
| 269 | p.currentPos = 0 |
| 270 | if len(tokens) > 0 { |
| 271 | p.currentToken = tokens[0] |
| 272 | } |
| 273 | |
| 274 | // Get a pre-allocated AST from the pool |
| 275 | result := ast.NewAST() |
| 276 | |
| 277 | // Pre-allocate statements slice based on a reasonable estimate |
| 278 | estimatedStmts := 1 // Most SQL queries have just one statement |
| 279 | if len(tokens) > 100 { |
| 280 | estimatedStmts = 2 // For larger inputs, allocate more |
| 281 | } |
| 282 | result.Statements = make([]ast.Statement, 0, estimatedStmts) |
| 283 | |
| 284 | // Parse statements using Type (int) comparisons for speed |
| 285 | for p.currentPos < len(tokens) && !p.isType(models.TokenTypeEOF) { |
| 286 | // Skip semicolons between statements |
| 287 | if p.isType(models.TokenTypeSemicolon) { |
| 288 | if err := p.checkStrictEmptySemicolon(); err != nil { |
| 289 | ast.ReleaseAST(result) |
| 290 | return nil, err |
| 291 | } |
| 292 | p.advance() |
| 293 | continue |
| 294 | } |
| 295 | |
| 296 | stmt, err := p.parseStatement() |
| 297 | if err != nil { |
| 298 | // Clean up the AST on error |
| 299 | ast.ReleaseAST(result) |
| 300 | return nil, err |
| 301 | } |
| 302 | result.Statements = append(result.Statements, stmt) |
| 303 | |
| 304 | // Optionally consume semicolon after statement |
| 305 | if p.isType(models.TokenTypeSemicolon) { |
| 306 | p.advance() |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | // Check if we got any statements |
| 311 | if len(result.Statements) == 0 { |
| 312 | ast.ReleaseAST(result) |
| 313 | if err := p.checkStrictEmpty(); err != nil { |
| 314 | return nil, err |
| 315 | } |
| 316 | return nil, goerrors.IncompleteStatementError(models.Location{}, "") |
| 317 | } |
| 318 | |
| 319 | return result, nil |
| 320 | } |
| 321 | |
| 322 | // ParseFromModelTokens parses tokenizer output ([]models.TokenWithSpan) directly into an AST. |
| 323 | // |
no test coverage detected