예제 #1
0
        public static string GenerateText(TypeDeclaration type, AbstractDynamicCompilationExtension[] extensions)
        {
            var unit = new CompilationUnit();

            var namespaces = new HashSet <string>
            {
                typeof(AbstractViewGenerator).Namespace,
                typeof(Enumerable).Namespace,
                typeof(int).Namespace,
                typeof(LinqOnDynamic).Namespace
            };

            foreach (var extension in extensions)
            {
                foreach (var ns in extension.GetNamespacesToImport())
                {
                    namespaces.Add(ns);
                }
            }

            foreach (var ns in namespaces)
            {
                unit.AddChild(new Using(ns));
            }

            unit.AddChild(type);
            var output = new CSharpOutputVisitor();

            unit.AcceptVisitor(output, null);

            return(output.Text);
        }
예제 #2
0
        public static string GenerateText(TypeDeclaration type)
        {
            var unit = new CompilationUnit();

            unit.AddChild(new Using(typeof(AbstractViewGenerator).Namespace));
            unit.AddChild(new Using(typeof(Enumerable).Namespace));
            unit.AddChild(new Using(typeof(int).Namespace));
            unit.AddChild(new Using(typeof(LinqOnDynamic).Namespace));
            unit.AddChild(type);

            var output = new CSharpOutputVisitor();

            unit.AcceptVisitor(output, null);

            return(output.Text);
        }
        public static NamespaceDeclaration AddNamespace(this CompilationUnit compilationUnit, string name)
        {
            var @namespace = new NamespaceDeclaration(name);

            compilationUnit.AddChild(@namespace);

            return(@namespace);
        }
        public static TypeDeclaration add_Type(this CompilationUnit compilationUnit, string typeName)
        {
            const Modifiers modifiers = Modifiers.None | Modifiers.Public;
            var             newType   = new TypeDeclaration(modifiers, new List <AttributeSection>());

            newType.Name = typeName;
            compilationUnit.AddChild(newType);
            return(newType);
        }
        /*public static TypeDeclaration add_Type(this CompilationUnit compilationUnit, IReturnType iReturnType)
         * {
         *
         * }*/

        public static TypeDeclaration add_Type(this CompilationUnit compilationUnit, IClass iClass)
        {
            try
            {
                if (iClass.Namespace.valid())
                {
                    var namespaceDeclaration = compilationUnit.add_Namespace(iClass.Namespace);
                    return(namespaceDeclaration.add_Type(iClass));
                }

                // move to method IClass.typeDeclaration();
                var typeName = iClass.Name;

                var newType = compilationUnit.type(typeName);           // check if already exists and if it does return it
                if (newType != null)
                {
                    return(newType);
                }

                const Modifiers modifiers = Modifiers.None | Modifiers.Public;
                newType = new TypeDeclaration(modifiers, new List <AttributeSection>())
                {
                    Name = typeName
                };

                foreach (var baseType in iClass.BaseTypes)
                {
                    newType.BaseTypes.Add(new TypeReference(baseType.FullyQualifiedName));
                }

                compilationUnit.AddChild(newType);

                return(newType);
                //  return newType;


                /*var classFinder = new ClassFinder(iClass,0,0);
                 * var typeReference = (TypeReference)ICSharpCode.SharpDevelop.Dom.Refactoring.CodeGenerator.ConvertType(iClass.DefaultReturnType, classFinder);
                 * if (typeReference != null)
                 * {
                 *  compilationUnit.AddChild(typeReference);
                 *  return typeReference;
                 * }*/
                //return compilationUnit.add_Type_(iClass.Namespace, iClass.Name);
            }
            catch (Exception ex)
            {
                ex.log("in TypeReference.add_Type");
            }
            return(compilationUnit.add_Type(iClass.Namespace, iClass.Name));
        }
예제 #6
0
        public static string GenerateText(TypeDeclaration type, OrderedPartCollection <AbstractDynamicCompilationExtension> extensions)
        {
            var unit = new CompilationUnit();

            var namespaces = new HashSet <string>
            {
                typeof(SystemTime).Namespace,
                typeof(AbstractViewGenerator).Namespace,
                typeof(Enumerable).Namespace,
                typeof(IEnumerable <>).Namespace,
                typeof(IEnumerable).Namespace,
                typeof(int).Namespace,
                typeof(LinqOnDynamic).Namespace,
                typeof(Field).Namespace,
                typeof(CultureInfo).Namespace,
            };

            foreach (var extension in extensions)
            {
                foreach (var ns in extension.Value.GetNamespacesToImport())
                {
                    namespaces.Add(ns);
                }
            }

            foreach (var ns in namespaces)
            {
                unit.AddChild(new Using(ns));
            }

            unit.AddChild(type);
            var output = new CSharpOutputVisitor();

            unit.AcceptVisitor(output, null);

            return(output.Text);
        }
예제 #7
0
        /// <summary>
        /// Adds an import (using) if it is not specified in another compile unit.
        /// </summary>
        public static void AddImport(CompilationUnit unit, CompilationUnit outUnit, string ns)
        {
            if (unit != null)
            {
                foreach (INode node in unit.Children)
                {
                    UsingDeclaration decl = node as UsingDeclaration;
                    if (decl != null)
                    {
                        foreach (Using us in decl.Usings)
                        {
                            if (us.Name == ns)
                            {
                                return;
                            }
                        }
                    }
                }
            }

            outUnit.AddChild(new UsingDeclaration(ns));
        }
        // 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()
        {
            LoggingService.Debug("NRefactoryDesignerLoader.Parse()");

            lastTextContent = this.Generator.ViewContent.DesignerCodeFileContent;

            ParseInformation parseInfo = ParserService.GetParseInformation(this.Generator.ViewContent.DesignerCodeFile.FileName);

            IClass         formClass;
            bool           isFirstClassInFile;
            IList <IClass> parts = FindFormClassParts(parseInfo, out formClass, out isFirstClassInFile);

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

            if (formClass.ProjectContent.GetClass("System.Drawing.Point", 0) == null)
            {
                throw new FormsDesignerLoadException(
                          StringParser.Parse(
                              missingReferenceMessage, new string[, ] {
                    { "Name", "System.Drawing" }
                }
                              ));
            }
            if (formClass.ProjectContent.GetClass("System.Windows.Forms.Form", 0) == null)
            {
                throw new FormsDesignerLoadException(
                          StringParser.Parse(
                              missingReferenceMessage, new string[, ] {
                    { "Name", "System.Windows.Forms" }
                }
                              ));
            }

            List <KeyValuePair <string, CompilationUnit> > compilationUnits = new List <KeyValuePair <string, CompilationUnit> >();
            bool foundInitMethod = false;

            foreach (IClass part in parts)
            {
                string fileName = part.CompilationUnit.FileName;
                if (fileName == null)
                {
                    continue;
                }
                bool found = false;
                foreach (KeyValuePair <string, CompilationUnit> entry in compilationUnits)
                {
                    if (FileUtility.IsEqualFileName(fileName, entry.Key))
                    {
                        found = true;
                        break;
                    }
                }
                if (found)
                {
                    continue;
                }

                ITextBuffer fileContent;
                if (FileUtility.IsEqualFileName(fileName, this.Generator.ViewContent.PrimaryFileName))
                {
                    fileContent = this.Generator.ViewContent.PrimaryFileContent;
                }
                else if (FileUtility.IsEqualFileName(fileName, this.Generator.ViewContent.DesignerCodeFile.FileName))
                {
                    fileContent = new StringTextBuffer(this.Generator.ViewContent.DesignerCodeFileContent);
                }
                else
                {
                    fileContent = ParserService.GetParseableFileContent(fileName);
                }

                ICSharpCode.NRefactory.IParser p = ICSharpCode.NRefactory.ParserFactory.CreateParser(language, fileContent.CreateReader());
                p.Parse();
                if (p.Errors.Count > 0)
                {
                    throw new FormsDesignerLoadException("Syntax errors in " + fileName + ":\r\n" + p.Errors.ErrorOutput);
                }

                // Try to fix the type names to fully qualified ones
                FixTypeNames(p.CompilationUnit, part.CompilationUnit, ref foundInitMethod);
                compilationUnits.Add(new KeyValuePair <string, CompilationUnit>(fileName, p.CompilationUnit));
            }

            if (!foundInitMethod)
            {
                throw new FormsDesignerLoadException("The InitializeComponent method was not found. Designer cannot be loaded.");
            }

            CompilationUnit      combinedCu = new CompilationUnit();
            NamespaceDeclaration nsDecl     = new NamespaceDeclaration(formClass.Namespace);

            combinedCu.AddChild(nsDecl);
            TypeDeclaration formDecl = new TypeDeclaration(Modifiers.Public, null);

            nsDecl.AddChild(formDecl);
            formDecl.Name = formClass.Name;
            foreach (KeyValuePair <string, CompilationUnit> entry in compilationUnits)
            {
                foreach (object o in entry.Value.Children)
                {
                    TypeDeclaration td = o as TypeDeclaration;
                    if (td != null && td.Name == formDecl.Name)
                    {
                        foreach (INode node in td.Children)
                        {
                            formDecl.AddChild(node);
                        }
                        formDecl.BaseTypes.AddRange(td.BaseTypes);
                    }
                    if (o is NamespaceDeclaration)
                    {
                        foreach (object o2 in ((NamespaceDeclaration)o).Children)
                        {
                            td = o2 as TypeDeclaration;
                            if (td != null && td.Name == formDecl.Name)
                            {
                                foreach (INode node in td.Children)
                                {
                                    formDecl.AddChild(node);
                                }
                                formDecl.BaseTypes.AddRange(td.BaseTypes);
                            }
                        }
                    }
                }
            }

            CodeDomVisitor visitor = new CodeDomVisitor();

            visitor.EnvironmentInformationProvider = new ICSharpCode.SharpDevelop.Dom.NRefactoryResolver.NRefactoryInformationProvider(formClass.ProjectContent);
            visitor.VisitCompilationUnit(combinedCu, null);

            // output generated CodeDOM to the console :
                        #if DEBUG
            if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
            {
                CodeDomVerboseOutputGenerator outputGenerator = new CodeDomVerboseOutputGenerator();
                outputGenerator.GenerateCodeFromMember(visitor.codeCompileUnit.Namespaces[0].Types[0], Console.Out, null);
                this.CodeDomProvider.GenerateCodeFromCompileUnit(visitor.codeCompileUnit, 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 be compiled correctly.\n" +
                                           "Please move other classes below the form class definition or move them to other files.");
            }

            return(visitor.codeCompileUnit);
        }
예제 #9
0
        public string Generate()
        {
            // Parse the source code
            IParser parser = ParserFactory.CreateParser(InputFile);

            parser.Parse();

            bool hasWarnings = false;

            // Prepare the output
            CompilationUnit generated = new CompilationUnit();

            if (Header != null)
            {
                generated.AddChild(new IdentifierExpression(Header));
            }
            foreach (UsingDeclaration usingDec in parser.CompilationUnit.Children.OfType <UsingDeclaration>())
            {
                generated.AddChild(usingDec);
            }
            if (generated.Children.OfType <UsingDeclaration>().Count() > 0)
            {
                generated.AddChild(new IdentifierExpression("\r\n"));
            }
            TypeDeclaration extensionMethodsType = new TypeDeclaration(Modifiers.Public | Modifiers.Partial | Modifiers.Static, new List <AttributeSection>())
            {
                Name = TypeName
            };

            generated.AddChild(
                Namespace == null ?
                (INode)extensionMethodsType :
                new NamespaceDeclaration(Namespace)
            {
                Children = extensionMethodsType.ToList <INode>()
            }
                );

//			// Add the ProcessOutParameter method
//			if (ProcessOutParameter) {
//				extensionMethodsType.AddChild(
//					new MethodDeclaration() {
//						Modifier = Modifiers.Static,
//						TypeReference = new TypeReference("void", true),
//						Name = ProcessOutParameterMethodName,
//						Parameters =
//							new ParameterDeclarationExpression(
//								new TypeReference("object", true),
//								"parameter"
//							).ToList(),
//						Body = new BlockStatement()
//					}
//				);
//				extensionMethodsType.AddChild(new IdentifierExpression("\t\t\r\n"));
//			}

            // Add the extesion methods
            foreach (NamespaceDeclaration ns in parser.CompilationUnit.Children.OfType <NamespaceDeclaration>())
            {
                foreach (TypeDeclaration type in ns.Children.OfType <TypeDeclaration>())
                {
                    foreach (MethodDeclaration method in type.Children.OfType <MethodDeclaration>())
                    {
                        MethodDeclaration extensionMethod = new MethodDeclaration();
                        // Signature
                        extensionMethod.Modifier          = Modifiers.Public | Modifiers.Static;
                        extensionMethod.TypeReference     = method.TypeReference;
                        extensionMethod.IsExtensionMethod = true;
                        if (string.IsNullOrEmpty(MethodPrefix))
                        {
                            extensionMethod.Name = method.Name;
                        }
                        else if (method.Name.StartsWith(MethodPrefix))
                        {
                            extensionMethod.Name = method.Name.Substring(MethodPrefix.Length);
                        }
                        else
                        {
                            extensionMethod.Name = method.Name;
                            Console.WriteLine("Warning: {0}.{1} is missing prefix {2}.", type.Name, method.Name, MethodPrefix);
                            hasWarnings = true;
                        }
                        // HACK: GetType is used by System.Object
                        if (extensionMethod.Name == "GetType")
                        {
                            extensionMethod.Name = "GetTheType";
                        }
                        // Parameters
                        extensionMethod.Parameters.Add(new ParameterDeclarationExpression(new TypeReference(type.Name), ThisParameterName));
                        foreach (ParameterDeclarationExpression param in method.Parameters)
                        {
                            ParameterDeclarationExpression newParam = new ParameterDeclarationExpression(param.TypeReference, param.ParameterName)
                            {
                                ParamModifier = param.ParamModifier
                            };
                            extensionMethod.Parameters.Add(newParam);
                        }
                        // Invocation
                        extensionMethod.Body = new BlockStatement();
                        InvocationExpression invoc = new InvocationExpression(
                            new MemberReferenceExpression(new IdentifierExpression(ThisParameterName), method.Name)
                            );
                        // Generate arguments
                        bool hasProcessOuts = false;
                        foreach (ParameterDeclarationExpression param in method.Parameters)
                        {
                            // Add argument to invocation
                            if (param.ParamModifier == ParameterModifiers.Ref)
                            {
                                invoc.Arguments.Add(new DirectionExpression(FieldDirection.Ref, new IdentifierExpression(param.ParameterName)));
                            }
                            else if (param.ParamModifier == ParameterModifiers.Out)
                            {
                                invoc.Arguments.Add(new DirectionExpression(FieldDirection.Out, new IdentifierExpression(param.ParameterName)));
                            }
                            else
                            {
                                invoc.Arguments.Add(new IdentifierExpression(param.ParameterName));
                            }
                            // Call ProcessOutParameter
                            if (ProcessOutParameter)
                            {
                                if (param.ParamModifier == ParameterModifiers.Ref ||
                                    param.ParamModifier == ParameterModifiers.Out ||
                                    param.TypeReference.IsArrayType)
                                {
                                    if (!ProcessOutParameterIgnores.Contains(param.TypeReference.Type))
                                    {
                                        extensionMethod.Body.AddChild(
                                            new ExpressionStatement(
                                                new InvocationExpression(
                                                    new IdentifierExpression(ProcessOutParameterMethodName),
                                                    new IdentifierExpression(param.ParameterName).ToList <Expression>()
                                                    )
                                                )
                                            );
                                        hasProcessOuts = true;
                                    }
                                }
                            }
                        }
                        // Process return value
                        if (method.TypeReference.Type == typeof(void).FullName)
                        {
                            extensionMethod.Body.Children.Insert(0, new ExpressionStatement(invoc));
                        }
                        else
                        {
                            if ((!ProcessOutParameter || ProcessOutParameterIgnores.Contains(method.TypeReference.Type)) && !hasProcessOuts)
                            {
                                // Short version
                                extensionMethod.Body.Children.Insert(0, new ReturnStatement(invoc));
                            }
                            else
                            {
                                // Declare and get return value
                                extensionMethod.Body.Children.Insert(0,
                                                                     new LocalVariableDeclaration(
                                                                         new VariableDeclaration(ReturnValueName, invoc, method.TypeReference)
                                                                         )
                                                                     );
                                // Call ProcessOutParameter
                                if (method.TypeReference.Type != typeof(void).FullName && !ProcessOutParameterIgnores.Contains(method.TypeReference.Type))
                                {
                                    extensionMethod.Body.AddChild(
                                        new ExpressionStatement(
                                            new InvocationExpression(
                                                new IdentifierExpression(ProcessOutParameterMethodName),
                                                new IdentifierExpression(ReturnValueName).ToList <Expression>()
                                                )
                                            )
                                        );
                                }
                                // Return it
                                extensionMethod.Body.AddChild(
                                    new ReturnStatement(new IdentifierExpression(ReturnValueName))
                                    );
                            }
                        }
                        // Convert out parameter to return value
                        if (ConvertOutParameterToReturn &&
                            method.TypeReference.Type == typeof(void).FullName &&
                            extensionMethod.Parameters.Count > 0 &&
                            extensionMethod.Parameters.Last().ParamModifier == ParameterModifiers.Out &&
                            extensionMethod.Parameters.Where(p => p.ParamModifier == ParameterModifiers.Out).Count() == 1)
                        {
                            ParameterDeclarationExpression param = extensionMethod.Parameters.Last();
                            // Change signature
                            extensionMethod.TypeReference = param.TypeReference;
                            extensionMethod.Parameters.Remove(param);
                            // Define local variable instead
                            extensionMethod.Body.Children.Insert(
                                0,
                                new LocalVariableDeclaration(
                                    new VariableDeclaration(param.ParameterName, Expression.Null, param.TypeReference)
                                    )
                                );
                            // Return it
                            extensionMethod.Body.AddChild(
                                new ReturnStatement(new IdentifierExpression(param.ParameterName))
                                );
                        }
                        extensionMethodsType.AddChild(extensionMethod);
                        extensionMethodsType.AddChild(new IdentifierExpression("\t\t\r\n"));
                    }
                }
            }

            // Pretty print
            CSharpOutputVisitor csOut = new CSharpOutputVisitor();

            csOut.VisitCompilationUnit(generated, null);
            string output = csOut.Text;

            // Save to file
            if (OutputFile != null)
            {
                File.WriteAllText(OutputFile, output);
            }

            if (hasWarnings)
            {
                Console.WriteLine("Press any key to continue...");
                Console.ReadKey();
            }

            return(output);
        }
        public void ComplexExample()
        {
            string          code = @"class A {
	Button closeButton;
	void M() {
		System.Windows.Forms.Panel panel1;
		closeButton = new System.Windows.Forms.Button();
		panel1 = new System.Windows.Forms.Panel();
		panel1.SuspendLayout();
		panel1.Controls.Add(this.closeButton);
		closeButton.BackColor = System.Drawing.Color.FromArgb();
		panel1.BackColor = System.Drawing.SystemColors.Info;
	}
}";
            TypeDeclaration decl = Ast.ParseUtilCSharp.ParseGlobal <TypeDeclaration>(code);
            CompilationUnit cu   = new CompilationUnit();

            cu.AddChild(decl);
            CodeNamespace ns = (CodeNamespace)cu.AcceptVisitor(new CodeDomVisitor(), null);

            Assert.AreEqual("A", ns.Types[0].Name);
            Assert.AreEqual("closeButton", ns.Types[0].Members[0].Name);
            Assert.AreEqual("M", ns.Types[0].Members[1].Name);
            CodeMemberMethod m = (CodeMemberMethod)ns.Types[0].Members[1];

            CodeVariableDeclarationStatement s0 = (CodeVariableDeclarationStatement)m.Statements[0];

            Assert.AreEqual("panel1", s0.Name);
            Assert.AreEqual("System.Windows.Forms.Panel", s0.Type.BaseType);

            CodeAssignStatement cas = (CodeAssignStatement)m.Statements[1];

            Assert.AreEqual("closeButton", ((CodeFieldReferenceExpression)cas.Left).FieldName);

            cas = (CodeAssignStatement)m.Statements[2];
            Assert.AreEqual("panel1", ((CodeVariableReferenceExpression)cas.Left).VariableName);

            CodeExpressionStatement    ces = (CodeExpressionStatement)m.Statements[3];
            CodeMethodInvokeExpression mie = (CodeMethodInvokeExpression)ces.Expression;

            Assert.AreEqual("SuspendLayout", mie.Method.MethodName);
            Assert.AreEqual("panel1", ((CodeVariableReferenceExpression)mie.Method.TargetObject).VariableName);

            ces = (CodeExpressionStatement)m.Statements[4];
            mie = (CodeMethodInvokeExpression)ces.Expression;
            Assert.AreEqual("Add", mie.Method.MethodName);
            CodePropertyReferenceExpression pre = (CodePropertyReferenceExpression)mie.Method.TargetObject;

            Assert.AreEqual("Controls", pre.PropertyName);
            Assert.AreEqual("panel1", ((CodeVariableReferenceExpression)pre.TargetObject).VariableName);

            cas = (CodeAssignStatement)m.Statements[5];
            pre = (CodePropertyReferenceExpression)cas.Left;
            Assert.AreEqual("BackColor", pre.PropertyName);
            Assert.AreEqual("closeButton", ((CodeFieldReferenceExpression)pre.TargetObject).FieldName);
            mie = (CodeMethodInvokeExpression)cas.Right;
            Assert.AreEqual("FromArgb", mie.Method.MethodName);
            Assert.IsTrue(mie.Method.TargetObject is CodeTypeReferenceExpression);
            Assert.AreEqual("System.Drawing.Color", (mie.Method.TargetObject as CodeTypeReferenceExpression).Type.BaseType);

            cas = (CodeAssignStatement)m.Statements[6];
            pre = (CodePropertyReferenceExpression)cas.Left;
            Assert.AreEqual("BackColor", pre.PropertyName);
            Assert.AreEqual("panel1", ((CodeVariableReferenceExpression)pre.TargetObject).VariableName);
            pre = (CodePropertyReferenceExpression)cas.Right;
            Assert.AreEqual("Info", pre.PropertyName);
            Assert.IsTrue(pre.TargetObject is CodeTypeReferenceExpression);
            Assert.AreEqual("System.Drawing.SystemColors", (pre.TargetObject as CodeTypeReferenceExpression).Type.BaseType);
        }
예제 #11
0
파일: Utility.cs 프로젝트: dw4dev/Phalanger
		/// <summary>
		/// Adds an import (using) if it is not specified in another compile unit.
		/// </summary>
		public static void AddImport(CompilationUnit unit, CompilationUnit outUnit, string ns)
		{
			if (unit != null)
			{
				foreach (INode node in unit.Children)
				{
					UsingDeclaration decl = node as UsingDeclaration;
					if (decl != null)
					{
						foreach (Using us in decl.Usings)
						{
							if (us.Name == ns) return;
						}
					}
				}
			}

			outUnit.AddChild(new UsingDeclaration(ns));
		}