From 7c0548e03214c9a097a01baa019fde30c1394e7d Mon Sep 17 00:00:00 2001 From: Tyler Brinks Date: Sat, 2 Nov 2024 07:27:53 -0600 Subject: [PATCH] Preserve EOF exception line number --- src/SqlParser.Tests/ParserCommonTests.cs | 13 +++++++++++++ src/SqlParser/Parser.Base.cs | 20 ++++++++++++++++---- src/SqlParser/Tokens/EOF.cs | 5 +++++ 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/src/SqlParser.Tests/ParserCommonTests.cs b/src/SqlParser.Tests/ParserCommonTests.cs index 30f10bf..3b369cf 100644 --- a/src/SqlParser.Tests/ParserCommonTests.cs +++ b/src/SqlParser.Tests/ParserCommonTests.cs @@ -5,6 +5,7 @@ using static SqlParser.Ast.Expression; using Action = SqlParser.Ast.Action; using DataType = SqlParser.Ast.DataType; +using Double = System.Double; using Map = SqlParser.Ast.Map; using Subscript = SqlParser.Ast.Subscript; @@ -36,6 +37,18 @@ void TestExplain( } } + [Fact] + public void Parser_EOF_Exception_Preserves_Line_And_Column() + { + var exception = Assert.Throws( + () => ParseSqlStatements(""" + select * + from table + """, [new PostgreSqlDialect()])); + Assert.Equal(2, exception.Line); + Assert.Equal(7, exception.Column); + } + [Fact] public void Parse_Insert_Values() { diff --git a/src/SqlParser/Parser.Base.cs b/src/SqlParser/Parser.Base.cs index 53f974c..2e3bd12 100644 --- a/src/SqlParser/Parser.Base.cs +++ b/src/SqlParser/Parser.Base.cs @@ -85,7 +85,9 @@ public Token PeekNthToken(int nth) if (position >= _tokens.Count) { - return new EOF(); + var eof = new EOF(); + eof.SetLocation(_tokens[^1].Location); + return eof; } var token = _tokens[position]; @@ -109,7 +111,9 @@ public Token PeekNthTokenNoSkip(int nth) { if (_index + nth >= _tokens.Count) { - return new EOF(); + var eof = new EOF(); + eof.SetLocation(_tokens[^1].Location); + return eof; } return _tokens[_index + nth]; @@ -152,7 +156,9 @@ public IEnumerable PeekTokensWithLocation(int count) { if (index >= _tokens.Count) { - yield return new EOF(); + var eof = new EOF(); + eof.SetLocation(_tokens[^1].Location); + yield return eof; break; } @@ -186,7 +192,13 @@ public Token NextToken() var position = _index - 1; if (position >= _tokens.Count) { - return new EOF(); + var eof = new EOF(); + if (_tokens.Count > 0) + { + eof.SetLocation(_tokens[^1].Location); + } + + return eof; } var token = _tokens[_index - 1]; diff --git a/src/SqlParser/Tokens/EOF.cs b/src/SqlParser/Tokens/EOF.cs index 9a92547..9f4680b 100644 --- a/src/SqlParser/Tokens/EOF.cs +++ b/src/SqlParser/Tokens/EOF.cs @@ -6,6 +6,11 @@ namespace SqlParser.Tokens; /// public class EOF() : StringToken("EOF") { + public EOF(Location location) : this() + { + SetLocation(location); + } + public override bool Equals(object? obj) { return obj is EOF;