//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.SqlServer.Management.SqlParser.Parser;
using Microsoft.SqlTools.ServiceLayer.Utility;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
namespace Microsoft.SqlTools.ServiceLayer.LanguageServices.Completion
{
///
/// A class to calculate the numbers used by SQL parser using the text positions and content
///
internal class ScriptDocumentInfo
{
///
/// Create new instance
///
public ScriptDocumentInfo(TextDocumentPosition textDocumentPosition, ScriptFile scriptFile, ScriptParseInfo scriptParseInfo)
{
StartLine = textDocumentPosition.Position.Line;
ParserLine = textDocumentPosition.Position.Line + 1;
StartColumn = TextUtilities.PositionOfPrevDelimeter(
scriptFile.Contents,
textDocumentPosition.Position.Line,
textDocumentPosition.Position.Character);
EndColumn = TextUtilities.PositionOfNextDelimeter(
scriptFile.Contents,
textDocumentPosition.Position.Line,
textDocumentPosition.Position.Character);
ParserColumn = textDocumentPosition.Position.Character + 1;
ScriptParseInfo = scriptParseInfo;
Contents = scriptFile.Contents;
// need to adjust line & column for base-1 parser indices
Token = GetToken(scriptParseInfo, ParserLine, ParserColumn);
}
///
/// Gets a string containing the full contents of the file.
///
public string Contents { get; private set; }
///
/// Script Parse Info Instance
///
public ScriptParseInfo ScriptParseInfo { get; private set; }
///
/// Start Line
///
public int StartLine { get; private set; }
///
/// Parser Line
///
public int ParserLine { get; private set; }
///
/// Start Column
///
public int StartColumn { get; private set; }
///
/// end Column
///
public int EndColumn { get; private set; }
///
/// Parser Column
///
public int ParserColumn { get; private set; }
///
/// The token text in the file content used for completion list
///
public string TokenText
{
get
{
return Token != null ? Token.Text : null;
}
}
///
/// The token in the file content used for completion list
///
public Token Token { get; private set; }
///
/// Returns the token that will be used by SQL parser for creating the completion list
///
internal static Token GetToken(ScriptParseInfo scriptParseInfo, int startLine, int startColumn)
{
if (scriptParseInfo != null && scriptParseInfo.ParseResult != null && scriptParseInfo.ParseResult.Script != null && scriptParseInfo.ParseResult.Script.Tokens != null)
{
var tokenIndex = scriptParseInfo.ParseResult.Script.TokenManager.FindToken(startLine, startColumn);
if (tokenIndex >= 0)
{
// return the current token
int currentIndex = 0;
foreach (var token in scriptParseInfo.ParseResult.Script.Tokens)
{
if (currentIndex == tokenIndex)
{
return token;
}
++currentIndex;
}
}
}
return null;
}
}
}