Example #1
0
        public void ParseAndWrite(PARSE_TYPE type, string inputText)
        {
            // parse through framework
            SyntaxTree tree = new N.CSharpParser().Parse(inputText);

            // dispatch to visitor
            var defaultVisitor = new NRefactoryVisitor();
            tree.AcceptVisitor(defaultVisitor);

            IEnumerable<CLRType> CLRTypesDetected = defaultVisitor.CLRTypes;
            switch (type)
            {
                case PARSE_TYPE.FIELDS:
                    CLRTypesDetected.ToList().ForEach(clrType => clrType.WriteFieldsUML(m_richSb));
                    break;

                case PARSE_TYPE.PROPERTIES:
                    CLRTypesDetected.ToList().ForEach(clrType => clrType.WritePropertiesUML(m_richSb));
                    break;

                case PARSE_TYPE.METHODS:
                    CLRTypesDetected.ToList().ForEach(clrType => clrType.WriteMethodsUML(m_richSb));
                    break;

                case PARSE_TYPE.ALL:
                    CLRTypesDetected.ToList().ForEach(clrType => clrType.Design(m_richSb));
                    break;

                default:
                    throw new NotSupportedException();

            }
        }
		public void TestCollectNodes()
		{
			var cu = new CSharpParser().Parse("using System;\nclass Test {\n  int field; // comment\n}");
			CollectNodesVisitor v = new CollectNodesVisitor();
			cu.AcceptVisitor(v);
			Assert.AreEqual(cu.DescendantsAndSelf.ToList(), v.nodes);
		}
        public string Parse(PARSE_TYPE type, string inputText)
        {
            // parse through framework
            SyntaxTree tree = new N.CSharpParser().Parse(inputText);

            // dispatch to visitor
            var defaultVisitor = new NRefactoryVisitor();
            tree.AcceptVisitor(defaultVisitor);

            IEnumerable<CLRType> inputTextTypes = defaultVisitor.CLRTypes;
            switch (type)
            {
                case PARSE_TYPE.FIELDS:
                    return inputTextTypes.Aggregate(new StringBuilder(), (sb, clr) => sb.AppendLine(clr.GetFieldsUML())).ToString();

                case PARSE_TYPE.PROPERTIES:
                    return inputTextTypes.Aggregate(new StringBuilder(), (sb, clr) => sb.AppendLine(clr.GetPropertiesUML())).ToString();

                case PARSE_TYPE.METHODS:
                    return inputTextTypes.Aggregate(new StringBuilder(), (sb, clr) => sb.AppendLine(clr.GetMethodsUML())).ToString();

                case PARSE_TYPE.ALL:
                    return inputTextTypes.Aggregate(new StringBuilder(), (sb, clr) => sb.AppendLine(clr.Design())).ToString();

                default:
                    throw new NotSupportedException();

            }
        }
 /// <summary>
 /// Formats the specified part of the document.
 /// </summary>
 public static void Format(IDocument document, int offset, int length, CSharpFormattingOptions options)
 {
     var syntaxTree = new CSharpParser().Parse(document);
     var fv = new AstFormattingVisitor(options, document);
     fv.FormattingRegion = new DomRegion(document.GetLocation(offset), document.GetLocation(offset + length));
     syntaxTree.AcceptVisitor(fv);
     fv.ApplyChanges(offset, length);
 }
        protected static IDocument GetResult(CSharpFormattingOptions policy, string input)
        {
            var adapter = new ReadOnlyDocument (input);
            var visitor = new AstFormattingVisitor (policy, adapter, factory);

            var compilationUnit = new CSharpParser ().Parse (new StringReader (input), "test.cs");
            compilationUnit.AcceptVisitor (visitor, null);

            return new ReadOnlyDocument (ApplyChanges (input, visitor.Changes));
        }
        protected static void Continue(CSharpFormattingOptions policy, IDocument document, string expectedOutput)
        {
            var visitior = new AstFormattingVisitor (policy, document, factory);

            var compilationUnit = new CSharpParser ().Parse (new StringReader (document.Text), "test.cs");
            compilationUnit.AcceptVisitor (visitior, null);
            string newText = ApplyChanges (document.Text, visitior.Changes);
            if (expectedOutput != newText) {
                Console.WriteLine (newText);
            }
            Assert.AreEqual (expectedOutput, newText);
        }
		/*public static string ApplyChanges (string text, List<TextReplaceAction> changes)
		{
			changes.Sort ((x, y) => y.Offset.CompareTo (x.Offset));
			StringBuilder b = new StringBuilder(text);
			foreach (var change in changes) {
				//Console.WriteLine ("---- apply:" + change);
//				Console.WriteLine (adapter.Text);
				if (change.Offset > b.Length)
					continue;
				b.Remove(change.Offset, change.RemovedChars);
				b.Insert(change.Offset, change.InsertedText);
			}
//			Console.WriteLine ("---result:");
//			Console.WriteLine (adapter.Text);
			return b.ToString();
		}*/
		
		protected static IDocument GetResult (CSharpFormattingOptions policy, string input, FormattingMode mode = FormattingMode.OnTheFly)
		{
			input = NormalizeNewlines (input);
			var document = new StringBuilderDocument (input);
			var options = new TextEditorOptions ();
			options.EolMarker = "\n";
			var visitor = new AstFormattingVisitor (policy, document, options);
			visitor.FormattingMode = mode;
			var compilationUnit = new CSharpParser ().Parse (document, "test.cs");
			compilationUnit.AcceptVisitor (visitor);
			visitor.ApplyChanges();
			return document;
		}
Example #8
0
		/*public static string ApplyChanges (string text, List<TextReplaceAction> changes)
		{
			changes.Sort ((x, y) => y.Offset.CompareTo (x.Offset));
			StringBuilder b = new StringBuilder(text);
			foreach (var change in changes) {
				//Console.WriteLine ("---- apply:" + change);
//				Console.WriteLine (adapter.Text);
				if (change.Offset > b.Length)
					continue;
				b.Remove(change.Offset, change.RemovedChars);
				b.Insert(change.Offset, change.InsertedText);
			}
//			Console.WriteLine ("---result:");
//			Console.WriteLine (adapter.Text);
			return b.ToString();
		}*/
		
		protected static IDocument GetResult(CSharpFormattingOptions policy, string input, FormattingMode mode = FormattingMode.Intrusive)
		{
			input = NormalizeNewlines(input);
			var document = new StringBuilderDocument(input);
			var options = new TextEditorOptions();
			options.EolMarker = "\n";
			options.WrapLineLength = 80;
			var visitor = new AstFormattingVisitor (policy, document, options);
			visitor.FormattingMode = mode;
			var syntaxTree = new CSharpParser ().Parse (document, "test.cs");
			syntaxTree.AcceptVisitor (visitor);
			visitor.ApplyChanges();
			return document;
		}
Example #9
0
 public CodeFormatResponse Format(CodeFormatRequest request)
 {
     var document = new StringBuilderDocument(request.Buffer);
     var options = new TextEditorOptions();
     options.EolMarker = Environment.NewLine;
     options.WrapLineLength = 80;
     options.TabsToSpaces = request.ExpandTab;
     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);
 }
Example #10
0
		protected static void Continue (CSharpFormattingOptions policy, IDocument document, string expectedOutput, FormattingMode formattingMode = FormattingMode.OnTheFly)
		{
			expectedOutput = NormalizeNewlines (expectedOutput);
			var options = new TextEditorOptions ();
			options.EolMarker = "\n";
			var visitior = new AstFormattingVisitor (policy, document, options);
			visitior.FormattingMode = formattingMode;
			var syntaxTree = new CSharpParser ().Parse (document, "test.cs");
			syntaxTree.AcceptVisitor (visitior);
			visitior.ApplyChanges();
			string newText = document.Text;
			if (expectedOutput != newText) {
				Console.WriteLine (newText);
			}
			Assert.AreEqual (expectedOutput, newText);
		}
		public override ValueReference Evaluate (EvaluationContext ctx, string expression, object expectedType)
		{
			expression = expression.TrimStart ();

			if (expression.Length > 0 && expression[0] == '?')
				expression = expression.Substring (1).Trim ();

			if (expression.StartsWith ("var", StringComparison.Ordinal) && char.IsWhiteSpace (expression[3])) {
				expression = expression.Substring (4).Trim (' ', '\t');
				string variable = null;

				for (int n = 0; n < expression.Length; n++) {
					if (!char.IsLetterOrDigit (expression[n]) && expression[n] != '_') {
						variable = expression.Substring (0, n);
						if (!expression.Substring (n).Trim (' ', '\t').StartsWith ("=", StringComparison.Ordinal))
							variable = null;
						break;
					}

					if (n == expression.Length - 1) {
						variable = expression;
						expression = null;
						break;
					}
				}

				if (!string.IsNullOrEmpty (variable))
					userVariables[variable] = new UserVariableReference (ctx, variable);

				if (expression == null)
					return null;
			}

			expression = ReplaceExceptionTag (expression, ctx.Options.CurrentExceptionTag);

			var expr = new CSharpParser ().ParseExpression (expression);
			if (expr == null)
				throw new EvaluatorException ("Could not parse expression '{0}'", expression);

			var evaluator = new NRefactoryExpressionEvaluatorVisitor (ctx, expression, expectedType, userVariables);
			return expr.AcceptVisitor<ValueReference> (evaluator);
		}
Example #12
0
        public void ParseAndWrite(PARSE_TYPE type, string inputText)
        {
            // parse through framework
            SyntaxTree tree = new N.CSharpParser().Parse(inputText);

            // dispatch to visitor
            var defaultVisitor = new NRefactoryVisitorV2();
            tree.AcceptVisitor(defaultVisitor);

            IEnumerable<Declaration> CLRDeclarations = defaultVisitor.Declarations;
            switch (type)
            {
                case PARSE_TYPE.FIELDS:
                    CLRDeclarations.OfType<ClassesAndStructs>().ToList().ForEach(cs =>
                        cs.Fields.OrderByDescending(x => !x.Static).ToList().ForEach(f => f.Design(m_richSb).WriteLine()));
                    break;

                case PARSE_TYPE.PROPERTIES:
                    CLRDeclarations.OfType<ClassesAndStructsAndInterfaces>().ToList().ForEach(csi => csi.Properties.OrderByDescending(x => !x.Static).ToList().ForEach(p => p.Design(m_richSb).WriteLine()));
                    break;

                case PARSE_TYPE.METHODS:
                    CLRDeclarations.OfType<ClassesAndStructsAndInterfaces>().ToList().ForEach(csi =>
                        csi.Methods.OrderByDescending(x => !x.Static).ToList().Aggregate(new List<Method>(), (l, m) =>
                        {
                            l.Insert((m.Ctor && m.Static) ? 0 : l.Count, m);
                            return l;
                        })
                        .ForEach(m => m.Design(m_richSb).WriteLine())
                     );
                    break;

                case PARSE_TYPE.ALL:
                    CLRDeclarations.OfType<ITypeDeclaration>().ToList().ForEach(clrType => clrType.DesignType(m_richSb));
                    break;

                default:
                    throw new NotSupportedException();

            }
        }
		string Resolve (DebuggerSession session, SourceLocation location, string expression, bool tryTypeOf)
		{
			expression = expression.TrimStart ();

			if (expression.Length > 0 && expression[0] == '?')
				return "?" + Resolve (session, location, expression.Substring (1).Trim ());

			if (expression.StartsWith ("var", StringComparison.Ordinal) && char.IsWhiteSpace (expression[3]))
				return "var " + Resolve (session, location, expression.Substring (4).Trim (' ', '\t'));

			expression = ReplaceExceptionTag (expression, session.Options.EvaluationOptions.CurrentExceptionTag);

			Expression expr = new CSharpParser ().ParseExpression (expression);
			if (expr == null)
				return expression;

			var resolver = new NRefactoryExpressionResolverVisitor (session, location, expression);
			expr.AcceptVisitor (resolver);

			string resolved = resolver.GetResolvedExpression ();
			if (resolved == expression && !tryTypeOf && (expr is BinaryOperatorExpression) && IsTypeName (expression)) {
				// This is a hack to be able to parse expressions such as "List<string>". The NRefactory parser
				// can parse a single type name, so a solution is to wrap it around a typeof(). We do it if
				// the evaluation fails.
				string res = Resolve (session, location, "typeof(" + expression + ")", true);
				return res.Substring (7, res.Length - 8);
			}

			return resolved;
		}
		protected static void Continue (CSharpFormattingPolicy policy, ITextEditorAdapter adapter, string expectedOutput)
		{
			var visitior = new AstFormattingVisitor (policy, adapter);
			
			var compilationUnit = new CSharpParser ().Parse (new StringReader (adapter.Text));
			compilationUnit.AcceptVisitor (visitior, null);
			((TextEditorTestAdapter)adapter).ApplyChanges (visitior.Changes);
			Assert.AreEqual (expectedOutput, adapter.Text);
		}
Example #15
0
		protected static void Continue (CSharpFormattingOptions policy, ITextEditorAdapter adapter, string expectedOutput)
		{
			var visitior = new AstFormattingVisitor (policy, adapter, factory);
			
			var compilationUnit = new CSharpParser ().Parse (new StringReader (adapter.Text));
			compilationUnit.AcceptVisitor (visitior, null);
			ApplyChanges (((TextEditorTestAdapter)adapter), visitior.Changes);
			if (expectedOutput != adapter.Text) {
				Console.WriteLine (adapter.Text);
			}
			Assert.AreEqual (expectedOutput, adapter.Text);
		}
Example #16
0
		protected static ITextEditorAdapter GetResult (CSharpFormattingOptions policy, string input)
		{
			var adapter = new TextEditorTestAdapter (input);
			var visitior = new AstFormattingVisitor (policy, adapter, factory);
			
			var compilationUnit = new CSharpParser ().Parse (new StringReader (adapter.Text));
			compilationUnit.AcceptVisitor (visitior, null);
			
			ApplyChanges (adapter, visitior.Changes);

			return adapter;
		}
		protected static ITextEditorAdapter Test (CSharpFormattingOptions policy, string input, string expectedOutput)
		{
			var adapter = new TextEditorTestAdapter (input);
			var visitior = new AstFormattingVisitor (policy, adapter);
			
			var compilationUnit = new CSharpParser ().Parse (new StringReader (adapter.Text));
			compilationUnit.AcceptVisitor (visitior, null);
			adapter.ApplyChanges (visitior.Changes);
			Assert.AreEqual (expectedOutput, adapter.Text);
			return adapter;
		}
Example #18
0
        void Run(Config config)
        {
            if (config.ShowHelp)
            {
                Console.WriteLine("Netjs compiler, Copyright 2014 Frank A. Krueger");
                Console.WriteLine("netjs [options] assembly-file");
                Console.WriteLine("   -help                Lists all compiler options (short: -?)");
                return;
            }

            if (string.IsNullOrEmpty(config.MainAssembly))
            {
                throw new Exception("No assembly specified.");
            }

            var asmPath = Path.GetFullPath(config.MainAssembly);
            Step("Loading " + asmPath);
            string sourceCode;
            if (asmPath.EndsWith(".cs"))
            {
                sourceCode = File.ReadAllText(asmPath);
            }
            else
            {
                sourceCode = decompileAssembly(asmPath);
                File.WriteAllText("temp.cs", sourceCode);
            }
            asmDir = Path.GetDirectoryName(asmPath);
            var outPath = Path.ChangeExtension(asmPath, ".ts");

            var syntaxTree = new CSharpParser().Parse(sourceCode, "temp.cs");
            var compilation = createCompilation(asmPath, syntaxTree);

            /*{
                var resolver = new CSharpAstResolver(compilation, syntaxTree);
                var expr = syntaxTree.Descendants.OfType<Expression>().Where(e => (e.ToString()) == "(text + \"\\0\")").First();
                Console.WriteLine(resolver.Resolve(expr).Type.FullName);
            }*/
            Step("Translating C# to TypeScript");
            CsToTs.Run(compilation, syntaxTree);

            Step("Writing to " + outPath);
            using (var outputWriter = new StreamWriter(outPath))
            {
                syntaxTree.AcceptVisitor(new ICSharpCode.NRefactory.CSharp.InsertParenthesesVisitor { InsertParenthesesForReadability = true });
                syntaxTree.AcceptVisitor(new FromILSharp.TSOutputVisitor(outputWriter, FormattingOptionsFactory.CreateAllman()));
            }

            Step("Done");
        }