public FieldInfoWrapper(IFieldSymbol parameter, MetadataLoadContextInternal metadataLoadContext) { _field = parameter; _metadataLoadContext = metadataLoadContext; NeedsAtSign = SyntaxFacts.GetKeywordKind(_field.Name) != SyntaxKind.None || SyntaxFacts.GetContextualKeywordKind(_field.Name) != SyntaxKind.None; }
public void Lexer_Should_Get_Keyword_Pure_Kind() { String text = "pure"; SyntaxKind kind = SyntaxFacts.GetKeywordKind(text); Assert.Equal(SyntaxKind.PureKeyword, kind); }
public void KeywordKinds() { // Verify the labels are consistent with the VB compiler. foreach (var pair in MemberSignatureParser.KeywordKinds) { var expectedKind = SyntaxFacts.GetKeywordKind(pair.Key).ToString(); var actualKind = pair.Value.ToString(); Assert.Equal(expectedKind, actualKind); } // Verify all values are also in Keywords. foreach (var keyword in MemberSignatureParser.KeywordKinds.Keys) { Assert.True(MemberSignatureParser.Keywords.Contains(keyword)); } // Verify all values of SyntaxKind are recognized. const string keywordSuffix = "Keyword"; foreach (var value in typeof(MemberSignatureParser.SyntaxKind).GetEnumValues()) { var kind = (MemberSignatureParser.SyntaxKind)value; if (kind == MemberSignatureParser.SyntaxKind.None) { continue; } var pair = MemberSignatureParser.KeywordKinds.First(p => p.Value == kind); var kindText = kind.ToString(); Assert.EndsWith(keywordSuffix, kindText); var expectedText = kindText.Substring(0, kindText.Length - keywordSuffix.Length); Assert.Equal(expectedText, pair.Key, StringComparer.OrdinalIgnoreCase); } }
public static string SanitizeStringForCSharpIdentifier(string str, string fallback = "") { if (SyntaxFacts.IsReservedKeyword(SyntaxFacts.GetKeywordKind(str))) { return($"@{str}"); } if (SyntaxFacts.IsValidIdentifier(str)) { return(str); } if (string.IsNullOrWhiteSpace(str)) { return(fallback); } if (!SyntaxFacts.IsIdentifierStartCharacter(str[0])) { str = $"_{str}"; } var sanitizedString = new string(str .Where(c => SyntaxFacts.IsIdentifierPartCharacter(c)) .ToArray()); return(SyntaxFacts.IsValidIdentifier(sanitizedString) ? sanitizedString : fallback); }
public static SymbolDisplayPart MassageErrorTypeNames( this SymbolDisplayPart part, string?replacement = null ) { if (part.Kind == SymbolDisplayPartKind.ErrorTypeName) { var text = part.ToString(); if (text == string.Empty) { return(replacement == null ? new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, "object") : new SymbolDisplayPart(SymbolDisplayPartKind.Text, null, replacement)); } if (SyntaxFacts.GetKeywordKind(text) != SyntaxKind.None) { return(new SymbolDisplayPart( SymbolDisplayPartKind.ErrorTypeName, null, string.Format("@{0}", text) )); } } return(part); }
public static bool IsKeyword(this string name) { var isAnyKeyword = SyntaxFacts.GetKeywordKind(name) != SyntaxKind.None || SyntaxFacts.GetContextualKeywordKind(name) != SyntaxKind.None; return(isAnyKeyword); }
static SyntaxToken ConvertIdentifier(SyntaxToken id, SemanticModel semanticModel, bool isAttribute = false) { var keywordKind = SyntaxFacts.GetKeywordKind(id.ValueText); if (keywordKind != SyntaxKind.None && !SyntaxFacts.IsPredefinedType(keywordKind)) { return(SyntaxFactory.Identifier("@" + id.ValueText)); } string text = id.ValueText; if (id.SyntaxTree == semanticModel.SyntaxTree) { var symbol = semanticModel.GetSymbolInfo(id.Parent).Symbol; if (symbol != null && !string.IsNullOrWhiteSpace(symbol.Name)) { if (symbol.IsConstructor() && isAttribute) { text = symbol.ContainingType.Name; if (text.EndsWith("Attribute", StringComparison.Ordinal)) { text = text.Remove(text.Length - "Attribute".Length); } } else { text = symbol.Name; } } } return(SyntaxFactory.Identifier(text)); }
public void Lexer_Should_Get_Keyword_View_Kind() { String text = "view"; SyntaxKind kind = SyntaxFacts.GetKeywordKind(text); Assert.Equal(SyntaxKind.ViewKeyword, kind); }
/// <summary> /// Convert a string to a valid C# identifier that conforms to language specification 2.4.2 /// </summary> /// <param name="string">The string to convert</param> /// <param name="prefix">(Optional) string to prefix the identifier with.</param> /// <returns>A valid C# identifier</returns> public static string GetValidCSharpIdentifier(this string @string, string prefix = null) { if (!string.IsNullOrWhiteSpace(prefix)) { @string = prefix + @string; } @string = @string.Trim(); @string = Regex.Replace(@string, @"(?!\\u[0-9A-Fa-f]{4})[^\w]", match => { if (match.Index == 0 && match.Value == "@") { return("@"); } return(@"_"); }); if (!Regex.IsMatch(@string, "^[_@a-zA-Z]")) { @string = $"_{@string}"; } else if (SyntaxFacts.GetKeywordKind(@string) != SyntaxKind.None) { @string = $"@{@string}"; } return(@string); }
public void Lexer_Should_Get_Keyword_Contract_Kind() { String text = "contract"; SyntaxKind kind = SyntaxFacts.GetKeywordKind(text); Assert.Equal(SyntaxKind.ContractKeyword, kind); }
public PropertyInfoWrapper(IPropertySymbol property, MetadataLoadContextInternal metadataLoadContext) { _property = property; _metadataLoadContext = metadataLoadContext; NeedsAtSign = SyntaxFacts.GetKeywordKind(_property.Name) != SyntaxKind.None || SyntaxFacts.GetContextualKeywordKind(_property.Name) != SyntaxKind.None; }
private Token ScanIdentifierAfterStartCharacter(bool verbatim) { // Assert the offset is immediately following the start character. Debug.Assert(_offset > 0); Debug.Assert(UnicodeCharacterUtilities.IsIdentifierStartCharacter(_text[_offset - 1])); Debug.Assert(_offset == 1 || !UnicodeCharacterUtilities.IsIdentifierPartCharacter(_text[_offset - 2])); int length = _text.Length; int start = _offset - 1; while ((_offset < length) && UnicodeCharacterUtilities.IsIdentifierPartCharacter(_text[_offset])) { _offset++; } var text = _text.Substring(start, _offset - start); var keywordKind = verbatim ? SyntaxKind.None : SyntaxFacts.GetKeywordKind(text); if (keywordKind == SyntaxKind.None) { return(new Token(TokenKind.Identifier, text)); } return(new Token(TokenKind.Keyword, text, keywordKind)); }
/// <summary> /// Create a backing <see cref="FieldDeclarationSyntax"/> for the <paramref name="propertyDeclaration"/> /// Handles name collisions and reserved keywords. /// </summary> /// <param name="editor">The <see cref="DocumentEditor"/>.</param> /// <param name="propertyDeclaration">The <see cref="PropertyDeclarationSyntax"/>.</param> /// <returns>A <see cref="FieldDeclarationSyntax"/>.</returns> public static FieldDeclarationSyntax CreateBackingField(this DocumentEditor editor, PropertyDeclarationSyntax propertyDeclaration) { if (editor is null) { throw new System.ArgumentNullException(nameof(editor)); } if (propertyDeclaration is null) { throw new System.ArgumentNullException(nameof(propertyDeclaration)); } var property = editor.SemanticModel.GetDeclaredSymbol(propertyDeclaration); var name = editor.SemanticModel.UnderscoreFields() == CodeStyleResult.Yes ? $"_{property.Name.ToFirstCharLower()}" : property.Name.ToFirstCharLower(); while (property.ContainingType.MemberNames.Any(x => x == name)) { name += "_"; } if (SyntaxFacts.GetKeywordKind(name) != SyntaxKind.None || SyntaxFacts.GetContextualKeywordKind(name) != SyntaxKind.None) { name = "@" + name; } return((FieldDeclarationSyntax)editor.Generator.FieldDeclaration( name, accessibility: Accessibility.Private, modifiers: DeclarationModifiers.None, type: propertyDeclaration.Type, initializer: propertyDeclaration.Initializer?.Value)); }
internal static FieldDeclarationSyntax AddBackingField(this DocumentEditor editor, PropertyDeclarationSyntax propertyDeclaration, bool usesUnderscoreNames, CancellationToken cancellationToken) { var property = editor.SemanticModel.GetDeclaredSymbolSafe(propertyDeclaration, cancellationToken); var name = usesUnderscoreNames ? $"_{property.Name.ToFirstCharLower()}" : property.Name.ToFirstCharLower(); while (property.ContainingType.MemberNames.Any(x => x == name)) { name += "_"; } if (SyntaxFacts.GetKeywordKind(name) != SyntaxKind.None || SyntaxFacts.GetContextualKeywordKind(name) != SyntaxKind.None) { name = "@" + name; } var backingField = (FieldDeclarationSyntax)editor.Generator.FieldDeclaration( name, accessibility: Accessibility.Private, modifiers: DeclarationModifiers.None, type: propertyDeclaration.Type, initializer: propertyDeclaration.Initializer?.Value); var type = (TypeDeclarationSyntax)propertyDeclaration.Parent; editor.ReplaceNode( type, (node, generator) => AddBackingField((TypeDeclarationSyntax)node, backingField, property.Name, generator)); return(backingField); }
SyntaxToken ConvertIdentifier(SyntaxToken id) { if (SyntaxFacts.GetKeywordKind(id.ValueText) != SyntaxKind.None) { return(SyntaxFactory.Identifier("[" + id.ValueText + "]")); } return(SyntaxFactory.Identifier(id.ValueText)); }
private static void HandleXmlNodeSyntax(SyntaxNodeAnalysisContext context) { var xmlNodeSyntax = (XmlNodeSyntax)context.Node; var name = xmlNodeSyntax.GetName(); if (name is null || name.Prefix != null) { return; } if (name.LocalName.ValueText != XmlCommentHelper.SeeXmlTag) { return; } SyntaxList <XmlAttributeSyntax> attributes; if (xmlNodeSyntax is XmlEmptyElementSyntax xmlEmptyElement) { attributes = xmlEmptyElement.Attributes; } else { attributes = ((XmlElementSyntax)xmlNodeSyntax).StartTag.Attributes; } foreach (var attribute in attributes) { if (attribute.Name is null || attribute.Name.Prefix != null) { continue; } if (attribute.Name.LocalName.ValueText != XmlCommentHelper.LangwordArgumentName) { continue; } var text = ((XmlTextAttributeSyntax)attribute).TextTokens; string valueText; if (text.Count == 1) { valueText = text[0].ValueText; } else { valueText = string.Join(string.Empty, text.Select(textToken => textToken.ValueText)); } if (SyntaxFacts.GetKeywordKind(valueText) != SyntaxKind.None || SyntaxFacts.GetContextualKeywordKind(valueText) != SyntaxKind.None) { continue; } context.ReportDiagnostic(Diagnostic.Create(Descriptor, attribute.Name.LocalName.GetLocation())); } }
private static bool IsKeyWord(string identifier) { if (SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None || SyntaxFacts.GetContextualKeywordKind(identifier) != SyntaxKind.None) { return(true); } return(false); }
static string EscapeKeyword(string text) { if (SyntaxFacts.GetKeywordKind(text) != SyntaxKind.None) { return("@" + text); } return(text); }
private static string EscapeIdentifier(this string value) { value = string.Concat(value.Select(Escape)); if (SyntaxFacts.GetKeywordKind(value) != SyntaxKind.None) { value = "@" + value; } return(value); }
private void VisitFunctionDeclaration(Cursor cursor) { string functionName = cursor.GetSpelling(); if (!functionName.StartsWith("cblas_")) { return; } builder.AppendLine(); string resultTypeName = GetTypeName(cursor.GetResultType()); var parameters = new List <string>(); foreach (var child in cursor.GetChildren()) { if (child.Kind == CursorKind.ParmDecl) { var parameterType = child.GetTypeInfo(); if (parameterType.Kind == TypeKind.Void) // e.g., void foo(void); { break; } string typeName = GetTypeName(parameterType); string parameterName = child.GetSpelling(); if (string.IsNullOrEmpty(parameterName)) { parameterName = $"arg{parameters.Count + 1}"; } // Escape keywords if (SyntaxFacts.GetKeywordKind(parameterName) != SyntaxKind.None) { parameterName = '@' + parameterName; } parameters.Add($"{typeName} {parameterName}"); } } builder.AppendLine($"[DllImport(dllName)]"); if (parameters.Count == 0) { builder.AppendLine($"public static extern {resultTypeName} {functionName}();"); } else { builder.AppendLine($"public static extern {resultTypeName} {functionName}("); for (int i = 0; i < parameters.Count; i++) { string end = i == parameters.Count - 1 ? ");" : ","; builder.IncreaseIndent().AppendLine(parameters[i] + end); } } }
void AddXmlDocCommands() { AddCommand(MyToolBar, KnownImageIds.MarkupTag, "Tag XML Doc with <c>", ctx => { SurroundWith(ctx, "<c>", "</c>", true); }); AddCommand(MyToolBar, KnownImageIds.GoToNext, "Tag XML Doc with <see> or <paramref>", ctx => { // updates the semantic model before executing the command, // for it could be modified by external editor commands or duplicated document windows if (UpdateSemanticModel() == false) { return; } ctx.View.Edit((view, edit) => { foreach (var item in view.Selection.SelectedSpans) { var t = item.GetText(); var d = _Context.GetNode(item.Start, false, false).GetAncestorOrSelfDeclaration(); if (d != null) { var mp = (d as BaseMethodDeclarationSyntax).FindParameter(t); if (mp != null) { edit.Replace(item, "<paramref name=\"" + t + "\"/>"); continue; } var tp = d.FindTypeParameter(t); if (tp != null) { edit.Replace(item, "<typeparamref name=\"" + t + "\"/>"); continue; } } edit.Replace(item, (SyntaxFacts.GetKeywordKind(t) != SyntaxKind.None ? "<see langword=\"" : "<see cref=\"") + t + "\"/>"); } }); }); AddCommand(MyToolBar, KnownImageIds.ParagraphHardReturn, "Tag XML Doc with <para>", ctx => { SurroundWith(ctx, "<para>", "</para>", false); }); AddCommand(MyToolBar, KnownImageIds.Bold, "Tag XML Doc with HTML <b>", ctx => { SurroundWith(ctx, "<b>", "</b>", true); }); AddCommand(MyToolBar, KnownImageIds.Italic, "Tag XML Doc with HTML <i>", ctx => { SurroundWith(ctx, "<i>", "</i>", true); }); AddCommand(MyToolBar, KnownImageIds.Underline, "Tag XML Doc with HTML <u>", ctx => { SurroundWith(ctx, "<u>", "</u>", true); }); AddCommand(MyToolBar, KnownImageIds.CommentCode, "Comment selection\nRight click: Comment line", ctx => { if (ctx.RightClick) { ctx.View.ExpandSelectionToLine(); } TextEditorHelper.ExecuteEditorCommand("Edit.CommentSelection"); }); }
public static SyntaxToken ValidIdentifier(string identifier) { if (!SyntaxFacts.IsValidIdentifier(identifier) || SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None) { throw new ArgumentException("identifier", Strings.InvalidIdentifier(identifier)); } return(Identifier(identifier)); }
public void SyntaxFacts_Keyword_GetKeywordKind_DetectsAllReservedKeywords() { foreach (var kind in SyntaxFacts.GetReservedKeywordKinds()) { var text = kind.GetText(); var keywordKind = SyntaxFacts.GetKeywordKind(text); Assert.Equal(kind, keywordKind); } }
static SyntaxToken ConvertIdentifier(SyntaxToken id) { var keywordKind = SyntaxFacts.GetKeywordKind(id.ValueText); if (keywordKind != SyntaxKind.None && !SyntaxFacts.IsPredefinedType(keywordKind)) { return(SyntaxFactory.Identifier("[" + id.ValueText + "]")); } return(SyntaxFactory.Identifier(id.ValueText)); }
private void ReadIdentifierOrKeywordToken() { while (char.IsLetter(Current)) { position++; } int _length = position - start; string _text = text.ToString(start, _length); kind = SyntaxFacts.GetKeywordKind(_text); }
public static SyntaxToken Keyword(String keyword) { var kind = SyntaxFacts.GetKeywordKind(keyword); if (kind == SyntaxKind.None) { throw new ArgumentOutOfRangeException("keyword", "Value must be a recognized keyword."); } return(Keyword(kind)); }
public void SyntaxFacts_Keyword_GetKeywordKind_DetectsAllReservedKeywords_RegardlessOfCase() { foreach (var kind in SyntaxFacts.GetReservedKeywordKinds()) { var text = kind.GetText(); var textWithMixedCast = GetMixedCase(text); var keywordKind = SyntaxFacts.GetKeywordKind(textWithMixedCast); Assert.Equal(kind, keywordKind); } }
private void LexIdentifierOrKeyword() { while (Char.IsLetter(Current)) { position++; } var length = position - start; var source = text.ToString(start, length); kind = SyntaxFacts.GetKeywordKind(source); }
public virtual string Identifier([NotNull] string name, [CanBeNull] ICollection <string> scope = null) { Check.NotEmpty(name, nameof(name)); var builder = new StringBuilder(); var partStart = 0; for (var i = 0; i < name.Length; i++) { if (!SyntaxFacts.IsIdentifierPartCharacter(name[i])) { if (partStart != i) { builder.Append(name.Substring(partStart, i - partStart)); } partStart = i + 1; } } if (partStart != name.Length) { builder.Append(name.Substring(partStart)); } if (!SyntaxFacts.IsIdentifierStartCharacter(builder[0])) { builder.Insert(0, "_"); } var identifier = builder.ToString(); if (scope != null) { var uniqueIdentifier = identifier; var qualifier = 0; while (scope.Contains(uniqueIdentifier)) { uniqueIdentifier = identifier + qualifier++; } scope.Add(uniqueIdentifier); identifier = uniqueIdentifier; } if (SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None || SyntaxFacts.GetPreprocessorKeywordKind(identifier) != SyntaxKind.None || SyntaxFacts.GetContextualKeywordKind(identifier) != SyntaxKind.None) { return("@" + identifier); } return(identifier); }
public static SyntaxToken TryEscapeIdentifierToken( SyntaxToken syntaxToken, SyntaxNode parentOfToken ) { // do not escape an already escaped identifier if (syntaxToken.IsVerbatimIdentifier()) { return(syntaxToken); } if ( SyntaxFacts.GetKeywordKind(syntaxToken.ValueText) == SyntaxKind.None && SyntaxFacts.GetContextualKeywordKind(syntaxToken.ValueText) == SyntaxKind.None ) { return(syntaxToken); } if ( SyntaxFacts.GetContextualKeywordKind(syntaxToken.ValueText) == SyntaxKind.UnderscoreToken ) { return(syntaxToken); } var parent = parentOfToken.Parent; if (parentOfToken is SimpleNameSyntax && parent.Kind() == SyntaxKind.XmlNameAttribute) { // do not try to escape XML name attributes return(syntaxToken); } // do not escape global in a namespace qualified name if (parent.Kind() == SyntaxKind.AliasQualifiedName && syntaxToken.ValueText == "global") { return(syntaxToken); } // safe to escape identifier return(syntaxToken .CopyAnnotationsTo( SyntaxFactory.VerbatimIdentifier( syntaxToken.LeadingTrivia, syntaxToken.ToString(), syntaxToken.ValueText, syntaxToken.TrailingTrivia ) ) .WithAdditionalAnnotations(Simplifier.Annotation)); }