public static IEnumerable<pMixinAttributeResolvedResult> GetAllPMixinAttributes(
     this ICreateCodeGenerationPlanPipelineState manager,
     TypeDeclaration target)
 {
     return manager.ResolveAttributesPipeline.PartialClassLevelResolvedPMixinAttributes[target]
         .OfType<pMixinAttributeResolvedResult>();
 }
        public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration)
        {
            if (!typeDeclaration.HasModifier(Modifiers.Public))
            {
                base.VisitTypeDeclaration(typeDeclaration);
                return;
            }

            var idx = this.Results.BaseName.LastIndexOf('.');
            var filename = this.Results.BaseName;
            if (idx != -1)
                filename = filename.Substring(0, idx);
            if (typeDeclaration.Name != filename)
            {
                this.Results.Issues.Add(new LintIssue(typeDeclaration)
                {
                    Index = LintIssueIndex.ClassNameDoesNotMatchFileName,
                    Parameters = new[]
                    {
                        typeDeclaration.Name,
                        filename
                    }
                });
            }

            base.VisitTypeDeclaration(typeDeclaration);
        }
Example #3
0
		/// <summary>
		/// Makes sure that the PHP-visible type is serializable.
		/// </summary>
		private void AddSerializibility(TypeDeclaration type, TypeDeclaration outType)
		{
			// make the type serializable
			if (!Utility.IsDecoratedByAttribute(type, "System.SerializableAttribute"))
			{
				AttributeSection section = new AttributeSection();
				section.Attributes.Add(new ICSharpCode.NRefactory.Parser.AST.Attribute("Serializable", null, null));
				outType.Attributes.Add(section);

				ConstructorDeclaration ctor = new ConstructorDeclaration(type.Name, 
					((type.Modifier & Modifier.Sealed) == Modifier.Sealed ? Modifier.Private : Modifier.Protected),
					new List<ParameterDeclarationExpression>(), null);

				ctor.Parameters.Add(
					new ParameterDeclarationExpression(new TypeReference("System.Runtime.Serialization.SerializationInfo"), "info"));
				ctor.Parameters.Add(
					new ParameterDeclarationExpression(new TypeReference("System.Runtime.Serialization.StreamingContext"), "context"));

				ctor.ConstructorInitializer = new ConstructorInitializer();
				ctor.ConstructorInitializer.ConstructorInitializerType = ConstructorInitializerType.Base;
					
				ctor.ConstructorInitializer.Arguments.Add(new IdentifierExpression("info"));
				ctor.ConstructorInitializer.Arguments.Add(new IdentifierExpression("context"));

				ctor.Body = new BlockStatement();

				outType.AddChild(ctor);
			}
		}
			public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration)
			{
				bool oldIsSealedType = isSealedType;
				isSealedType = typeDeclaration.Modifiers.HasFlag(Modifiers.Sealed);
				base.VisitTypeDeclaration(typeDeclaration);
				isSealedType = oldIsSealedType;
			}
		public override object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data)
		{
			Push();
			object result = base.VisitTypeDeclaration(typeDeclaration, data);
			Pop();
			return result;
		}
			void CheckName(TypeDeclaration node, AffectedEntity entity, Identifier identifier, Modifiers accessibilty)
			{
				TypeResolveResult resolveResult = ctx.Resolve(node) as TypeResolveResult;
				if (resolveResult == null)
					return;
				var type = resolveResult.Type;
				if (type.DirectBaseTypes.Any(t => t.FullName == "System.Attribute")) {
					if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.CustomAttributes, identifier, accessibilty)) {
						return;
					}
				} else if (type.DirectBaseTypes.Any(t => t.FullName == "System.EventArgs")) {
					if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.CustomEventArgs, identifier, accessibilty)) {
						return;
					}
				} else if (type.DirectBaseTypes.Any(t => t.FullName == "System.Exception")) {
					if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.CustomExceptions, identifier, accessibilty)) {
						return;
					}
				}

				var typeDef = type.GetDefinition();
				if (typeDef != null && typeDef.Attributes.Any(attr => attr.AttributeType.FullName == "NUnit.Framework.TestFixtureAttribute")) {
					if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.TestType, identifier, accessibilty)) {
						return;
					}
				}

				CheckNamedResolveResult(resolveResult, node, entity, identifier, accessibilty);
			}
Example #7
0
            public override object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data)
            {
                if (typeDeclaration.ClassType == ClassType.Class && typeDeclaration.Modifiers.HasFlag(Modifiers.Abstract))
                    UnlockWith(typeDeclaration);

                return base.VisitTypeDeclaration(typeDeclaration, data);
            }
        public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration)
        {
            if (!typeDeclaration.HasModifier(Modifiers.Public))
            {
                base.VisitTypeDeclaration(typeDeclaration);
                return;
            }

            this.m_TotalClasses++;
            if (this.m_TotalClasses > 1)
            {
                this.Results.Issues.Add(new LintIssue(typeDeclaration)
                {
                    Index = LintIssueIndex.MoreThanOneClassInFile,
                    Parameters = new[]
                    {
                        typeDeclaration.Name,
                        this.m_FirstClassName
                    }
                });
            }
            else
            {
                this.m_FirstClassName = typeDeclaration.Name;
            }

            base.VisitTypeDeclaration(typeDeclaration);
        }
 public TypeDeclaration(Position pos, Symbol name, Type type, TypeDeclaration next)
 {
     Pos = pos;
     Name = name;
     Type = type;
     Next = next;
 }
Example #10
0
            public override object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data)
            {
                if(typeDeclaration.ClassType == ClassType.Class && typeDeclaration.Name != "Program")
                    UnlockWith(typeDeclaration);

                return base.VisitTypeDeclaration(typeDeclaration, data);
            }
            public override object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data)
            {
                if(typeDeclaration.ClassType == ClassType.Interface)
                    UnlockWith(typeDeclaration);

                return base.VisitTypeDeclaration(typeDeclaration, data);
            }
 public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration)
 {
     if (typeDeclaration.TypeKeyword.ToString() == "enum")
     {
         _currentEnumMembers = new List<NameNode>();
         EnumMembers.Add(typeDeclaration, _currentEnumMembers);
     }
     base.VisitTypeDeclaration(typeDeclaration);
 }
Example #13
0
 public static string CreateTypeSignature(TypeDeclaration type)
 {
     var @namespace = type.GetParent<NamespaceDeclaration>();
     var builder = new StringBuilder();
     builder.Append(@namespace.FullName.ToJavaNamespace());
     builder.Append("/");
     builder.Append(type.Name);
     return builder.ToString();
 }
			public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration)
			{
				var oldGenericStatus = isInGenericType;

				isInGenericType = typeDeclaration.TypeParameters.Count > 0;

				base.VisitTypeDeclaration(typeDeclaration);
				isInGenericType = oldGenericStatus;
			}
        static void AddImplementation(RefactoringContext context, TypeDeclaration result, ICSharpCode.NRefactory.TypeSystem.IType guessedType)
        {
            foreach (var property in guessedType.GetProperties ()) {
                if (!property.IsAbstract)
                    continue;
                if (property.IsIndexer) {
                    var indexerDecl = new IndexerDeclaration() {
                        ReturnType = context.CreateShortType(property.ReturnType),
                        Modifiers = GetModifiers(property),
                        Name = property.Name
                    };
                    indexerDecl.Parameters.AddRange(ConvertParameters(context, property.Parameters));
                    if (property.CanGet)
                        indexerDecl.Getter = new Accessor();
                    if (property.CanSet)
                        indexerDecl.Setter = new Accessor();
                    result.AddChild(indexerDecl, Roles.TypeMemberRole);
                    continue;
                }
                var propDecl = new PropertyDeclaration() {
                    ReturnType = context.CreateShortType(property.ReturnType),
                    Modifiers = GetModifiers (property),
                    Name = property.Name
                };
                if (property.CanGet)
                    propDecl.Getter = new Accessor();
                if (property.CanSet)
                    propDecl.Setter = new Accessor();
                result.AddChild(propDecl, Roles.TypeMemberRole);
            }

            foreach (var method in guessedType.GetMethods ()) {
                if (!method.IsAbstract)
                    continue;
                var decl = new MethodDeclaration() {
                    ReturnType = context.CreateShortType(method.ReturnType),
                    Modifiers = GetModifiers (method),
                    Name = method.Name,
                    Body = new BlockStatement() {
                        new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")))
                    }
                };
                decl.Parameters.AddRange(ConvertParameters(context, method.Parameters));
                result.AddChild(decl, Roles.TypeMemberRole);
            }

            foreach (var evt in guessedType.GetEvents ()) {
                if (!evt.IsAbstract)
                    continue;
                var decl = new EventDeclaration() {
                    ReturnType = context.CreateShortType(evt.ReturnType),
                    Modifiers = GetModifiers (evt),
                    Name = evt.Name
                };
                result.AddChild(decl, Roles.TypeMemberRole);
            }
        }
 // TODO: Dry up
 protected static Attribute FindContentTypeAttribute(TypeDeclaration type, ContentType definition)
 {
     string attributeName;
     if (definition is MediaType)
         attributeName = "MediaType";
     else
         attributeName = "DocumentType";
     var attribute = FindAttribute(type.Attributes, attributeName);
     return attribute;
 }
        protected override void OnParseInfo(TypeDeclaration type, ContentType definition)
        {
            base.OnParseInfo(type, definition);

            var docType = (DocumentType)definition;
            var info = (DocumentTypeInfo)docType.Info;

            info.DefaultTemplate = StringFieldValue(type, "DefaultTemplate");
            info.AllowedTemplates = StringArrayValue(type, "AllowedTemplates").ToList();
        }
 public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration)
 {
     if (typeDeclaration.ClassType == ClassType.Struct && !_isCorelibCompilation) {
         _errorReporter.Message(7998, typeDeclaration.GetRegion(), "user-defined value type (struct)");
         _result = false;
     }
     else {
         base.VisitTypeDeclaration(typeDeclaration);
     }
 }
 protected override void OnParseInfo(TypeDeclaration type, Definitions.ContentType definition)
 {
     var info = definition.Info;
     info.Alias = type.Name.CamelCase();
     info.Name = AttributeValue(type, "DisplayName", type.Name.SplitPascalCase());
     info.Description = AttributeValue(type, "Description", null);
     info.Master = FindMaster(type, Configuration).CamelCase();
     info.AllowAtRoot = BoolFieldValue(type, "AllowAtRoot");
     info.Icon = StringFieldValue(type, "icon", "folder.gif");
     info.Thumbnail = StringFieldValue(type, "thumbnail", "folder.png");
 }
        protected override void OnParseInfo(TypeDeclaration type, ContentType definition)
        {
            base.OnParseInfo(type, definition);

            var docType = (DocumentType)definition;
            var info = (DocumentTypeInfo)docType.Info;
            var attribute = FindAttribute(type.Attributes, "DocumentType");

            info.DefaultTemplate = AttributeArgumentValue<string>(attribute, "DefaultTemplate", null);
            info.AllowedTemplates = StringArrayValue(attribute, "AllowedTemplates").ToList();
        }
 static TypeDeclaration AddBaseTypesAccordingToNamingRules(RefactoringContext context, NamingConventionService service, TypeDeclaration result)
 {
     if (service.HasValidRule(result.Name, AffectedEntity.CustomAttributes, Modifiers.Public)) {
         result.BaseTypes.Add(context.CreateShortType("System", "Attribute"));
     } else if (service.HasValidRule(result.Name, AffectedEntity.CustomEventArgs, Modifiers.Public)) {
         result.BaseTypes.Add(context.CreateShortType("System", "EventArgs"));
     } else if (service.HasValidRule(result.Name, AffectedEntity.CustomExceptions, Modifiers.Public)) {
         result.BaseTypes.Add(context.CreateShortType("System", "Exception"));
     }
     return result;
 }
            public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration)
            {
                var typeResolveResult = ctx.Resolve(typeDeclaration);
                var newTypeParameters = typeResolveResult.Type.GetDefinition().TypeParameters;

                var oldTypeParameters = availableTypeParameters;
                availableTypeParameters = Concat(availableTypeParameters, newTypeParameters);

                base.VisitTypeDeclaration(typeDeclaration);

                availableTypeParameters = oldTypeParameters;
            }
		public override object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data)
		{
			// fix default visibility of inner classes
			if (currentTypeDeclaration != null && (typeDeclaration.Modifier & Modifiers.Visibility) == 0)
				typeDeclaration.Modifier |= Modifiers.Public;
			
			TypeDeclaration oldTypeDeclaration = currentTypeDeclaration;
			currentTypeDeclaration = typeDeclaration;
			base.VisitTypeDeclaration(typeDeclaration, data);
			currentTypeDeclaration = oldTypeDeclaration;
			return null;
		}
            public override object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data)
            {
                if (typeDeclaration.ClassType == ClassType.Enum)
                {
                    if (typeDeclaration.Children.Count() > 10)
                    {
                        UnlockWith(typeDeclaration);
                    }
                }

                return base.VisitTypeDeclaration(typeDeclaration, data);
            }
Example #25
0
        private void handle(TypeDeclaration type, DirectoryInfo projectFolder)
        {
            if (type.ClassType != ClassType.Enum)
                return;

            Dictionary<String, String> textDict = new Dictionary<string, string>();
            foreach (AttributeSection attribute in type.Attributes)
            {
                String attributeText = attribute.ToString();
                Match attributeNameMatch = getAttrubuteNameRegex.Match(attribute.ToString());

                Group attributeNameGroup = attributeNameMatch.Groups["name"];
                if (!attributeNameGroup.Success || attributeNameGroup.Value != "TextResource")
                    continue;

                foreach (Match match in regex.Matches(type.ToString()))
                {
                    Group keyGroup = match.Groups["key"];
                    Group valueGroup = match.Groups["value"];
                    if (!keyGroup.Success || !valueGroup.Success)
                        continue;
                    String key = keyGroup.Value.Trim();
                    String value = valueGroup.Value.Trim();
                    textDict.Add(key, value);
                }
            }
            if (textDict.Count == 0)
                return;

            TypeDeclaration currentType = type;
            String typeFullName = null;
            while (true)
            {
                if (typeFullName == null)
                    typeFullName = type.Name;
                else
                    typeFullName = String.Format("{0}+{1}", currentType.Name, typeFullName);
                if (currentType.Parent is TypeDeclaration)
                {
                    currentType = (TypeDeclaration)currentType.Parent;
                    continue;
                }
                else if (currentType.Parent is NamespaceDeclaration)
                {
                    NamespaceDeclaration namesp = (NamespaceDeclaration)currentType.Parent;
                    typeFullName = String.Format("{0}.{1}", namesp.FullName, typeFullName);
                    break;
                }
                else
                    throw new ApplicationException("Type's parent unknown!");
            }
            handle(typeFullName, textDict, projectFolder);
        }
            public override object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data)
            {
                if (typeDeclaration.ClassType == ClassType.Class)
                {
                    var iComparableMarker = typeDeclaration.BaseTypes.OfType<SimpleType>().FirstOrDefault(a => a.Identifier.EndsWith("IComparable"));
                    if (iComparableMarker != null)
                    {
                        UnlockWith(iComparableMarker);
                    }
                }

                return base.VisitTypeDeclaration(typeDeclaration, data);
            }
Example #27
0
		/// <summary>
		/// Dynamizes a given type.
		/// </summary>
		private TypeDeclaration Dynamize(TypeDeclaration type)
		{
			if (!Utility.IsDecoratedByAttribute(type, "PHP.Core.ImplementsType")) return null;

			TypeDeclaration out_type = new TypeDeclaration(type.Modifier, new List<AttributeSection>());
			out_type.Name = type.Name;

			AddSerializibility(type, out_type);
			FixInheritance(type, out_type);
			DynamizeMembers(type, out_type);

			return out_type;
		}
            public override object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data)
            {
                if (typeDeclaration.ClassType == ClassType.Class)
                {
                    var interfaceMarker = typeDeclaration.BaseTypes.OfType<MemberType>().FirstOrDefault();
                    if (interfaceMarker != null)
                    {
                        UnlockWith(interfaceMarker);
                    }
                }

                return base.VisitTypeDeclaration(typeDeclaration, data);
            }
			public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration)
			{
				foreach (var token_ in typeDeclaration.ModifierTokens) {
					var token = token_;
					if (token.Modifier == Modifiers.Internal) {
						AddIssue(token, ctx.TranslateString("Remove 'internal' modifier"), script => {
							int offset = script.GetCurrentOffset(token.StartLocation);
							int endOffset = script.GetCurrentOffset(token.GetNextNode().StartLocation);
							script.RemoveText(offset, endOffset - offset);
						});
					}
				}
			}
		public static MethodDeclaration CreateEventInvocator (RefactoringContext context, TypeDeclaration declaringType, EventDeclaration eventDeclaration, VariableInitializer initializer, IMethod invokeMethod, bool useExplictType)
		{
			bool hasSenderParam = false;
			IEnumerable<IParameter> pars = invokeMethod.Parameters;
			if (invokeMethod.Parameters.Any()) {
				var first = invokeMethod.Parameters [0];
				if (first.Name == "sender" /*&& first.Type == "System.Object"*/) {
					hasSenderParam = true;
					pars = invokeMethod.Parameters.Skip(1);
				}
			}
			const string handlerName = "handler";

			var arguments = new List<Expression>();
			if (hasSenderParam)
				arguments.Add(eventDeclaration.HasModifier (Modifiers.Static) ? (Expression)new PrimitiveExpression (null) : new ThisReferenceExpression());
			bool useThisMemberReference = false;
			foreach (var par in pars) {
				arguments.Add(new IdentifierExpression(par.Name));
				useThisMemberReference |= par.Name == initializer.Name;
			}
			var proposedHandlerName = GetNameProposal(initializer);
			var modifiers = eventDeclaration.HasModifier(Modifiers.Static) ? Modifiers.Static : Modifiers.Protected | Modifiers.Virtual;
			if (declaringType.HasModifier (Modifiers.Sealed)) {
				modifiers = Modifiers.None;
			}
			var methodDeclaration = new MethodDeclaration {
				Name = proposedHandlerName,
				ReturnType = new PrimitiveType ("void"),
				Modifiers = modifiers,
				Body = new BlockStatement {
					new VariableDeclarationStatement (
						useExplictType ? eventDeclaration.ReturnType.Clone () : new PrimitiveType ("var"), handlerName, 
						useThisMemberReference ? 
						(Expression)new MemberReferenceExpression (new ThisReferenceExpression (), initializer.Name) 
						: new IdentifierExpression (initializer.Name)
						),
					new IfElseStatement {
						Condition = new BinaryOperatorExpression (new IdentifierExpression (handlerName), BinaryOperatorType.InEquality, new PrimitiveExpression (null)),
						TrueStatement = new InvocationExpression (new IdentifierExpression (handlerName), arguments)
					}
				}
			};

			foreach (var par in pars) {
				var typeName = context.CreateShortType(par.Type);
				var decl = new ParameterDeclaration(typeName, par.Name);
				methodDeclaration.Parameters.Add(decl);
			}
			return methodDeclaration;
		}
Example #31
0
        /// <summary>
        /// Changes the base types of a type declaration.
        /// </summary>
        /// <param name="type">The type declaration to modify.</param>
        /// <param name="baseTypes">The new base types.</param>
        public void ChangeBaseTypes(TypeDeclaration type, IEnumerable <AstType> baseTypes)
        {
            var dummyType = new TypeDeclaration();

            dummyType.BaseTypes.AddRange(baseTypes);

            int offset;
            int endOffset;
            var sb = new StringBuilder();

            if (type.BaseTypes.Any())
            {
                offset    = GetCurrentOffset(type.ColonToken.StartLocation);
                endOffset = GetCurrentOffset(type.BaseTypes.Last().EndLocation);
            }
            else
            {
                sb.Append(' ');
                if (type.TypeParameters.Any())
                {
                    offset = endOffset = GetCurrentOffset(type.RChevronToken.EndLocation);
                }
                else
                {
                    offset = endOffset = GetCurrentOffset(type.NameToken.EndLocation);
                }
            }

            if (dummyType.BaseTypes.Any())
            {
                sb.Append(": ");
                sb.Append(string.Join(", ", dummyType.BaseTypes));
            }

            Replace(offset, endOffset - offset, sb.ToString());
            FormatText(type);
        }
Example #32
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,
            };

            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);
        }
Example #33
0
        public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration)
        {
            if (!typeDeclaration.HasModifier(Modifiers.Public))
            {
                base.VisitTypeDeclaration(typeDeclaration);
                return;
            }

            var parent = typeDeclaration.GetParent <TypeDeclaration>();

            if (parent != null && typeDeclaration.HasModifier(Modifiers.Public))
            {
                this.Results.Issues.Add(new LintIssue(typeDeclaration)
                {
                    Index      = LintIssueIndex.PublicNestedClassDefined,
                    Parameters = new[]
                    {
                        typeDeclaration.Name
                    }
                });
            }

            base.VisitTypeDeclaration(typeDeclaration);
        }
        private void AddGetSet(PropertyDeclaration propertyDeclaration, MethodDeclaration accessorMethod, IList fields)
        {
            BlockStatement  block;
            string          fieldName       = accessorMethod.Name.Substring(3);
            TypeDeclaration typeDeclaration = (TypeDeclaration)accessorMethod.Parent;

            if (IsInterface(typeDeclaration) || (IsAbstractClass(typeDeclaration) && !HasField(fields, fieldName) && accessorMethod.Body == BlockStatement.Null))
            {
                block = BlockStatement.Null;
            }
            else
            {
                block = new BlockStatement();
                block.Children.AddRange(accessorMethod.Body.Children);
            }
            if (accessorMethod.Name.StartsWith("get"))
            {
                propertyDeclaration.GetRegion = new PropertyGetRegion(block, null);
            }
            else if (accessorMethod.Name.StartsWith("set"))
            {
                propertyDeclaration.SetRegion = new PropertySetRegion(block, null);
            }
        }
Example #35
0
        InterfaceRenderInformation renderInterface(TypeDeclaration interfaceDecl)
        {
            var ret = new InterfaceRenderInformation();

            ret.isRoutableViewModel = interfaceDecl.BaseTypes
                                      .OfType <SimpleType>()
                                      .Any(x => x.Identifier == "IRoutableViewModel") ? ret : null;

            ret.definition    = "public " + chompedString(interfaceDecl.ToString().Replace("[Once]", ""));
            ret.interfaceName = chompedString(interfaceDecl.Name);
            ret.implClassName = ret.interfaceName.Substring(1); // Skip the 'I'

            ret.properties = interfaceDecl.Children
                             .Where(x => x is PropertyDeclaration || x is MethodDeclaration)
                             .Select(renderPropertyDeclaration)
                             .ToArray();

            ret.onceProperties = ret.properties
                                 .Where(x => x.onceProp != null)
                                 .Select(x => x.onceProp)
                                 .ToArray();

            return(ret);
        }
Example #36
0
 public void ConvertAsEnum(TypeDeclaration @enum)
 {
     Result.Append($"[External{(@enum.IsStringLiteralEnum ? ", Enum(Emit.StringNamePreserveCase)" : "")}]");
     WriteNewLine();
     Result.Append($"public enum {@enum.name}");
     WriteNewLine();
     Result.Append('{');
     Indent++;
     foreach (var value in @enum.fields)
     {
         WriteNewLine();
         if (value.UsesNameAttribute)
         {
             UseNameAttribute(value.orgName);
         }
         Result.Append(value.name);
         Result.Append(',');
     }
     Indent--;
     WriteNewLine();
     Result.Append('}');
     WriteNewLine();
     WriteNewLine();
 }
Example #37
0
        private void CreateInterfaceFieldsClass(TypeDeclaration typeDeclaration)
        {
            List <INode> fields = AstUtil.GetChildrenWithType(typeDeclaration, typeof(FieldDeclaration));

            if (fields.Count > 0)
            {
                TypeDeclaration fieldsClass = new TypeDeclaration(Modifiers.Public, null);
                fieldsClass.Type = ClassType.Class;
                fieldsClass.Name = typeDeclaration.Name + fieldsClassSuffix;
                fieldsClass.Children.AddRange(fields);
                fieldsClass.Parent = typeDeclaration.Parent;
                ApplyModifiers(fields);

                NamespaceDeclaration nsDeclaration = (NamespaceDeclaration)AstUtil.GetParentOfType(typeDeclaration, typeof(NamespaceDeclaration));
                nsDeclaration.AddChild(fieldsClass);

                string fullName = GetFullName(fieldsClass);

                CodeBase.Types[fullName] = fieldsClass;
                string typeName = GetFullName(typeDeclaration);

                CodeBase.References[typeName] = fullName;
            }
        }
        public override object Visit(TypeDeclaration typeDeclaration, object data)
        {
            TypeDeclaration oldTypeDeclaration = currentTypeDeclaration;

            this.currentTypeDeclaration = typeDeclaration;
            CodeTypeDeclaration codeTypeDeclaration = new CodeTypeDeclaration(typeDeclaration.Name);

            codeTypeDeclaration.IsClass     = typeDeclaration.Type == ClassType.Class;
            codeTypeDeclaration.IsEnum      = typeDeclaration.Type == ClassType.Enum;
            codeTypeDeclaration.IsInterface = typeDeclaration.Type == ClassType.Interface;
            codeTypeDeclaration.IsStruct    = typeDeclaration.Type == ClassType.Struct;

            if (typeDeclaration.BaseTypes != null)
            {
                foreach (TypeReference typeRef in typeDeclaration.BaseTypes)
                {
                    codeTypeDeclaration.BaseTypes.Add(new CodeTypeReference(typeRef.Type));
                }
            }

            typeDeclarations.Push(codeTypeDeclaration);
            typeDeclaration.AcceptChildren(this, data);
            typeDeclarations.Pop();

            if (typeDeclarations.Count > 0)
            {
                typeDeclarations.Peek().Members.Add(codeTypeDeclaration);
            }
            else
            {
                namespaceDeclarations.Peek().Types.Add(codeTypeDeclaration);
            }
            currentTypeDeclaration = oldTypeDeclaration;

            return(null);
        }
Example #39
0
        private List <ParameterDeclarationExpression> GetBaseConstructorParameters(ObjectCreateExpression obc)
        {
            List <ParameterDeclarationExpression> result = new List <ParameterDeclarationExpression>();
            TypeDeclaration anonymousClass = obc.AnonymousClass;

            if (obc.Parameters.Count > 0)
            {
                TypeReference baseType     = (TypeReference)anonymousClass.BaseTypes[0];
                string        baseTypeName = GetFullName(baseType);
                if (CodeBase.Types.Contains(baseTypeName))
                {
                    TypeDeclaration baseTypeDeclaration = (TypeDeclaration)CodeBase.Types[baseTypeName];
                    IList           cons = AstUtil.GetChildrenWithType(baseTypeDeclaration, typeof(ConstructorDeclaration));
                    foreach (ConstructorDeclaration constructor in cons)
                    {
                        if (MatchArguments(constructor.Parameters, obc.Parameters))
                        {
                            result.AddRange(constructor.Parameters);
                        }
                    }
                }
            }
            return(result);
        }
Example #40
0
        internal static TypeNodeKind GetTypeKind(TypeDeclaration type)
        {
            if (type.IsInterface)
            {
                return(TypeNodeKind.Interface);
            }

            var baseType = type.BaseType;

            if (baseType != null)
            {
                var module = type.Module;

                if (baseType.Equals(module, "ValueType", "System", "mscorlib"))
                {
                    return(TypeNodeKind.ValueType);
                }

                if (baseType.Equals(module, "Enum", "System", "mscorlib"))
                {
                    return(TypeNodeKind.Enum);
                }

                if (baseType.Equals(module, "MulticastDelegate", "System", "mscorlib"))
                {
                    return(TypeNodeKind.Delegate);
                }

                if (baseType.Equals(module, "Delegate", "System", "mscorlib"))
                {
                    return(TypeNodeKind.Delegate);
                }
            }

            return(TypeNodeKind.Class);
        }
Example #41
0
        public void AttributesOnTypeParameter()
        {
            string          program = @"class Test<[A,B]C> {}";
            TypeDeclaration type    = ParseUtilCSharp.ParseGlobal <TypeDeclaration>(program);

            Assert.IsTrue(
                new TypeParameterDeclaration {
                Attributes =
                {
                    new AttributeSection  {
                        Attributes =
                        {
                            new Attribute {
                                Type = new SimpleType("A")
                            },
                            new Attribute {
                                Type = new SimpleType("B")
                            }
                        }
                    }
                },
                Name = "C"
            }.IsMatch(type.TypeParameters.Single()));
        }
Example #42
0
 private void VerifyDerivedMethod(TypeDeclaration typeDeclaration, InvocationExpression invocationExpression, object data)
 {
     if (typeDeclaration.BaseTypes.Count > 0)
     {
         TypeReference baseType = (TypeReference)typeDeclaration.BaseTypes[0];
         string        fullName = GetFullName(baseType);
         if (CodeBase.Mappings.Contains(fullName))
         {
             TypeMapping mapping = CodeBase.Mappings[fullName];
             if (mapping != null)
             {
                 ReplaceMember(invocationExpression, data, baseType);
             }
         }
         else if (CodeBase.Types.Contains(fullName))
         {
             TypeDeclaration baseTypeDeclaration = (TypeDeclaration)CodeBase.Types[fullName];
             if (baseTypeDeclaration.Type == ClassType.Class)
             {
                 VerifyDerivedMethod(baseTypeDeclaration, invocationExpression, data);
             }
         }
     }
 }
            public override void VisitTypeDeclaration(TypeDeclaration declaration)
            {
                var result   = ctx.Resolve(declaration) as TypeResolveResult;
                var baseType = result.Type.DirectBaseTypes.FirstOrDefault(t => !t.IsKnownType(KnownTypeCode.Object) && t.Kind != TypeKind.Interface);

                if (baseType != null)
                {
                    var baseConstructor = baseType.GetConstructors(c => c.Parameters.Count == 0).FirstOrDefault();
                    var memberLookup    = new MemberLookup(result.Type.GetDefinition(), ctx.Compilation.MainAssembly, false);

                    if (baseConstructor == null || !memberLookup.IsAccessible(baseConstructor, true))
                    {
                        var constructor = result.Type.GetConstructors(f => !f.IsSynthetic).FirstOrDefault();

                        if (constructor == null)
                        {
                            // If there are no constructors declared then the base constructor isn't being invoked
                            this.AddIssue(declaration, baseType);
                        }
                    }
                }

                base.VisitTypeDeclaration(declaration);
            }
Example #44
0
        private TypeReference GetInstanceType(string type, string method)
        {
            TypeReference declaringType = null;

            if (CodeBase.Types.Contains(type))
            {
                TypeDeclaration typeDeclaration = (TypeDeclaration)CodeBase.Types[type];
                declaringType = GetDeclaringType(typeDeclaration, method);
                if (declaringType == null && typeDeclaration.BaseTypes.Count > 0)
                {
                    declaringType = GetMethodType(method, typeDeclaration.BaseTypes);
                }
                if (declaringType == null)
                {
                    string obj = "java.lang.Object";
                    if (CodeBase.Types.Contains(obj))
                    {
                        typeDeclaration = (TypeDeclaration)CodeBase.Types[obj];
                    }
                    declaringType = GetDeclaringType(typeDeclaration, method);
                }
            }
            return(declaringType);
        }
Example #45
0
        private RestRoutesDescriptor GetRestRoutesDescriptor(TypeDeclaration typeDeclaration)
        {
            foreach (var attributeSection in typeDeclaration.Attributes)
            {
                foreach (var attribute in attributeSection.Attributes.Where(a => a.Name == "RestRoutes"))
                {
                    var restRoutesDescriptor = new RestRoutesDescriptor
                    {
                        Name       = ResolvePrimitiveValue(attribute.PositionalArguments[0]),
                        Collection = ResolvePrimitiveValue(attribute.PositionalArguments[1]),
                        Identifier = ResolvePrimitiveValue(attribute.PositionalArguments[2])
                    };

                    if (attribute.PositionalArguments.Count > 3)
                    {
                        restRoutesDescriptor.RestVerbResolverType = ResolveTypeOfValue(attribute.PositionalArguments[3]);
                    }

                    return(restRoutesDescriptor);
                }
            }

            return(null);
        }
        private void PrintType(TypeDeclaration type, bool ignoreEnclosingType, bool ignoreNamespace)
        {
            if (!ignoreEnclosingType)
            {
                var enclosingType = type.GetEnclosingType();
                if (enclosingType != null)
                {
                    PrintType(enclosingType, ignoreEnclosingType, ignoreNamespace);
                    _builder.Append(".");
                }
            }

            if (!ignoreNamespace)
            {
                if (!string.IsNullOrEmpty(type.Namespace))
                {
                    _builder.Append(type.Namespace);
                    _builder.Append(".");
                }
            }

            PrintTypeName(type.Name, type.GenericParameters.Count > 0);
            PrintGenericParameters(type.GenericParameters);
        }
Example #47
0
        /// <summary>
        /// 对类中的元素进行一定的排序
        /// </summary>
        /// <returns></returns>
        private static void SortClassMembers(TypeDeclaration classNode)
        {
            var     fields  = classNode.Descendants.OfType <FieldDeclaration>().ToArray();
            AstNode keyNode = fields.FirstOrDefault();

            foreach (var item in fields)
            {
                if (item != keyNode)
                {
                    classNode.Members.Remove(item);
                    classNode.InsertChildAfter(keyNode, item, Roles.TypeMemberRole);
                    keyNode = item;
                }
            }
            var InitComponentsNode = classNode.Descendants.OfType <MethodDeclaration>().Where(x => x.Name == initcomponentMethod).FirstOrDefault();
            var PropBindingsNode   = classNode.Descendants.OfType <MethodDeclaration>().Where(x => x.Name == propbindingsMethod).FirstOrDefault();

            classNode.Members.Remove(InitComponentsNode);
            classNode.InsertChildAfter(keyNode, InitComponentsNode, Roles.TypeMemberRole);
            keyNode = InitComponentsNode;

            classNode.Members.Remove(PropBindingsNode);
            classNode.InsertChildAfter(keyNode, PropBindingsNode, Roles.TypeMemberRole);
        }
        public static MethodDeclaration                 add_Method(this TypeDeclaration typeDeclaration, string methodName, Dictionary <string, object> invocationParameters, bool resolveInvocationParametersType, BlockStatement body)
        {
            var newMethod = new MethodDeclaration();

            newMethod.Body     = body;
            newMethod.Modifier = Modifiers.None | Modifiers.Public;
            newMethod.Name     = methodName;
            newMethod.setReturnType();
            if (invocationParameters != null)
            {
                foreach (var invocationParameter in invocationParameters)
                {
                    var resolvedType = (resolveInvocationParametersType && invocationParameter.Value != null && invocationParameter.Key != "returnData")
                                               ? invocationParameter.Value.typeFullName()
                                               : "dynamic";
                    //: "System.Object";
                    var parameterType = new TypeReference(resolvedType, true);
                    var parameter     = new ParameterDeclarationExpression(parameterType, invocationParameter.Key);
                    newMethod.Parameters.Add(parameter);
                }
            }
            typeDeclaration.AddChild(newMethod);
            return(newMethod);
        }
Example #49
0
        /// <summary>
        /// 获得type中的所有comment对象,注意这里的comment对象都是以行为单位的
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static List <Comment> GetAllComments(string content, TypeDeclaration type)
        {
            List <Comment> comments = new List <Comment>();

            using (IParser parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(content)))
            {
                parser.ParseMethodBodies = false;
                parser.Parse();

                List <ISpecial> currentSpecials = parser.Lexer.SpecialTracker.CurrentSpecials;
                foreach (ISpecial currentSpecial in currentSpecials)
                {
                    if (currentSpecial is Comment)
                    {
                        //确保找到的comment在给定的type范围之内
                        if (currentSpecial.StartPosition.Line > type.StartLocation.Line && currentSpecial.EndPosition.Line < type.EndLocation.Line)
                        {
                            comments.Add(currentSpecial as Comment);
                        }
                    }
                }
            }
            return(comments);
        }
Example #50
0
        /// <inheritdoc/>
        public override void VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration)
        {
            bool            isStatic = (constructorDeclaration.Modifiers & Modifiers.Static) != 0;
            TypeDeclaration type     = constructorDeclaration.Parent as TypeDeclaration;
            String          name     = null;

            if (type != null && type.Name != constructorDeclaration.Name)
            {
                name = type.NameToken.Name;
            }
            else
            {
                name = constructorDeclaration.NameToken.Name;
            }
            Formatter.AppendIndented(String.Empty);
            if (!isStatic)
            {
                IType type2 = constructorDeclaration.GetResolveResult().Type;
                WriteMethodHeader(name, constructorDeclaration.Parameters);
                Formatter.AppendLine(";");
            }
            else
            {
                Formatter.Append("static Boolean ");
                Formatter.AppendName(name);
                Formatter.AppendLine("_Static();");
                Formatter.AppendIndented("static Boolean ");
                Formatter.AppendName(name);
                Formatter.AppendLine("_Initilized;");
            }
            HadConstructor = true;
            if (constructorDeclaration.Parameters.Count == 0)
            {
                HadDefaultConstructor = true;
            }
        }
            public override void VisitTypeDeclaration(TypeDeclaration declaration)
            {
                IType outerType     = currentType;
                IType outerBaseType = baseType;

                var result = ctx.Resolve(declaration) as TypeResolveResult;

                currentType = result != null ? result.Type : SpecialType.UnknownType;
                baseType    = currentType.DirectBaseTypes.FirstOrDefault(t => t.Kind != TypeKind.Interface) ?? SpecialType.UnknownType;

                base.VisitTypeDeclaration(declaration);

                if (currentType.Kind == TypeKind.Class && currentType.GetConstructors().All(ctor => ctor.IsSynthetic))
                {
                    // current type only has the compiler-provided default ctor
                    if (!BaseTypeHasUsableParameterlessConstructor())
                    {
                        AddIssue(new CodeIssue(declaration.NameToken, GetIssueText(baseType)));
                    }
                }

                currentType = outerType;
                baseType    = outerBaseType;
            }
Example #52
0
        protected bool Extends(TypeDeclaration typeDeclaration, TypeReference typeReference)
        {
            bool   extends      = false;
            string typeFullName = GetFullName(typeReference);

            foreach (TypeReference baseType in typeDeclaration.BaseTypes)
            {
                string baseTypeName = GetFullName(baseType);
                if (baseTypeName == typeFullName)
                {
                    return(true);
                }
                else if (CodeBase.Types.Contains(baseTypeName))
                {
                    TypeDeclaration baseTypeDeclaration = (TypeDeclaration)CodeBase.Types[baseTypeName];
                    extends = Extends(baseTypeDeclaration, typeReference);
                    if (extends)
                    {
                        return(extends);
                    }
                }
            }
            return(extends);
        }
        public void InterfaceSetterGetter()
        {
            string program  = TestUtil.GetInput();
            string expected = TestUtil.GetExpected();

            CompilationUnit      cu  = TestUtil.ParseProgram(program);
            NamespaceDeclaration ns  = (NamespaceDeclaration)cu.Children[0];
            TypeDeclaration      ty1 = (TypeDeclaration)ns.Children[0];
            TypeDeclaration      ty2 = (TypeDeclaration)ns.Children[1];
            TypeDeclaration      ty3 = (TypeDeclaration)ns.Children[2];

            CodeBase.Types.Add("Test.IShape", ty1);
            CodeBase.Types.Add("Test.Shape", ty2);
            CodeBase.Types.Add("Test.Rectangle", ty3);

            InheritorsVisitor inheritorsVisitor = new InheritorsVisitor();

            inheritorsVisitor.CodeBase = CodeBase;
            inheritorsVisitor.VisitCompilationUnit(cu, null);
            VisitCompilationUnit(cu, null);

            TestUtil.CodeEqual(expected, TestUtil.GenerateCode(cu));
            Assert.AreEqual(6, CodeBase.References.Count);
        }
Example #54
0
 public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration)
 {
     if (firstClassStartLine == -1)
     {
         firstClassStartLine = typeDeclaration.StartLocation.Line;
     }
     if (typeDeclaration.ClassType == ClassType.Class)
     {
         declarations.Add(new Declaration(typeDeclaration, "class"));
     }
     else if (typeDeclaration.ClassType == ClassType.Struct)
     {
         declarations.Add(new Declaration(typeDeclaration, "struct"));
     }
     else if (typeDeclaration.ClassType == ClassType.Interface)
     {
         declarations.Add(new Declaration(typeDeclaration, "interface"));
     }
     else if (typeDeclaration.ClassType == ClassType.Enum)
     {
         declarations.Add(new Declaration(typeDeclaration, "enum"));
     }
     base.VisitTypeDeclaration(typeDeclaration);
 }
        public static string GetExampleInvocation(this MethodDeclaration method)
        {
            if (method == null)
            {
                throw new ArgumentNullException("method");
            }

            StringBuilder builder = new StringBuilder();

            AstNode entity            = method;
            NamespaceDeclaration ns   = null;
            TypeDeclaration      type = null;

            while (ns == null)
            {
                if (entity.Parent == null)
                {
                    break;
                }

                entity = entity.Parent;

                if (type == null)
                {
                    type = entity as TypeDeclaration;
                }

                ns = entity as NamespaceDeclaration;
            }

            if (type == null)
            {
                return(null);
            }

            if (!method.Modifiers.HasFlag(Modifiers.Static))
            {
                builder.Append("var obj = new ");

                if (ns != null)
                {
                    builder.Append(ns.FullName);
                    builder.Append(".");
                }

                builder.Append(type.Name);
                builder.AppendLine(" ();");

                builder.Append("obj.");
            }
            else
            {
                if (ns != null)
                {
                    builder.Append(ns.FullName);
                    builder.Append(".");
                }

                builder.Append(type.Name);
                builder.Append(".");
            }

            builder.Append(method.Name);
            builder.Append(" (");

            BuildParameters(method.Parameters, builder);

            builder.Append(");");

            return(builder.ToString());
        }
Example #56
0
 public TypeReference GetType(Expression ex, INode parent)
 {
     if (ex is IdentifierExpression)
     {
         return(GetIdentifierType(ex, parent));
     }
     else if (ex is FieldReferenceExpression)
     {
         FieldReferenceExpression fieldReference = (FieldReferenceExpression)ex;
         Expression    targetObject = fieldReference.TargetObject;
         TypeReference targetType   = GetType(targetObject);
         if (targetType != null)
         {
             string fullName = TypeResolver.GetFullName(targetType);
             if (targetType.RankSpecifier != null && targetType.RankSpecifier.Length > 0 && !(ex.Parent is IndexerExpression))
             {
                 fullName = "JavaArray";
             }
             if (CodeBase.Types.Contains(fullName))
             {
                 TypeDeclaration typeDeclaration = (TypeDeclaration)CodeBase.Types[fullName];
                 if (typeDeclaration.Type == ClassType.Enum)
                 {
                     return(AstUtil.GetTypeReference(typeDeclaration.Name, ex.Parent));
                 }
                 else
                 {
                     return(GetTypeInMembers(typeDeclaration, fieldReference.FieldName));
                 }
             }
         }
         return(null);
     }
     else if (ex is PrimitiveExpression)
     {
         return(GetConstantType((PrimitiveExpression)ex));
     }
     else if (ex is InvocationExpression)
     {
         return(GetType(((InvocationExpression)ex).TargetObject));
     }
     else if (ex is IndexerExpression)
     {
         return(GetType(((IndexerExpression)ex).TargetObject));
     }
     else if (ex is BinaryOperatorExpression)
     {
         return(GetType(((BinaryOperatorExpression)ex).Left));
     }
     else if (ex is ObjectCreateExpression)
     {
         return(((ObjectCreateExpression)ex).CreateType);
     }
     else if (ex is ThisReferenceExpression)
     {
         TypeDeclaration ty = (TypeDeclaration)AstUtil.GetParentOfType(ex, typeof(TypeDeclaration));
         return(AstUtil.GetTypeReference(ty.Name, ex.Parent));
     }
     else if (ex is CastExpression)
     {
         CastExpression cast = (CastExpression)ex;
         return(cast.CastTo);
     }
     else if (ex is ArrayCreateExpression)
     {
         return(((ArrayCreateExpression)ex).CreateType);
     }
     else if (ex is BaseReferenceExpression)
     {
         TypeDeclaration typeDeclaration = (TypeDeclaration)AstUtil.GetParentOfType(ex, typeof(TypeDeclaration));
         if (typeDeclaration.BaseTypes.Count > 0)
         {
             return((TypeReference)typeDeclaration.BaseTypes[0]);
         }
         else
         {
             return(AstUtil.GetTypeReference("System.Object", parent));
         }
     }
     else if (ex is ParenthesizedExpression)
     {
         return(GetType(((ParenthesizedExpression)ex).Expression));
     }
     else if (ex is TypeReferenceExpression)
     {
         return(((TypeReferenceExpression)ex).TypeReference);
     }
     else if (ex is AssignmentExpression)
     {
         return(GetType(((AssignmentExpression)ex).Left));
     }
     else if (ex is UnaryOperatorExpression)
     {
         return(GetType(((UnaryOperatorExpression)ex).Expression));
     }
     else if (ex is TypeOfExpression)
     {
         TypeReference typeReference = new TypeReference("java.lang.Class");
         typeReference.Parent = parent;
         return(typeReference);
     }
     else if (ex is TypeOfIsExpression)
     {
         return(GetType(((TypeOfIsExpression)ex).Expression));
     }
     else if (ex is ConditionalExpression)
     {
         return(GetType(((ConditionalExpression)ex).TrueExpression));
     }
     else if (ex is ParameterDeclarationExpression)
     {
         return(((ParameterDeclarationExpression)ex).TypeReference);
     }
     else if (ex == Expression.Null)
     {
         return(null);
     }
     else
     {
         throw new NotSupportedException(ex.GetType().Name);
     }
 }
Example #57
0
        protected TypeReference GetIdentifierType(Expression ex, INode parent)
        {
            string        identifier    = ((IdentifierExpression)ex).Identifier;
            TypeReference typeReference = null;
            INode         parentScope   = parent;

            while (parentScope != null)
            {
                if (parentScope is CastExpression)
                {
                    CastExpression castExpression = (CastExpression)parentScope;
                    if (castExpression.Expression is IdentifierExpression &&
                        ((IdentifierExpression)castExpression.Expression).Identifier == identifier)
                    {
                        return(castExpression.CastTo);
                    }
                }
                else if (parentScope is BlockStatement)
                {
                    typeReference = GetTypeInLocalVariables((BlockStatement)parentScope, identifier);
                    if (typeReference != null)
                    {
                        return(typeReference);
                    }
                }
                else if (parentScope is CatchClause)
                {
                    string catchVar = ((CatchClause)parentScope).VariableName;
                    if (catchVar == identifier)
                    {
                        return(((CatchClause)parentScope).TypeReference);
                    }
                }
                else if (parentScope is ForStatement)
                {
                    ForStatement forStatement = (ForStatement)parentScope;
                    if (forStatement.Initializers.Count > 0)
                    {
                        Statement variable = (Statement)forStatement.Initializers[0];
                        if (variable is LocalVariableDeclaration)
                        {
                            LocalVariableDeclaration localVariable = (LocalVariableDeclaration)variable;
                            if (((VariableDeclaration)localVariable.Variables[0]).Name == identifier)
                            {
                                return(localVariable.TypeReference);
                            }
                        }
                    }
                }
                else if (parentScope is ForeachStatement ||
                         parentScope is MethodDeclaration ||
                         parentScope is ConstructorDeclaration ||
                         parentScope is TypeDeclaration)
                {
                    break;
                }
                parentScope = parentScope.Parent;
            }
            if (parentScope is ConstructorDeclaration || parentScope is MethodDeclaration)
            {
                BlockStatement body = GetBody(parentScope);
                List <ParameterDeclarationExpression> parameters = ((ParametrizedNode)parentScope).Parameters;
                TypeDeclaration typeDeclaration = AstUtil.GetParentOfType(parentScope, typeof(TypeDeclaration)) as TypeDeclaration;
                typeReference = GetTypeInLocalVariables(body, identifier);

                if (typeReference == null)
                {
                    typeReference = GetTypeInArguments(parameters, identifier);
                }
                if (typeReference == null)
                {
                    typeReference = GetTypeInMembers(typeDeclaration, identifier);
                }
                if (typeReference == null)
                {
                    typeReference = GetStaticClassType(identifier, ex.Parent);
                }
            }
            else if (parentScope is TypeDeclaration)
            {
                typeReference = GetTypeInMembers((TypeDeclaration)parentScope, identifier);
                if (typeReference == null)
                {
                    typeReference = GetStaticClassType(identifier, ex.Parent);
                }
            }
            else if (parentScope is ForeachStatement)
            {
                string        foreachVarName      = ((ForeachStatement)parentScope).VariableName;
                TypeReference foreachVariableType = ((ForeachStatement)parentScope).TypeReference;
                if (identifier == foreachVarName)
                {
                    return(foreachVariableType);
                }
                else
                {
                    typeReference = GetType(ex, parentScope.Parent);
                }
            }
            if (typeReference != null && typeReference.Parent == null)
            {
                typeReference.Parent = parent;
            }
            return(typeReference);
        }
Example #58
0
 public override void Exit(TypeDeclaration typeDeclaration)
 {
     currentTypeName = null;
 }
        EntityDeclaration ConvertTypeDefinition(ITypeDefinition typeDefinition)
        {
            Modifiers modifiers = Modifiers.None;

            if (this.ShowAccessibility)
            {
                modifiers |= ModifierFromAccessibility(typeDefinition.Accessibility);
            }
            if (this.ShowModifiers)
            {
                if (typeDefinition.IsStatic)
                {
                    modifiers |= Modifiers.Static;
                }
                else if (typeDefinition.IsAbstract)
                {
                    modifiers |= Modifiers.Abstract;
                }
                else if (typeDefinition.IsSealed)
                {
                    modifiers |= Modifiers.Sealed;
                }
                if (typeDefinition.IsShadowing)
                {
                    modifiers |= Modifiers.New;
                }
            }

            ClassType classType;

            switch (typeDefinition.Kind)
            {
            case TypeKind.Struct:
                classType  = ClassType.Struct;
                modifiers &= ~Modifiers.Sealed;
                break;

            case TypeKind.Enum:
                classType  = ClassType.Enum;
                modifiers &= ~Modifiers.Sealed;
                break;

            case TypeKind.Interface:
                classType  = ClassType.Interface;
                modifiers &= ~Modifiers.Abstract;
                break;

            case TypeKind.Delegate:
                IMethod invoke = typeDefinition.GetDelegateInvokeMethod();
                if (invoke != null)
                {
                    return(ConvertDelegate(invoke, modifiers));
                }
                else
                {
                    goto default;
                }

            default:
                classType = ClassType.Class;
                break;
            }

            var decl = new TypeDeclaration();

            decl.ClassType = classType;
            decl.Modifiers = modifiers;
            decl.Name      = typeDefinition.Name;

            int outerTypeParameterCount = (typeDefinition.DeclaringTypeDefinition == null) ? 0 : typeDefinition.DeclaringTypeDefinition.TypeParameterCount;

            if (this.ShowTypeParameters)
            {
                foreach (ITypeParameter tp in typeDefinition.TypeParameters.Skip(outerTypeParameterCount))
                {
                    decl.TypeParameters.Add(ConvertTypeParameter(tp));
                }
            }

            if (this.ShowBaseTypes)
            {
                foreach (IType baseType in typeDefinition.DirectBaseTypes)
                {
                    decl.BaseTypes.Add(ConvertType(baseType));
                }
            }

            if (this.ShowTypeParameters && this.ShowTypeParameterConstraints)
            {
                foreach (ITypeParameter tp in typeDefinition.TypeParameters)
                {
                    var constraint = ConvertTypeParameterConstraint(tp);
                    if (constraint != null)
                    {
                        decl.Constraints.Add(constraint);
                    }
                }
            }
            return(decl);
        }
 public override object VisitTypeDeclaration(TypeDeclaration declaration, object data)
 {
     MakePublic(declaration);
     return(base.VisitTypeDeclaration(declaration, data));
 }