本文整理汇总了C#中TextSpan类的典型用法代码示例。如果您正苦于以下问题:C# TextSpan类的具体用法?C# TextSpan怎么用?C# TextSpan使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
TextSpan类属于命名空间,在下文中一共展示了TextSpan类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: GetRefactoringsAsync
public async Task<IEnumerable<CodeAction>> GetRefactoringsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var node = root.FindNode(textSpan);
var switchStatementNode = node as SwitchStatementSyntax;
if (switchStatementNode == null)
return null;
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var memberEx = switchStatementNode.Expression as MemberAccessExpressionSyntax;
if (memberEx == null)
return null;
var symbolInfo = semanticModel.GetTypeInfo(memberEx.Name);
var enumTypeInfo = symbolInfo.Type;
if (enumTypeInfo.TypeKind != TypeKind.Enum)
return null;
var enumName = enumTypeInfo.Name;
var nameSpace = enumTypeInfo.ContainingNamespace.Name;
var enumType = Type.GetType(nameSpace + "." + enumName);
if (enumType == null)
return null;
return new[] { CodeAction.Create("Explode Switch", c => ExplodeSwitch(document, root, semanticModel, switchStatementNode, c)) };
}
开发者ID:Zache,项目名称:SwitchExploder,代码行数:27,代码来源:CodeRefactoringProvider.cs
示例2: TokenStream
public TokenStream(TreeData treeData, OptionSet optionSet, TextSpan spanToFormat, AbstractTriviaDataFactory factory)
{
using (Logger.LogBlock(FunctionId.Formatting_TokenStreamConstruction, CancellationToken.None))
{
// initialize basic info
_factory = factory;
_treeData = treeData;
_optionSet = optionSet;
// use some heuristics to get initial size of list rather than blindly start from default size == 4
int sizeOfList = spanToFormat.Length / MagicTextLengthToTokensRatio;
_tokens = new List<SyntaxToken>(sizeOfList);
_tokens.AddRange(_treeData.GetApplicableTokens(spanToFormat));
Contract.Requires(this.TokenCount > 0);
// initialize trivia related info
_cachedOriginalTriviaInfo = new TriviaData[this.TokenCount - 1];
_tokenToIndexMap = new Dictionary<SyntaxToken, int>(this.TokenCount);
for (int i = 0; i < this.TokenCount; i++)
{
_tokenToIndexMap.Add(_tokens[i], i);
}
// Func Cache
_getTriviaData = this.GetTriviaData;
_getOriginalTriviaData = this.GetOriginalTriviaData;
}
DebugCheckTokenOrder();
}
开发者ID:GuilhermeSa,项目名称:roslyn,代码行数:32,代码来源:TokenStream.cs
示例3: GetRefactoring
public CodeRefactoring GetRefactoring(IDocument document, TextSpan textSpan, CancellationToken cancellationToken)
{
var tree = (SyntaxTree)document.GetSyntaxTree(cancellationToken);
var token = tree.GetRoot().FindToken(textSpan.Start);
if (token.Parent is ClassDeclarationSyntax || token.Parent is StructDeclarationSyntax) {
var t = (TypeDeclarationSyntax)token.Parent;
if (!CanInferNonTrivialConstructor(t)) return null;
return new CodeRefactoring(new[] { new ReadyCodeAction("Infer Non-Trivial Constructor", document, t, () => {
var c = TryInferNonTrivialConstructor(t, document.TryGetSemanticModel());
var i = 0;
var ms = t.Members.Insert(i, new[] {c}).List();
return t.With(members: ms);
})});
}
if (token.Parent is MemberDeclarationSyntax && (token.Parent.Parent is ClassDeclarationSyntax || token.Parent.Parent is StructDeclarationSyntax)) {
var m = (MemberDeclarationSyntax)token.Parent;
var t = (TypeDeclarationSyntax)m.Parent;
if (!CanInferNonTrivialConstructor(t)) return null;
return new CodeRefactoring(new[] { new ReadyCodeAction("Infer Non-Trivial Constructor Here", document, t, () => {
var c = TryInferNonTrivialConstructor(t, document.TryGetSemanticModel());
var i = t.Members.IndexOf(m);
var ms = t.Members.Insert(i, new[] {c}).List();
return t.With(members: ms);
})});
}
return null;
}
开发者ID:Strilanc,项目名称:Croslyn,代码行数:30,代码来源:InferNonTrivialConstructor.cs
示例4: Create
public static CompletionItem Create(
string displayText,
TextSpan span,
ISymbol symbol,
int contextPosition = -1,
int descriptionPosition = -1,
string sortText = null,
string insertionText = null,
Glyph? glyph = null,
string filterText = null,
bool preselect = false,
SupportedPlatformData supportedPlatforms = null,
bool isArgumentName = false,
ImmutableDictionary<string, string> properties = null,
CompletionItemRules rules = null)
{
return Create(
displayText: displayText,
span: span,
symbols: ImmutableArray.Create(symbol),
contextPosition: contextPosition,
descriptionPosition: descriptionPosition,
sortText: sortText,
insertionText: insertionText,
glyph: glyph,
filterText: filterText,
preselect: preselect,
supportedPlatforms: supportedPlatforms,
isArgumentName: isArgumentName,
properties: properties,
rules: rules);
}
开发者ID:RoryVL,项目名称:roslyn,代码行数:32,代码来源:SymbolCompletionItem.cs
示例5: AddClassification
private void AddClassification(TextSpan span, string type)
{
if (ShouldAddSpan(span))
{
_result.Add(new ClassifiedSpan(type, span));
}
}
开发者ID:XieShuquan,项目名称:roslyn,代码行数:7,代码来源:Worker.cs
示例6: CheckIfSpanWithinSequencePoints
public static bool CheckIfSpanWithinSequencePoints(TextSpan span, string source, string pdb)
{
// calculate row and column from span
var text = SourceText.From(source);
var startLine = text.Lines.GetLineFromPosition(span.Start);
var startRow = startLine.LineNumber + 1;
var startColumn = span.Start - startLine.Start + 1;
var endLine = text.Lines.GetLineFromPosition(span.End);
var endRow = endLine.LineNumber + 1;
var endColumn = span.End - endLine.Start + 1;
var doc = new XmlDocument();
doc.LoadXml(pdb);
foreach (XmlNode entry in doc.GetElementsByTagName("sequencePoints"))
{
foreach (XmlElement item in entry.ChildNodes)
{
if (startRow.ToString() == item.GetAttribute("startLine") &&
startColumn.ToString() == item.GetAttribute("startColumn") &&
endRow.ToString() == item.GetAttribute("endLine") &&
endColumn.ToString() == item.GetAttribute("endColumn"))
{
return true;
}
}
}
return false;
}
开发者ID:GloryChou,项目名称:roslyn,代码行数:31,代码来源:CSharpPDBTestBase.cs
示例7: ApiLine
internal ApiLine(string text, TextSpan span, SourceText sourceText, string path)
{
Text = text;
Span = span;
SourceText = sourceText;
Path = path;
}
开发者ID:Anniepoh,项目名称:roslyn-analyzers,代码行数:7,代码来源:DeclarePublicAPIAnalyzer.Impl.cs
示例8: XmlDocCommentCompletionItem
public XmlDocCommentCompletionItem(CompletionListProvider provider,
TextSpan filterSpan,
string displayText,
CompletionItemRules rules)
: this(provider, filterSpan, displayText, displayText, string.Empty, rules)
{
}
开发者ID:SoumikMukherjeeDOTNET,项目名称:roslyn,代码行数:7,代码来源:XmlDocCommentCompletionItem.cs
示例9: WriteDocumentationCommentXml
/// <summary>
/// Traverses the symbol table processing XML documentation comments and optionally writing them to
/// a provided stream.
/// </summary>
/// <param name="compilation">Compilation that owns the symbol table.</param>
/// <param name="assemblyName">Assembly name override, if specified. Otherwise the <see cref="ISymbol.Name"/> of the source assembly is used.</param>
/// <param name="xmlDocStream">Stream to which XML will be written, if specified.</param>
/// <param name="diagnostics">Will be supplemented with documentation comment diagnostics.</param>
/// <param name="cancellationToken">To stop traversing the symbol table early.</param>
/// <param name="filterTree">Only report diagnostics from this syntax tree, if non-null.</param>
/// <param name="filterSpanWithinTree">If <paramref name="filterTree"/> and filterSpanWithinTree is non-null, report diagnostics within this span in the <paramref name="filterTree"/>.</param>
public static void WriteDocumentationCommentXml(CSharpCompilation compilation, string assemblyName, Stream xmlDocStream, DiagnosticBag diagnostics, CancellationToken cancellationToken, SyntaxTree filterTree = null, TextSpan? filterSpanWithinTree = null)
{
StreamWriter writer = null;
if (xmlDocStream != null && xmlDocStream.CanWrite)
{
writer = new StreamWriter(
stream: xmlDocStream,
encoding: new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false),
bufferSize: 0x400, // Default.
leaveOpen: true); // Don't close caller's stream.
}
using (writer)
{
var compiler = new DocumentationCommentCompiler(assemblyName ?? compilation.SourceAssembly.Name, compilation, writer, filterTree, filterSpanWithinTree,
processIncludes: true, isForSingleSymbol: false, diagnostics: diagnostics, cancellationToken: cancellationToken);
compiler.Visit(compilation.SourceAssembly.GlobalNamespace);
Debug.Assert(compiler._indentDepth == 0);
}
if (filterTree != null)
{
// Will respect the DocumentationMode.
UnprocessedDocumentationCommentFinder.ReportUnprocessed(filterTree, filterSpanWithinTree, diagnostics, cancellationToken);
}
else
{
foreach (SyntaxTree tree in compilation.SyntaxTrees)
{
// Will respect the DocumentationMode.
UnprocessedDocumentationCommentFinder.ReportUnprocessed(tree, null, diagnostics, cancellationToken);
}
}
}
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:45,代码来源:DocumentationCommentCompiler.cs
示例10: GetDocumentHighlightsAsync
public async Task<ImmutableArray<DocumentHighlights>> GetDocumentHighlightsAsync(
Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken)
{
// use speculative semantic model to see whether we are on a symbol we can do HR
var span = new TextSpan(position, 0);
var solution = document.Project.Solution;
var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false);
var symbol = await SymbolFinder.FindSymbolAtPositionAsync(
semanticModel, position, solution.Workspace, cancellationToken).ConfigureAwait(false);
if (symbol == null)
{
return ImmutableArray<DocumentHighlights>.Empty;
}
symbol = await GetSymbolToSearchAsync(document, position, semanticModel, symbol, cancellationToken).ConfigureAwait(false);
if (symbol == null)
{
return ImmutableArray<DocumentHighlights>.Empty;
}
// Get unique tags for referenced symbols
return await GetTagsForReferencedSymbolAsync(
new SymbolAndProjectId(symbol, document.Project.Id), documentsToSearch,
solution, cancellationToken).ConfigureAwait(false);
}
开发者ID:XieShuquan,项目名称:roslyn,代码行数:26,代码来源:AbstractDocumentHighlightsService.cs
示例11: GetItemsWorkerAsync
protected async override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken)
{
var position = completionContext.Position;
var document = completionContext.Document;
var span = new TextSpan(position, 0);
var semanticModel = await document.GetCSharpSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false);
var syntaxTree = semanticModel.SyntaxTree;
// var ctx = await completionContext.GetSyntaxContextAsync (engine.Workspace, cancellationToken).ConfigureAwait (false);
if (syntaxTree.IsInNonUserCode(position, cancellationToken) ||
syntaxTree.IsPreProcessorDirectiveContext(position, cancellationToken))
{
return Enumerable.Empty<CompletionData> ();
}
if (!syntaxTree.IsRightOfDotOrArrowOrColonColon(position, cancellationToken))
{
return Enumerable.Empty<CompletionData> ();
}
var node = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken)
.GetPreviousTokenIfTouchingWord(position)
.Parent;
if (node.Kind() == SyntaxKind.ExplicitInterfaceSpecifier)
{
return await GetCompletionsOffOfExplicitInterfaceAsync(
engine, document, semanticModel, position, ((ExplicitInterfaceSpecifierSyntax)node).Name, cancellationToken).ConfigureAwait(false);
}
return Enumerable.Empty<CompletionData> ();
}
开发者ID:pabloescribanoloza,项目名称:monodevelop,代码行数:32,代码来源:ExplicitInterfaceContextHandler.cs
示例12: SourceDefinitionTreeItem
public SourceDefinitionTreeItem(Document document, TextSpan sourceSpan, ISymbol symbol, ushort glyphIndex)
: base(document, sourceSpan, glyphIndex)
{
_symbolDisplay = symbol.ToDisplayString(definitionDisplayFormat);
this.DisplayText = $"[{document.Project.Name}] {_symbolDisplay}";
}
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:7,代码来源:SourceDefinitionTreeItem.cs
示例13: Test
protected void Test(string code,
string allCode,
Tuple<string, string>[] expected,
CSharpParseOptions options = null)
{
var start = allCode.IndexOf(code);
var length = code.Length;
var span = new TextSpan(start, length);
var actual = GetClassificationSpans(allCode, span, options: options).ToList();
actual.Sort((t1, t2) => t1.TextSpan.Start - t2.TextSpan.Start);
var max = Math.Max(expected.Length, actual.Count);
for (int i = 0; i < max; i++)
{
if (i >= expected.Length)
{
AssertEx.Fail("Unexpected actual classification: {0}", GetText(actual[i]));
}
else if (i >= actual.Count)
{
AssertEx.Fail("Missing classification for: {0}", GetText(expected[i]));
}
var tuple = expected[i];
var classification = actual[i];
var text = allCode.Substring(classification.TextSpan.Start, classification.TextSpan.Length);
Assert.Equal(tuple.Item1, text);
Assert.Equal(tuple.Item2, classification.ClassificationType);
}
}
开发者ID:elemk0vv,项目名称:roslyn-1,代码行数:33,代码来源:AbstractCSharpClassifierTests.cs
示例14: RecoverNode
protected static SyntaxNode RecoverNode(SyntaxTree tree, TextSpan textSpan, int kind)
{
var token = tree.GetRoot().FindToken(textSpan.Start, findInsideTrivia: true);
var node = token.Parent;
while (node != null)
{
if (node.Span == textSpan && node.RawKind == kind)
{
return node;
}
var structuredTrivia = node as IStructuredTriviaSyntax;
if (structuredTrivia != null)
{
node = structuredTrivia.ParentTrivia.Token.Parent;
}
else
{
node = node.Parent;
}
}
throw Contract.Unreachable;
}
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:25,代码来源:AbstractSyntaxTreeFactoryService.cs
示例15: GetDocumentDiagnostics
public static IEnumerable<Diagnostic> GetDocumentDiagnostics(DiagnosticAnalyzer workspaceAnalyzerOpt, Document document, TextSpan span, Action<Exception, DiagnosticAnalyzer, Diagnostic> onAnalyzerException = null, bool logAnalyzerExceptionAsDiagnostics = false)
{
using (var testDriver = new TestDiagnosticAnalyzerDriver(document.Project, workspaceAnalyzerOpt, onAnalyzerException, logAnalyzerExceptionAsDiagnostics))
{
return testDriver.GetDocumentDiagnostics(workspaceAnalyzerOpt, document, span);
}
}
开发者ID:noahstein,项目名称:roslyn,代码行数:7,代码来源:DiagnosticProviderTestUtilities.cs
示例16: Ctor1
public void Ctor1()
{
var span = new TextSpan(0, 42);
Assert.Equal(0, span.Start);
Assert.Equal(42, span.Length);
Assert.Equal(42, span.End);
}
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:7,代码来源:TextSpanTest.cs
示例17: ChangeIndentation
/// <summary>
/// Changes the indentation of the current line based on the last
/// bit of code typed.
/// </summary>
/// <param name="changedArea">Area of changed code</param>
public void ChangeIndentation(TextSpan changedArea)
{
TextSpan area = changedArea;
string text = source.GetText(area);
string line = source.GetLineUptoPosition(area.iStartLine, area.iStartIndex);
if (!line.EndsWith(text))
{
// if commit includes last bit of text typed, the line won't have it yet
// so stick it on for our parsing sanity
// ** probably not the best thing to be doing here, but we can't just
// get the whole line, because we may be pressing return in the centre
// of it
line += text;
}
if (RequiresIndent(line))
{
source.SetText(area, text + Indent); // add an indent to the end of the changed text
MoveCaret(Indent.Length); // move the caret to the new end of line
}
else if (RequiresDedent(line))
{
source.SetText(area, text.Remove(text.Length - Indent.Length)); // remove an indent
MoveCaret(-Indent.Length); // move caret in a bit
}
}
开发者ID:arnitamayo,项目名称:boolangstudio,代码行数:32,代码来源:LineIndenter.cs
示例18: Ctor2
public void Ctor2()
{
var span = new TextSpan(1, 40);
Assert.Equal(1, span.Start);
Assert.Equal(40, span.Length);
Assert.Equal(41, span.End);
}
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:7,代码来源:TextSpanTest.cs
示例19: GetEncapsulateFieldCodeActionsAsync
public async Task<IEnumerable<EncapsulateFieldCodeAction>> GetEncapsulateFieldCodeActionsAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var fields = (await GetFieldsAsync(document, span, cancellationToken).ConfigureAwait(false)).ToImmutableArrayOrEmpty();
if (fields.Length == 0)
{
return SpecializedCollections.EmptyEnumerable<EncapsulateFieldCodeAction>();
}
if (fields.Length == 1)
{
// there is only one field
return EncapsulateOneField(document, span, fields[0], index: 0);
}
else
{
// there are multiple fields.
var current = SpecializedCollections.EmptyEnumerable<EncapsulateFieldCodeAction>();
if (span.IsEmpty)
{
// if there is no selection, get action for each field + all of them.
for (var i = 0; i < fields.Length; i++)
{
current = current.Concat(EncapsulateOneField(document, span, fields[i], i));
}
}
return current.Concat(EncapsulateAllFields(document, span));
}
}
开发者ID:rgani,项目名称:roslyn,代码行数:30,代码来源:AbstractEncapsulateFieldService.cs
示例20: SignatureHelpModel
public SignatureHelpModel(TextSpan applicableSpan, IEnumerable<SignatureItem> signatures, SignatureItem signature, int selectedParameter)
{
Signatures = signatures.ToImmutableArray();
ApplicableSpan = applicableSpan;
Signature = signature;
SelectedParameter = selectedParameter;
}
开发者ID:pminiszewski,项目名称:HlslTools,代码行数:7,代码来源:SignatureHelpModel.cs
注:本文中的TextSpan类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论