string TypeToString(ConvertTypeOptions options, ITypeDefOrRef type, IHasCustomAttribute typeAttributes = null)
        {
            AstType astType = AstBuilder.ConvertType(null, null, type, typeAttributes, options);

            StringWriter w = new StringWriter();

            if (type.TryGetByRefSig() != null)
            {
                ParamDef pd = typeAttributes as ParamDef;
                if (pd != null && (!pd.IsIn && pd.IsOut))
                {
                    w.Write("out ");
                }
                else
                {
                    w.Write("ref ");
                }

                if (astType is ComposedType && ((ComposedType)astType).PointerRank > 0)
                {
                    ((ComposedType)astType).PointerRank--;
                }
            }

            astType.AcceptVisitor(new CSharpOutputVisitor(w, FormattingOptionsFactory.CreateAllman()));
            return(w.ToString());
        }
Esempio n. 2
0
 public OmniSharpConfiguration()
 {
     PathReplacements        = new List <PathReplacement>();
     IgnoredCodeIssues       = new List <string>();
     TextEditorOptions       = new TextEditorOptions();
     CSharpFormattingOptions = FormattingOptionsFactory.CreateAllman();
 }
Esempio n. 3
0
        /// <summary>
        /// Build the script
        /// </summary>
        private void BuildScript()
        {
            this.explorerPresenter.CommandHistory.ModelChanged -= new CommandHistory.ModelChangedDelegate(this.CommandHistory_ModelChanged);

            try
            {
                // format the code first.
                string code = this.managerView.Editor.Text;
                code = new CSharpFormatter(FormattingOptionsFactory.CreateAllman()).Format(code);

                // set the code property manually first so that compile error can be trapped via
                // an exception.
                this.manager.Code = code;

                // If it gets this far then compiles ok.
                this.explorerPresenter.CommandHistory.Add(new Commands.ChangeProperty(this.manager, "Code", code));

                this.explorerPresenter.MainPresenter.ShowMessage("Manager script compiled successfully", DataStore.ErrorLevel.Information);
            }
            catch (Models.Core.ApsimXException err)
            {
                string msg = err.Message;
                if (err.InnerException != null)
                {
                    this.explorerPresenter.MainPresenter.ShowMessage(string.Format("[{0}]: {1}", err.model.Name, err.InnerException.Message), DataStore.ErrorLevel.Error);
                }
                else
                {
                    this.explorerPresenter.MainPresenter.ShowMessage(string.Format("[{0}]: {1}", err.model.Name, err.Message), DataStore.ErrorLevel.Error);
                }
            }
            this.explorerPresenter.CommandHistory.ModelChanged += new CommandHistory.ModelChangedDelegate(this.CommandHistory_ModelChanged);
        }
Esempio n. 4
0
        private static CSharpFormattingOptions CreateOptionSet(FormattingOptionSet defaultOptionSet)
        {
            switch (defaultOptionSet)
            {
            case FormattingOptionSet.Orcomp:
                return(CreateOrcompOptions());

            case FormattingOptionSet.KRStyle:
                return(FormattingOptionsFactory.CreateKRStyle());

            case FormattingOptionSet.Mono:
                return(FormattingOptionsFactory.CreateMono());

            case FormattingOptionSet.SharpDevelop:
                return(FormattingOptionsFactory.CreateSharpDevelop());

            case FormattingOptionSet.VisualStudio:
                return(FormattingOptionsFactory.CreateAllman());

            case FormattingOptionSet.GNU:
                return(FormattingOptionsFactory.CreateGNU());

            case FormattingOptionSet.Whitesmiths:
                return(FormattingOptionsFactory.CreateWhitesmiths());

            default:
                return(FormattingOptionsFactory.CreateAllman());
            }
        }
Esempio n. 5
0
        public void TestBug18254()
        {
            var policy = FormattingOptionsFactory.CreateAllman();

            Test(policy,
                 @"class Test
{
	void Foo()
	{
		UIView.Animate(duration, () =>
{
    view.Alpha = 0;
}, null);

	}
}",
                 @"class Test
{
	void Foo()
	{
		UIView.Animate(duration, () =>
			{
				view.Alpha = 0;
			}, null);

	}
}");
        }
Esempio n. 6
0
        private static string FormatInternal(string code)
        {
            var cSharpParser = new CSharpParser();
            var expr         = cSharpParser.ParseExpression(code);

            if (cSharpParser.HasErrors)
            {
                throw new ArgumentException(string.Join(Environment.NewLine, cSharpParser.Errors.Select(e => e.ErrorType + " " + e.Message + " " + e.Region)));
            }

            // Wrap expression in parenthesized expression, this is necessary because the transformations
            // can't replace the root node of the syntax tree
            expr = new ParenthesizedExpression(expr);
            // Apply transformations
            new IntroduceQueryExpressions().Run(expr);
            new CombineQueryExpressions().Run(expr);
            new IntroduceParenthesisForNestedQueries().Run(expr);

            new RemoveQueryContinuation().Run(expr);

            // Unwrap expression
            expr = ((ParenthesizedExpression)expr).Expression;

            var format = expr.GetText(FormattingOptionsFactory.CreateAllman());

            if (format.Substring(0, 3) == "\r\n\t")
            {
                format = format.Remove(0, 3);
            }
            format = format.Replace("\r\n\t", "\n");
            return(format);
        }
Esempio n. 7
0
        private static CSharpFormattingOptions CreateFormattingOptions()
        {
            var options = FormattingOptionsFactory.CreateAllman();

            options.IndentationString = "    ";
            return(options);
        }
Esempio n. 8
0
        public static string FormatCodeWithNRefactory(string code, ref int pos)
        {
            //https://github.com/icsharpcode/NRefactory/blob/master/ICSharpCode.NRefactory.CSharp/Formatter/FormattingOptionsFactory.cs

            //it is all great though:
            // all empty lines are lost
            // Fluent calls are destroyed
            // cannot handle classless: if any parsing error happens the generation result is completely unpredictable (the cone can be even lost)
            // Does not allow mixed brace styles despite BraceStyle.DoNotCHange
            // Hard to trace 'pos'
            //
            var option = FormattingOptionsFactory.CreateAllman();

            option.BlankLinesAfterUsings = 2;
            //BraceStyle.NextLine
            //option.SpaceWithinMethodCallParentheses = true;
            //option.BlankLinesBeforeFirstDeclaration = 0;
            //option.BlankLinesBetweenTypes = 1;
            //option.BlankLinesBetweenFields = 0;
            //option.BlankLinesBetweenEventFields = 0;
            //option.BlankLinesBetweenMembers = 1;
            //option.BlankLinesInsideRegion = 1;
            //option.InterfaceBraceStyle = BraceStyle.NextLineShifted;

            var syntaxTree = new CSharpParser().Parse(code, "test.cs");

            return(syntaxTree.GetText(option));
        }
Esempio n. 9
0
        string TypeToString(ConvertTypeOptions options, TypeReference type, ICustomAttributeProvider typeAttributes = null)
        {
            AstType astType = AstBuilder.ConvertType(type, typeAttributes, options);

            StringWriter w = new StringWriter();

            if (type.IsByReference)
            {
                ParameterDefinition pd = typeAttributes as ParameterDefinition;
                if (pd != null && (!pd.IsIn && pd.IsOut))
                {
                    w.Write("out ");
                }
                else
                {
                    w.Write("ref ");
                }

                if (astType is ComposedType && ((ComposedType)astType).PointerRank > 0)
                {
                    ((ComposedType)astType).PointerRank--;
                }
            }

            astType.AcceptVisitor(new CSharpOutputVisitor(w, FormattingOptionsFactory.CreateAllman()));
            return(w.ToString());
        }
Esempio n. 10
0
        public static void FormattCSharpCode(string inputPath, string outputPath)
        {
            string code = File.ReadAllText(inputPath, Encoding.UTF8);

            code = new CSharpFormatter(FormattingOptionsFactory.CreateAllman()).Format(code);

            File.WriteAllText(outputPath, code, Encoding.UTF8);
        }
Esempio n. 11
0
        private void OnDoReformat(object sender, EventArgs e)
        {
            CSharpFormatter formatter = new CSharpFormatter(FormattingOptionsFactory.CreateAllman());
            string          newText   = formatter.Format(this.managerView.Editor.Text);

            this.managerView.Editor.Text = newText;
            this.explorerPresenter.CommandHistory.Add(new Commands.ChangeProperty(this.manager, "Code", newText));
        }
Esempio n. 12
0
        public static CSharpFormattingOptions CreateOrcompOptions()
        {
            var options = FormattingOptionsFactory.CreateAllman();

            // TODO: Implement intended differences here like:
            // For the values are in effect in the incoming parameter, please refer to the AllmanFormattingOptions.txt in the doc
            // options.WhileNewLinePlacement = NewLinePlacement.NewLine;
            return(options);
        }
Esempio n. 13
0
        public void GenerateCode(AstNode node, ITextOutput output)
        {
            var outputFormatter = new TextOutputFormatter(output)
            {
                FoldBraces = true
            };
            var formattingPolicy = FormattingOptionsFactory.CreateAllman();

            node.AcceptVisitor(new CppOutputVisitor(outputFormatter, formattingPolicy));
        }
Esempio n. 14
0
        public void TestBrackets_If_AllmanOpenBrace()
        {
            var indent = Helper.CreateEngine(@"
class Foo {
	void Test ()
	{
		if (true)
		{$"        , FormattingOptionsFactory.CreateAllman());

            Assert.AreEqual("\t\t", indent.ThisLineIndent);
            Assert.AreEqual("\t\t\t", indent.NextLineIndent);
        }
 public static CSharpMethodBodyStatistics GetBodyStatistics(this MethodDeclaration declaration)
 {
     using (var writer = new StringWriter()) {
         var visitor = new CSharpOutputVisitor(writer, FormattingOptionsFactory.CreateAllman());
         declaration.AcceptVisitor(visitor);
         var bodyAsString = writer.ToString();
         return(new CSharpMethodBodyStatistics(
                    bodyAsString.Split(new[] { Environment.NewLine }, StringSplitOptions.None).Length,
                    bodyAsString.Length,
                    bodyAsString.GetHashCode()));
     }
 }
Esempio n. 16
0
        private void FormatDocument_Click(object sender, RoutedEventArgs e)
        {
            CSharpFormattingOptions policy    = FormattingOptionsFactory.CreateAllman();
            CSharpParser            parser    = new CSharpParser();
            SyntaxTree          tree          = parser.Parse(scriptTextBox.Text);
            StringWriter        writer        = new StringWriter();
            CSharpOutputVisitor outputVisitor = new CSharpOutputVisitor(writer, policy);

            outputVisitor.VisitSyntaxTree(tree);

            scriptTextBox.Text = writer.ToString();
        }
Esempio n. 17
0
 /// <summary>
 /// Perform a reformat of the text
 /// </summary>
 /// <param name="sender">Sender object</param>
 /// <param name="e">Event arguments</param>
 private void OnDoReformat(object sender, EventArgs e)
 {
     try
     {
         CSharpFormatter formatter = new CSharpFormatter(FormattingOptionsFactory.CreateAllman());
         string          newText   = formatter.Format(managerView.Editor.Text);
         managerView.Editor.Text = newText;
         explorerPresenter.CommandHistory.Add(new Commands.ChangeProperty(manager, "Code", newText));
     }
     catch (Exception err)
     {
         explorerPresenter.MainPresenter.ShowError(err);
     }
 }
Esempio n. 18
0
        void GenerateCode(AstBuilder astBuilder, ITextOutput output)
        {
            var syntaxTree = astBuilder.SyntaxTree;

            syntaxTree.AcceptVisitor(new InsertParenthesesVisitor {
                InsertParenthesesForReadability = true
            });

            // generate AST
            var transform = new CSharpToHpp();

            transform.Run(syntaxTree);

            var include = new IncludeVisitor();

            syntaxTree.AcceptVisitor(include);

            // generate include
            string include_name = "__" + include.namespacename.ToUpper() + "_" + include.typename.ToUpper() + "_H__";

            output.WriteLine("#ifndef " + include_name);
            output.WriteLine("#define " + include_name);
            output.WriteLine();

            if (include.foundClass)
            {
                output.WriteLine("#include <QuantKit/quantkit_global.h>");
                output.WriteLine("#include <QString>");
                output.WriteLine("#include <QDateTime>");
                output.WriteLine("#include <QSharedDataPointer>");
                output.WriteLine();
                output.WriteLine("#include \"qt_extension.h\"");
                output.WriteLine();
                output.WriteLine();
            }

            //Generate hpp Code
            var outputFormatter = new TextOutputFormatter(output)
            {
                FoldBraces = true
            };
            var formattingPolicy = FormattingOptionsFactory.CreateAllman();

            syntaxTree.AcceptVisitor(new HppOutputVisitor(outputFormatter, formattingPolicy));

            // generate endif
            output.WriteLine();
            output.WriteLine("#endif // " + include_name);
        }
Esempio n. 19
0
        public void TestBrackets_AnonymousMethodCloseingBracketAlignment()
        {
            var policy = FormattingOptionsFactory.CreateAllman();
            var indent = Helper.CreateEngine(@"
class Foo 
{
	void Test ()
	{ 
		Foo (delegate
		{
		}$
", policy);

            Assert.AreEqual("\t\t", indent.ThisLineIndent);
        }
Esempio n. 20
0
        public void TestBrackets_IndentBlocksInsideExpressionsOpenBrace()
        {
            var policy = FormattingOptionsFactory.CreateAllman();

            var indent = Helper.CreateEngine(@"
class Foo 
{
	void Test()
	{ 
		Foo (new MyOBject
			{$
", policy);

            Assert.AreEqual("\t\t\t", indent.ThisLineIndent);
            Assert.AreEqual("\t\t\t\t", indent.NextLineIndent);
        }
Esempio n. 21
0
        public void TestBrackets_AnonymousMethodOpenBracketAlignment()
        {
            var policy = FormattingOptionsFactory.CreateAllman();
            // policy.IndentBlocksInsideExpressions = false;
            var indent = Helper.CreateEngine(@"
class Foo 
{
	void Test ()
	{ 
		Foo (delegate
		{$
", policy);

            Assert.AreEqual("\t\t", indent.ThisLineIndent);
            Assert.AreEqual("\t\t\t", indent.NextLineIndent);
        }
        protected static void AssertRoundtripCode(string fileName, bool optimize = false, bool useDebug = false, int compilerVersion = 4)
        {
            var code = RemoveIgnorableLines(File.ReadLines(fileName));
            AssemblyDefinition assembly = CompileLegacy(code, optimize, useDebug, compilerVersion);

            CSharpDecompiler decompiler = new CSharpDecompiler(assembly.MainModule, new DecompilerSettings());

            decompiler.AstTransforms.Insert(0, new RemoveCompilerAttribute());

            var syntaxTree = decompiler.DecompileWholeModuleAsSingleFile();

            var options = FormattingOptionsFactory.CreateAllman();

            options.IndentSwitchBody = false;
            CodeAssert.AreEqual(code, syntaxTree.ToString(options));
        }
Esempio n. 23
0
        public void TestBrackets_IndentBlocksInsideExpressions_RightHandExpression_OpenBracketOnNonEmptyLine()
        {
            var policy = FormattingOptionsFactory.CreateAllman();

            policy.IndentBlocksInsideExpressions = true;
            var indent = Helper.CreateEngine(@"
class Foo 
{
	void Test ()
	{
		var foo = delegate {$
", policy);

            Assert.AreEqual("\t\t", indent.ThisLineIndent);
            Assert.AreEqual("\t\t\t", indent.NextLineIndent);
        }
Esempio n. 24
0
        public CodeFormatResponse Format(Request request)
        {
            var document = new StringBuilderDocument(request.Buffer);
            var options  = new TextEditorOptions();

            options.EolMarker      = Environment.NewLine;
            options.WrapLineLength = 80;
            var policy  = FormattingOptionsFactory.CreateAllman();
            var visitor = new AstFormattingVisitor(policy, document, options);

            visitor.FormattingMode = FormattingMode.Intrusive;
            var syntaxTree = new CSharpParser().Parse(document, request.FileName);

            syntaxTree.AcceptVisitor(visitor);
            visitor.ApplyChanges();
            return(new CodeFormatResponse(document.Text));
        }
        public void initializeExpr(Solution solution, int choice, string checkAccessMethodName)
        {
            foreach (var file in solution.AllFiles)
            {
                if (file.IndexOfWebMthdDecl.Count == 0 &&
                    file.IndexOfIfElStmt.Count == 0 &&
                    file.IndexOfTryCatchStmt.Count == 0 &&
                    file.IndexOfClassDecl.Count == 0 &&
                    file.IndexOfUsingDecl.Count == 0)
                {
                    continue;
                }

                file.syntaxTree.Freeze();

                // Create a document containing the file content:
                var document          = new StringBuilderDocument(file.originalText);
                var formattingOptions = FormattingOptionsFactory.CreateAllman();
                var options           = new TextEditorOptions();

                using (var script = new DocumentScript(document, formattingOptions, options))
                {
                    switch (choice)
                    {
                    case 1:     //AddUsingAPIDecl(file, script);
                        RemoveAccessControlCheckAccess(file, script, checkAccessMethodName);
                        WriteValidationMethodStructure(file, script);
                        WriteIfElseStructureInWebmethodTry(file, script);

                        break;

                    case 2: WriteValidationMethodBody(file, script);
                        WriteAccessControlStmtInTryCatch(file, script, checkAccessMethodName);
                        InsertParametersIfElseInWebmethodTry(file, script);
                        DummyTextForTryCallValidation(file, script);
                        AddPageNameGlobalinClass(file, script);
                        CheckTryCatchInWebMethodBody(file, script);
                        break;
                    }
                }
                //File.WriteAllText(Path.ChangeExtension(file.fileName, ".output.cs"), document.Text);
                File.WriteAllText(file.fileName, document.Text);
            }
            Console.WriteLine("Done. Press Any Key to Exit..............");
        }
Esempio n. 26
0
        public void TestIssue389()
        {
            var policy = FormattingOptionsFactory.CreateAllman();
            var indent = Helper.CreateEngine(@"
public class Test
{
	public void FooBar()
	{
		if (true)
		{$
			
		}
	}
}", policy);

            Assert.AreEqual("\t\t", indent.ThisLineIndent);
            Assert.AreEqual("\t\t\t", indent.NextLineIndent);
        }
Esempio n. 27
0
        private static string RemoveMethods(string code, IEnumerable <MethodVisitorResult> methods)
        {
            var document = new StringBuilderDocument(code);

            using (var script = new DocumentScript(
                       document,
                       FormattingOptionsFactory.CreateAllman(),
                       new TextEditorOptions()))
            {
                foreach (var method in methods)
                {
                    var offset = script.GetCurrentOffset(method.MethodDefinition.GetRegion().Begin);
                    script.Replace(method.MethodDefinition, new MethodDeclaration());
                    script.Replace(offset, new MethodDeclaration().GetText().Trim().Length, "");
                }
            }
            return(document.Text);
        }
Esempio n. 28
0
        public void TestBrackets_IndentBlocksInsideExpressions_ClosingBracket()
        {
            var policy = FormattingOptionsFactory.CreateAllman();

            policy.IndentBlocksInsideExpressions = true;
            var indent = Helper.CreateEngine(@"
class Foo 
{
	void Test ()
	{
		Foo (delegate
			{
			}$
", policy);

            Assert.AreEqual("\t\t\t", indent.ThisLineIndent);
            Assert.AreEqual("\t\t\t", indent.NextLineIndent);
        }
Esempio n. 29
0
        void GenerateCode(AstBuilder astBuilder, ITextOutput output)
        {
            var syntaxTree = astBuilder.SyntaxTree;

            syntaxTree.AcceptVisitor(new InsertParenthesesVisitor {
                InsertParenthesesForReadability = true
            });

            // Xml
            var dom = new XmlDocument();

            dom.AppendChild(dom.CreateElement("CodeDom")); // root node

            // generate AST
            VisitSyntaxTree(syntaxTree, dom);

            //Generate C# Code
            var csharpText      = new StringWriter();
            var csharpoutput    = new PlainTextOutput(csharpText);
            var outputFormatter = new TextOutputFormatter(csharpoutput)
            {
                FoldBraces = true
            };
            var formattingPolicy = FormattingOptionsFactory.CreateAllman();

            syntaxTree.AcceptVisitor(new CSharpOutputVisitor(outputFormatter, formattingPolicy));

            // insert to xml as cdata
            var csharpcode = dom.CreateElement("Code");
            var cdata      = dom.CreateCDataSection(csharpText.ToString());

            csharpcode.AppendChild(cdata);
            dom.DocumentElement.AppendChild(csharpcode);

            // write to output
            var text   = new StringWriter();
            var writer = new XmlTextWriter(text)
            {
                Formatting = Formatting.Indented
            };

            dom.WriteContentTo(writer);
            output.Write(text.ToString());
        }
Esempio n. 30
0
        private static string RemoveClasses(string code, IEnumerable <TypeDeclaration> classes)
        {
            var document = new StringBuilderDocument(code);

            using (
                var script = new DocumentScript(
                    document,
                    FormattingOptionsFactory.CreateAllman(),
                    new TextEditorOptions()))
            {
                foreach (var @class in classes)
                {
                    var offset = script.GetCurrentOffset(@class.GetRegion().Begin);
                    script.Replace(@class, new TypeDeclaration());
                    script.Replace(offset, new TypeDeclaration().GetText().Trim().Length, "");
                }
            }
            return(document.Text);
        }