void WriteTypeDeclarationName(ITypeDefinition typeDef, TokenWriter writer, AlFormattingOptions formattingPolicy)
        {
            TypeSystemAstBuilder astBuilder = CreateAstBuilder();
            EntityDeclaration    node       = astBuilder.ConvertEntity(typeDef);

            if (typeDef.DeclaringTypeDefinition != null)
            {
                WriteTypeDeclarationName(typeDef.DeclaringTypeDefinition, writer, formattingPolicy);
                writer.WriteToken(Roles.Dot, ".");
            }
            else if ((ConversionFlags & ConversionFlags.UseFullyQualifiedEntityNames) == ConversionFlags.UseFullyQualifiedEntityNames)
            {
                if (!string.IsNullOrEmpty(typeDef.Namespace))
                {
                    WriteQualifiedName(typeDef.Namespace, writer, formattingPolicy);
                    writer.WriteToken(Roles.Dot, ".");
                }
            }
            writer.WriteIdentifier(node.NameToken);
            if ((ConversionFlags & ConversionFlags.ShowTypeParameterList) == ConversionFlags.ShowTypeParameterList)
            {
                var outputVisitor = new AlOutputVisitor(writer, formattingPolicy);
                outputVisitor.WriteTypeParameters(node.GetChildrenByRole(Roles.TypeParameter));
            }
        }
        void WriteQualifiedName(string name, TokenWriter writer, AlFormattingOptions formattingPolicy)
        {
            var node          = AstType.Create(name);
            var outputVisitor = new AlOutputVisitor(writer, formattingPolicy);

            node.AcceptVisitor(outputVisitor);
        }
Пример #3
0
        public static IReadOnlyDictionary <AstNode, ISegment> WriteNode(StringWriter writer, AstNode node, AlFormattingOptions policy, ITextEditorOptions editorOptions)
        {
            var formatter = new SegmentTrackingOutputFormatter(writer);

            formatter.IndentationString = editorOptions.IndentationString;
            var visitor = new AlOutputVisitor(formatter, policy);

            node.AcceptVisitor(visitor);
            return(formatter.Segments);
        }
Пример #4
0
 public override void WriteIdentifier(Identifier identifier)
 {
     WriteIndentation();
     if (identifier.IsVerbatim || AlOutputVisitor.IsKeyword(identifier.Name, identifier))
     {
         textWriter.Write('@');
         column++;
     }
     textWriter.Write(identifier.Name);
     column         += identifier.Name.Length;
     isAtStartOfLine = false;
 }
Пример #5
0
 public override void WriteIdentifier(Identifier identifier)
 {
     if (identifier.IsVerbatim || AlOutputVisitor.IsKeyword(identifier.Name, identifier))
     {
         if (lastWritten == LastWritten.KeywordOrIdentifier)
         {
             // this space is not strictly required, so we call Space()
             Space();
         }
     }
     else if (lastWritten == LastWritten.KeywordOrIdentifier)
     {
         // this space is strictly required, so we directly call the formatter
         base.Space();
     }
     base.WriteIdentifier(identifier);
     lastWritten = LastWritten.KeywordOrIdentifier;
 }
        void WriteMemberDeclarationName(IMember member, TokenWriter writer, AlFormattingOptions formattingPolicy)
        {
            TypeSystemAstBuilder astBuilder = CreateAstBuilder();
            EntityDeclaration    node       = astBuilder.ConvertEntity(member);

            if ((ConversionFlags & ConversionFlags.ShowDeclaringType) == ConversionFlags.ShowDeclaringType)
            {
                ConvertType(member.DeclaringType, writer, formattingPolicy);
                writer.WriteToken(Roles.Dot, ".");
            }
            switch (member.SymbolKind)
            {
            case SymbolKind.Indexer:
                writer.WriteKeyword(Roles.Identifier, "self");
                break;

            case SymbolKind.Constructor:
                WriteQualifiedName(member.DeclaringType.Name, writer, formattingPolicy);
                break;

            case SymbolKind.Destructor:
                writer.WriteToken(DestructorDeclaration.TildeRole, "~");
                WriteQualifiedName(member.DeclaringType.Name, writer, formattingPolicy);
                break;

            case SymbolKind.Operator:
                switch (member.Name)
                {
                case "op_Implicit":
                    writer.WriteKeyword(OperatorDeclaration.ImplicitRole, "implicit");
                    writer.Space();
                    writer.WriteKeyword(OperatorDeclaration.OperatorKeywordRole, "operator");
                    writer.Space();
                    ConvertType(member.ReturnType, writer, formattingPolicy);
                    break;

                case "op_Explicit":
                    writer.WriteKeyword(OperatorDeclaration.ExplicitRole, "explicit");
                    writer.Space();
                    writer.WriteKeyword(OperatorDeclaration.OperatorKeywordRole, "operator");
                    writer.Space();
                    ConvertType(member.ReturnType, writer, formattingPolicy);
                    break;

                default:
                    writer.WriteKeyword(OperatorDeclaration.OperatorKeywordRole, "operator");
                    writer.Space();
                    var operatorType = OperatorDeclaration.GetOperatorType(member.Name);
                    if (operatorType.HasValue)
                    {
                        writer.WriteToken(OperatorDeclaration.GetRole(operatorType.Value), OperatorDeclaration.GetToken(operatorType.Value));
                    }
                    else
                    {
                        writer.WriteIdentifier(node.NameToken);
                    }
                    break;
                }
                break;

            default:
                writer.WriteIdentifier(Identifier.Create(member.Name));
                break;
            }
            if ((ConversionFlags & ConversionFlags.ShowTypeParameterList) == ConversionFlags.ShowTypeParameterList && member.SymbolKind == SymbolKind.Method)
            {
                var outputVisitor = new AlOutputVisitor(writer, formattingPolicy);
                outputVisitor.WriteTypeParameters(node.GetChildrenByRole(Roles.TypeParameter));
            }
        }
 /// <inheritdoc />
 public string Encode(string text)
 {
     return(AlOutputVisitor.ConvertString(text));
 }
        protected override string GenerateCode(ITypeDefinition currentClass)
        {
            List <PropertyOrFieldWrapper> filtered = parameterList
                                                     .Where(p => p.IsIncluded)
                                                     .OrderBy(p => p.Index)
                                                     .ToList();

            var test = refactoringContext.GetNode();
            var insertedConstructor = refactoringContext.GetNode().PrevSibling as ConstructorDeclaration;

            if (insertedConstructor == null)
            {
                // We are not inside of a constructor declaration
                return(null);
            }

            using (Script script = refactoringContext.StartScript()) {
                BlockStatement originalCtorBody = insertedConstructor.Body;

                foreach (PropertyOrFieldWrapper w in filtered)
                {
                    if (w.AddCheckForNull)
                    {
                        // true = reference, null = generic or unknown
                        if (w.Type.IsReferenceType != false)
                        {
                            script.AddTo(originalCtorBody,
                                         new IfElseStatement(
                                             new BinaryOperatorExpression(new IdentifierExpression(w.ParameterName), BinaryOperatorType.Equality, new PrimitiveExpression(null)),
                                             new ThrowStatement(new ObjectCreateExpression(new SimpleType("ArgumentNullException"), new List <Expression>()
                            {
                                new PrimitiveExpression(w.ParameterName, '"' + w.ParameterName + '"')
                            }))
                                             )
                                         );
                        }
                        else
                        {
                            script.AddTo(originalCtorBody,
                                         new IfElseStatement(
                                             new UnaryOperatorExpression(UnaryOperatorType.Not, new MemberReferenceExpression(new IdentifierExpression(w.MemberName), "HasValue")),
                                             new ThrowStatement(new ObjectCreateExpression(new SimpleType("ArgumentNullException"), new List <Expression>()
                            {
                                new PrimitiveExpression(w.ParameterName, '"' + w.ParameterName + '"')
                            }))
                                             )
                                         );
                        }
                    }
                    if (w.AddRangeCheck)
                    {
                        script.AddTo(originalCtorBody,
                                     new IfElseStatement(
                                         new BinaryOperatorExpression(
                                             new BinaryOperatorExpression(new IdentifierExpression(w.ParameterName), BinaryOperatorType.LessThan, new IdentifierExpression("lower")),
                                             BinaryOperatorType.ConditionalOr,
                                             new BinaryOperatorExpression(new IdentifierExpression(w.ParameterName), BinaryOperatorType.GreaterThan, new IdentifierExpression("upper"))
                                             ),
                                         new ThrowStatement(
                                             new ObjectCreateExpression(
                                                 new SimpleType("ArgumentOutOfRangeException"),
                                                 new List <Expression>()
                        {
                            new PrimitiveExpression(w.ParameterName, '"' + w.ParameterName + '"'), new IdentifierExpression(w.ParameterName), new BinaryOperatorExpression(new PrimitiveExpression("Value must be between "), BinaryOperatorType.Add, new BinaryOperatorExpression(new IdentifierExpression("lower"), BinaryOperatorType.Add, new BinaryOperatorExpression(new PrimitiveExpression(" and "), BinaryOperatorType.Add, new IdentifierExpression("upper"))))
                        }
                                                 )
                                             )
                                         )
                                     );
                    }
                }

                foreach (PropertyOrFieldWrapper w in filtered)
                {
                    script.AddTo(originalCtorBody,
                                 new ExpressionStatement(new AssignmentExpression(new MemberReferenceExpression(new ThisReferenceExpression(), w.MemberName), AssignmentOperatorType.Assign, new IdentifierExpression(w.ParameterName)))
                                 );
                }
            }

            AnchorElement parameterListElement = insertionContext.ActiveElements
                                                 .OfType <AnchorElement>()
                                                 .FirstOrDefault(item => item.Name.Equals("parameterList", StringComparison.OrdinalIgnoreCase));

            if (parameterListElement != null)
            {
                StringBuilder pList = new StringBuilder();

                var parameters = filtered
                                 .Select(p => new ParameterDeclaration(refactoringContext.CreateShortType(p.Type), p.ParameterName))
                                 .ToList();

                using (StringWriter textWriter = new StringWriter(pList)) {
                    // Output parameter list as string
                    var             formattingOptions = AlFormattingPolicies.Instance.GetProjectOptions(refactoringContext.Compilation.GetProject());
                    AlOutputVisitor outputVisitor     = new AlOutputVisitor(textWriter, formattingOptions.OptionsContainer.GetEffectiveOptions());
                    for (int i = 0; i < parameters.Count; i++)
                    {
                        if (i > 0)
                        {
                            textWriter.Write(",");
                        }
                        outputVisitor.VisitParameterDeclaration(parameters[i]);
                    }
                }

                parameterListElement.Text = pList.ToString();
            }

            return(null);
        }
Пример #9
0
        public override async void Execute(EditorRefactoringContext context)
        {
            SyntaxTree st = await context.GetSyntaxTreeAsync().ConfigureAwait(false);

            ICompilation compilation = await context.GetCompilationAsync().ConfigureAwait(false);

            AlFullParseInformation info = await context.GetParseInformationAsync().ConfigureAwait(false) as AlFullParseInformation;

            EntityDeclaration node     = (EntityDeclaration)st.GetNodeAt(context.CaretLocation, n => n is TypeDeclaration || n is DelegateDeclaration);
            IDocument         document = context.Editor.Document;

            FileName newFileName = FileName.Create(Path.Combine(Path.GetDirectoryName(context.FileName), MakeValidFileName(node.Name)));
            string   header      = CopyFileHeader(document, info);
            string   footer      = CopyFileEnd(document, info);

            AstNode newNode = node.Clone();

            foreach (var ns in node.Ancestors.OfType <NamespaceDeclaration>())
            {
                var newNS = new NamespaceDeclaration(ns.Name);
                newNS.Members.AddRange(ns.Children.Where(ch => ch is UsingDeclaration ||
                                                         ch is UsingAliasDeclaration ||
                                                         ch is ExternAliasDeclaration).Select(usingDecl => usingDecl.Clone()));
                newNS.AddMember(newNode);
                newNode = newNS;
            }

            var topLevelUsings = st.Children.Where(ch => ch is UsingDeclaration ||
                                                   ch is UsingAliasDeclaration ||
                                                   ch is ExternAliasDeclaration);
            StringBuilder   newCode           = new StringBuilder(header);
            var             formattingOptions = AlFormattingPolicies.Instance.GetProjectOptions(compilation.GetProject());
            AlOutputVisitor visitor           = new AlOutputVisitor(new StringWriter(newCode), formattingOptions.OptionsContainer.GetEffectiveOptions());

            foreach (var topLevelUsing in topLevelUsings)
            {
                topLevelUsing.AcceptVisitor(visitor);
            }

            newNode.AcceptVisitor(visitor);

            newCode.AppendLine(footer);

            IViewContent viewContent = FileService.NewFile(newFileName, newCode.ToString());

            viewContent.PrimaryFile.SaveToDisk(newFileName);
            // now that the code is saved in the other file, remove it from the original document
            RemoveExtractedNode(context, node);

            IProject project = (IProject)compilation.GetProject();

            if (project != null)
            {
                FileProjectItem projectItem = new FileProjectItem(project, ItemType.Compile);
                projectItem.FileName = newFileName;
                ProjectService.AddProjectItem(project, projectItem);
                FileService.FireFileCreated(newFileName, false);
                project.Save();
                ProjectBrowserPad.RefreshViewAsync();
            }
        }