private void CheckModifiers(Location location, DiagnosticBag diagnostics) { const DeclarationModifiers partialMethodInvalidModifierMask = (DeclarationModifiers.AccessibilityMask & ~DeclarationModifiers.Private) | DeclarationModifiers.Virtual | DeclarationModifiers.Abstract | DeclarationModifiers.Override | DeclarationModifiers.New | DeclarationModifiers.Sealed | DeclarationModifiers.Extern; if (IsPartial && !ReturnsVoid) { diagnostics.Add(ErrorCode.ERR_PartialMethodMustReturnVoid, location); } else if (IsPartial && !ContainingType.IsInterface && (DeclarationModifiers & partialMethodInvalidModifierMask) != 0) { diagnostics.Add(ErrorCode.ERR_PartialMethodInvalidModifier, location); } else if (this.DeclaredAccessibility == Accessibility.Private && (IsVirtual || IsAbstract || IsOverride)) { diagnostics.Add(ErrorCode.ERR_VirtualPrivate, location, this); } else if (IsStatic && (IsOverride || IsVirtual || IsAbstract)) { // A static member '{0}' cannot be marked as override, virtual, or abstract diagnostics.Add(ErrorCode.ERR_StaticNotVirtual, location, this); } else if (IsOverride && (IsNew || IsVirtual)) { // A member '{0}' marked as override cannot be marked as new or virtual diagnostics.Add(ErrorCode.ERR_OverrideNotNew, location, this); } else if (IsSealed && !IsOverride) { // '{0}' cannot be sealed because it is not an override diagnostics.Add(ErrorCode.ERR_SealedNonOverride, location, this); } else if (IsSealed && ContainingType.TypeKind == TypeKind.Struct) { // The modifier '{0}' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.SealedKeyword)); } else if (!ContainingType.IsInterfaceType() && _lazyReturnType.IsStatic) { // '{0}': static types cannot be used as return types diagnostics.Add(ErrorCode.ERR_ReturnTypeIsStaticClass, location, _lazyReturnType); } else if (IsAbstract && IsExtern) { diagnostics.Add(ErrorCode.ERR_AbstractAndExtern, location, this); } else if (IsAbstract && IsSealed) { diagnostics.Add(ErrorCode.ERR_AbstractAndSealed, location, this); } else if (IsAbstract && IsVirtual) { diagnostics.Add(ErrorCode.ERR_AbstractNotVirtual, location, this.Kind.Localize(), this); } else if (IsAbstract && ContainingType.TypeKind == TypeKind.Struct) { // The modifier '{0}' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.AbstractKeyword)); } else if (IsVirtual && ContainingType.TypeKind == TypeKind.Struct) { // The modifier '{0}' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.VirtualKeyword)); } else if (IsAbstract && !ContainingType.IsAbstract && (ContainingType.TypeKind == TypeKind.Class || ContainingType.TypeKind == TypeKind.Submission)) { // '{0}' is abstract but it is contained in non-abstract class '{1}' diagnostics.Add(ErrorCode.ERR_AbstractInConcreteClass, location, this, ContainingType); } else if (IsVirtual && ContainingType.IsSealed) { // '{0}' is a new virtual member in sealed class '{1}' diagnostics.Add(ErrorCode.ERR_NewVirtualInSealed, location, this, ContainingType); } else if (bodySyntaxReferenceOpt == null && IsAsync) { diagnostics.Add(ErrorCode.ERR_BadAsyncLacksBody, location); } else if (bodySyntaxReferenceOpt == null && !IsExtern && !IsAbstract && !IsPartial && !IsExpressionBodied) { diagnostics.Add(ErrorCode.ERR_ConcreteMissingBody, location, this); } else if (ContainingType.IsSealed && this.DeclaredAccessibility.HasProtected() && !this.IsOverride) { diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), location, this); } else if (ContainingType.IsStatic && !IsStatic) { diagnostics.Add(ErrorCode.ERR_InstanceMemberInStaticClass, location, Name); } else if (_lazyIsVararg && (IsGenericMethod || ContainingType.IsGenericType || _lazyParameters.Length > 0 && _lazyParameters[_lazyParameters.Length - 1].IsParams)) { diagnostics.Add(ErrorCode.ERR_BadVarargs, location); } else if (_lazyIsVararg && IsAsync) { diagnostics.Add(ErrorCode.ERR_VarargsAsync, location); } }
protected override string GetOperatorText(SyntaxKind binaryExprKind) => binaryExprKind == SyntaxKind.LogicalAndExpression ? SyntaxFacts.GetText(SyntaxKind.AmpersandAmpersandToken) : SyntaxFacts.GetText(SyntaxKind.BarBarToken);
internal override bool ShouldIncludeAccessibilityModifier(SyntaxNode typeNode) { var typeDeclaration = typeNode as TypeDeclarationSyntax; return(typeDeclaration.Modifiers.Any(m => SyntaxFacts.IsAccessibilityModifier(m.Kind()))); }
protected override bool IsKeyword(SyntaxToken token) => SyntaxFacts.IsKeywordKind(token.Kind());
private BoundExpression BindPostfixUnaryExpression(PostfixUnaryExpressionSyntax node) { var operatorKind = SyntaxFacts.GetUnaryOperatorKind(node.Kind); return(BindUnaryExpression(node.OperatorToken, node.Operand, operatorKind)); }
protected override LineColumnRule GetLineColumnRuleBetween(SyntaxTrivia trivia1, LineColumnDelta existingWhitespaceBetween, bool implicitLineBreak, SyntaxTrivia trivia2) { if (IsStartOrEndOfFile(trivia1, trivia2)) { return(LineColumnRule.PreserveLinesWithAbsoluteIndentation(lines: 0, indentation: 0)); } // [trivia] [whitespace] [token] case if (trivia2.IsKind(SyntaxKind.None)) { var insertNewLine = this.FormattingRules.GetAdjustNewLinesOperation(this.Token1, this.Token2) != null; if (IsMultilineComment(trivia1)) { return(LineColumnRule.PreserveLinesWithGivenIndentation(lines: insertNewLine ? 1 : 0)); } if (insertNewLine) { return(LineColumnRule.PreserveLinesWithDefaultIndentation(lines: 0)); } if (existingWhitespaceBetween.Lines > 0 && existingWhitespaceBetween.Spaces != this.Spaces) { return(LineColumnRule.PreserveWithGivenSpaces(spaces: this.Spaces)); } return(LineColumnRule.Preserve); } // preprocessor case if (SyntaxFacts.IsPreprocessorDirective(trivia2.Kind())) { // Check for immovable preprocessor directives, which are bad directive trivia // without a preceding line break if (trivia2.IsKind(SyntaxKind.BadDirectiveTrivia) && existingWhitespaceBetween.Lines == 0 && !implicitLineBreak) { _succeeded = false; return(LineColumnRule.Preserve); } // if current line is the first line of the file, don't put extra line 1 var lines = (trivia1.IsKind(SyntaxKind.None) && this.Token1.IsKind(SyntaxKind.None)) ? 0 : 1; if (trivia2.IsKind(SyntaxKind.RegionDirectiveTrivia) || trivia2.IsKind(SyntaxKind.EndRegionDirectiveTrivia)) { return(LineColumnRule.PreserveLinesWithDefaultIndentation(lines)); } return(LineColumnRule.PreserveLinesWithAbsoluteIndentation(lines, indentation: 0)); } // comments case if (trivia2.IsRegularOrDocComment()) { // Start of new comments group. // // 1. Comment groups must contain the same kind of comments // 2. Every block comment is a group of its own if (!trivia1.IsKind(trivia2.Kind()) || trivia2.IsMultiLineComment() || trivia2.IsMultiLineDocComment() || existingWhitespaceBetween.Lines > 1) { if (this.FormattingRules.GetAdjustNewLinesOperation(this.Token1, this.Token2) != null) { return(LineColumnRule.PreserveLinesWithDefaultIndentation(lines: 0)); } return(LineColumnRule.PreserveLinesWithGivenIndentation(lines: 0)); } // comments after existing comment if (existingWhitespaceBetween.Lines == 0) { return(LineColumnRule.PreserveLinesWithGivenIndentation(lines: 0)); } return(LineColumnRule.PreserveLinesWithFollowingPrecedingIndentation); } if (trivia2.IsKind(SyntaxKind.SkippedTokensTrivia)) { // if there is any skipped tokens, it is not possible to format this trivia range. _succeeded = false; } return(LineColumnRule.Preserve); }
public Cursor MoveToFirstToken() { var cursor = this; if (!cursor.IsFinished) { for (var node = cursor.CurrentNodeOrToken; node.Kind() != SyntaxKind.None && !SyntaxFacts.IsAnyToken(node.Kind()); node = cursor.CurrentNodeOrToken) { cursor = cursor.MoveToFirstChild(); } } return(cursor); }
internal static DeclarationModifiers MakeModifiers( NamedTypeSymbol containingType, SyntaxToken firstIdentifier, SyntaxTokenList modifiers, BindingDiagnosticBag diagnostics, out bool modifierErrors ) { DeclarationModifiers defaultAccess = (containingType.IsInterface) ? DeclarationModifiers.Public : DeclarationModifiers.Private; DeclarationModifiers allowedModifiers = DeclarationModifiers.AccessibilityMask | DeclarationModifiers.Const | DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Volatile | DeclarationModifiers.Fixed | DeclarationModifiers.Unsafe | DeclarationModifiers.Abstract; // filtered out later var errorLocation = new SourceLocation(firstIdentifier); DeclarationModifiers result = ModifierUtils.MakeAndCheckNontypeMemberModifiers( modifiers, defaultAccess, allowedModifiers, errorLocation, diagnostics, out modifierErrors ); if ((result & DeclarationModifiers.Abstract) != 0) { diagnostics.Add(ErrorCode.ERR_AbstractField, errorLocation); result &= ~DeclarationModifiers.Abstract; } if ((result & DeclarationModifiers.Fixed) != 0) { if ((result & DeclarationModifiers.Static) != 0) { // The modifier 'static' is not valid for this item diagnostics.Add( ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.StaticKeyword) ); } if ((result & DeclarationModifiers.ReadOnly) != 0) { // The modifier 'readonly' is not valid for this item diagnostics.Add( ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.ReadOnlyKeyword) ); } if ((result & DeclarationModifiers.Const) != 0) { // The modifier 'const' is not valid for this item diagnostics.Add( ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.ConstKeyword) ); } if ((result & DeclarationModifiers.Volatile) != 0) { // The modifier 'volatile' is not valid for this item diagnostics.Add( ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.VolatileKeyword) ); } result &= ~( DeclarationModifiers.Static | DeclarationModifiers.ReadOnly | DeclarationModifiers.Const | DeclarationModifiers.Volatile ); Debug.Assert( ( result & ~( DeclarationModifiers.AccessibilityMask | DeclarationModifiers.Fixed | DeclarationModifiers.Unsafe | DeclarationModifiers.New ) ) == 0 ); } if ((result & DeclarationModifiers.Const) != 0) { if ((result & DeclarationModifiers.Static) != 0) { // The constant '{0}' cannot be marked static diagnostics.Add( ErrorCode.ERR_StaticConstant, errorLocation, firstIdentifier.ValueText ); } if ((result & DeclarationModifiers.ReadOnly) != 0) { // The modifier 'readonly' is not valid for this item diagnostics.Add( ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.ReadOnlyKeyword) ); } if ((result & DeclarationModifiers.Volatile) != 0) { // The modifier 'volatile' is not valid for this item diagnostics.Add( ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.VolatileKeyword) ); } if ((result & DeclarationModifiers.Unsafe) != 0) { // The modifier 'unsafe' is not valid for this item diagnostics.Add( ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.UnsafeKeyword) ); } result |= DeclarationModifiers.Static; // "constants are considered static members" } else { // NOTE: always cascading on a const, so suppress. // NOTE: we're being a bit sneaky here - we're using the containingType rather than this symbol // to determine whether or not unsafe is allowed. Since this symbol and the containing type are // in the same compilation, it won't make a difference. We do, however, have to pass the error // location explicitly. containingType.CheckUnsafeModifier(result, errorLocation, diagnostics); } return(result); }
private static SyntaxTokenList UpdateDeclarationAccessibility(SyntaxTokenList modifiersList, Accessibility newAccesibility, CodeGenerationOptions options) { var newModifierTokens = new List <SyntaxToken>(); AbstractCSharpCodeGenerator.AddAccessibilityModifiers(newAccesibility, newModifierTokens, options, Accessibility.NotApplicable); if (newModifierTokens.Count == 0) { return(modifiersList); } return(GetUpdatedDeclarationAccessibilityModifiers(newModifierTokens, modifiersList, (SyntaxToken modifier) => SyntaxFacts.IsAccessibilityModifier(modifier.CSharpKind())) .ToSyntaxTokenList()); }
protected static SymbolDisplayPart Punctuation(SyntaxKind kind) { return(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, SyntaxFacts.GetText(kind))); }
private Tuple <NamedTypeSymbol, ImmutableArray <NamedTypeSymbol> > MakeOneDeclaredBases(ConsList <TypeSymbol> newBasesBeingResolved, SingleTypeDeclaration decl, BindingDiagnosticBag diagnostics) { BaseListSyntax bases = GetBaseListOpt(decl); if (bases == null) { return(null); } NamedTypeSymbol localBase = null; var localInterfaces = ArrayBuilder <NamedTypeSymbol> .GetInstance(); var baseBinder = this.DeclaringCompilation.GetBinder(bases); // Wrap base binder in a location-specific binder that will avoid generic constraint checks // (to avoid cycles if the constraint types are not bound yet). Instead, constraint checks // are handled by the caller. baseBinder = baseBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this); int i = -1; foreach (var baseTypeSyntax in bases.Types) { i++; var typeSyntax = baseTypeSyntax.Type; if (typeSyntax.Kind() != SyntaxKind.PredefinedType && !SyntaxFacts.IsName(typeSyntax.Kind())) { diagnostics.Add(ErrorCode.ERR_BadBaseType, typeSyntax.GetLocation()); } var location = new SourceLocation(typeSyntax); TypeSymbol baseType; if (i == 0 && TypeKind == TypeKind.Class) // allow class in the first position { baseType = baseBinder.BindType(typeSyntax, diagnostics, newBasesBeingResolved).Type; SpecialType baseSpecialType = baseType.SpecialType; if (IsRestrictedBaseType(baseSpecialType)) { // check for one of the specific exceptions required for compiling mscorlib if (this.SpecialType == SpecialType.System_Enum && baseSpecialType == SpecialType.System_ValueType || this.SpecialType == SpecialType.System_MulticastDelegate && baseSpecialType == SpecialType.System_Delegate) { // allowed } else if (baseSpecialType == SpecialType.System_Array && this.ContainingAssembly.CorLibrary == this.ContainingAssembly) { // Specific exception for System.ArrayContracts, which is only built when CONTRACTS_FULL is defined. // (See InheritanceResolver::CheckForBaseClassErrors). } else { // '{0}' cannot derive from special class '{1}' diagnostics.Add(ErrorCode.ERR_DeriveFromEnumOrValueType, location, this, baseType); continue; } } if (baseType.IsSealed && !this.IsStatic) // Give precedence to ERR_StaticDerivedFromNonObject { diagnostics.Add(ErrorCode.ERR_CantDeriveFromSealedType, location, this, baseType); continue; } bool baseTypeIsErrorWithoutInterfaceGuess = false; // If baseType is an error symbol and our best guess is that the desired symbol // is an interface, then put baseType in the interfaces list, rather than the // base type slot, to avoid the frustrating scenario where an error message // indicates that the symbol being returned as the base type was elsewhere // interpreted as an interface. if (baseType.TypeKind == TypeKind.Error) { baseTypeIsErrorWithoutInterfaceGuess = true; TypeKind guessTypeKind = baseType.GetNonErrorTypeKindGuess(); if (guessTypeKind == TypeKind.Interface) { //base type is an error *with* a guessed interface baseTypeIsErrorWithoutInterfaceGuess = false; } } if ((baseType.TypeKind == TypeKind.Class || baseType.TypeKind == TypeKind.Delegate || baseType.TypeKind == TypeKind.Struct || baseTypeIsErrorWithoutInterfaceGuess) && ((object)localBase == null)) { localBase = (NamedTypeSymbol)baseType; Debug.Assert((object)localBase != null); if (this.IsStatic && localBase.SpecialType != SpecialType.System_Object) { // Static class '{0}' cannot derive from type '{1}'. Static classes must derive from object. var info = diagnostics.Add(ErrorCode.ERR_StaticDerivedFromNonObject, location, this, localBase); localBase = new ExtendedErrorTypeSymbol(localBase, LookupResultKind.NotReferencable, info); } checkPrimaryConstructorBaseType(baseTypeSyntax, localBase); continue; } } else { baseType = baseBinder.BindType(typeSyntax, diagnostics, newBasesBeingResolved).Type; } if (i == 0) { checkPrimaryConstructorBaseType(baseTypeSyntax, baseType); } switch (baseType.TypeKind) { case TypeKind.Interface: foreach (var t in localInterfaces) { if (t.Equals(baseType, TypeCompareKind.ConsiderEverything)) { diagnostics.Add(ErrorCode.ERR_DuplicateInterfaceInBaseList, location, baseType); } else if (t.Equals(baseType, TypeCompareKind.ObliviousNullableModifierMatchesAny)) { // duplicates with ?/! differences are reported later, we report local differences between oblivious and ?/! here diagnostics.Add(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, location, baseType, this); } } if (this.IsStatic) { // '{0}': static classes cannot implement interfaces diagnostics.Add(ErrorCode.ERR_StaticClassInterfaceImpl, location, this, baseType); } if (this.IsRefLikeType) { // '{0}': ref structs cannot implement interfaces diagnostics.Add(ErrorCode.ERR_RefStructInterfaceImpl, location, this, baseType); } if (baseType.ContainsDynamic()) { diagnostics.Add(ErrorCode.ERR_DeriveFromConstructedDynamic, location, this, baseType); } localInterfaces.Add((NamedTypeSymbol)baseType); continue; case TypeKind.Class: if (TypeKind == TypeKind.Class) { if ((object)localBase == null) { localBase = (NamedTypeSymbol)baseType; diagnostics.Add(ErrorCode.ERR_BaseClassMustBeFirst, location, baseType); continue; } else { diagnostics.Add(ErrorCode.ERR_NoMultipleInheritance, location, this, localBase, baseType); continue; } } goto default; case TypeKind.TypeParameter: diagnostics.Add(ErrorCode.ERR_DerivingFromATyVar, location, baseType); continue; case TypeKind.Error: // put the error type in the interface list so we don't lose track of it localInterfaces.Add((NamedTypeSymbol)baseType); continue; case TypeKind.Dynamic: diagnostics.Add(ErrorCode.ERR_DeriveFromDynamic, location, this); continue; case TypeKind.Submission: throw ExceptionUtilities.UnexpectedValue(baseType.TypeKind); default: diagnostics.Add(ErrorCode.ERR_NonInterfaceInInterfaceList, location, baseType); continue; } } if (this.SpecialType == SpecialType.System_Object && ((object)localBase != null || localInterfaces.Count != 0)) { var name = GetName(bases.Parent); diagnostics.Add(ErrorCode.ERR_ObjectCantHaveBases, new SourceLocation(name)); } return(new Tuple <NamedTypeSymbol, ImmutableArray <NamedTypeSymbol> >(localBase, localInterfaces.ToImmutableAndFree())); void checkPrimaryConstructorBaseType(BaseTypeSyntax baseTypeSyntax, TypeSymbol baseType) { if (baseTypeSyntax is PrimaryConstructorBaseTypeSyntax primaryConstructorBaseType && (!IsRecord || TypeKind != TypeKind.Class || baseType.TypeKind == TypeKind.Interface || ((RecordDeclarationSyntax)decl.SyntaxReference.GetSyntax()).ParameterList is null)) { diagnostics.Add(ErrorCode.ERR_UnexpectedArgumentList, primaryConstructorBaseType.ArgumentList.Location); } } }
protected static SymbolDisplayPart Keyword(SyntaxKind kind) { return(new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, SyntaxFacts.GetText(kind))); }
public void AnalyzeNode(SyntaxNodeAnalysisContext context) { var node = context.Node; if (node.IsKind(SyntaxKind.IfStatement)) { var ifStatement = (IfStatementSyntax)node; if (AnalyzeIfStatement(ifStatement)) { context.ReportDiagnostic(Diagnostic.Create(s_descriptor, ifStatement.IfKeyword.GetLocation(), SyntaxFacts.GetText(SyntaxKind.IfKeyword))); } } if (node.IsKind(SyntaxKind.ElseClause)) { var elseClause = (ElseClauseSyntax)node; if (AnalyzeElseClause(elseClause)) { context.ReportDiagnostic(Diagnostic.Create(s_descriptor, elseClause.ElseKeyword.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ElseKeyword))); } } if (node.IsKind(SyntaxKind.ForStatement)) { var forStatement = (ForStatementSyntax)node; if (AnalyzeForStatement(forStatement)) { context.ReportDiagnostic(Diagnostic.Create(s_descriptor, forStatement.ForKeyword.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ForKeyword))); } } if (node.IsKind(SyntaxKind.ForEachStatement) || node.IsKind(SyntaxKind.ForEachComponentStatement)) { var forEachStatement = (CommonForEachStatementSyntax)node; if (AnalyzeForEachStatement(forEachStatement)) { context.ReportDiagnostic(Diagnostic.Create(s_descriptor, forEachStatement.ForEachKeyword.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ForEachKeyword))); } } if (node.IsKind(SyntaxKind.WhileStatement)) { var whileStatement = (WhileStatementSyntax)node; if (AnalyzeWhileStatement(whileStatement)) { context.ReportDiagnostic(Diagnostic.Create(s_descriptor, whileStatement.WhileKeyword.GetLocation(), SyntaxFacts.GetText(SyntaxKind.WhileKeyword))); } } if (node.IsKind(SyntaxKind.DoStatement)) { var doStatement = (DoStatementSyntax)node; if (AnalyzeDoStatement(doStatement)) { context.ReportDiagnostic(Diagnostic.Create(s_descriptor, doStatement.DoKeyword.GetLocation(), SyntaxFacts.GetText(SyntaxKind.DoKeyword))); } } if (node.IsKind(SyntaxKind.UsingStatement)) { var usingStatement = (UsingStatementSyntax)context.Node; if (AnalyzeUsingStatement(usingStatement)) { context.ReportDiagnostic(Diagnostic.Create(s_descriptor, usingStatement.UsingKeyword.GetLocation(), SyntaxFacts.GetText(SyntaxKind.UsingKeyword))); } } if (node.IsKind(SyntaxKind.LockStatement)) { var lockStatement = (LockStatementSyntax)context.Node; if (AnalyzeLockStatement(lockStatement)) { context.ReportDiagnostic(Diagnostic.Create(s_descriptor, lockStatement.LockKeyword.GetLocation(), SyntaxFacts.GetText(SyntaxKind.LockKeyword))); } } }
protected static void VerifyModelForDeclarationField( SemanticModel model, SingleVariableDesignationSyntax designation, bool duplicate, params IdentifierNameSyntax[] references) { var symbol = model.GetDeclaredSymbol(designation); Assert.Equal(designation.Identifier.ValueText, symbol.Name); Assert.Equal(SymbolKind.Field, symbol.Kind); Assert.Equal(designation, symbol.DeclaringSyntaxReferences.Single().GetSyntax()); Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)designation)); var symbols = model.LookupSymbols(designation.SpanStart, name: designation.Identifier.ValueText); var names = model.LookupNames(designation.SpanStart); if (duplicate) { Assert.True(symbols.Count() > 1); Assert.Contains(symbol, symbols); } else { Assert.Same(symbol, symbols.Single()); } Assert.Contains(designation.Identifier.ValueText, names); var local = (IFieldSymbol)symbol; switch (designation.Parent) { case DeclarationPatternSyntax decl: var typeSyntax = decl.Type; Assert.True(SyntaxFacts.IsInNamespaceOrTypeContext(typeSyntax)); Assert.True(SyntaxFacts.IsInTypeOnlyContext(typeSyntax)); var type = local.Type; if (typeSyntax.IsVar && type.IsErrorType()) { Assert.Null(model.GetSymbolInfo(typeSyntax).Symbol); } else { Assert.Equal(type, model.GetSymbolInfo(typeSyntax).Symbol); } AssertTypeInfo(model, decl.Type, type); break; case var parent: Assert.True(parent is VarPatternSyntax); break; } var declarator = designation.Ancestors().OfType <VariableDeclaratorSyntax>().FirstOrDefault(); var inFieldDeclaratorArgumentlist = declarator != null && declarator.Parent.Parent.Kind() != SyntaxKind.LocalDeclarationStatement && (declarator.ArgumentList?.Contains(designation)).GetValueOrDefault(); // this is a declaration site, not a use site. Assert.Null(model.GetSymbolInfo(designation).Symbol); Assert.Null(model.GetSymbolInfo(designation).Symbol); foreach (var reference in references) { var referenceInfo = model.GetSymbolInfo(reference); symbols = model.LookupSymbols(reference.SpanStart, name: designation.Identifier.ValueText); if (duplicate) { Assert.Null(referenceInfo.Symbol); Assert.Contains(symbol, referenceInfo.CandidateSymbols); Assert.True(symbols.Count() > 1); Assert.Contains(symbol, symbols); } else { Assert.Same(symbol, referenceInfo.Symbol); Assert.Same(symbol, symbols.Single()); Assert.Equal(local.Type, model.GetTypeInfo(reference).Type); } Assert.True(model.LookupNames(reference.SpanStart).Contains(designation.Identifier.ValueText)); } if (!inFieldDeclaratorArgumentlist) { var dataFlowParent = designation.FirstAncestorOrSelf <ExpressionSyntax>(); if (model.IsSpeculativeSemanticModel) { Assert.Throws <NotSupportedException>(() => model.AnalyzeDataFlow(dataFlowParent)); } else { var dataFlow = model.AnalyzeDataFlow(dataFlowParent); if (dataFlow.Succeeded) { Assert.False(dataFlow.VariablesDeclared.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.AlwaysAssigned.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.WrittenInside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.DataFlowsIn.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.ReadInside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.DataFlowsOut.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.ReadOutside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.WrittenOutside.Contains(symbol, ReferenceEqualityComparer.Instance)); } } } }
protected override bool IsWhitespace(char ch) { return(SyntaxFacts.IsWhitespace(ch)); }
private static string ConvertSingleModifierToSyntaxText(DeclarationModifiers modifier) { switch (modifier) { case DeclarationModifiers.Abstract: return(SyntaxFacts.GetText(SyntaxKind.AbstractKeyword)); case DeclarationModifiers.Sealed: return(SyntaxFacts.GetText(SyntaxKind.SealedKeyword)); case DeclarationModifiers.Static: return(SyntaxFacts.GetText(SyntaxKind.StaticKeyword)); case DeclarationModifiers.New: return(SyntaxFacts.GetText(SyntaxKind.NewKeyword)); case DeclarationModifiers.Public: return(SyntaxFacts.GetText(SyntaxKind.PublicKeyword)); case DeclarationModifiers.Protected: return(SyntaxFacts.GetText(SyntaxKind.ProtectedKeyword)); case DeclarationModifiers.Internal: return(SyntaxFacts.GetText(SyntaxKind.InternalKeyword)); case DeclarationModifiers.ProtectedInternal: return(SyntaxFacts.GetText(SyntaxKind.ProtectedKeyword) + " " + SyntaxFacts.GetText(SyntaxKind.InternalKeyword)); case DeclarationModifiers.Private: return(SyntaxFacts.GetText(SyntaxKind.PrivateKeyword)); case DeclarationModifiers.PrivateProtected: return(SyntaxFacts.GetText(SyntaxKind.PrivateKeyword) + " " + SyntaxFacts.GetText(SyntaxKind.ProtectedKeyword)); case DeclarationModifiers.ReadOnly: return(SyntaxFacts.GetText(SyntaxKind.ReadOnlyKeyword)); case DeclarationModifiers.Const: return(SyntaxFacts.GetText(SyntaxKind.ConstKeyword)); case DeclarationModifiers.Volatile: return(SyntaxFacts.GetText(SyntaxKind.VolatileKeyword)); case DeclarationModifiers.Extern: return(SyntaxFacts.GetText(SyntaxKind.ExternKeyword)); case DeclarationModifiers.Partial: return(SyntaxFacts.GetText(SyntaxKind.PartialKeyword)); case DeclarationModifiers.Unsafe: return(SyntaxFacts.GetText(SyntaxKind.UnsafeKeyword)); case DeclarationModifiers.Fixed: return(SyntaxFacts.GetText(SyntaxKind.FixedKeyword)); case DeclarationModifiers.Virtual: return(SyntaxFacts.GetText(SyntaxKind.VirtualKeyword)); case DeclarationModifiers.Override: return(SyntaxFacts.GetText(SyntaxKind.OverrideKeyword)); case DeclarationModifiers.Async: return(SyntaxFacts.GetText(SyntaxKind.AsyncKeyword)); case DeclarationModifiers.Ref: return(SyntaxFacts.GetText(SyntaxKind.RefKeyword)); default: throw ExceptionUtilities.UnexpectedValue(modifier); } }
protected override bool IsNewLine(char ch) { return(SyntaxFacts.IsNewLine(ch)); }
public static bool IsWordCharacter(char ch) { return(SyntaxFacts.IsIdentifierStartCharacter(ch) || SyntaxFacts.IsIdentifierPartCharacter(ch)); }
protected override bool IsInNamespaceOrTypeContext(ExpressionSyntax node) { return(SyntaxFacts.IsInNamespaceOrTypeContext(node)); }
private void AnalyzeLockSymbol(SyntaxNodeAnalysisContext context) { var lockStatement = (LockStatementSyntax)context.Node; if (!lockStatement.Statement.IsKind(SyntaxKind.Block) && !lockStatement.Statement.IsKind(SyntaxKind.LockStatement)) { context.ReportDiagnostic(Diagnostic.Create(Rule, lockStatement.LockKeyword.GetLocation(), "A", SyntaxFacts.GetText(SyntaxKind.LockKeyword))); } }
protected async override Task <IEnumerable <CompletionData> > GetItemsWorkerAsync(CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken) { var semanticModel = ctx.SemanticModel; var result = new List <CompletionData> (); if (info.TriggerCharacter == ' ') { var newExpression = ObjectCreationContextHandler.GetObjectCreationNewExpression(ctx.SyntaxTree, completionContext.Position, cancellationToken); if (newExpression == null && info.CompletionTriggerReason == CompletionTriggerReason.CharTyped && !ctx.LeftToken.IsKind(SyntaxKind.EqualsToken) && !ctx.LeftToken.IsKind(SyntaxKind.EqualsEqualsToken)) { return(Enumerable.Empty <CompletionData> ()); } completionResult.AutoCompleteEmptyMatch = false; } var parent = ctx.TargetToken.Parent; bool isInAttribute = ctx.CSharpSyntaxContext.IsAttributeNameContext; bool isInBaseList = parent != null && parent.IsKind(SyntaxKind.BaseList); bool isInUsingDirective = parent != null && parent.Parent != null && parent.Parent.IsKind(SyntaxKind.UsingDirective) && !parent.IsKind(SyntaxKind.QualifiedName); var isInQuery = ctx.CSharpSyntaxContext.IsInQuery; var completionDataLookup = new Dictionary <Tuple <string, SymbolKind>, ISymbolCompletionData> (); bool isInCatchTypeExpression = parent != null && parent.IsKind(SyntaxKind.CatchDeclaration) || parent.IsKind(SyntaxKind.QualifiedName) && parent.Parent != null && parent.Parent.IsKind(SyntaxKind.CatchDeclaration); Action <ISymbolCompletionData> addData = d => { var key = Tuple.Create(d.DisplayText, d.Symbol.Kind); ISymbolCompletionData data; if (completionDataLookup.TryGetValue(key, out data)) { data.AddOverload(d); return; } completionDataLookup.Add(key, d); result.Add(d); }; var completionCategoryLookup = new Dictionary <string, CompletionCategory> (); foreach (var symbol in Recommender.GetRecommendedSymbolsAtPosition(semanticModel, completionContext.Position, engine.Workspace, null, cancellationToken)) { if (symbol.Kind == SymbolKind.NamedType) { if (isInAttribute) { var type = (ITypeSymbol)symbol; if (type.IsAttribute()) { var v = type.Name.Substring(0, type.Name.Length - "Attribute".Length); var needsEscaping = SyntaxFacts.GetKeywordKind(v) != SyntaxKind.None; needsEscaping = needsEscaping || (isInQuery && SyntaxFacts.IsQueryContextualKeyword(SyntaxFacts.GetContextualKeywordKind(v))); if (!needsEscaping) { addData(engine.Factory.CreateSymbolCompletionData(this, symbol, v)); continue; } } } if (isInBaseList) { var type = (ITypeSymbol)symbol; if (type.IsSealed || type.IsStatic) { continue; } } if (isInCatchTypeExpression) { var type = (ITypeSymbol)symbol; if (!IsException(type)) { continue; } } } if (isInUsingDirective && symbol.Kind != SymbolKind.Namespace) { continue; } var newData = engine.Factory.CreateSymbolCompletionData(this, symbol, symbol.Name.EscapeIdentifier(isInQuery)); var categorySymbol = (ISymbol)symbol.ContainingType ?? symbol.ContainingNamespace; if (categorySymbol != null) { CompletionCategory category; var key = categorySymbol.ToDisplayString(); if (!completionCategoryLookup.TryGetValue(key, out category)) { completionCategoryLookup [key] = category = engine.Factory.CreateCompletionDataCategory(categorySymbol); } newData.CompletionCategory = category; } addData(newData); } return(result); }
private void AnalyzeElseSymbol(SyntaxNodeAnalysisContext context) { var elseClause = (ElseClauseSyntax)context.Node; if (!elseClause.Statement.IsKind(SyntaxKind.Block) && !elseClause.Statement.IsKind(SyntaxKind.IfStatement)) { context.ReportDiagnostic(Diagnostic.Create(Rule, elseClause.ElseKeyword.GetLocation(), "An", SyntaxFacts.GetText(SyntaxKind.ElseKeyword))); } }
public LocalFunctionSymbol( Binder binder, Symbol containingSymbol, LocalFunctionStatementSyntax syntax) : base(syntax.GetReference()) { _containingSymbol = containingSymbol; _declarationDiagnostics = new DiagnosticBag(); _declarationModifiers = DeclarationModifiers.Private | syntax.Modifiers.ToDeclarationModifiers(diagnostics: _declarationDiagnostics); if (SyntaxFacts.HasYieldOperations(syntax.Body)) { _lazyIteratorElementType = TypeWithAnnotations.Boxed.Sentinel; } this.CheckUnsafeModifier(_declarationModifiers, _declarationDiagnostics); ScopeBinder = binder; binder = binder.WithUnsafeRegionIfNecessary(syntax.Modifiers); if (syntax.TypeParameterList != null) { binder = new WithMethodTypeParametersBinder(this, binder); _typeParameters = MakeTypeParameters(_declarationDiagnostics); } else { _typeParameters = ImmutableArray <SourceMethodTypeParameterSymbol> .Empty; ReportErrorIfHasConstraints(syntax.ConstraintClauses, _declarationDiagnostics); } if (IsExtensionMethod) { _declarationDiagnostics.Add(ErrorCode.ERR_BadExtensionAgg, Locations[0]); } foreach (var param in syntax.ParameterList.Parameters) { ReportAttributesDisallowed(param.AttributeLists, _declarationDiagnostics); } if (syntax.ReturnType.Kind() == SyntaxKind.RefType) { var returnType = (RefTypeSyntax)syntax.ReturnType; if (returnType.ReadOnlyKeyword.Kind() == SyntaxKind.ReadOnlyKeyword) { _refKind = RefKind.RefReadOnly; } else { _refKind = RefKind.Ref; } } else { _refKind = RefKind.None; } _binder = binder; }
private void AnalyzeForEachSymbol(SyntaxNodeAnalysisContext context) { var forEachStatement = (ForEachStatementSyntax)context.Node; if (!forEachStatement.Statement.IsKind(SyntaxKind.Block)) { context.ReportDiagnostic(Diagnostic.Create(Rule, forEachStatement.ForEachKeyword.GetLocation(), "A", SyntaxFacts.GetText(SyntaxKind.ForEachKeyword))); } }
protected override bool IsContextualKeyword(SyntaxToken token) { return(SyntaxFacts.IsContextualKeyword(token.Kind())); }
private void AnalyzeDoSymbol(SyntaxNodeAnalysisContext context) { var doStatement = (DoStatementSyntax)context.Node; if (!doStatement.Statement.IsKind(SyntaxKind.Block)) { context.ReportDiagnostic(Diagnostic.Create(Rule, doStatement.DoKeyword.GetLocation(), "A", SyntaxFacts.GetText(SyntaxKind.DoKeyword))); } }
private SourceConstructorSymbol( SourceMemberContainerTypeSymbol containingType, Location location, ConstructorDeclarationSyntax syntax, MethodKind methodKind, DiagnosticBag diagnostics) : base(containingType, syntax.GetReference(), ImmutableArray.Create(location), isIterator: SyntaxFacts.HasYieldOperations(syntax.Body)) { bool hasBlockBody = syntax.Body != null; _isExpressionBodied = !hasBlockBody && syntax.ExpressionBody != null; bool hasBody = hasBlockBody || _isExpressionBodied; bool modifierErrors; var declarationModifiers = this.MakeModifiers(syntax.Modifiers, methodKind, hasBody, location, diagnostics, out modifierErrors); this.MakeFlags(methodKind, declarationModifiers, returnsVoid: true, isExtensionMethod: false); if (syntax.Identifier.ValueText != containingType.Name) { // This is probably a method declaration with the type missing. diagnostics.Add(ErrorCode.ERR_MemberNeedsType, location); } if (IsExtern) { if (methodKind == MethodKind.Constructor && syntax.Initializer != null) { diagnostics.Add(ErrorCode.ERR_ExternHasConstructorInitializer, location, this); } if (hasBody) { diagnostics.Add(ErrorCode.ERR_ExternHasBody, location, this); } } if (methodKind == MethodKind.StaticConstructor) { CheckFeatureAvailabilityAndRuntimeSupport(syntax, location, hasBody, diagnostics); } var info = ModifierUtils.CheckAccessibility(this.DeclarationModifiers, this, isExplicitInterfaceImplementation: false); if (info != null) { diagnostics.Add(info, location); } if (!modifierErrors) { this.CheckModifiers(methodKind, hasBody, location, diagnostics); } CheckForBlockAndExpressionBody( syntax.Body, syntax.ExpressionBody, syntax, diagnostics); }
private static void CheckParameterModifiers( ParameterSyntax parameter, DiagnosticBag diagnostics) { var seenThis = false; var seenRef = false; var seenOut = false; var seenParams = false; var seenIn = false; foreach (var modifier in parameter.Modifiers) { switch (modifier.Kind()) { case SyntaxKind.ThisKeyword: if (seenThis) { diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ThisKeyword)); } else if (seenOut) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ThisKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else if (seenParams) { diagnostics.Add(ErrorCode.ERR_BadParamModThis, modifier.GetLocation()); } else { seenThis = true; } break; case SyntaxKind.RefKeyword: if (seenRef) { diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword)); } else if (seenParams) { diagnostics.Add(ErrorCode.ERR_ParamsCantBeWithModifier, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword)); } else if (seenOut) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else if (seenIn) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword), SyntaxFacts.GetText(SyntaxKind.InKeyword)); } else { seenRef = true; } break; case SyntaxKind.OutKeyword: if (seenOut) { diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else if (seenThis) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword), SyntaxFacts.GetText(SyntaxKind.ThisKeyword)); } else if (seenParams) { diagnostics.Add(ErrorCode.ERR_ParamsCantBeWithModifier, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else if (seenRef) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword), SyntaxFacts.GetText(SyntaxKind.RefKeyword)); } else if (seenIn) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword), SyntaxFacts.GetText(SyntaxKind.InKeyword)); } else { seenOut = true; } break; case SyntaxKind.ParamsKeyword: if (seenParams) { diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword)); } else if (seenThis) { diagnostics.Add(ErrorCode.ERR_BadParamModThis, modifier.GetLocation()); } else if (seenRef) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword), SyntaxFacts.GetText(SyntaxKind.RefKeyword)); } else if (seenIn) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword), SyntaxFacts.GetText(SyntaxKind.InKeyword)); } else if (seenOut) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else { seenParams = true; } break; case SyntaxKind.InKeyword: if (seenIn) { diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword)); } else if (seenOut) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else if (seenRef) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword), SyntaxFacts.GetText(SyntaxKind.RefKeyword)); } else if (seenParams) { diagnostics.Add(ErrorCode.ERR_ParamsCantBeWithModifier, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword)); } else { seenIn = true; } break; default: throw ExceptionUtilities.UnexpectedValue(modifier.Kind()); } } }
public static bool IsValidIdentifier(string identifier) { return(SyntaxFacts.IsValidIdentifier(identifier)); }
void AddXmlDocCommands() { AddCommand(MyToolBar, KnownImageIds.MarkupTag, "Tag XML Doc with <c>", ctx => { WrapWith(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) => { ctx.KeepToolBar(true); string t = null; foreach (var item in view.Selection.SelectedSpans) { t = item.GetText(); var d = _Context.GetNode(item.Start, false, false).GetAncestorOrSelfDeclaration(); if (d != null) { if (((d as BaseMethodDeclarationSyntax)?.ParameterList ?? (d as DelegateDeclarationSyntax)?.ParameterList) ?.Parameters.Any(p => p.Identifier.Text == t) == true) { edit.Replace(item, "<paramref name=\"" + t + "\"/>"); continue; } if (d.FindTypeParameter(t) != null) { edit.Replace(item, "<typeparamref name=\"" + t + "\"/>"); continue; } } edit.Replace(item, (SyntaxFacts.GetKeywordKind(t) != SyntaxKind.None ? "<see langword=\"" : "<see cref=\"") + t + "\"/>"); } if (t != null && Keyboard.Modifiers == ModifierKeys.Control && FindNext(ctx, t) == false) { ctx.HideToolBar(); } }); }); AddCommand(MyToolBar, KnownImageIds.ParagraphHardReturn, "Tag XML Doc with <para>", ctx => { WrapWith(ctx, "<para>", "</para>", false); }); AddCommand(MyToolBar, KnownImageIds.Bold, "Tag XML Doc with HTML <b>", ctx => { WrapWith(ctx, "<b>", "</b>", true); }); AddCommand(MyToolBar, KnownImageIds.Italic, "Tag XML Doc with HTML <i>", ctx => { WrapWith(ctx, "<i>", "</i>", true); }); AddCommand(MyToolBar, KnownImageIds.Underline, "Tag XML Doc with HTML <u>", ctx => { WrapWith(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"); }); }