static CodeCompileUnit ParseInternal (TextReader codeStream)
		{
			var cs = codeStream.ReadToEnd ();
			var tree = SyntaxTree.Parse (cs, "a.cs");
			if (tree.Errors.Count > 0)
				throw new ArgumentException ("Stream contained errors.");

			var convertVisitor = new CodeDomConvertVisitor ();
		
			return convertVisitor.Convert (Compilation.Value, tree, tree.ToTypeSystem ());
		}
        static CodeCompileUnit ParseInternal(TextReader codeStream)
        {
            var cs   = codeStream.ReadToEnd();
            var tree = SyntaxTree.Parse(cs, "a.cs");

            if (tree.Errors.Count > 0)
            {
                throw new ArgumentException("Stream contained errors.");
            }

            var convertVisitor = new CodeDomConvertVisitor();

            return(convertVisitor.Convert(Compilation.Value, tree, tree.ToTypeSystem()));
        }
        string Convert(Expression expr)
        {
            ResolveVisitor rv = new ResolveVisitor(resolver, null);

            rv.Scan(expr);
            var          codeExpr = (CodeExpression)convertVisitor.Convert(expr, rv);
            StringWriter writer   = new StringWriter();

            writer.NewLine = " ";
            new CSharpCodeProvider().GenerateCodeFromExpression(codeExpr, writer, new CodeGeneratorOptions {
                IndentString = " "
            });
            return(Regex.Replace(writer.ToString(), @"\s+", " "));
        }
        string ConvertHelper(AstNode node, Action <CSharpCodeProvider, CodeObject, TextWriter, CodeGeneratorOptions> action)
        {
            CSharpResolver resolver = new CSharpResolver(compilation);

            resolver = resolver.WithCurrentUsingScope(unresolvedFile.RootUsingScope.Resolve(compilation));
            resolver = resolver.WithCurrentTypeDefinition(compilation.FindType(KnownTypeCode.Object).GetDefinition());
            var codeObj = convertVisitor.Convert(node, new CSharpAstResolver(resolver, node));

            StringWriter writer = new StringWriter();

            writer.NewLine = " ";
            action(new CSharpCodeProvider(), codeObj, writer, new CodeGeneratorOptions {
                IndentString = " "
            });
            return(Regex.Replace(writer.ToString(), @"\s+", " ").Trim());
        }
        string Convert(Expression expr)
        {
            CSharpResolver resolver = new CSharpResolver(compilation);

            resolver = resolver.WithCurrentUsingScope(parsedFile.RootUsingScope.Resolve(compilation));
            resolver = resolver.WithCurrentTypeDefinition(compilation.FindType(KnownTypeCode.Object).GetDefinition());
            var codeExpr = (CodeExpression)convertVisitor.Convert(expr, new CSharpAstResolver(resolver, expr, parsedFile));

            StringWriter writer = new StringWriter();

            writer.NewLine = " ";
            new CSharpCodeProvider().GenerateCodeFromExpression(codeExpr, writer, new CodeGeneratorOptions {
                IndentString = " "
            });
            return(Regex.Replace(writer.ToString(), @"\s+", " "));
        }
Example #6
0
        // Steps to load the designer:
        // - Parse main file
        // - Find other files containing parts of the form
        // - Parse all files and look for fields (for controls) and InitializeComponents method
        // - Create CodeDom objects for fields and InitializeComponents statements
        // - If debug build and Ctrl pressed, output CodeDom to console
        // - Return CodeDom objects to the .NET designer
        protected override CodeCompileUnit Parse()
        {
            SD.Log.Debug("AlDesignerLoader.Parse()");

            lastTextContentVersion = context.DesignerCodeFileDocument.Version;
            var primaryParseInfo = context.GetPrimaryFileParseInformation();
            var compilation      = context.GetCompilation();

            // Find designer class
            ITypeDefinition designerClass        = FormsDesignerSecondaryDisplayBinding.GetDesignableClass(primaryParseInfo.UnresolvedFile, compilation, out primaryPart);
            IMethod         initializeComponents = FormsDesignerSecondaryDisplayBinding.GetInitializeComponents(designerClass);

            if (initializeComponents == null)
            {
                throw new FormsDesignerLoadException("The InitializeComponent method was not found. Designer cannot be loaded.");
            }
            Debug.Assert(primaryPart != null);
            Debug.Assert(designerClass != null);

            bool isFirstClassInFile = primaryParseInfo.UnresolvedFile.TopLevelTypeDefinitions[0] == primaryPart;

            // TODO: translate
            const string missingReferenceMessage = "Your project is missing a reference to '${Name}' - please add it using 'Project > Add Reference'.";

            if (compilation.FindType(typeof(System.Drawing.Point)).Kind == TypeKind.Unknown)
            {
                throw new FormsDesignerLoadException(StringParser.Parse(missingReferenceMessage, new StringTagPair("Name", "System.Drawing")));
            }
            if (compilation.FindType(typeof(System.Windows.Forms.Form)).Kind == TypeKind.Unknown)
            {
                throw new FormsDesignerLoadException(StringParser.Parse(missingReferenceMessage, new StringTagPair("Name", "System.Windows.Forms")));
            }

            CodeDomConvertVisitor cv = new CodeDomConvertVisitor();

            cv.UseFullyQualifiedTypeNames = true;

            AlFullParseInformation designerParseInfo;
            MethodDeclaration      initializeComponentsDeclaration = initializeComponents.GetDeclaration(out designerParseInfo) as MethodDeclaration;

            if (initializeComponentsDeclaration == null)
            {
                throw new FormsDesignerLoadException("Could not find source code for InitializeComponents");
            }
            var resolver   = designerParseInfo.GetResolver(compilation);
            var codeMethod = (CodeMemberMethod)cv.Convert(initializeComponentsDeclaration, resolver);
            var codeClass  = new CodeTypeDeclaration(designerClass.Name);

            codeClass.Attributes = MemberAttributes.Public;
            codeClass.BaseTypes.AddRange(designerClass.DirectBaseTypes.Select(cv.Convert).ToArray());
            codeClass.Members.Add(codeMethod);

            foreach (var field in designerClass.Fields)
            {
                var codeField = new CodeMemberField(cv.Convert(field.Type), field.Name);
                codeField.Attributes = GetAccessibility(field);
                codeClass.Members.Add(codeField);
            }
            var codeNamespace = new CodeNamespace(designerClass.Namespace);

            codeNamespace.Types.Add(codeClass);
            var codeUnit = new CodeCompileUnit();

            codeUnit.Namespaces.Add(codeNamespace);

            // output generated CodeDOM to the console :
                        #if DEBUG
            if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
            {
                CodeDomVerboseOutputGenerator outputGenerator = new CodeDomVerboseOutputGenerator();
                outputGenerator.GenerateCodeFromMember(codeMethod, Console.Out, null);
                this.CodeDomProvider.GenerateCodeFromCompileUnit(codeUnit, Console.Out, null);
            }
                        #endif

            LoggingService.Debug("NRefactoryDesignerLoader.Parse() finished");

            if (!isFirstClassInFile)
            {
                MessageService.ShowWarning("The form must be the first class in the file in order for form resources to be compiled correctly.\n" +
                                           "Please move other classes below the form class definition or move them to other files.");
            }

            return(codeUnit);
        }
        CodeObject ConvertInContext(string program)
        {
            var p = PrepareResolver(program);

            return(convertVisitor.Convert(p.Item2, p.Item1));
        }
		// Steps to load the designer:
		// - Parse main file
		// - Find other files containing parts of the form
		// - Parse all files and look for fields (for controls) and InitializeComponents method
		// - Create CodeDom objects for fields and InitializeComponents statements
		// - If debug build and Ctrl pressed, output CodeDom to console
		// - Return CodeDom objects to the .NET designer
		protected override CodeCompileUnit Parse()
		{
			SD.Log.Debug("CSharpDesignerLoader.Parse()");
			
			lastTextContentVersion = context.DesignerCodeFileDocument.Version;
			var primaryParseInfo = context.GetPrimaryFileParseInformation();
			var compilation = context.GetCompilation();
			
			// Find designer class
			ITypeDefinition designerClass = FormsDesignerSecondaryDisplayBinding.GetDesignableClass(primaryParseInfo.UnresolvedFile, compilation, out primaryPart);
			IMethod initializeComponents = FormsDesignerSecondaryDisplayBinding.GetInitializeComponents(designerClass);
			
			if (initializeComponents == null) {
				throw new FormsDesignerLoadException("The InitializeComponent method was not found. Designer cannot be loaded.");
			}
			Debug.Assert(primaryPart != null);
			Debug.Assert(designerClass != null);
			
			bool isFirstClassInFile = primaryParseInfo.UnresolvedFile.TopLevelTypeDefinitions[0] == primaryPart;
			
			// TODO: translate
			const string missingReferenceMessage = "Your project is missing a reference to '${Name}' - please add it using 'Project > Add Reference'.";
			if (compilation.FindType(typeof(System.Drawing.Point)).Kind == TypeKind.Unknown) {
				throw new FormsDesignerLoadException(StringParser.Parse(missingReferenceMessage, new StringTagPair("Name", "System.Drawing")));
			}
			if (compilation.FindType(typeof(System.Windows.Forms.Form)).Kind == TypeKind.Unknown) {
				throw new FormsDesignerLoadException(StringParser.Parse(missingReferenceMessage, new StringTagPair("Name" , "System.Windows.Forms")));
			}
			
			CodeDomConvertVisitor cv = new CodeDomConvertVisitor();
			cv.UseFullyQualifiedTypeNames = true;
			
			CSharpFullParseInformation designerParseInfo;
			MethodDeclaration initializeComponentsDeclaration = initializeComponents.GetDeclaration(out designerParseInfo) as MethodDeclaration;
			if (initializeComponentsDeclaration == null)
				throw new FormsDesignerLoadException("Could not find source code for InitializeComponents");
			var resolver = designerParseInfo.GetResolver(compilation);
			var codeMethod = (CodeMemberMethod) cv.Convert(initializeComponentsDeclaration, resolver);
			var codeClass = new CodeTypeDeclaration(designerClass.Name);
			codeClass.Attributes = MemberAttributes.Public;
			codeClass.BaseTypes.AddRange(designerClass.DirectBaseTypes.Select(cv.Convert).ToArray());
			codeClass.Members.Add(codeMethod);
			
			foreach (var field in designerClass.Fields) {
				var codeField = new CodeMemberField(cv.Convert(field.Type), field.Name);
				codeClass.Members.Add(codeField);
			}
			var codeNamespace = new CodeNamespace(designerClass.Namespace);
			codeNamespace.Types.Add(codeClass);
			var codeUnit = new CodeCompileUnit();
			codeUnit.Namespaces.Add(codeNamespace);
			
			// output generated CodeDOM to the console :
			#if DEBUG
			if ((Control.ModifierKeys & Keys.Control) == Keys.Control) {
				CodeDomVerboseOutputGenerator outputGenerator = new CodeDomVerboseOutputGenerator();
				outputGenerator.GenerateCodeFromMember(codeMethod, Console.Out, null);
				this.CodeDomProvider.GenerateCodeFromCompileUnit(codeUnit, Console.Out, null);
			}
			#endif
			
			LoggingService.Debug("NRefactoryDesignerLoader.Parse() finished");
			
			if (!isFirstClassInFile) {
				MessageService.ShowWarning("The form must be the first class in the file in order for form resources to be compiled correctly.\n" +
				                           "Please move other classes below the form class definition or move them to other files.");
			}
			
			return codeUnit;
		}
		static CodeCompileUnit ParseInternal (TextReader codeStream)
		{
			var tree = SyntaxTree.Parse (codeStream);

			if (tree.Errors.Count > 0)
				throw new ArgumentException ("Stream contained errors.");

			var convertVisitor = new CodeDomConvertVisitor ();

			CodeCompileUnit ccu = convertVisitor.Convert (Compilation.Value, tree, tree.ToTypeSystem ());
			
			//C# parser seems to insist on putting imports in the "Global" namespace; fix it up
			for (int i = 0; i < ccu.Namespaces.Count; i++) {
				CodeNamespace global = ccu.Namespaces [i];
				if ((global.Name == "Global") && (global.Types.Count == 0)) {
					global.Name = "";
					ccu.Namespaces.RemoveAt (i);
					ccu.Namespaces.Insert (0, global);
					
					//clear out repeat imports...
					for (int j = 1; j < ccu.Namespaces.Count; j++) {
						CodeNamespace cn = ccu.Namespaces [j];
						
						//why can't we remove imports? will have to collect ones to keep
						//then clear and refill
						CodeNamespaceImportCollection imps = new CodeNamespaceImportCollection ();
						
						for (int m = 0; m < cn.Imports.Count; m++) {
							bool found = false;
							
							for (int n = 0; n < global.Imports.Count; n++)
								if (global.Imports [n] == cn.Imports [m])
									found = true;
						
							if (!found)
								imps.Add (cn.Imports [m]);
						}
						
						cn.Imports.Clear ();
						
						foreach (CodeNamespaceImport imp in imps)
							cn.Imports.Add (imp);
					}
					
					break;
				}
			}
			return ccu;
		}