/// <summary> /// Gets whether this type definition is derived from the base type definition. /// </summary> public static bool IsDerivedFrom(this ITypeDefinition type, ITypeDefinition baseType) { if (type.Compilation != baseType.Compilation) { throw new InvalidOperationException("Both arguments to IsDerivedFrom() must be from the same compilation."); } return type.GetAllBaseTypeDefinitions().Contains(baseType); }
public static void AddAttribute(ITypeDefinition cls, string name, params object[] parameters) { bool isOpen; string fileName = cls.Region.FileName; var buffer = TextFileProvider.Instance.GetTextEditorData (fileName, out isOpen); var attr = new CodeAttributeDeclaration (name); foreach (var parameter in parameters) { attr.Arguments.Add (new CodeAttributeArgument (new CodePrimitiveExpression (parameter))); } var type = new CodeTypeDeclaration ("temp"); type.CustomAttributes.Add (attr); Project project; if (!cls.TryGetSourceProject (out project)) { LoggingService.LogError ("Error can't get source project for:" + cls.FullName); } var provider = ((DotNetProject)project).LanguageBinding.GetCodeDomProvider (); var sw = new StringWriter (); provider.GenerateCodeFromType (type, sw, new CodeGeneratorOptions ()); string code = sw.ToString (); int start = code.IndexOf ('['); int end = code.LastIndexOf (']'); code = code.Substring (start, end - start + 1) + Environment.NewLine; int pos = buffer.LocationToOffset (cls.Region.BeginLine, cls.Region.BeginColumn); code = buffer.GetLineIndent (cls.Region.BeginLine) + code; buffer.Insert (pos, code); if (!isOpen) { File.WriteAllText (fileName, buffer.Text); buffer.Dispose (); } }
/// <summary> /// Creates the <see cref="Table"/> from the descriptor. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> /// <param name="type">The <see cref="ITypeDefinition"/>.</param> /// <returns>Returns the created <see cref="Table"/>.</returns> /// <exception cref="ArgumentNullException">Thrown if one of the parameters is null.</exception> public Table Create(IMansionContext context, ITypeDefinition type) { // validate arguments if (context == null) throw new ArgumentNullException("context"); if (type == null) throw new ArgumentNullException("type"); // invoke template method var table = DoCreate(context, type); // create the columns for this table foreach (var property in type.Properties) { ColumnDescriptor columnDescriptor; if (!property.TryGetDescriptor(out columnDescriptor)) continue; // add the column to the table table.Add(columnDescriptor.Create(context, table, property)); } // return the created table return table; }
protected override ITest CreateTestClass(ITypeDefinition typeDefinition) { if (NUnitTestFramework.IsTestClass(typeDefinition)) return new NUnitTestClass(this, typeDefinition.FullTypeName); else return null; }
protected override string GenerateCode(ITypeDefinition currentClass) { // string[] fields = listBox.SelectedItems.OfType<PropertyOrFieldWrapper>().Select(f2 => f2.MemberName).ToArray(); string[] fields = parameterList.Where(f => f.IsIncluded).Select(f2 => f2.MemberName).ToArray(); PrimitiveExpression formatString = new PrimitiveExpression(GenerateFormatString(currentClass, editor.Language.CodeGenerator, fields)); List<Expression> param = new List<Expression>() { formatString }; ReturnStatement ret = new ReturnStatement(new InvocationExpression( new MemberReferenceExpression(new TypeReferenceExpression(ConvertType(KnownTypeCode.String)), "Format"), param.Concat(fields.Select(f => new IdentifierExpression(f))).ToList() )); if (baseCallNode != null) { MethodDeclaration insertedOverrideMethod = refactoringContext.GetNode().PrevSibling as MethodDeclaration; if (insertedOverrideMethod == null) { // We are not inside of a method declaration return null; } using (Script script = refactoringContext.StartScript()) { NewLineNode nextNewLineNode = insertedOverrideMethod.NextSibling as NewLineNode; // Find base method call and replace it by return statement script.AddTo(insertedOverrideMethod.Body, ret); AppendNewLine(script, insertedOverrideMethod, nextNewLineNode); } } return null; }
private SimpleTypeResolveContext(ICompilation compilation, IAssembly currentAssembly, ITypeDefinition currentTypeDefinition, IMember currentMember) { this.compilation = compilation; this.currentAssembly = currentAssembly; this.currentTypeDefinition = currentTypeDefinition; this.currentMember = currentMember; }
CodeType CreateCodeTypeForTypeDefinition(ITypeDefinition typeDefinition) { if (typeDefinition.Kind == TypeKind.Interface) { return new CodeInterface(context, typeDefinition); } return new CodeClass2(context, typeDefinition); }
private void WriteBaseConstructorCall(ITypeDefinition type) { if (!_forCompilation) return; ITypeDefinition baseType = type.BaseClasses.FirstOrDefault().GetDefinitionOrNull(); if (baseType == null) return; var ctors = baseType.Methods.Where(m => m.IsConstructor && _filter.Include(m)); var defaultCtor = ctors.Where(c => c.ParameterCount == 0); // Don't need a base call if we have a default constructor if (defaultCtor.Any()) return; var ctor = ctors.FirstOrDefault(); if (ctor == null) return; WriteSpace(); WriteSymbol(":", true); WriteKeyword("base"); WriteSymbol("("); _writer.WriteList(ctor.Parameters, p => WriteDefaultOf(p.Type)); WriteSymbol(")"); }
public OverrideEqualsGetHashCodeMethodsDialog(InsertionContext context, ITextEditor editor, ITextAnchor endAnchor, ITextAnchor insertionPosition, ITypeDefinition selectedClass, IMethod selectedMethod, AstNode baseCallNode) : base(context, editor, insertionPosition) { if (selectedClass == null) throw new ArgumentNullException("selectedClass"); InitializeComponent(); this.selectedClass = selectedClass; this.insertionEndAnchor = endAnchor; this.selectedMethod = selectedMethod; this.baseCallNode = baseCallNode; addIEquatable.Content = string.Format(StringParser.Parse("${res:AddIns.SharpRefactoring.OverrideEqualsGetHashCodeMethods.AddInterface}"), "IEquatable<" + selectedClass.Name + ">"); string otherMethod = selectedMethod.Name == "Equals" ? "GetHashCode" : "Equals"; addOtherMethod.Content = StringParser.Parse("${res:AddIns.SharpRefactoring.OverrideEqualsGetHashCodeMethods.AddOtherMethod}", new StringTagPair("otherMethod", otherMethod)); addIEquatable.IsEnabled = !selectedClass.GetAllBaseTypes().Any( type => { if (!type.IsParameterized || (type.TypeParameterCount != 1)) return false; if (type.FullName != "System.IEquatable") return false; return type.TypeArguments.First().FullName == selectedClass.FullName; } ); }
static AnonymousMethodExpression GetAnonymousMethodExpression (RefactoringContext context, out ITypeDefinition delegateType) { delegateType = null; var anonymousMethodExpression = context.GetNode<AnonymousMethodExpression> (); if (anonymousMethodExpression == null || !anonymousMethodExpression.DelegateToken.Contains (context.Location.Line, context.Location.Column) || anonymousMethodExpression.HasParameterList) return null; AstType resolvedType = null; var parent = anonymousMethodExpression.Parent; if (parent is AssignmentExpression) { resolvedType = context.ResolveType (((AssignmentExpression)parent).Left); } else if (parent is VariableDeclarationStatement) { resolvedType = context.ResolveType (((VariableDeclarationStatement)parent).Type); } else if (parent is InvocationExpression) { // TODO: handle invocations } if (resolvedType == null) return null; delegateType = context.GetDefinition (resolvedType); if (delegateType == null || delegateType.ClassType != ClassType.Delegate) return null; return anonymousMethodExpression; }
private JsClass GetJsClass(ITypeDefinition typeDefinition) { JsClass result; if (!_types.TryGetValue(typeDefinition, out result)) { var semantics = _metadataImporter.GetTypeSemantics(typeDefinition); if (semantics.GenerateCode) { var errors = Utils.FindTypeUsageErrors(typeDefinition.GetAllBaseTypes(), _metadataImporter); if (errors.HasErrors) { var oldRegion = _errorReporter.Region; try { _errorReporter.Region = typeDefinition.Region; foreach (var ut in errors.UsedUnusableTypes) _errorReporter.Message(Messages._7500, ut.FullName, typeDefinition.FullName); foreach (var t in errors.MutableValueTypesBoundToTypeArguments) _errorReporter.Message(Messages._7539, t.FullName); } finally { _errorReporter.Region = oldRegion; } } result = new JsClass(typeDefinition); } else { result = null; } _types[typeDefinition] = result; } return result; }
private MinimalResolveContext() { List<ITypeDefinition> types = new List<ITypeDefinition>(); types.Add(systemObject = new DefaultTypeDefinition(this, "System", "Object") { Accessibility = Accessibility.Public }); types.Add(systemValueType = new DefaultTypeDefinition(this, "System", "ValueType") { Accessibility = Accessibility.Public, BaseTypes = { systemObject } }); types.Add(CreateStruct("System", "Boolean")); types.Add(CreateStruct("System", "SByte")); types.Add(CreateStruct("System", "Byte")); types.Add(CreateStruct("System", "Int16")); types.Add(CreateStruct("System", "UInt16")); types.Add(CreateStruct("System", "Int32")); types.Add(CreateStruct("System", "UInt32")); types.Add(CreateStruct("System", "Int64")); types.Add(CreateStruct("System", "UInt64")); types.Add(CreateStruct("System", "Single")); types.Add(CreateStruct("System", "Double")); types.Add(CreateStruct("System", "Decimal")); types.Add(new DefaultTypeDefinition(this, "System", "String") { Accessibility = Accessibility.Public, BaseTypes = { systemObject } }); types.Add(new VoidTypeDefinition(this)); foreach (ITypeDefinition type in types) type.Freeze(); this.types = types.AsReadOnly(); }
public bool IsForwardable(ITypeDefinition type) { INestedTypeDefinition nestedType = type as INestedTypeDefinition; if (nestedType != null) return false; return true; }
protected override ITest CreateTestClass(ITypeDefinition typeDefinition) { if (IsTestClass(typeDefinition)) { return new MSTestClass(this, typeDefinition.FullTypeName); } return null; }
void Init(string program) { var pc = new CSharpProjectContent().AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib }); var syntaxTree = SyntaxTree.Parse(program, "program.cs"); compilation = pc.AddOrUpdateFiles(syntaxTree.ToTypeSystem()).CreateCompilation(); typeDefinition = compilation.MainAssembly.TopLevelTypeDefinitions.FirstOrDefault(); }
string TypeToString(ITypeReference type, ITypeDefinition currentTypeDef = null) { var builder = CreateBuilder(currentTypeDef); IType resolvedType = type.Resolve(ctx); AstType node = builder.ConvertType(resolvedType); return node.ToString(); }
public override DifferenceType Diff(IDifferences differences, ITypeDefinition impl, ITypeDefinition contract) { if (impl == null || contract == null) return DifferenceType.Unknown; return DiffConstraints(differences, impl, impl.GenericParameters, contract.GenericParameters); }
public CodeType(CodeModelContext context, ITypeDefinition typeDefinition, params IType[] typeArguments) : base(context, typeDefinition) { this.typeDefinition = typeDefinition; this.typeArguments = typeArguments; this.InfoLocation = GetInfoLocation(); }
static IEnumerable<ISymbol> CollectTypeRelatedMembers (ITypeDefinition type) { yield return type; foreach (var c in type.GetDefinition ().GetMembers (m => !m.IsSynthetic && (m.SymbolKind == SymbolKind.Constructor || m.SymbolKind == SymbolKind.Destructor), GetMemberOptions.IgnoreInheritedMembers)) { yield return c; } }
static List<AbstractColumn> CreateItemsSource(ITypeDefinition typeDefinitions) { return typeDefinitions.Properties.Select(p => new AbstractColumn(){ ColumnName = p.Name, DataTypeName = p.ReturnType.ReflectionName }).ToList(); }
protected virtual JsNode _Visit(ITypeDefinition ce) { if (CompilerConfiguration.Current.EnableLogging) { Log.Debug("JsTypeImporter: Visit Type: " + ce.ToString()); } JsNode node; if (ce.Kind == TypeKind.Class) { node = _VisitClass(ce); } else if (ce.Kind == TypeKind.Interface) { node = _VisitInterface(ce); } else if (ce.Kind == TypeKind.Delegate) { node = _VisitDelegate(ce); } else if (ce.Kind == TypeKind.Struct) { node = _VisitStruct(ce); } else if (ce.Kind == TypeKind.Enum) { node = _VisitEnum(ce); } else { throw new NotImplementedException(); } return node; }
public bool Include(ITypeDefinition type) { string typeId = type.DocId(); // include so long as it isn't in the exclude list. return !_docIds.Contains(typeId); }
private bool AddedBaseType(IDifferences differences, ITypeDefinition impl, ITypeDefinition contract) { // For interfaces we rely only on the AddedInterface check if (impl.IsInterface || contract.IsInterface) return false; // Base types must be in the same order so we have to compare them in order List<ITypeReference> implBaseTypes = new List<ITypeReference>(impl.GetAllBaseTypes()); int lastIndex = 0; foreach (var contractBaseType in contract.GetAllBaseTypes()) { lastIndex = implBaseTypes.FindIndex(lastIndex, item1BaseType => _typeComparer.Equals(item1BaseType, contractBaseType)); if (lastIndex < 0) { differences.AddIncompatibleDifference(this, "Type '{0}' does not inherit from base type '{1}' in the implementation but it does in the contract.", contract.FullName(), contractBaseType.FullName()); return true; } } return false; }
public static ITypeReference Unspecialize(ITypeDefinition type) { var sntd = type as ISpecializedNestedTypeDefinition; if (sntd != null) return sntd.UnspecializedVersion; var gti = type as IGenericTypeInstance; if (gti != null) return gti.GenericType; return type; }
static void FindDerivedSymbols (ITypeDefinition cls, IMember member) { var solution = IdeApp.ProjectOperations.CurrentSelectedSolution; if (solution == null) return; var sourceProject = TypeSystemService.GetProject (cls); if (sourceProject == null) return; var compilations = ReferenceFinder.GetAllReferencingProjects (solution, sourceProject) .Select (TypeSystemService.GetCompilation).Where (c => c != null).ToList (); using (var monitor = IdeApp.Workbench.ProgressMonitors.GetSearchProgressMonitor (true, true)) { var label = member == null ? GettextCatalog.GetString ("Searching for derived classes in solution...") : GettextCatalog.GetString ("Searching for derived members in solution..."); monitor.BeginTask (label, compilations.Count); Parallel.ForEach (compilations, comp => { try { SearchCompilation (monitor, comp, cls, member); } catch (Exception ex) { LoggingService.LogInternalError (ex); monitor.ReportError ("Unhandled error while searching", ex); } monitor.Step (1); }); monitor.EndTask (); }; }
public virtual void PrintTypeDefinition(ITypeDefinition typeDefinition) { if (typeDefinition.IsDelegate) { PrintDelegateDefinition(typeDefinition); return; } if (((INamedEntity)typeDefinition).Name.Value.Contains("PrivateImplementationDetails")) return; PrintTypeDefinitionAttributes(typeDefinition); PrintToken(CSharpToken.Indent); PrintTypeDefinitionVisibility(typeDefinition); PrintTypeDefinitionModifiers(typeDefinition); PrintTypeDefinitionKeywordType(typeDefinition); PrintTypeDefinitionName(typeDefinition); if (typeDefinition.IsGeneric) { this.Traverse(typeDefinition.GenericParameters); } PrintTypeDefinitionBaseTypesAndInterfaces(typeDefinition); PrintTypeDefinitionLeftCurly(typeDefinition); // Get the members in metadata order for each type // Note that it's important to preserve the metadata order here (eg. sequential layout fields, // methods in COMImport types, etc.). var members = new List<ITypeDefinitionMember>(); foreach (var m in typeDefinition.Methods) members.Add(m); foreach (var m in typeDefinition.Events) members.Add(m); foreach (var m in typeDefinition.Properties) members.Add(m); foreach (var m in typeDefinition.Fields) members.Add(m); foreach (var m in typeDefinition.NestedTypes) members.Add(m); Traverse(members); PrintTypeDefinitionRightCurly(typeDefinition); }
public virtual void PrintDelegateDefinition(ITypeDefinition delegateDefinition) { PrintTypeDefinitionAttributes(delegateDefinition); PrintToken(CSharpToken.Indent); IMethodDefinition invokeMethod = null; foreach (var invokeMember in delegateDefinition.GetMatchingMembers(m => m.Name.Value == "Invoke")) { IMethodDefinition idef = invokeMember as IMethodDefinition; if (idef != null) { invokeMethod = idef; break; } } PrintTypeDefinitionVisibility(delegateDefinition); if (IsMethodUnsafe(invokeMethod)) PrintKeywordUnsafe(); PrintKeywordDelegate(); PrintMethodDefinitionReturnType(invokeMethod); PrintToken(CSharpToken.Space); PrintTypeDefinitionName(delegateDefinition); if (delegateDefinition.GenericParameterCount > 0) { this.Traverse(delegateDefinition.GenericParameters); } if (invokeMethod != null) Traverse(invokeMethod.Parameters); PrintToken(CSharpToken.Semicolon); }
public MixinsWeaverStrategy(ITypeDefinition typeDefinition, ITypeMapCollection mixinsMap, IEnumerable<IMethodWeaver> methodWeavers, INCopDependencyAwareRegistry registry) { this.registry = registry; this.mixinsMap = mixinsMap; this.methodWeavers = methodWeavers; this.typeDefinition = typeDefinition; }
public TsType Visit(ITypeDefinition ce) { var name = SkJs.GetEntityJsName(ce); var ce2 = new TsType { Name = name, Kind=(ce.IsInterface() || ce.IsDelegate()) ? TsTypeKind.Interface : TsTypeKind.Class, TypeParameters = ce.TypeParameters.Select(Visit).ToList() }; if (name.Contains(".")) { var pair = name.SplitAt(name.LastIndexOf("."), true); ce2.Name = pair[1]; ce2.ModuleName = pair[0]; ce2.IsModuleExport = true; } if (ce.IsDelegate()) { var func = Visit(ce.GetDelegateInvokeMethod()); //func.IsCallSignature = true; func.Name = null; ce2.Members.Add(func); } else { var members = TypeConverter.ClrConverter.GetMembersToExport(ce); var members2 = members.Select(Visit).Where(t => t != null).ToList(); ce2.Members.AddRange(members2); if (ce2.Kind == TsTypeKind.Class) { ce2.Members.OfType<TsFunction>().Where(t => !t.IsConstructor || !t.Type.IsNullOrVoid()).ForEach(t => t.Body = "return null;"); ce2.Members.OfType<TsFunction>().Where(t => t.IsConstructor).ForEach(t => t.Body = ""); } } return ce2; }
private JsClass GetJsClass(ITypeDefinition typeDefinition) { JsClass result; if (!_types.TryGetValue(typeDefinition, out result)) { if (typeDefinition.Kind == TypeKind.Struct && !_allowUserDefinedStructs) { var oldRegion = _errorReporter.Region; _errorReporter.Region = typeDefinition.Region; _errorReporter.Message(Messages._7998, "user-defined value type (struct)"); _errorReporter.Region = oldRegion; } var semantics = _metadataImporter.GetTypeSemantics(typeDefinition); if (semantics.GenerateCode) { var unusableTypes = Utils.FindUsedUnusableTypes(typeDefinition.GetAllBaseTypes(), _metadataImporter).ToList(); if (unusableTypes.Count > 0) { foreach (var ut in unusableTypes) { var oldRegion = _errorReporter.Region; _errorReporter.Region = typeDefinition.Region; _errorReporter.Message(Messages._7500, ut.FullName, typeDefinition.FullName); _errorReporter.Region = oldRegion; } } result = new JsClass(typeDefinition); } else { result = null; } _types[typeDefinition] = result; } return result; }
public string GetTypeName(ITypeDefinition type, TypeDefinition typeDefinition) { throw new NotImplementedException(); }
public void Methods() { string program = @" enum Color {} namespace Acme { struct ValueType { } class Widget: IProcess { public class NestedClass { public void M(int i) {} } public static void M0() {...} public void M1(char c, out float f, ref ValueType v) {...} public void M2(short[] x1, int[,] x2, long[][] x3) {...} public void M3(long[][] x3, Widget[][,,] x4) {...} public unsafe void M4(char *pc, Color **pf) {...} public unsafe void M5(void *pv, double *[][,] pd) {...} public void M6(int? i, params object[] args) {...} } class MyList<T> { public void Test(T t) { } } class UseList { public void Process(MyList<Color> list) { } public MyList<T> GetValues<T>(T inputValue) { return null; } } }"; Init(program); ITypeDefinition widget = GetTypeDefinition("Acme", "Widget"); Assert.AreEqual("M:Acme.Widget.NestedClass.M(System.Int32)", widget.NestedTypes.Single().Methods.Single(m => m.EntityType == EntityType.Method).Documentation); Assert.AreEqual("M:Acme.Widget.M0", widget.Methods.Single(m => m.Name == "M0").Documentation); Assert.AreEqual("M:Acme.Widget.M1(System.Char,System.Single@,Acme.ValueType@)", widget.Methods.Single(m => m.Name == "M1").Documentation); Assert.AreEqual("M:Acme.Widget.M2(System.Int16[],System.Int32[0:,0:],System.Int64[][])", widget.Methods.Single(m => m.Name == "M2").Documentation); Assert.AreEqual("M:Acme.Widget.M3(System.Int64[][],Acme.Widget[0:,0:,0:][])", widget.Methods.Single(m => m.Name == "M3").Documentation); Assert.AreEqual("M:Acme.Widget.M4(System.Char*,Color**)", widget.Methods.Single(m => m.Name == "M4").Documentation); Assert.AreEqual("M:Acme.Widget.M5(System.Void*,System.Double*[0:,0:][])", widget.Methods.Single(m => m.Name == "M5").Documentation); Assert.AreEqual("M:Acme.Widget.M6(System.Nullable{System.Int32},System.Object[])", widget.Methods.Single(m => m.Name == "M6").Documentation); Assert.AreEqual("M:Acme.MyList`1.Test(`0)", GetTypeDefinition("Acme", "MyList", 1).Methods.Single(m => m.Name == "Test").Documentation); Assert.AreEqual("M:Acme.UseList.Process(Acme.MyList{Color})", GetTypeDefinition("Acme", "UseList").Methods.Single(m => m.Name == "Process").Documentation); Assert.AreEqual("M:Acme.UseList.GetValues``1(``0)", GetTypeDefinition("Acme", "UseList").Methods.Single(m => m.Name == "GetValues").Documentation); }
public abstract CodeGeneratorMemberResult CreateMemberImplementation(ITypeDefinition implementingType, IUnresolvedTypeDefinition part, IMember member, bool explicitDeclaration);
public static List <KeyValuePair <IMember, bool> > CollectMembersToImplement(ITypeDefinition implementingType, IType interfaceType, bool explicitly) { var def = interfaceType.GetDefinition(); List <KeyValuePair <IMember, bool> > toImplement = new List <KeyValuePair <IMember, bool> > (); bool alreadyImplemented; // Stub out non-implemented events defined by @iface foreach (var ev in interfaceType.GetEvents(e => !e.IsSynthetic && e.DeclaringTypeDefinition.ReflectionName == def.ReflectionName)) { bool needsExplicitly = explicitly; alreadyImplemented = implementingType.GetAllBaseTypeDefinitions().Any(x => x.Kind != TypeKind.Interface && x.Events.Any(y => y.Name == ev.Name)); if (!alreadyImplemented) { toImplement.Add(new KeyValuePair <IMember, bool> (ev, needsExplicitly)); } } // Stub out non-implemented methods defined by @iface foreach (var method in interfaceType.GetMethods(d => !d.IsSynthetic && d.DeclaringTypeDefinition.ReflectionName == def.ReflectionName)) { bool needsExplicitly = explicitly; alreadyImplemented = false; foreach (var cmet in implementingType.GetMethods()) { if (CompareMethods(method, cmet)) { if (!needsExplicitly && !cmet.ReturnType.Equals(method.ReturnType)) { needsExplicitly = true; } else { alreadyImplemented |= !needsExplicitly /*|| cmet.InterfaceImplementations.Any (impl => impl.InterfaceType.Equals (interfaceType))*/; } } } if (!alreadyImplemented) { toImplement.Add(new KeyValuePair <IMember, bool> (method, needsExplicitly)); } } // Stub out non-implemented properties defined by @iface foreach (var prop in interfaceType.GetProperties(p => !p.IsSynthetic && p.DeclaringTypeDefinition.ReflectionName == def.ReflectionName)) { bool needsExplicitly = explicitly; alreadyImplemented = false; foreach (var t in implementingType.GetAllBaseTypeDefinitions()) { if (t.Kind == TypeKind.Interface) { continue; } foreach (IProperty cprop in t.Properties) { if (cprop.Name == prop.Name) { if (!needsExplicitly && !cprop.ReturnType.Equals(prop.ReturnType)) { needsExplicitly = true; } else { alreadyImplemented |= !needsExplicitly /* || cprop.InterfaceImplementations.Any (impl => impl.InterfaceType.Resolve (ctx).Equals (interfaceType))*/; } } } } if (!alreadyImplemented) { toImplement.Add(new KeyValuePair <IMember, bool> (prop, needsExplicitly)); } } return(toImplement); }
private IEnumerable <ITypeDefinition> SelfAndNested(ITypeDefinition def) { return(new[] { def }.Concat(def.NestedTypes.SelectMany(SelfAndNested))); }
public override string ToTypeName(IType type, ITypeDefinition typeDefinition, IPersistence persistence, bool fullName, bool forceNullable) { if (persistence != null && persistence.TypeDefined) { return(persistence.TypeName); } StringBuilder s = new StringBuilder(); // Oracle 10g data types // http://docs.oracle.com/cd/B19306_01/server.102/b14220/datatype.htm if (type is IScalarType) { BaseType bt = (type as IScalarType).BaseType; ITypeDefinition typeDef = typeDefinition != null ? typeDefinition : (type as IScalarType).TypeDefinition; switch (bt) { case BaseType.TypeBool: CheckNativeBoolean(type.Model.Lamp.Config.Layers.PersistenceConfig.BooleanValuePersistence); switch (type.Model.Lamp.Config.Layers.PersistenceConfig.BooleanValuePersistence) { case BooleanValuePersistence.YesNo: case BooleanValuePersistence.TrueFalse: s.Append("VARCHAR(1)"); break; } break; case BaseType.TypeAnsiChar: case BaseType.TypeChar: case BaseType.TypeAnsiString: case BaseType.TypeString: if (bt == BaseType.TypeString) { s.Append("N"); } if (typeDef.Fixed || typeDef.Length == 1) { s.Append("CHAR"); } else { s.Append("VARCHAR2"); } s.AppendFormat("({0})", typeDef.Length); break; case BaseType.TypeDate: s.Append("DATE"); break; case BaseType.TypeDateTime: s.Append("DATE"); break; case BaseType.TypeCurrency: case BaseType.TypeDecimal: if (typeDef.Precision > 0) { s.AppendFormat("NUMBER({0}, {1})", typeDef.Length, typeDef.Precision); } else { s.AppendFormat("NUMBER({0})", typeDef.Length); } break; case BaseType.TypeFloat: s.Append("BINARY_DOUBLE"); break; case BaseType.TypeInt: if (typeDef.Length == 8) { s.Append("NUMBER(19)"); } else if (typeDef.Length == 2) { s.Append("NUMBER(5)"); } else if (typeDef.Length == 1) { s.Append("NUMBER(3)"); } else { s.Append("NUMBER(10)"); } break; case BaseType.TypeByte: s.Append("CHAR(1)"); break; case BaseType.TypeUuid: s.Append("RAW(16)"); break; } } else if (type is IEnumerationType) { s.AppendFormat("NUMBER({0})", Math.Ceiling(Math.Log10((type as IEnumerationType).Length))); } else if (type is IEntityType) { IEntityType et = (type as IEntityType); s.Append(et.Entity.Constraints.PrimaryId.Attributes[0].Persistence.TypeName); } return(s.ToString()); }
public AnalyzedTypeTreeNode(ITypeDefinition analyzedType) { this.analyzedType = analyzedType ?? throw new ArgumentNullException(nameof(analyzedType)); this.LazyLoading = true; }
public CompositePropertyWeaverBuilder(ICompositePropertyMap compositePropertyMap, ITypeDefinition typeDefinition) : base(compositePropertyMap.ImplementationMember, compositePropertyMap.ImplementationType, compositePropertyMap.ContractType, typeDefinition) { this.compositePropertyMap = compositePropertyMap; }
public DisplayClass(ILVariable variable, ITypeDefinition type) { Variable = variable; Type = type; VariablesToDeclare = new Dictionary <IField, VariableToDeclare>(); }
public Type GetType(string name, bool throwOnError, bool ignoreCase) { if (string.IsNullOrEmpty(name)) { return(null); } if (IgnoreType(name)) { return(null); } if (ignoreCase) { Type cachedType; if (typeCacheIgnoreCase.TryGetValue(name, out cachedType)) { return(cachedType); } } else { Type cachedType; if (typeCache.TryGetValue(name, out cachedType)) { return(cachedType); } } #if DEBUG if (!name.StartsWith("System.", StringComparison.Ordinal)) { count++; LoggingService.Debug(count + " TypeResolutionService: Looking for " + name); } #endif try { Type type = Type.GetType(name, false, ignoreCase); if (type == null) { IProject p = CallingProject; if (p != null) { ICompilation compilation = SD.ParserService.GetCompilation(p); ITypeDefinition definition = ReflectionHelper.ParseReflectionName(name) .Resolve(compilation).GetDefinition(); if (definition != null) { using (var resolver = new ProjectAssemblyResolver(compilation, this)) { Assembly assembly = LoadAssembly(definition.ParentAssembly); if (assembly != null) { type = assembly.GetType(name, false, ignoreCase); } } } } } // type lookup for typename, assembly, xyz style lookups if (type == null) { int idx = name.IndexOf(",", StringComparison.Ordinal); if (idx > 0) { string[] splitName = name.Split(','); string typeName = splitName[0]; string assemblyName = splitName[1].Substring(1); Assembly assembly = null; try { assembly = Assembly.Load(assemblyName); } catch (Exception e) { LoggingService.Error(e); } if (assembly != null) { string fileName = GetOriginalAssemblyFullPath(assembly); if (!String.IsNullOrEmpty(fileName)) { lock (loadedAssembliesForCurrentDocument) { loadedAssembliesForCurrentDocument [fileName] = GetHash(fileName); } } lock (designerAssemblies) { if (!designerAssemblies.Contains(assembly)) { designerAssemblies.Add(assembly); } } type = assembly.GetType(typeName, false, ignoreCase); } else { type = Type.GetType(typeName, false, ignoreCase); } } } if (type == null) { lock (designerAssemblies) { foreach (Assembly asm in DesignerAssemblies) { try { Type t = asm.GetType(name, false); if (t != null) { AddToCache(name, t, ignoreCase); return(t); } } catch (FileNotFoundException) { } catch (FileLoadException) { } catch (BadImageFormatException) { // ignore assembly load errors } } } } if (throwOnError && type == null) { throw new TypeLoadException(name + " not found by TypeResolutionService"); } AddToCache(name, type, ignoreCase); return(type); } catch (Exception e) { LoggingService.Error(e); } return(null); }
public virtual void PrintTypeDefinitionBaseTypesAndInterfaces(ITypeDefinition typeDefinition) { PrintBaseTypesAndInterfacesList(typeDefinition); }
public override Task InsertWithCursor(string operation, ITypeDefinition parentType, IEnumerable <AstNode> nodes) { var tcs = new TaskCompletionSource <object>(); if (parentType == null) { return(tcs.Task); } var part = parentType.Parts.FirstOrDefault(); if (part == null) { return(tcs.Task); } var loadedDocument = Ide.IdeApp.Workbench.OpenDocument(part.Region.FileName); loadedDocument.RunWhenLoaded(delegate { var editor = loadedDocument.Editor; var loc = part.Region.Begin; var parsedDocument = loadedDocument.UpdateParseDocument(); var declaringType = parsedDocument.GetInnermostTypeDefinition(loc); var mode = new InsertionCursorEditMode( editor.Parent, CodeGenerationService.GetInsertionPoints(loadedDocument, declaringType)); if (mode.InsertionPoints.Count == 0) { MessageService.ShowError( GettextCatalog.GetString("No valid insertion point can be found in type '{0}'.", declaringType.Name) ); return; } if (declaringType.Kind == TypeKind.Enum) { foreach (var node in nodes.Reverse()) { var output = OutputNode(CodeGenerationService.CalculateBodyIndentLevel(declaringType), node); var point = mode.InsertionPoints.First(); var offset = loadedDocument.Editor.LocationToOffset(point.Location); var text = output.Text + ","; var delta = point.Insert(editor, text); output.RegisterTrackedSegments(this, delta + offset); } tcs.SetResult(null); return; } var helpWindow = new Mono.TextEditor.PopupWindow.InsertionCursorLayoutModeHelpWindow(); helpWindow.TransientFor = MonoDevelop.Ide.IdeApp.Workbench.RootWindow; helpWindow.TitleText = operation; mode.HelpWindow = helpWindow; mode.CurIndex = 0; operationsRunning++; mode.StartMode(); mode.Exited += delegate(object s, InsertionCursorEventArgs iCArgs) { if (iCArgs.Success) { if (iCArgs.InsertionPoint.LineAfter == NewLineInsertion.None && iCArgs.InsertionPoint.LineBefore == NewLineInsertion.None && nodes.Count() > 1) { iCArgs.InsertionPoint.LineAfter = NewLineInsertion.BlankLine; } foreach (var node in nodes.Reverse()) { var output = OutputNode(CodeGenerationService.CalculateBodyIndentLevel(declaringType), node); var offset = loadedDocument.Editor.LocationToOffset(iCArgs.InsertionPoint.Location); var text = output.Text; var delta = iCArgs.InsertionPoint.Insert(editor, text); output.RegisterTrackedSegments(this, delta + offset); } tcs.SetResult(null); } else { Rollback(); } DisposeOnClose(); }; }); return(tcs.Task); }
protected virtual List <JEntityDeclaration> _VisitStruct(ITypeDefinition ce) { throw new CompilerException(ce, "Member is not supported for export"); }
public virtual void PrintTypeDefinitionRightCurly(ITypeDefinition typeDefinition) { PrintToken(CSharpToken.RightCurly); }
internal abstract bool TryGetTypeHandle(ITypeDefinition def, out TypeHandle handle);
public virtual List <JEntityDeclaration> _VisitDelegate(ITypeDefinition ce) { return(_VisitClass(ce)); }
public void AddMappings(ITypeDefinition <RegionTemplateRecord> typeDefinition, string dataSetName) { typeDefinition.AddField("regionVersionId", r => r.RegionVersionId, 0); typeDefinition.AddField("templatePath", r => r.TemplatePath, "/blankRegion"); typeDefinition.AddField("pageArea", r => r.PageArea, PageArea.Body); }
JCompilationUnit ExportTypeNamespace(ITypeDefinition ce) { return(new JCompilationUnit { PackageName = ce.GetPackageName() }); }
public string GetString(ITypeDefinition type, OutputFlags flags) { return(GetString((IEntity)type, new OutputSettings(flags))); }
public AbstractWeaverBuilder(TMember memberInfoImpl, Type implementationType, Type contractType, ITypeDefinition typeDefinition) { ContractType = contractType; MemberInfoImpl = memberInfoImpl; ImplementationType = implementationType; TypeDefinition = typeDefinition; }
public static bool IsObjectOrValueType(this IType type) { ITypeDefinition definition = type.GetDefinition(); return(definition != null && (definition.KnownTypeCode == KnownTypeCode.Object || definition.KnownTypeCode == KnownTypeCode.ValueType)); }
public int CompareTo(ITypeDefinition other) { return(other == null ? -1 : string.Compare(ToString(), other.ToString(), StringComparison.InvariantCultureIgnoreCase)); }
protected void Uninitialize() { currentTypeDefinition = null; currentMethod = null; }
public TypeDefinition GetTypeDefinition(ITypeDefinition item) { return(TryGetOrAdd(_typecache, item, tdef => ILSpyHelper.FindMatchingType(AssemblyDefinition, tdef))); }
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; if (ShowAttributes) { decl.Attributes.AddRange (typeDefinition.Attributes.Select ((a) => new AttributeSection (ConvertAttribute (a)))); } if (AddResolveResultAnnotations) { decl.AddAnnotation(new TypeResolveResult(typeDefinition)); } 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) { if (baseType.IsKnownType (KnownTypeCode.Enum)) { if (!typeDefinition.EnumUnderlyingType.IsKnownType (KnownTypeCode.Int32)) { decl.BaseTypes.Add (ConvertType (typeDefinition.EnumUnderlyingType)); } } else if (!baseType.IsKnownType (KnownTypeCode.Object) && !baseType.IsKnownType (KnownTypeCode.ValueType)) { decl.BaseTypes.Add (ConvertType (baseType)); } } } if (this.ShowTypeParameters && this.ShowTypeParameterConstraints) { foreach (ITypeParameter tp in typeDefinition.TypeParameters.Skip(outerTypeParameterCount)) { var constraint = ConvertTypeParameterConstraint(tp); if (constraint != null) decl.Constraints.Add(constraint); } } return decl; }
public AssemblyQualifiedTypeName(ITypeDefinition typeDefinition) { this.AssemblyName = typeDefinition.ParentAssembly.AssemblyName; this.TypeName = typeDefinition.FullTypeName; }
public SetPropertyMethodSignatureWeaver(IPropertyTypeBuilder propertyBuilder, ITypeDefinition typeDefinition) : base(propertyBuilder, typeDefinition) { }
protected void Initialize(TransformContext context) { currentTypeDefinition = context.CurrentTypeDefinition; currentMethod = context.CurrentMember as IMethod; }
public EnumSpec(TypeSpec declaringType, ITypeDefinition definition, TypeSpec underlyingType, MetaType info, Modifiers modifiers) : base(MemberKind.Enum, declaringType, definition, info, modifiers | Modifiers.SEALED) { this.underlying = underlyingType; }
Expression ConvertEnumValue(IType type, long val) { ITypeDefinition enumDefinition = type.GetDefinition(); TypeCode enumBaseTypeCode = ReflectionHelper.GetTypeCode(enumDefinition.EnumUnderlyingType); foreach (IField field in enumDefinition.Fields) { if (field.IsConst && object.Equals(CSharpPrimitiveCast.Cast(TypeCode.Int64, field.ConstantValue, false), val)) return ConvertType(type).Member(field.Name); } if (IsFlagsEnum(enumDefinition)) { long enumValue = val; Expression expr = null; long negatedEnumValue = ~val; // limit negatedEnumValue to the appropriate range switch (enumBaseTypeCode) { case TypeCode.Byte: case TypeCode.SByte: negatedEnumValue &= byte.MaxValue; break; case TypeCode.Int16: case TypeCode.UInt16: negatedEnumValue &= ushort.MaxValue; break; case TypeCode.Int32: case TypeCode.UInt32: negatedEnumValue &= uint.MaxValue; break; } Expression negatedExpr = null; foreach (IField field in enumDefinition.Fields.Where(fld => fld.IsConst)) { long fieldValue = (long)CSharpPrimitiveCast.Cast(TypeCode.Int64, field.ConstantValue, false); if (fieldValue == 0) continue; // skip None enum value if ((fieldValue & enumValue) == fieldValue) { var fieldExpression = ConvertType(type).Member(field.Name); if (expr == null) expr = fieldExpression; else expr = new BinaryOperatorExpression(expr, BinaryOperatorType.BitwiseOr, fieldExpression); enumValue &= ~fieldValue; } if ((fieldValue & negatedEnumValue) == fieldValue) { var fieldExpression = ConvertType(type).Member(field.Name); if (negatedExpr == null) negatedExpr = fieldExpression; else negatedExpr = new BinaryOperatorExpression(negatedExpr, BinaryOperatorType.BitwiseOr, fieldExpression); negatedEnumValue &= ~fieldValue; } } if (enumValue == 0 && expr != null) { if (!(negatedEnumValue == 0 && negatedExpr != null && negatedExpr.Descendants.Count() < expr.Descendants.Count())) { return expr; } } if (negatedEnumValue == 0 && negatedExpr != null) { return new UnaryOperatorExpression(UnaryOperatorType.BitNot, negatedExpr); } } return new PrimitiveExpression(CSharpPrimitiveCast.Cast(enumBaseTypeCode, val, false)).CastTo(ConvertType(type)); }