本文整理汇总了C#中Microsoft.CodeAnalysis.SyntaxTree.GetText方法的典型用法代码示例。如果您正苦于以下问题:C# SyntaxTree.GetText方法的具体用法?C# SyntaxTree.GetText怎么用?C# SyntaxTree.GetText使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.CodeAnalysis.SyntaxTree
的用法示例。
在下文中一共展示了SyntaxTree.GetText方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ReportAllErrors
protected override IEnumerable<string> ReportAllErrors(SyntaxTree userSolution)
{
var text = userSolution.GetText();
var longLines = text.Lines.Where(line => line.End - line.Start > maxLineLen).ToList();
if (longLines.Count == 0) yield break;
var position = userSolution.GetLineSpan(longLines[0].Span);
yield return Report(
position,
"Слишком длинная строка. Не заставляйте людей использовать горизонтальный скролл");
}
示例2: ToResult
private static SyntaxTree ToResult(Compilation compilation, string name, SyntaxTree tree, string path, bool writeToDisk)
{
var ext = (compilation.Language == LanguageNames.VisualBasic) ? ".vb" : ".cs";
var fileName = $"{FixUpName(name)}{ext}";
path = PathUtilities.CombinePossiblyRelativeAndRelativePaths(path, fileName);
if (writeToDisk)
{
var sourceText = tree.GetText();
var encoding = sourceText.Encoding ?? Encoding.UTF8;
PortableShim.File.WriteAllText(path, sourceText.ToString(), encoding);
}
return tree.WithFilePath(path);
}
示例3: IsPartialMethodCompletionContext
protected override bool IsPartialMethodCompletionContext(SyntaxTree tree, int position, CancellationToken cancellationToken, out DeclarationModifiers modifiers, out SyntaxToken token)
{
var touchingToken = tree.FindTokenOnLeftOfPosition(position, cancellationToken);
var targetToken = touchingToken.GetPreviousTokenIfTouchingWord(position);
var text = tree.GetText(cancellationToken);
token = targetToken;
modifiers = default(DeclarationModifiers);
if (targetToken.IsKind(SyntaxKind.VoidKeyword, SyntaxKind.PartialKeyword) ||
(targetToken.Kind() == SyntaxKind.IdentifierToken && targetToken.HasMatchingText(SyntaxKind.PartialKeyword)))
{
return !IsOnSameLine(touchingToken.GetNextToken(), touchingToken, text) &&
VerifyModifiers(tree, position, cancellationToken, out modifiers);
}
return false;
}
示例4: GetTextChanges
// return a set of text changes that when applied to the old document produces the new document
internal static IList<TextChange> GetTextChanges(SyntaxTree before, SyntaxTree after)
{
if (before == after)
{
return SpecializedCollections.EmptyList<TextChange>();
}
else if (before == null)
{
return new[] { new TextChange(new TextSpan(0, 0), after.GetText().ToString()) };
}
else if (after == null)
{
throw new ArgumentNullException("after");
}
else
{
return GetTextChanges(before.GetRoot(), after.GetRoot());
}
}
示例5: GetPossiblyDifferentTextSpans
internal static IList<TextSpan> GetPossiblyDifferentTextSpans(SyntaxTree before, SyntaxTree after)
{
if (before == after)
{
// They're the same, so nothing changed.
return SpecializedCollections.EmptyList<TextSpan>();
}
else if (before == null)
{
// The tree is completely new, everything has changed.
return new[] { new TextSpan(0, after.GetText().Length) };
}
else if (after == null)
{
throw new ArgumentNullException("after");
}
else
{
return GetPossiblyDifferentTextSpans(before.GetRoot(), after.GetRoot());
}
}
示例6: TryGetBreakpointSpan
internal static bool TryGetBreakpointSpan(SyntaxTree tree, int position, CancellationToken cancellationToken, out TextSpan breakpointSpan)
{
var source = tree.GetText(cancellationToken);
// If the line is entirely whitespace, then don't set any breakpoint there.
var line = source.Lines.GetLineFromPosition(position);
if (IsBlank(line))
{
breakpointSpan = default(TextSpan);
return false;
}
// If the user is asking for breakpoint in an inactive region, then just create a line
// breakpoint there.
if (tree.IsInInactiveRegion(position, cancellationToken))
{
breakpointSpan = default(TextSpan);
return true;
}
var root = tree.GetRoot(cancellationToken);
return root.TryGetClosestBreakpointSpan(position, out breakpointSpan);
}
示例7: PersistSyntaxTree
/// <summary>
/// Writes the DbContext to disk using the given Roslyn SyntaxTree.
/// The method expects that SyntaxTree has a file path associated with it.
/// Handles both writing a new file and editing an existing file.
/// </summary>
/// <param name="newTree"></param>
private void PersistSyntaxTree(SyntaxTree newTree)
{
Debug.Assert(newTree != null);
Debug.Assert(!String.IsNullOrEmpty(newTree.FilePath));
Directory.CreateDirectory(Path.GetDirectoryName(newTree.FilePath));
using (var fileStream = new FileStream(newTree.FilePath, FileMode.OpenOrCreate, FileAccess.Write))
{
using (var streamWriter = new StreamWriter(stream: fileStream, encoding: Encoding.UTF8))
{
newTree.GetText().Write(streamWriter);
}
}
}
示例8: VisualDiff
/// <summary>
/// Get a string that represents the differences in the file in a way that is readable
/// </summary>
/// <param name="ancestor">SyntaxTree that changed was modified from</param>
/// <param name="diffs">all the changes to the ancestor</param>
/// <returns>a string that can be inspected to see the changes</returns>
public static string VisualDiff(IEnumerable<Diff> diffs, SyntaxTree ancestor)
{
var builder = new StringBuilder();
var currentAncestorPos = 0;
foreach (var d in diffs)
{
var dStart = d.Ancestor.Span.Start;
if (dStart > currentAncestorPos)
{
builder.Append(ancestor
.GetText()
.ToString(TextSpan.FromBounds(currentAncestorPos, dStart)));
}
builder.Append(d);
currentAncestorPos = d.Ancestor.Span.End;
}
builder.Append(ancestor
.GetText()
.ToString(TextSpan.FromBounds(currentAncestorPos, ancestor.Length)));
return builder.ToString();
}
示例9: GetElementLocation
/// <summary>
/// Gets the location representing the position of the given element in the source file.
/// </summary>
/// <param name="syntaxTree">The syntax tree to use for generating the location.</param>
/// <param name="element">The XML element to get the location of.</param>
/// <returns>The location representing the position of the given element in the source file.</returns>
internal Location GetElementLocation(SyntaxTree syntaxTree, XElement element)
{
var headerSourceText = syntaxTree.GetText().GetSubText(TextSpan.FromBounds(this.fileHeaderStart, this.fileHeaderEnd)).ToString();
var tagStart = "<" + element.Name.LocalName;
var index = headerSourceText.IndexOf(tagStart);
var textSpan = TextSpan.FromBounds(this.fileHeaderStart + index, this.fileHeaderStart + index + tagStart.Length);
return Location.Create(syntaxTree, textSpan);
}
示例10: VerifyModifiers
static bool VerifyModifiers(SyntaxTree tree, int position, CancellationToken cancellationToken/*, out DeclarationModifiers modifiers*/)
{
var touchingToken = tree.FindTokenOnLeftOfPosition(position, cancellationToken);
var token = touchingToken.GetPreviousToken();
bool foundPartial = touchingToken.IsKindOrHasMatchingText(SyntaxKind.PartialKeyword);
bool foundAsync = false;
while (IsOnSameLine(token, touchingToken, tree.GetText(cancellationToken)))
{
if (token.IsKind(SyntaxKind.ExternKeyword, SyntaxKind.PublicKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.InternalKeyword))
{
//modifiers = default(DeclarationModifiers);
return false;
}
if (token.IsKindOrHasMatchingText(SyntaxKind.AsyncKeyword))
{
foundAsync = true;
}
foundPartial = foundPartial || token.IsKindOrHasMatchingText(SyntaxKind.PartialKeyword);
token = token.GetPreviousToken();
}
/*modifiers = new DeclarationModifiers()
.WithPartial(true)
.WithAsync (foundAsync);*/
return foundPartial;
}
示例11: getSnippet
private static string getSnippet(SyntaxTree tree, int startPos, int endPos)
{
var rawSnippet = tree.GetText().GetSubText(new Microsoft.CodeAnalysis.Text.TextSpan(startPos, endPos - startPos)).ToString();
return removeWhitespace(rawSnippet);
}
示例12: AnalyzeSyntax
private SyntaxTree AnalyzeSyntax(SyntaxTree tree, string code)
{
var root = tree.GetRoot();
var codeErrors = root.GetDiagnostics().Where(error => error.Id == "CS1022").
OrderBy(error => error.Location.SourceSpan.Start).GetEnumerator();
Diagnostic currError = null;
int currErrorPos = 0;
if (codeErrors != null && codeErrors.MoveNext())
currError = codeErrors.Current;
List<StatementSyntax> statements = new List<StatementSyntax>();
List<MemberDeclarationSyntax> members = new List<MemberDeclarationSyntax>();
List<MemberDeclarationSyntax> types = new List<MemberDeclarationSyntax>();
foreach (var child in root.ChildNodes())
{
if (child is IncompleteMemberSyntax)
continue;
if (child is FieldDeclarationSyntax)
{
//case: code variable?
FieldDeclarationSyntax field = (FieldDeclarationSyntax)child;
//td: !!! variable initialization
continue;
}
if (child is MethodDeclarationSyntax)
{
//case: bad method?
MethodDeclarationSyntax method = (MethodDeclarationSyntax)child;
if (method.Body == null)
continue;
}
if (child is MemberDeclarationSyntax)
{
bool foundError = false;
if (currError != null)
{
if (child.SpanStart > currError.Location.SourceSpan.Start)
{
SourceText errorSource = tree.GetText().GetSubText(new TextSpan(currErrorPos, child.SpanStart - currErrorPos));
parseStatements(errorSource.ToString(), currErrorPos, statements);
foundError = true;
currError = null;
while (codeErrors.MoveNext())
{
var nextError = codeErrors.Current;
if (nextError.Location.SourceSpan.Start > child.Span.End)
{
currError = nextError;
break;
}
}
}
}
currErrorPos = child.Span.End;
var toAdd = child as MemberDeclarationSyntax;
if (foundError)
{
toAdd = toAdd.ReplaceTrivia(child.GetLeadingTrivia(), (oldTrivia, newTrivia) =>
{
return SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, string.Empty);
});
}
if (toAdd is TypeDeclarationSyntax || toAdd is EnumDeclarationSyntax)
types.Add(toAdd);
else if (!(toAdd is NamespaceDeclarationSyntax))
members.Add(toAdd);
}
else
{
//any other top level construct indicates completeness
return tree;
}
}
if (currError != null)
{
SourceText errorSource = tree.GetText().GetSubText(new TextSpan(currErrorPos, tree.GetRoot().FullSpan.End - currErrorPos));
parseStatements(errorSource.ToString(), currErrorPos, statements);
}
bool hasCode = statements.Count > 0;
bool hasMembers = members.Count > 0;
if (!hasCode && !hasMembers)
{
return tree; //nothing to se here
}
var complete = ctx_.Complete(statements, members, types);
return complete != null? complete : tree;
//var container = SyntaxFactory.ClassDeclaration("application");
//.........这里部分代码省略.........
示例13: ExpectedIssues
private static Dictionary<int, string> ExpectedIssues(SyntaxTree syntaxTree)
{
var expectedIssueMessage = new Dictionary<int, string>();
foreach (var line in syntaxTree.GetText().Lines)
{
var lineText = line.ToString();
if (!lineText.Contains(NONCOMPLIANT_START))
{
continue;
}
var lineNumber = GetNonCompliantLineNumber(line);
expectedIssueMessage.Add(lineNumber, null);
var match = Regex.Match(lineText, NONCOMPLIANT_MESSAGE_PATTERN);
if (!match.Success)
{
continue;
}
var message = match.Groups[1].ToString();
expectedIssueMessage[lineNumber] = message.Substring(2, message.Length - 4);
}
return expectedIssueMessage;
}
示例14: ExpectedIssueLocations
private static Dictionary<int, ExactIssueLocation> ExpectedIssueLocations(SyntaxTree syntaxTree, string language)
{
var exactLocations = new Dictionary<int, ExactIssueLocation>();
var locationPattern = language == LanguageNames.CSharp
? EXPECTED_ISSUE_LOCATION_PATTERN_CSHARP
: EXPECTED_ISSUE_LOCATION_PATTERN_VBNET;
foreach (var line in syntaxTree.GetText().Lines)
{
var lineText = line.ToString();
var match = Regex.Match(lineText, locationPattern);
if (!match.Success)
{
var commentStart = language == LanguageNames.CSharp ? COMMENT_START_CSHARP : COMMENT_START_VBNET;
if (Regex.IsMatch(lineText, commentStart + EXPECTED_ISSUE_LOCATION_PATTERN + "$"))
{
Assert.Fail("Line matches expected location pattern, but doesn't start at the beginning of the line.");
}
continue;
}
var position = match.Groups[1];
exactLocations.Add(line.LineNumber, new ExactIssueLocation
{
Line = line.LineNumber,
StartPosition = position.Index,
Length = position.Length,
});
}
return exactLocations;
}
示例15: ExpectedIssues
private static IEnumerable<int> ExpectedIssues(SyntaxTree syntaxTree)
{
return syntaxTree.GetText().Lines
.Where(l => l.ToString().Contains(NONCOMPLIANT_START))
.Select(l => GetNoncompliantLineNumber(l));
}