Пример #1
0
    public override void VisitVariableDeclaration(VariableDeclarationSyntax node)
    {
      // start with variable type
      if (node.Type.IsVar)
      {
        // no idea
        cb.AppendWithIndent("auto ");
      }
      else
      {
        var si = model.GetSymbolInfo(node.Type);
        ITypeSymbol ts = (ITypeSymbol) si.Symbol;
        cb.AppendWithIndent(ts.ToCppType()).Append(" ");
      }

      // now comes the name(s)
      for (int i = 0; i < node.Variables.Count; ++i)
      {
        var v = node.Variables[i];
        cb.Append(v.Identifier.Text);
        if (v.Initializer != null)
        {
          cb.Append(" = ");
          v.Initializer.Accept(this);
        }

        cb.AppendLine(i + 1 == node.Variables.Count ? ";" : ",");
      }
    }
Пример #2
0
        public static string VariableDeclaration(VariableDeclarationSyntax declaration)
        {
            var isConst = declaration.Parent is LocalDeclarationStatementSyntax
                          && ((LocalDeclarationStatementSyntax) declaration.Parent).IsConst;

            var output = isConst ? "let " :  "var ";

            foreach (var currVar in declaration.Variables)
            {
                output += currVar.Identifier.Text;

                if (!declaration.Type.IsVar)
                {
                    output += ": " + SyntaxNode(declaration.Type);
                }

                if (currVar.Initializer != null)
                {
                    output += " " + SyntaxNode(currVar.Initializer);
                }
                output += ", ";
            }

            return output.TrimEnd(',', ' ');
        }
        private bool IsReportable(VariableDeclarationSyntax variableDeclaration, SemanticModel semanticModel)
        {
            bool result;
            TypeSyntax variableTypeName = variableDeclaration.Type;
            if (variableTypeName.IsVar)
            {
                // Implicitly-typed variables cannot have multiple declarators. Short circuit if it does.
                bool hasMultipleVariables = variableDeclaration.Variables.Skip(1).Any();
                if(hasMultipleVariables == false)
                {
                    // Special case: Ensure that 'var' isn't actually an alias to another type. (e.g. using var = System.String).
                    IAliasSymbol aliasInfo = semanticModel.GetAliasInfo(variableTypeName);
                    if (aliasInfo == null)
                    {
                        // Retrieve the type inferred for var.
                        ITypeSymbol type = semanticModel.GetTypeInfo(variableTypeName).ConvertedType;

                        // Special case: Ensure that 'var' isn't actually a type named 'var'.
                        if (type.Name.Equals("var", StringComparison.Ordinal) == false)
                        {
                            // Special case: Ensure that the type is not an anonymous type.
                            if (type.IsAnonymousType == false)
                            {
                                // Special case: Ensure that it's not a 'new' expression.
                                if (variableDeclaration.Variables.First().Initializer.Value.IsKind(SyntaxKind.ObjectCreationExpression))
                                {
                                    result = false;
                                }
                                else
                                {
                                    result = true;
                                }
                            }
                            else
                            {
                                result = false;
                            }
                        }
                        else
                        {
                            result = false;
                        }
                    }
                    else
                    {
                        result = false;
                    }
                }
                else
                {
                    result = false;
                }
            }
            else
            {
                result = false;
            }

            return result;
        }
 /// <summary>
 /// Returns true if type information could be gleaned by simply looking at the given statement.
 /// This typically means that the type name occurs in right hand side of an assignment.
 /// </summary>
 private bool IsTypeApparentInDeclaration(VariableDeclarationSyntax variableDeclaration, SemanticModel semanticModel, TypeStylePreference stylePreferences, CancellationToken cancellationToken)
 {
     var initializer = variableDeclaration.Variables.Single().Initializer;
     var initializerExpression = GetInitializerExpression(initializer);
     var declaredTypeSymbol = semanticModel.GetTypeInfo(variableDeclaration.Type, cancellationToken).Type;
     return TypeStyleHelper.IsTypeApparentInAssignmentExpression(stylePreferences, initializerExpression, semanticModel,cancellationToken, declaredTypeSymbol);
 }
        public static void Go(OutputWriter writer, VariableDeclarationSyntax declaration)
        {
            foreach (var variable in declaration.Variables)
            {
                ISymbol symbol = TypeProcessor.GetDeclaredSymbol(variable);

                var isRef = false; //UsedAsRef(variable, symbol);

                writer.WriteIndent();
                // writer.Write("var ");

                //                if (isRef) //Not needed c++ can passby ref
                //                {
                //
                //                    var typeStr = TypeProcessor.ConvertType(declaration.Declaration.Type);
                //
                //                    var localSymbol = symbol as ILocalSymbol;
                //                    var ptr = localSymbol != null && !localSymbol.Type.IsValueType?"*" : "";
                //                                        writer.Write("gc::gc_ptr < " + typeStr+ ptr + " >");
                //                    writer.Write("" + typeStr + ptr + "");
                //
                //                    writer.Write(" ");
                //                    writer.Write(WriteIdentifierName.TransformIdentifier(variable.Identifier.Text));
                //                    
                //                    Program.RefOutSymbols.TryAdd(symbol, null);
                //
                //                    writer.Write(" = std::make_shared < ");
                //                    writer.Write(typeStr + ptr);
                //                    writer.Write(" >(");
                //
                //                    WriteInitializer(writer, declaration, variable);
                //
                //                    writer.Write(")");
                //                }
                //                else
                {
                    var lsymbol = symbol as ILocalSymbol;

                    if (lsymbol != null && lsymbol.Type.IsValueType == false)
                    {
                        writer.Write(" ");
// Ideally Escape analysis should take care of this, but for now all value types are on heap and ref types on stack
                    }

                    writer.Write(TypeProcessor.ConvertType(declaration.Type));

                    if (lsymbol != null && lsymbol.Type.IsValueType == false)
                        writer.Write(" ");

                    writer.Write(" ");
                    writer.Write(WriteIdentifierName.TransformIdentifier(variable.Identifier.Text));
                    writer.Write(" = ");

                    WriteInitializer(writer, declaration, variable);
                }

                writer.Write(";\r\n");
            }
        }
Пример #6
0
        public ArgumentSyntax WithDeclaration(VariableDeclarationSyntax declaration)
        {
            if (this.RefOrOutKeyword.Kind() != SyntaxKind.OutKeyword)
            {
                throw new InvalidOperationException();
            }

            return this.WithExpressionOrDeclaration(declaration);
        }
Пример #7
0
 public static glsl.VariableDeclarationSyntax Translate(this cs.VariableDeclarationSyntax node)
 {
     return(new glsl.VariableDeclarationSyntax()
     {
         Type = new glsl.TypeSyntax()
         {
             Name = model.GetSymbolInfo(node.Type).Symbol.Name
         },
         Variables = node.Variables.Select(v => v.Translate()).ToList()
     });
 }
Пример #8
0
 private async Task<Solution> RemoveHungarianPrefix(Document document, VariableDeclarationSyntax token, CancellationToken cancellationToken)
 {
     var identifierToken = token.Variables.First();
     var newName = DehungarianAnalyzer.SuggestDehungarianName(identifierToken.Identifier.Text);
     var semanticModel = await document.GetSemanticModelAsync(cancellationToken);
     var tokenSymbol = semanticModel.GetDeclaredSymbol(token.Variables.First(), cancellationToken);
     var originalSolution = document.Project.Solution;
     var optionSet = originalSolution.Workspace.Options;
     var newSolution = await Renamer.RenameSymbolAsync(document.Project.Solution, tokenSymbol, newName, optionSet, cancellationToken).ConfigureAwait(false);
     return newSolution;
 }
        static bool TryValidateLocalVariableType(LocalDeclarationStatementSyntax localDeclarationStatementSyntax, VariableDeclarationSyntax variableDeclarationSyntax)
        {
            //Either we don't have a local variable or we're using constant value
            if (localDeclarationStatementSyntax == null ||
                localDeclarationStatementSyntax.IsConst ||
                localDeclarationStatementSyntax.ChildNodes().OfType<VariableDeclarationSyntax>().Count() != 1)
                return false;

            //We don't want to raise a diagnostic if the local variable is already a var
            return !variableDeclarationSyntax.Type.IsVar;
        }
        private async Task<Document> ChangeToFunc(Document document, VariableDeclarationSyntax variableDeclaration, CancellationToken cancellationToken)
        {
            // Change the variable declaration
            var newDeclaration = variableDeclaration.WithType(SyntaxFactory.ParseTypeName("System.Func<System.Threading.Tasks.Task>").WithAdditionalAnnotations(Simplifier.Annotation, Formatter.Annotation)
                .WithLeadingTrivia(variableDeclaration.Type.GetLeadingTrivia()).WithTrailingTrivia(variableDeclaration.Type.GetTrailingTrivia()));

            var oldRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var newRoot = oldRoot.ReplaceNode(variableDeclaration, newDeclaration);
            var newDocument = document.WithSyntaxRoot(newRoot);

            // Return document with transformed tree.
            return newDocument;
        }
Пример #11
0
        private async Task<Document> MakeStaticDeclarationImplicit(Document document,
            VariableDeclarationSyntax variableDeclaration, CancellationToken
                cancellationToken)
        {
            var newVariableDeclaration = variableDeclaration.WithType(SyntaxFactory.IdentifierName("var"));

            newVariableDeclaration = newVariableDeclaration.WithAdditionalAnnotations(Formatter.Annotation);

            var oldRoot = await document.GetSyntaxRootAsync(cancellationToken);
            var newRoot = oldRoot.ReplaceNode(variableDeclaration, newVariableDeclaration);

            return document.WithSyntaxRoot(newRoot);

        }
        public VariableDeclarationTranslation(VariableDeclarationSyntax syntax, SyntaxTranslation parent) : base(syntax, parent)
        {
            Type = syntax.Type.Get<TypeTranslation>(this);
            Variables = syntax.Variables.Get<VariableDeclaratorSyntax, VariableDeclaratorTranslation>(this);
            if (!syntax.Type.IsVar)
            {
                Variables.GetEnumerable().First().FirstType = Type;
            }

            foreach (var item in Variables.GetEnumerable())
            {
                item.KnownType = Type;
            }
        }
        private async static Task<Document> UseVarAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var diagnosticSpan = diagnostic.Location.SourceSpan;
            var localDeclaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<LocalDeclarationStatementSyntax>().First();
            var variableDeclaration = localDeclaration.Declaration;
            var numVariables = variableDeclaration.Variables.Count;

            var newVariableDeclarations = new VariableDeclarationSyntax[numVariables];

            var varSyntax = SyntaxFactory.IdentifierName("var");

            //Create a new var declaration for each variable.
            for (var i = 0; i < numVariables; i++)
            {
                var originalVariable = variableDeclaration.Variables[i];
                var newLeadingTrivia = originalVariable.GetLeadingTrivia();

                //Get the trivia from the separator as well
                if (i != 0)
                {
                    newLeadingTrivia = newLeadingTrivia.InsertRange(0,
                        variableDeclaration.Variables.GetSeparator(i-1).GetAllTrivia());
                }

                newVariableDeclarations[i] = SyntaxFactory.VariableDeclaration(varSyntax)
                    .AddVariables(originalVariable.WithLeadingTrivia(newLeadingTrivia));
            }

            //ensure trivia for leading type node is preserved
            var originalTypeSyntax = variableDeclaration.Type;
            newVariableDeclarations[0] = newVariableDeclarations[0]
                .WithType((TypeSyntax) varSyntax.WithSameTriviaAs(originalTypeSyntax));

            var newLocalDeclarationStatements = newVariableDeclarations.Select(SyntaxFactory.LocalDeclarationStatement).ToList();


            //Preserve the trivia for the entire statement at the start and at the end
            newLocalDeclarationStatements[0] =
                newLocalDeclarationStatements[0].WithLeadingTrivia(variableDeclaration.GetLeadingTrivia());
            var lastIndex = numVariables -1;
            newLocalDeclarationStatements[lastIndex] =
                newLocalDeclarationStatements[lastIndex].WithTrailingTrivia(localDeclaration.GetTrailingTrivia());

            var newRoot = root.ReplaceNode(localDeclaration, newLocalDeclarationStatements);
            var newDocument = document.WithSyntaxRoot(newRoot);
            return newDocument;
        }
Пример #14
0
 /// <summary>Creates a new ForStatementSyntax instance.</summary>
 public static ForStatementSyntax ForStatement(SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, SeparatedSyntaxList<ExpressionSyntax> initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax condition, SyntaxToken secondSemicolonToken, SeparatedSyntaxList<ExpressionSyntax> incrementors, SyntaxToken closeParenToken, StatementSyntax statement)
 {
     return ForStatement(
         forKeyword: forKeyword,
         openParenToken: openParenToken,
         refKeyword: default(SyntaxToken),
         deconstruction: null,
         declaration: declaration,
         initializers: initializers,
         firstSemicolonToken: firstSemicolonToken,
         condition: condition,
         secondSemicolonToken: secondSemicolonToken,
         incrementors: incrementors,
         closeParenToken: closeParenToken,
         statement: statement);
 }
 private static void AnalyzeVariableDeclaration(OperationAnalysisContext context, IVariableDeclarationOperation variableDeclaration)
 {
     foreach (var declarator in variableDeclaration.Declarators)
     {
         if (IsInternal(context, declarator.Symbol.Type))
         {
             var syntax = context.Operation.Syntax switch
             {
                 CSharpSyntax.VariableDeclarationSyntax s => s.Type,
                  _ => context.Operation.Syntax
             };
             context.ReportDiagnostic(Diagnostic.Create(_descriptor, syntax.GetLocation(), declarator.Symbol.Type));
             return;
         }
     }
 }
Пример #16
0
 /// <summary>Creates a new ForStatementSyntax instance.</summary>
 public static ForStatementSyntax ForStatement(VariableDeclarationSyntax declaration, SeparatedSyntaxList<ExpressionSyntax> initializers, ExpressionSyntax condition, SeparatedSyntaxList<ExpressionSyntax> incrementors, StatementSyntax statement)
 {
     return ForStatement(
         SyntaxFactory.Token(SyntaxKind.ForKeyword),
         SyntaxFactory.Token(SyntaxKind.OpenParenToken),
         default(SyntaxToken),
         null,
         declaration,
         initializers,
         SyntaxFactory.Token(SyntaxKind.SemicolonToken),
         condition,
         SyntaxFactory.Token(SyntaxKind.SemicolonToken),
         incrementors,
         SyntaxFactory.Token(SyntaxKind.CloseParenToken),
         statement);
 }
Пример #17
0
        private void MakeLocalVariableList(VariableDeclarationSyntax syntax)
        {
            int count = 0;
            foreach (var v in syntax.Variables)
            {
                if (count == 0)
                {
                    _output.Write(v.Identifier, v.Identifier.ValueText);
                }
                else
                {
                    _output.TrivialWrite(", ");
                    _output.Write(v.Identifier, v.Identifier.ValueText);
                }

                if (v.Initializer != null)
                {
                    _output.TrivialWrite(" = ");
                    this.Visit(v.Initializer);
                }
                count++;
            }
        }
        public override void VisitVariableDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclarationSyntax node)
        {
            base.VisitVariableDeclaration(node);
            TColor color;

            if (node.Parent.IsKind(SyntaxKind.EventFieldDeclaration))
            {
                color = eventDeclarationColor;
            }
            else if (node.Parent.IsKind(SyntaxKind.FieldDeclaration))
            {
                color = fieldDeclarationColor;
            }
            else
            {
                color = variableDeclarationColor;
            }

            foreach (var declarations in node.Variables)
            {
                // var info = semanticModel.GetTypeInfo(declarations, cancellationToken);
                Colorize(declarations.Identifier, color);
            }
        }
        // doesn't include variables declared in declaration expressions
        private static void GetLocalNames(VariableDeclarationSyntax localDeclaration, ref List<SyntaxToken> result)
        {
            foreach (var local in localDeclaration.Variables)
            {
                if (result == null)
                {
                    result = new List<SyntaxToken>();
                }

                result.Add(local.Identifier);
            }
        }
        private static bool TryComputeLocalsDistance(VariableDeclarationSyntax leftOpt, VariableDeclarationSyntax rightOpt, out double distance)
        {
            List<SyntaxToken> leftLocals = null;
            List<SyntaxToken> rightLocals = null;

            if (leftOpt != null)
            {
                GetLocalNames(leftOpt, ref leftLocals);
            }

            if (rightOpt != null)
            {
                GetLocalNames(rightOpt, ref rightLocals);
            }

            if (leftLocals == null || rightLocals == null)
            {
                distance = 0;
                return false;
            }

            distance = ComputeDistance(leftLocals, rightLocals);
            return true;
        }
        private static double ComputeWeightedDistance(
            VariableDeclarationSyntax leftVariables,
            StatementSyntax leftStatement,
            VariableDeclarationSyntax rightVariables,
            StatementSyntax rightStatement)
        {
            double distance = ComputeDistance(leftStatement, rightStatement);

            // Put maximum weight behind the variables declared in the header of the statement.
            double localsDistance;
            if (TryComputeLocalsDistance(leftVariables, rightVariables, out localsDistance))
            {
                distance = distance * 0.4 + localsDistance * 0.6;
            }

            // If the statement is a block that declares local variables, 
            // weight them more than the rest of the statement.
            return AdjustForLocalsInBlock(distance, leftStatement, rightStatement, localsWeight: 0.2);
        }
Пример #22
0
        /// <summary>
        /// Given a variable declaration, figure out its type by looking at the declared symbol of the corresponding local.
        /// </summary>
        private SymbolInfo TypeFromLocal(VariableDeclarationSyntax variableDeclaration, CancellationToken cancellationToken)
        {
            TypeSymbol deconstructionType = (GetDeclaredSymbol(variableDeclaration.Variables.First(), cancellationToken) as LocalSymbol)?.Type;

            if (deconstructionType?.IsErrorType() == false)
            {
                return new SymbolInfo(deconstructionType);
            }

            return SymbolInfo.None;
        }
 public LocalDeclarationStatementSyntax Update(
     SyntaxTokenList modifiers,
     VariableDeclarationSyntax declaration,
     SyntaxToken semicolonToken
     ) => Update(AwaitKeyword, UsingKeyword, modifiers, declaration, semicolonToken);
Пример #24
0
        internal SeparatedSyntaxList <VariableDeclaratorSyntax> RemodelVariableDeclaration(CSS.VariableDeclarationSyntax declaration)
        {
            var visualBasicSyntaxNode = declaration.Type.Accept(_nodesVisitor);
            var type = (TypeSyntax)visualBasicSyntaxNode;
            var declaratorsWithoutInitializers = new List <Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclaratorSyntax>();
            var declarators = new List <VariableDeclaratorSyntax>();

            foreach (var v in declaration.Variables)
            {
                if (v.Initializer == null)
                {
                    declaratorsWithoutInitializers.Add(v);
                }
                else
                {
                    declarators.Add(
                        SyntaxFactory.VariableDeclarator(
                            SyntaxFactory.SingletonSeparatedList(ExtractIdentifier(v)),
                            declaration.Type.IsVar ? null : SyntaxFactory.SimpleAsClause(type),
                            SyntaxFactory.EqualsValue((ExpressionSyntax)ConvertTopLevelExpression(v.Initializer.Value))
                            )
                        );
                }
            }

            if (declaratorsWithoutInitializers.Count > 0)
            {
                declarators.Insert(0, SyntaxFactory.VariableDeclarator(SyntaxFactory.SeparatedList(declaratorsWithoutInitializers.Select(ExtractIdentifier)), SyntaxFactory.SimpleAsClause(type), null));
            }

            return(SyntaxFactory.SeparatedList(declarators));
        }
Пример #25
0
        internal BoundStatement BindForOrUsingOrFixedDeclarations(VariableDeclarationSyntax nodeOpt, LocalDeclarationKind localKind, DiagnosticBag diagnostics, out ImmutableArray<BoundLocalDeclaration> declarations)
        {
            if (nodeOpt == null)
            {
                declarations = ImmutableArray<BoundLocalDeclaration>.Empty;
                return null;
            }

            var typeSyntax = nodeOpt.Type;

            AliasSymbol alias;
            bool isVar;
            TypeSymbol declType = BindType(typeSyntax, diagnostics, out isVar, out alias);

            Debug.Assert((object)declType != null || isVar);

            var variables = nodeOpt.Variables;
            int count = variables.Count;
            Debug.Assert(count > 0);

            if (isVar && count > 1)
            {
                // There are a number of ways in which a var decl can be illegal, but in these 
                // cases we should report an error and then keep right on going with the inference.

                Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, nodeOpt);
            }

            var declarationArray = new BoundLocalDeclaration[count];

            for (int i = 0; i < count; i++)
            {
                var variableDeclarator = variables[i];
                var declaration = BindVariableDeclaration(localKind, isVar, variableDeclarator, typeSyntax, declType, alias, diagnostics);

                declarationArray[i] = declaration;
            }

            declarations = declarationArray.AsImmutableOrNull();

            return (count == 1) ?
                (BoundStatement)declarations[0] :
                new BoundMultipleLocalDeclarations(nodeOpt, declarations);
        }
Пример #26
0
        internal BoundLocalDeconstructionDeclaration BindDeconstructionDeclaration(CSharpSyntaxNode node, VariableDeclarationSyntax declaration, DiagnosticBag diagnostics)
        {
            Debug.Assert(node.Kind() == SyntaxKind.LocalDeclarationStatement || node.Kind() == SyntaxKind.VariableDeclaration);
            Debug.Assert(declaration.IsDeconstructionDeclaration);

            var value = declaration.Deconstruction.Value;
            return new BoundLocalDeconstructionDeclaration(node, BindDeconstructionDeclaration(node, declaration, value, diagnostics));
        }
Пример #27
0
        internal BoundDeconstructionAssignmentOperator BindDeconstructionDeclaration(CSharpSyntaxNode node, VariableDeclarationSyntax declaration, ExpressionSyntax right, DiagnosticBag diagnostics, BoundDeconstructValuePlaceholder rightPlaceholder = null)
        {
            ArrayBuilder<DeconstructionVariable> locals = BindDeconstructionDeclarationLocals(declaration, declaration.Type, diagnostics);

            var result = BindDeconstructionAssignment(node, right, locals, diagnostics, isDeclaration: true, rhsPlaceholder: rightPlaceholder);
            FreeDeconstructionVariables(locals);

            return result;
        }
Пример #28
0
 public UsingStatementSyntax Update(SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement)
 {
     return(Update(awaitKeyword: default, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement));
Пример #29
0
 public override void VisitVariableDeclaration(VariableDeclarationSyntax node)
 {
     base.VisitVariableDeclaration(node);
 }
Пример #30
0
 public FixedStatementSyntax Update(SyntaxToken fixedKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, SyntaxToken closeParenToken, StatementSyntax statement)
 => Update(attributeLists: default, fixedKeyword, openParenToken, declaration, closeParenToken, statement);
        /// <summary>
        /// build the summary text for the supplied member.
        /// </summary>
        /// <param name="variableDeclaratorSyntax">the variable declarator syntax.</param>
        /// <param name="returnType">the return type for the member variable.</param>
        /// <returns>a string containing the text.</returns>
        public string BuildSummaryTextForMemberVariable(VariableDeclaratorSyntax variableDeclaratorSyntax, VariableDeclarationSyntax returnType)
        {
            if (variableDeclaratorSyntax == null)
                throw new ArgumentNullException(nameof(variableDeclaratorSyntax));
            if (returnType == null)
                throw new ArgumentNullException(nameof(returnType));

            var id = returnType.Type.GetIdentifierName();
            var word = variableDeclaratorSyntax.Identifier.Text.Length > (id ?? string.Empty).Length
                ? variableDeclaratorSyntax.Identifier.Text
                : id;
            var words = this.SplitCamelCaseWords(word);
            var text = $"the {string.Join(" ", this.RemoveInvalidPrefix(this.RemoveNonPrintables(words)))}.";
            return text;
        }
            private void ClassifyUpdate(VariableDeclarationSyntax oldNode, VariableDeclarationSyntax newNode)
            {
                if (!SyntaxFactory.AreEquivalent(oldNode.Type, newNode.Type))
                {
                    ReportError(RudeEditKind.TypeUpdate);
                    return;
                }

                // separators may be added/removed:
            }
Пример #33
0
        /// <summary>
        /// Prepares locals corresponding to the variables of the declaration.
        /// The locals are kept in a tree which captures the nesting of variables.
        /// Each local is either a simple local (when its type is known) or a deconstruction local pending inference.
        /// The caller is responsible for releasing the nested ArrayBuilders.
        /// </summary>
        private ArrayBuilder<DeconstructionVariable> BindDeconstructionDeclarationLocals(VariableDeclarationSyntax node, TypeSyntax closestTypeSyntax, DiagnosticBag diagnostics)
        {
            Debug.Assert(node.IsDeconstructionDeclaration);
            SeparatedSyntaxList<VariableDeclarationSyntax> variables = node.Deconstruction.Variables;

            // There are four cases for VariableDeclaration:
            // - type and declarators are set, but deconstruction is null. This could represent `int x`, which is a single variable.
            // - type is null, declarators are set, but deconstruction is null. This could represent `x`, which is a single variable.
            // - type is set to 'var', declarators are null, and deconstruction is set. This could represent `var (...)`
            // - type and declarators are null, but deconstruction is set. This could represent `(int x, ...)`

            var localsBuilder = ArrayBuilder<DeconstructionVariable>.GetInstance(variables.Count);
            foreach (var variable in variables)
            {
                TypeSyntax typeSyntax = variable.Type ?? closestTypeSyntax;

                DeconstructionVariable local;
                if (variable.IsDeconstructionDeclaration)
                {
                    local = new DeconstructionVariable(BindDeconstructionDeclarationLocals(variable, typeSyntax, diagnostics), node.Deconstruction);
                }
                else
                {
                    local = new DeconstructionVariable(BindDeconstructionDeclarationLocal(variable, typeSyntax, diagnostics));
                }

                localsBuilder.Add(local);
            }

            return localsBuilder;
        }
        private bool ShouldAnalyzeVariableDeclaration(VariableDeclarationSyntax variableDeclaration, SemanticModel semanticModel, CancellationToken cancellationToken)
        {
            // implict type is applicable only for local variables and
            // such declarations cannot have multiple declarators and
            // must have an initializer.
            var isSupportedParentKind = variableDeclaration.IsParentKind(
                    SyntaxKind.LocalDeclarationStatement,
                    SyntaxKind.ForStatement,
                    SyntaxKind.UsingStatement);

            return isSupportedParentKind &&
                   variableDeclaration.Variables.Count == 1 &&
                   variableDeclaration.Variables.Single().Initializer.IsKind(SyntaxKind.EqualsValueClause);
        }
Пример #35
0
 public LocalDeclarationStatementSyntax Update(SyntaxTokenList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken)
 => Update(default(SyntaxToken), default(SyntaxToken), modifiers, declaration, semicolonToken);
Пример #36
0
        /// <summary>
        /// Returns a BoundLocal when the type was explicit, otherwise returns a DeconstructionLocalPendingInference.
        /// </summary>
        private BoundExpression BindDeconstructionDeclarationLocal(VariableDeclarationSyntax node, TypeSyntax closestTypeSyntax, DiagnosticBag diagnostics)
        {
            Debug.Assert(!node.IsDeconstructionDeclaration);
            Debug.Assert(node.Variables.Count == 1);

            var declarator = node.Variables[0];

            var localSymbol = LocateDeclaredVariableSymbol(declarator, closestTypeSyntax);

            // Check for variable declaration errors.
            // Use the binder that owns the scope for the local because this (the current) binder
            // might own nested scope.
            bool hasErrors = localSymbol.Binder.ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics);

            bool isVar;
            bool isConst = false;
            AliasSymbol alias;
            TypeSymbol declType = BindVariableType(node, diagnostics, closestTypeSyntax, ref isConst, out isVar, out alias);

            if (!isVar)
            {
                if (node.Type == null)
                {
                    // An explicit type can only be provided next to the variable
                    Error(diagnostics, ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, node);
                }

                return new BoundLocal(declarator, localSymbol, constantValueOpt: null, type: declType, hasErrors: node.Type == null);
            }

            return new DeconstructionLocalPendingInference(declarator, localSymbol);
        }
 private void ClassifyFieldInsert(VariableDeclarationSyntax fieldVariable)
 {
     ClassifyFieldInsert((BaseFieldDeclarationSyntax)fieldVariable.Parent);
 }
Пример #38
0
 public ForStatementSyntax Update(SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, SeparatedSyntaxList <ExpressionSyntax> initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax condition, SyntaxToken secondSemicolonToken, SeparatedSyntaxList <ExpressionSyntax> incrementors, SyntaxToken closeParenToken, StatementSyntax statement)
 => Update(AttributeLists, forKeyword, openParenToken, declaration, initializers, firstSemicolonToken, condition, secondSemicolonToken, incrementors, closeParenToken, statement);
        private async Task<bool> SemanticsChangedAsync(
            Document document,
            VariableDeclarationSyntax declaration,
            ExpressionSyntax invocationOrCreation,
            TypeSyntax newType,
            IdentifierNameSyntax identifier,
            DeclarationExpressionSyntax declarationExpression,
            CancellationToken cancellationToken)
        {
            if (newType.IsVar)
            {
                // Options want us to use 'var' if we can.  Make sure we didn't change
                // the semantics of teh call by doing this.

                // Find the symbol that the existing invocation points to.
                var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
                var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
                var previousSymbol = semanticModel.GetSymbolInfo(invocationOrCreation).Symbol;

                var annotation = new SyntaxAnnotation();
                var updatedInvocationOrCreation = invocationOrCreation.ReplaceNode(
                    identifier, declarationExpression).WithAdditionalAnnotations(annotation);

                // Note(cyrusn): "https://github.com/dotnet/roslyn/issues/14384" prevents us from just
                // speculatively binding the new expression.  So, instead, we fork things and see if
                // the new symbol we bind to is equivalent to the previous one.
                var newDocument = document.WithSyntaxRoot(
                    root.ReplaceNode(invocationOrCreation, updatedInvocationOrCreation));

                var newRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
                var newSemanticModel = await newDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

                updatedInvocationOrCreation = (ExpressionSyntax)newRoot.GetAnnotatedNodes(annotation).Single();

                var updatedSymbol = newSemanticModel.GetSymbolInfo(updatedInvocationOrCreation).Symbol;

                if (!SymbolEquivalenceComparer.Instance.Equals(previousSymbol, updatedSymbol))
                {
                    // We're pointing at a new symbol now.  Semantic have changed.
                    return true;
                }
            }

            return false;
        }
        static SeparatedSyntaxList <VariableDeclaratorSyntax> RemodelVariableDeclaration(CSS.VariableDeclarationSyntax declaration, NodesVisitor nodesVisitor)
        {
            var type = (TypeSyntax)declaration.Type.Accept(nodesVisitor);
            var declaratorsWithoutInitializers = new List <CSS.VariableDeclaratorSyntax>();
            var declarators = new List <VariableDeclaratorSyntax>();

            foreach (var v in declaration.Variables)
            {
                if (v.Initializer == null)
                {
                    declaratorsWithoutInitializers.Add(v);
                    continue;
                }
                else
                {
                    declarators.Add(
                        SyntaxFactory.VariableDeclarator(
                            SyntaxFactory.SingletonSeparatedList(ExtractIdentifier(v)),
                            declaration.Type.IsVar ? null : SyntaxFactory.SimpleAsClause(type),
                            SyntaxFactory.EqualsValue((ExpressionSyntax)v.Initializer.Value.Accept(nodesVisitor))
                            )
                        );
                }
            }

            if (declaratorsWithoutInitializers.Count > 0)
            {
                declarators.Insert(0, SyntaxFactory.VariableDeclarator(SyntaxFactory.SeparatedList(declaratorsWithoutInitializers.Select(ExtractIdentifier)), SyntaxFactory.SimpleAsClause(type), null));
            }

            return(SyntaxFactory.SeparatedList(declarators));
        }