public static void Main (string[] args) { var a = new SimpleType(0); Console.WriteLine("a = {0}", a.Value); Increment(ref a.Value); Console.WriteLine("a = {0}", a.Value); }
public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration) { Guard.AgainstNullArgument("methodDeclaration", methodDeclaration); IEnumerable<ParameterDeclaration> parameters = methodDeclaration .GetChildrenByRole(Roles.Parameter) .Select(x => (ParameterDeclaration)x.Clone()); var isVoid = false; var isAsync = methodDeclaration.Modifiers.HasFlag(Modifiers.Async); AstType returnType = methodDeclaration.GetChildByRole(Roles.Type).Clone(); var type = returnType as PrimitiveType; if (type != null) { isVoid = string.Compare( type.Keyword, "void", StringComparison.OrdinalIgnoreCase) == 0; } var methodType = new SimpleType(Identifier.Create(isVoid ? "Action" : "Func")); IEnumerable<AstType> types = parameters.Select( x => x.GetChildByRole(Roles.Type).Clone()); methodType .TypeArguments .AddRange(types); if (!isVoid) { methodType.TypeArguments.Add(returnType); } var methodName = GetIdentifierName(methodDeclaration); var methodBody = methodDeclaration .GetChildrenByRole(Roles.Body) .FirstOrDefault(); if (methodBody == null) { throw new NullReferenceException(string.Format("Method '{0}' has no method body", methodName)); } methodBody = (BlockStatement)methodBody.Clone(); var prototype = new VariableDeclarationStatement { Type = methodType }; prototype.Variables.Add(new VariableInitializer(methodName)); var anonymousMethod = new AnonymousMethodExpression(methodBody, parameters) { IsAsync = isAsync }; var expression = new ExpressionStatement { Expression = new AssignmentExpression( new IdentifierExpression(methodName), anonymousMethod) }; _methods.Add(new MethodVisitorResult { MethodDefinition = methodDeclaration, MethodPrototype = prototype, MethodExpression = expression }); }
public override SimpleType GetOriginalQueryableType() { var memberExp = GetTranslatedParameterOrMember(GetParameter("x")); var mappedItem = new SimpleType(MappedItemType, memberExp.Type); mappedItem.Includes.AddRange(Includes); return mappedItem; }
private void AddInclude(SimpleType source, MemberExpression memberSelector, LambdaExpression collectionInclude) { var members = source.GetAllMembers(); if (members.Count > 0 && memberSelector.GetDepth() > 1) { var innermostMember = ExpressionUtil.GetInnermostMemberExpression(memberSelector); foreach (var kvp in members) { if (kvp.Key == innermostMember.Member) { AddInclude(kvp.Value, ExpressionUtil.ReplaceInnermostMemberExpressionWithParameter(memberSelector) as MemberExpression, collectionInclude); return; } } } else { var parameter = ExpressionUtil.GetParameterExpression(memberSelector); if (collectionInclude != null) { source.Includes.Add(IncludeDirectiveUtil.GetIncludeInCollectionDirective(memberSelector, collectionInclude)); } else { source.Includes.Add(IncludeDirectiveUtil.GetIncludeDirective(memberSelector)); } } }
public void GenericWithArrayVariableDeclarationStatementTest1() { VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement<VariableDeclarationStatement>("G<int>[] a;"); AstType type = new SimpleType("G") { TypeArguments = { new PrimitiveType("int") } }.MakeArrayType(); Assert.IsTrue(new VariableDeclarationStatement(type, "a").IsMatch(lvd)); }
public SimpleFieldGenerator(FieldInfo fld) : base(fld) { _primitive = fld.DeclaringType.ParentConfig.ResolveName<SimpleType>( fld.DeclaringType, ((SimpleTypeRef) fld).TypeName ); _generator = new SimpleTypeGenerator(_primitive); }
public void the_same_graph_written_on_the_same_stream_is_not_detected_as_a_circular_reference() { var graph = new SimpleType(); using(var writer = CreateWriter()) { writer.Write(graph); writer.Write(graph); } }
static IEnumerable<CodeAction> GetActions(RefactoringContext context, SimpleType node) { var resolveResult = context.Resolve(node) as UnknownIdentifierResolveResult; if (resolveResult == null) yield break; yield return new CodeAction(context.TranslateString("Create delegate"), script => { script.CreateNewType(CreateType(context, node)); }, node); }
public void ComplexGenericVariableDeclarationStatementTest() { VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement<VariableDeclarationStatement>("Generic<Namespace.Printable, G<Printable[]> > where = new Generic<Namespace.Printable, G<Printable[]>>();"); AstType type = new SimpleType("Generic") { TypeArguments = { new MemberType { Target = new SimpleType("Namespace"), MemberName = "Printable" }, new SimpleType("G") { TypeArguments = { new SimpleType("Printable").MakeArrayType() } } }}; Assert.IsTrue(new VariableDeclarationStatement(type, "where", new ObjectCreateExpression { Type = type.Clone() }).IsMatch(lvd)); }
static DelegateDeclaration CreateType(RefactoringContext context, SimpleType simpleType) { var result = new DelegateDeclaration() { Name = simpleType.Identifier, Modifiers = ((EntityDeclaration)simpleType.Parent).Modifiers, ReturnType = new PrimitiveType("void"), Parameters = { new ParameterDeclaration(new PrimitiveType("object"), "sender"), new ParameterDeclaration(context.CreateShortType("System", "EventArgs"), "e") } }; return result; }
public void AddEntity() { // Setup var file = GetXmlFile(nameof(AddEntity)); var set = new XmlSet<SimpleType>(file); var simpleType = new SimpleType(); // Execute set.Add(simpleType); // Assert Assert.AreSame(simpleType, set.First()); Assert.AreEqual(1, set.Count); }
AstType ConvertToType (MemberName memberName) { AstType result; if (memberName.Left != null) { result = new MemberType () { MemberName = memberName.Name }; result.AddChild (ConvertToType (memberName.Left), MemberType.TargetRole); } else { result = new SimpleType () { Identifier = memberName.Name }; } if (memberName.TypeArguments != null && !memberName.TypeArguments.IsEmpty) { foreach (var arg in memberName.TypeArguments.Args) { result.AddChild (ConvertToType (arg), AstType.Roles.TypeArgument); } } return result; }
static TypeDeclaration CreateClassFromType(RefactoringContext context, SimpleType simpleType) { TypeDeclaration result; string className = simpleType.Identifier; if (simpleType.Parent is Attribute) { if (!className.EndsWith("Attribute")) className += "Attribute"; } result = new TypeDeclaration() { Name = className }; var entity = simpleType.GetParent<EntityDeclaration>(); if (entity != null) result.Modifiers |= entity.Modifiers & ~Modifiers.Internal; return result; }
public void graphs_which_contain_circular_references_are_not_supported() { var graph = new SimpleType(); // Root to self. graph.Value = graph; Assert.Throws<SerializationException>(() => Write(graph)); // Descendent to root. graph.Value = new SimpleType { Value = graph }; Assert.Throws<SerializationException>(() => Write(graph)); // Descendent to self. graph.Value = new SimpleType(); graph.Value.Value = graph.Value; Assert.Throws<SerializationException>(() => Write(graph)); // Descendent to parent. graph.Value = new SimpleType { Value = graph.Value }; Assert.Throws<SerializationException>(() => Write(graph)); }
public static AstType ConvertToTypeReference (this MonoDevelop.Projects.Dom.IReturnType returnType) { string primitiveType; if (TypeTable.TryGetValue (returnType.DecoratedFullName, out primitiveType)) return new PrimitiveType (primitiveType); AstType result = null; if (!string.IsNullOrEmpty (returnType.Namespace)) result = new SimpleType (returnType.Namespace); foreach (var part in returnType.Parts) { if (result == null) { var st = new SimpleType (part.Name); foreach (var type in part.GenericArguments.Select (ga => ConvertToTypeReference (ga))) st.AddChild (type, SimpleType.Roles.TypeArgument); result = st; } else { var mt = new ICSharpCode.NRefactory.CSharp.MemberType () { Target = result, MemberName = part.Name }; foreach (var type in part.GenericArguments.Select (ga => ConvertToTypeReference (ga))) mt.AddChild (type, SimpleType.Roles.TypeArgument); result = mt; } } /* List<TypeReference> genericTypes = new List<TypeReference> (); foreach (MonoDevelop.Projects.Dom.IReturnType genericType in returnType.GenericArguments) { genericTypes.Add (ConvertToTypeReference (genericType)); } TypeReference result = new AstType (returnType.FullName, genericTypes); result.IsKeyword = true; result.PointerNestingLevel = returnType.PointerNestingLevel; if (returnType.ArrayDimensions > 0) { int[] rankSpecfier = new int[returnType.ArrayDimensions]; for (int i = 0; i < returnType.ArrayDimensions; i++) { rankSpecfier[i] = returnType.GetDimension (i); } result.RankSpecifier = rankSpecfier; }*/ return result; }
public static ICSharpCode.NRefactory.CSharp.Attribute GenerateExportAttribute (RefactoringContext ctx, IMember member) { if (member == null) return null; var astType = ctx.CreateShortType ("MonoTouch.Foundation", "ExportAttribute"); if (astType is SimpleType) { astType = new SimpleType ("Export"); } else { astType = new MemberType (new MemberType (new SimpleType ("MonoTouch"), "Foundation"), "Export"); } var attr = new ICSharpCode.NRefactory.CSharp.Attribute { Type = astType, }; var exportAttribute = member.GetAttribute (new FullTypeName (new TopLevelTypeName ("MonoTouch.Foundation", "ExportAttribute"))); if (exportAttribute == null || exportAttribute.PositionalArguments.Count == 0) return null; attr.Arguments.Add (new PrimitiveExpression (exportAttribute.PositionalArguments.First ().ConstantValue)); return attr; }
/// <summary> /// Helper method to convert a SimpleType to a C#'s type. /// </summary> /// <returns>A <see cref="System.Type"/> object.</returns> /// <param name="containerType">Container type.</param> public static Type GetContainerType(SimpleType containerType) { if(containerType == null) throw new ArgumentNullException("containerType"); switch(containerType.Name){ case "dictionary": return typeof(Dictionary<,>); case "array": return typeof(Array); case "tuple": return typeof(Tuple); case "vector": return typeof(List<>); default: throw new EmitterException("Unknown container type!"); } }
public SimpleType CreateObject(int height, int parentId, int currentId) { int index = parentId * SimpleType.SimpleTypeListSize + (currentId + 1); var obj = new SimpleType() { IntProperty = index, StringProperty = index + " string value", EnumProperty = (MyEnum)(index % (Enum.GetNames(typeof(MyEnum)).Length)), CollectionProperty = new List<string>(), SimpleTypeList = new List<SimpleType>() }; for (int i = 0; i < SimpleType.CollectionSize; ++i) { obj.CollectionProperty.Add(index + "." + i); } if (height < SimpleType.GraphSize) { for (int i = 0; i < SimpleType.SimpleTypeListSize; ++i) { obj.SimpleTypeList.Add(CreateObject(height + 1, index, i)); } } return obj; }
public virtual void VisitSimpleType(SimpleType simpleType) { //throw this.CreateException(simpleType); }
public virtual Node VisitSimpleType(SimpleType simpleType) { throw new System.NotImplementedException(); }
private static void HandleGroupBy(SimpleType simpleType) { var initializer = simpleType.Ancestors.OfType <VariableInitializer>().Single(); var rootExpression = (InvocationExpression)initializer.Initializer; var nodes = rootExpression.Children.Where(x => x.NodeType != NodeType.Token).ToList(); if (nodes.Count < 2) { return; } var memberReferences = nodes.OfType <MemberReferenceExpression>().ToList(); if (!memberReferences.Any()) { return; } var groupByExpression = memberReferences.FirstOrDefault(ContainsGroupBy); if (groupByExpression == null) { return; } var indexOfGroupByExpression = nodes.IndexOf(groupByExpression); if (indexOfGroupByExpression != 0) { return; } var castExpression = nodes[indexOfGroupByExpression + 1] as CastExpression; if (castExpression == null) { return; } if (castExpression.Descendants.Contains(simpleType) == false) { return; } foreach (var ancestor in simpleType.Ancestors) { if (ancestor == groupByExpression || groupByExpression.Ancestors.Contains(ancestor) || groupByExpression.Descendants.Contains(ancestor)) { continue; } if (ancestor.Children.OfType <MemberReferenceExpression>().Any(ContainsGroupBy)) { return; } } var grouping = simpleType.NextSibling; var lambda = grouping.Children.OfType <LambdaExpression>().First(); var parameter = lambda.Parameters.First(); foreach (var invocation in lambda.Descendants.OfType <InvocationExpression>()) { var identifiers = invocation.Descendants.OfType <IdentifierExpression>().Where(x => x.Identifier == parameter.Name); foreach (var identifier in identifiers) { var parent = identifier.Parent as InvocationExpression; if (parent == null) { continue; } var member = (MemberReferenceExpression)parent.Target; if (member.MemberName == "Count") { throw new InvalidOperationException("Reduce cannot contain Count() methods in grouping."); } if (member.MemberName == "Average") { throw new InvalidOperationException("Reduce cannot contain Average() methods in grouping."); } } } }
public WebStatsEntry(SimpleType value, bool persist) { Data = value; Persist = persist; }
public static void Main() { SimpleType.DisplayEnvironment(); Console.ReadLine(); }
AstType ConvertImport (MemberName memberName) { if (memberName.Left != null) { // left.name var t = new MemberType(); t.IsDoubleColon = memberName.IsDoubleColon; t.AddChild (ConvertImport (memberName.Left), MemberType.TargetRole); if (!memberName.DotLocation.IsNull) t.AddChild (new CSharpTokenNode (Convert (memberName.DotLocation), 1), MemberType.Roles.Dot); t.AddChild (Identifier.Create (memberName.Name, Convert(memberName.Location)), MemberType.Roles.Identifier); AddTypeArguments (t, memberName.TypeArguments); return t; } else { SimpleType t = new SimpleType(); t.AddChild (Identifier.Create (memberName.Name, Convert(memberName.Location)), SimpleType.Roles.Identifier); AddTypeArguments (t, memberName.TypeArguments); return t; } }
public override void VisitSimpleType(SimpleType simpleType) { base.VisitSimpleType(simpleType); UseNamespace(ctx.Resolve(simpleType).Type.Namespace); }
private TypeSpecifier ParseTypeSpecifier(TypeSyntax typeSyntax, SemanticModel semanticModel) { if (typeSyntax is ArrayTypeSyntax) { try { return(new ArrayType { BaseType = (SimpleType)ParseTypeSpecifier(((ArrayTypeSyntax)typeSyntax).ElementType, semanticModel), }); } catch (InvalidCastException) { throw new ParseException("SimpleType以外の配列は使用禁止です。"); } } else if (typeSyntax is NullableTypeSyntax) { try { return(new NullableType { BaseType = (SimpleType)ParseTypeSpecifier(((NullableTypeSyntax)typeSyntax).ElementType, semanticModel), }); } catch (InvalidCastException) { throw new ParseException("SimpleType以外のnull可能型は使用禁止です。"); } } else if (typeSyntax is GenericNameSyntax) { var g = (GenericNameSyntax)typeSyntax; { var typeInfo = semanticModel.GetTypeInfo(typeSyntax); var symbolInfo = semanticModel.GetSymbolInfo(typeSyntax); return(new GenericType { OuterType = new SimpleType { Namespace = Utils.ToStr(typeInfo.Type.ContainingNamespace), TypeName = g.Identifier.ValueText, }, InnerType = g.TypeArgumentList.Arguments.Select(x => ParseTypeSpecifier(x, semanticModel)).ToList(), }); } } else { var type = semanticModel.GetTypeInfo(typeSyntax); var specifier = new SimpleType { Namespace = Utils.ToStr(type.Type.ContainingNamespace), TypeName = type.Type.Name, }; switch (type.Type.TypeKind) { case TypeKind.Class: specifier.TypeKind = SimpleTypeKind.Class; break; case TypeKind.Enum: specifier.TypeKind = SimpleTypeKind.Enum; break; case TypeKind.Error: specifier.TypeKind = SimpleTypeKind.Error; break; case TypeKind.Interface: specifier.TypeKind = SimpleTypeKind.Interface; break; case TypeKind.Struct: specifier.TypeKind = SimpleTypeKind.Struct; break; case TypeKind.TypeParameter: specifier.TypeKind = SimpleTypeKind.TypeParameter; // 基本的にGenericsの型なのでNamespaceは必要ない specifier.Namespace = string.Empty; break; default: specifier.TypeKind = SimpleTypeKind.Other; break; } return(specifier); } }
public void VisitSimpleType(SimpleType simpleType) { throw new NotImplementedException(); }
AstType ConvertTypeHelper(ITypeDefinition typeDef, IList <IType> typeArguments) { Debug.Assert(typeArguments.Count >= typeDef.TypeParameterCount); string keyword = KnownTypeReference.GetCSharpNameByTypeCode(typeDef.KnownTypeCode); if (keyword != null) { return(new PrimitiveType(keyword)); } // The number of type parameters belonging to outer classes int outerTypeParameterCount; if (typeDef.DeclaringType != null) { outerTypeParameterCount = typeDef.DeclaringType.TypeParameterCount; } else { outerTypeParameterCount = 0; } if (resolver != null) { // Look if there's an alias to the target type if (UseAliases) { for (ResolvedUsingScope usingScope = resolver.CurrentUsingScope; usingScope != null; usingScope = usingScope.Parent) { foreach (var pair in usingScope.UsingAliases) { if (pair.Value is TypeResolveResult) { if (TypeMatches(pair.Value.Type, typeDef, typeArguments)) { return(new SimpleType(pair.Key)); } } } } } IList <IType> localTypeArguments; if (typeDef.TypeParameterCount > outerTypeParameterCount) { localTypeArguments = new IType[typeDef.TypeParameterCount - outerTypeParameterCount]; for (int i = 0; i < localTypeArguments.Count; i++) { localTypeArguments[i] = typeArguments[outerTypeParameterCount + i]; } } else { localTypeArguments = EmptyList <IType> .Instance; } ResolveResult rr = resolver.ResolveSimpleName(typeDef.Name, localTypeArguments); TypeResolveResult trr = rr as TypeResolveResult; if (trr != null || (localTypeArguments.Count == 0 && resolver.IsVariableReferenceWithSameType(rr, typeDef.Name, out trr))) { if (!trr.IsError && TypeMatches(trr.Type, typeDef, typeArguments)) { // We can use the short type name SimpleType shortResult = new SimpleType(typeDef.Name); AddTypeArguments(shortResult, typeDef, typeArguments, outerTypeParameterCount, typeDef.TypeParameterCount); return(shortResult); } } } if (AlwaysUseShortTypeNames) { var shortResult = new SimpleType(typeDef.Name); AddTypeArguments(shortResult, typeDef, typeArguments, outerTypeParameterCount, typeDef.TypeParameterCount); return(shortResult); } MemberType result = new MemberType(); if (typeDef.DeclaringTypeDefinition != null) { // Handle nested types result.Target = ConvertTypeHelper(typeDef.DeclaringTypeDefinition, typeArguments); } else { // Handle top-level types if (string.IsNullOrEmpty(typeDef.Namespace)) { result.Target = new SimpleType("global"); result.IsDoubleColon = true; } else { result.Target = ConvertNamespace(typeDef.Namespace); } } result.MemberName = typeDef.Name; AddTypeArguments(result, typeDef, typeArguments, outerTypeParameterCount, typeDef.TypeParameterCount); return(result); }
public ArrayType(CodeContext /*!*/ context, string name, PythonTuple bases, PythonDictionary dict) : base(context, name, bases, dict) { object len; int iLen; if (!dict.TryGetValue("_length_", out len) || !(len is int) || (iLen = (int)len) < 0) { throw PythonOps.AttributeError("arrays must have _length_ attribute and it must be a positive integer"); } object type; if (!dict.TryGetValue("_type_", out type)) { throw PythonOps.AttributeError("class must define a '_type_' attribute"); } _length = iLen; _type = (INativeType)type; if (_type is SimpleType) { SimpleType st = (SimpleType)_type; if (st._type == SimpleTypeKind.Char) { // TODO: (c_int * 2).value isn't working SetCustomMember(context, "value", new ReflectedExtensionProperty( new ExtensionPropertyInfo(this, typeof(CTypes).GetMethod("GetCharArrayValue")), NameType.Property | NameType.Python ) ); SetCustomMember(context, "raw", new ReflectedExtensionProperty( new ExtensionPropertyInfo(this, typeof(CTypes).GetMethod("GetWCharArrayRaw")), NameType.Property | NameType.Python ) ); } else if (st._type == SimpleTypeKind.WChar) { SetCustomMember(context, "value", new ReflectedExtensionProperty( new ExtensionPropertyInfo(this, typeof(CTypes).GetMethod("GetWCharArrayValue")), NameType.Property | NameType.Python ) ); SetCustomMember(context, "raw", new ReflectedExtensionProperty( new ExtensionPropertyInfo(this, typeof(CTypes).GetMethod("GetWCharArrayRaw")), NameType.Property | NameType.Python ) ); } } }
public static TObj ReadSimpleType <TObj>(this GenericReader reader) { object value = new SimpleType(reader).Value; return(value is TObj ? (TObj)value : default(TObj)); }
public static void WriteSimpleType(this GenericWriter writer, object obj) { SimpleType.FromObject(obj).Serialize(writer); }
public BlockStatement CreateMethodBody(IEnumerable<ParameterDeclaration> parameters, ConcurrentDictionary<int, IEnumerable<ILVariable>> localVariables) { if (methodDef.Body == null) return null; if (localVariables == null) throw new ArgumentException("localVariables must be instantiated"); context.CancellationToken.ThrowIfCancellationRequested(); ILBlock ilMethod = new ILBlock(); ILAstBuilder astBuilder = new ILAstBuilder(); ilMethod.Body = astBuilder.Build(methodDef, true); context.CancellationToken.ThrowIfCancellationRequested(); ILAstOptimizer bodyGraph = new ILAstOptimizer(); bodyGraph.Optimize(context, ilMethod); context.CancellationToken.ThrowIfCancellationRequested(); var allVariables = ilMethod.GetSelfAndChildrenRecursive<ILExpression>().Select(e => e.Operand as ILVariable) .Where(v => v != null && !v.IsParameter).Distinct(); Debug.Assert(context.CurrentMethod == methodDef); NameVariables.AssignNamesToVariables(context, astBuilder.Parameters, allVariables, ilMethod); if (parameters != null) { foreach (var pair in (from p in parameters join v in astBuilder.Parameters on p.Annotation<ParameterDefinition>() equals v.OriginalParameter select new { p, v.Name })) { pair.p.Name = pair.Name; } } context.CancellationToken.ThrowIfCancellationRequested(); Ast.BlockStatement astBlock = TransformBlock(ilMethod); CommentStatement.ReplaceAll(astBlock); // convert CommentStatements to Comments Statement insertionPoint = astBlock.Statements.FirstOrDefault(); foreach (ILVariable v in localVariablesToDefine) { AstType type; if (v.Type.ContainsAnonymousType()) type = new SimpleType("var"); else type = AstBuilder.ConvertType(v.Type); var newVarDecl = new VariableDeclarationStatement(type, v.Name); astBlock.Statements.InsertBefore(insertionPoint, newVarDecl); } // store the variables - used for debugger int token = methodDef.MetadataToken.ToInt32(); localVariables.AddOrUpdate(token, allVariables, (key, oldValue) => allVariables); return astBlock; }
public override void VisitSimpleType(SimpleType simpleType) { this.CheckDependency(simpleType); base.VisitSimpleType(simpleType); }
AstType ConvertToType(MemberName memberName) { AstType result; if (memberName.Left != null) { result = new MemberType(); result.AddChild(ConvertToType(memberName.Left), MemberType.TargetRole); var loc = LocationsBag.GetLocations(memberName); if (loc != null) result.AddChild(new CSharpTokenNode(Convert(loc [0]), Roles.Dot), Roles.Dot); result.AddChild(Identifier.Create(memberName.Name, Convert(memberName.Location)), Roles.Identifier); } else { result = new SimpleType { IdentifierToken = Identifier.Create(memberName.Name, Convert(memberName.Location)) }; } if (memberName.TypeParameters != null) { var chevronLocs = LocationsBag.GetLocations(memberName.TypeParameters); if (chevronLocs != null) result.AddChild(new CSharpTokenNode(Convert(chevronLocs [chevronLocs.Count - 2]), Roles.LChevron), Roles.LChevron); for (int i = 0; i < memberName.TypeParameters.Count; i++) { var param = memberName.TypeParameters [i]; result.AddChild(new SimpleType(Identifier.Create(param.Name, Convert(param.Location))), Roles.TypeArgument); if (chevronLocs != null && i < chevronLocs.Count - 2) result.AddChild(new CSharpTokenNode(Convert(chevronLocs [i]), Roles.Comma), Roles.Comma); } if (chevronLocs != null) result.AddChild(new CSharpTokenNode(Convert(chevronLocs [chevronLocs.Count - 1]), Roles.RChevron), Roles.RChevron); } return result; }
public ComplexType(SimpleType first, SimpleType second) { First = first; Second = second; }
AstType ConvertImport(MemberName memberName) { if (memberName.Left != null) { // left.name var t = new MemberType(); // t.IsDoubleColon = memberName.IsDoubleColon; t.AddChild(ConvertImport(memberName.Left), MemberType.TargetRole); var loc = LocationsBag.GetLocations(memberName); if (loc != null) t.AddChild(new CSharpTokenNode(Convert(loc [0]), Roles.Dot), Roles.Dot); t.AddChild(Identifier.Create(memberName.Name, Convert(memberName.Location)), Roles.Identifier); AddTypeArguments(t, memberName); return t; } else { var t = new SimpleType(); t.AddChild(Identifier.Create(memberName.Name, Convert(memberName.Location)), Roles.Identifier); AddTypeArguments(t, memberName); return t; } }
public RedILNode VisitSimpleType(SimpleType simpleType, State data) { throw new System.NotImplementedException(); }
public void VisitSimpleType(SimpleType simpleType) { // no op }
static TypeDeclaration CreateClassFromType(RefactoringContext context, ClassType classType, SimpleType simpleType) { TypeDeclaration result; string className = simpleType.Identifier; if (simpleType.Parent is Attribute && classType == ClassType.Class) { if (!className.EndsWith("Attribute", System.StringComparison.Ordinal)) { className += "Attribute"; } } result = new TypeDeclaration { Name = className, ClassType = classType }; var entity = simpleType.GetParent <EntityDeclaration>(); if (entity != null) { result.Modifiers |= entity.Modifiers & Modifiers.Public; } var guessedType = TypeGuessing.GuessType(context, simpleType); if (guessedType.Kind == TypeKind.TypeParameter) { ImplementConstraints(context, result, (ITypeParameter)guessedType); } return(result); }
void QualifiedTypeName(out AstType type) { if (la.kind == 130) { Get(); } else if (StartOf(4)) { Identifier(); } else SynErr(246); type = new SimpleType(TextTokenType.Text, t.val, t.Location); while (la.kind == 26) { Get(); Identifier(); type = new QualifiedType(type, new Identifier (TextTokenType.Text, t.val, t.Location)); } }
private SimpleType Convert(SimpleType l, SimpleType r) { return(l.SType < r.SType ? r : l); }
protected virtual Class Matches(SimpleType type, Context context) { return(Type.Equals(type) ? this : null); }
public IActionResult Put([FromBody] SimpleType model) { return(Ok(model)); }
public string Mangle(SimpleType type) { return(Mangle(type.Name)); }
public override object VisitSimpleType(SimpleType simpleType, object data) { possibleTypeReferences.Add(simpleType); return(null); }
public ClassAdapter(SimpleType type, Domain domain) { _type = type; _domain = domain; }
private static void Main(string[] args) { ////装饰模式 //ConcreteComponent c = new ConcreteComponent(); //ConcreteDecoratorA d1 = new ConcreteDecoratorA(); //ConcreteDecoratorB d2 = new ConcreteDecoratorB(); //d1.SetComponent(c); //d2.SetComponent(d1); //d2.Operation(); ////代理模式 //SchollGirl mm = new SchollGirl(); //mm.Name = "敏敏"; //Proxy p = new Proxy(mm); //p.GiveDolls(); //p.GiveChocolate(); //p.GiveFlowers(); ////工厂方法模式 //IFactory factory = new UndergraduateFactory(); //LeiFeng student = factory.CreateLeiFeng(); //student.BuyRice(); //student.Sweep(); //student.Wash(); ////原型模式 //Resume a = new Resume("张三"); //a.SetPersonalInfo("男", "19"); //a.SetWorkExperience("2001-1-2", "aa公司"); //Resume b = (Resume)a.Clone(); //b.SetWorkExperience("2001-1-3", "bb公司"); //Resume c = (Resume)a.Clone(); //c.SetPersonalInfo("男", "20"); //c.SetWorkExperience("2001-1-4", "cc公司"); //a.Display(); //b.Display(); //c.Display(); ////模板方法模式 //AbstractClass c; //c = new ConcreteClassA(); //c.TemplateMethod(); //c = new ConcreteClassB(); //c.TemplateMethod(); ////c.F1(); ////c.F2(); ////外观类 //Facade facade = new Facade(); //facade.MethodA(); //facade.MethodB(); ////建造者模式 //Director director = new Director(); //Builder b1 = new ConcreteBuilder1(); //Builder b2 = new ConcreteBuilder2(); //director.Construct(b1); //Product p1 = b1.GetResult(); //p1.Show(); //director.Construct(b2); //Product p2 = b2.GetResult(); //p2.Show(); ////观察者模式 //ConcreteSubject s = new ConcreteSubject(); //s.Attach(new ConcreteObserver(s, "X")); //s.Attach(new ConcreteObserver(s, "Y")); //s.Attach(new ConcreteObserver(s, "Z")); //s.SubjectState = "abc"; //s.Notify(); ////抽象工厂模式 //User user = new User(); //IUser iu = DataAccess.CreateUser(); //iu.Insert(user); //iu.GetUser(1); ////委托、事件 //Cat c = new Cat("Tom"); //Mouse m1 = new Mouse("Jerry"); //Mouse m2 = new Mouse("Jack"); //c.CatShout += new Cat.CatShoutEventHandler(m1.Run); //c.CatShout += new Cat.CatShoutEventHandler(m2.Run); //c.Shout(); ////状态模式 //Context c = new Context(new ConcreteStateA()); //c.Request(); //c.Request(); //c.Request(); //c.Request(); new BLL.B().Method(); System.Console.Read(); return; var d = new DataTaimeList(); d.Add(DateTime.Now); d.Add(DateTime.Now); d.Add(DateTime.Now); d.Add(DateTime.Now); //Func<Object, ArgumentException> fn1 = null; //Func<string, Exception> fn2 = fn1; //Exception e = fn2("3"); SimpleType st = new SimpleType(); st.Dispose(); IDisposable dd = st; dd.Dispose(); System.Console.WriteLine("{0}:\t 所占字节数: {1}\t 最小值:{2}\t 最大值:{3}\n", typeof(char).Name, sizeof(char), char.MinValue, char.MaxValue); Char a = 'a'; ((IConvertible)65).ToChar(null); string str = "Hi" + Environment.NewLine + "there"; CultureInfo ci = new CultureInfo("de-DE"); String.Compare("A", "B", false, ci); StringInfo si = new StringInfo(); decimal dec = 123456.789m; var t = dec.ToString("G"); //Color[] colors = (Color[])Enum.GetValues(typeof(Color)); Color[] colors = GetEnumVlues <Color>(); foreach (var item in colors) { System.Console.WriteLine("{0:D}\t{0:G}", item); } string file = Assembly.GetEntryAssembly().Location; FileAttributes fa = File.GetAttributes(file); string[] names = new[] { "a", "b" }; var names2 = new[] { "a", "b" }; string[] sdf = new string[100]; object[] oa = sdf; oa[5] = "jeff"; int[] arr1 = new int[100]; for (int i = 0; i < arr1.Length; i++) { arr1[i] = i; } int[] arr2 = new int[100]; Array.ConstrainedCopy(arr1, 10, arr2, 10, arr1.Length - 10); Func <string> f = () => "aa"; Func <int, string> f2 = (int n) => n.ToString(); var abc = f2.Invoke(3); StaticDelegateDemo(); System.Console.WriteLine(Enum.Format(typeof(Color), 1, "G")); System.Console.Read(); }
private Func <object, object> Get_GetProjectedValue_Computation(SimpleType sourceType, SimpleType queryableType) { if (sourceType == queryableType) { return(tableEntity => tableEntity); } foreach (var kvp in sourceType.GetAllMembers()) { var memberGetter = Get_GetProjectedValue_Computation(kvp.Value, queryableType); if (memberGetter != null) { var translatedValueGetter = queryableType.GetTranslatedMemberValue(kvp.Key, entityContext._InternalServices.TypeTranslationUtil); return(tableEntity => memberGetter(translatedValueGetter(tableEntity))); } } if (sourceType.NonPrimitiveEnumerableItemType != null) { var collectionItemGetter = Get_GetProjectedValue_Computation(sourceType.NonPrimitiveEnumerableItemType, queryableType); if (collectionItemGetter != null) { return(tableEntity => { var list = new List <object>(); foreach (var item in (tableEntity as IEnumerable)) { list.Add(collectionItemGetter(item)); } return list; }); } } return(null); }
AstType ConvertToType (MemberName memberName) { AstType result; if (memberName.Left != null) { result = new MemberType (); result.AddChild (ConvertToType (memberName.Left), MemberType.TargetRole); var loc = LocationsBag.GetLocations (memberName.Left); if (loc != null) result.AddChild (new CSharpTokenNode (Convert (loc [0]), 1), MemberType.Roles.Dot); result.AddChild (Identifier.Create (memberName.Name, Convert (memberName.Location)), MemberType.Roles.Identifier); } else { result = new SimpleType () { IdentifierToken = Identifier.Create (memberName.Name, Convert (memberName.Location)) }; } if (memberName.TypeArguments != null && !memberName.TypeArguments.IsEmpty) { var chevronLocs = LocationsBag.GetLocations (memberName.TypeArguments); if (chevronLocs != null) result.AddChild (new CSharpTokenNode (Convert (chevronLocs[chevronLocs.Count - 2]), 1), InvocationExpression.Roles.LChevron); int i = 0; foreach (var arg in memberName.TypeArguments.Args) { result.AddChild (ConvertToType (arg), AstType.Roles.TypeArgument); if (chevronLocs != null && i < chevronLocs.Count - 2) result.AddChild (new CSharpTokenNode (Convert (chevronLocs [i++]), 1), InvocationExpression.Roles.Comma); } if (chevronLocs != null) result.AddChild (new CSharpTokenNode (Convert (chevronLocs[chevronLocs.Count - 1]), 1), InvocationExpression.Roles.RChevron); } return result; }
public BoogieBasicType(SimpleType type) { this.Type = type; }
static AstType ConvertToType(TypeParameter spec) { AstType result; result = new SimpleType { IdentifierToken = Identifier.Create(spec.Name, Convert(spec.Location)) }; return result; }
private bool FieldsMatch(SimpleType type, JsonSchema schema) { return(true); // TODO }
AstType ConvertToType(Mono.CSharp.Expression typeName) { if (typeName == null) // may happen in typeof(Generic<,,,,>) return new SimpleType(); var typeExpr = typeName as TypeExpression; if (typeExpr != null) { return new PrimitiveType(typeExpr.GetSignatureForError(), Convert(typeExpr.Location)); } var qam = typeName as QualifiedAliasMember; if (qam != null) { var loc = LocationsBag.GetLocations(typeName); var memberType = new MemberType(); memberType.Target = new SimpleType(qam.alias, Convert(qam.Location)); memberType.IsDoubleColon = true; if (loc != null && loc.Count > 0) memberType.AddChild(new CSharpTokenNode(Convert(loc [0]), Roles.DoubleColon), Roles.DoubleColon); memberType.MemberNameToken = Identifier.Create(qam.Name, loc != null ? Convert(loc [1]) : TextLocation.Empty); AddTypeArguments(qam, memberType); return memberType; } var ma = typeName as MemberAccess; if (ma != null) { var memberType = new MemberType(); memberType.AddChild(ConvertToType(ma.LeftExpression), MemberType.TargetRole); var loc = LocationsBag.GetLocations(ma); if (loc != null) memberType.AddChild(new CSharpTokenNode(Convert(loc [0]), Roles.Dot), Roles.Dot); memberType.MemberNameToken = Identifier.Create(ma.Name, Convert(ma.Location)); AddTypeArguments(ma, memberType); return memberType; } var sn = typeName as SimpleName; if (sn != null) { var result = new SimpleType(sn.Name, Convert(sn.Location)); AddTypeArguments(sn, result); return result; } var cc = typeName as ComposedCast; if (cc != null) { var baseType = ConvertToType(cc.Left); var result = new ComposedType { BaseType = baseType }; var ccSpec = cc.Spec; while (ccSpec != null) { if (ccSpec.IsNullable) { result.AddChild(new CSharpTokenNode(Convert(ccSpec.Location), ComposedType.NullableRole), ComposedType.NullableRole); } else if (ccSpec.IsPointer) { result.AddChild(new CSharpTokenNode(Convert(ccSpec.Location), ComposedType.PointerRole), ComposedType.PointerRole); } else { var location = LocationsBag.GetLocations(ccSpec); var spec = new ArraySpecifier { Dimensions = ccSpec.Dimension }; spec.AddChild(new CSharpTokenNode(Convert(ccSpec.Location), Roles.LBracket), Roles.LBracket); if (location != null) spec.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.RBracket), Roles.RBracket); result.ArraySpecifiers.Add(spec); } ccSpec = ccSpec.Next; } return result; } var sce = typeName as SpecialContraintExpr; if (sce != null) { switch (sce.Constraint) { case SpecialConstraint.Class: return new PrimitiveType("class", Convert(sce.Location)); case SpecialConstraint.Struct: return new PrimitiveType("struct", Convert(sce.Location)); case SpecialConstraint.Constructor: return new PrimitiveType("new", Convert(sce.Location)); } } return new SimpleType("unknown"); }
public override void VisitSimpleType(SimpleType simpleType) { new TypeBlock(this, simpleType).Emit(); }
public virtual void VisitSimpleType(SimpleType simpleType) { VisitChildren (simpleType); }
private string getName(SimpleType type) { return(getName(type.Identifier, type.TypeArguments)); }
public void VisitSimpleType(SimpleType simpleType) { StartNode(simpleType); WriteIdentifier(simpleType.Identifier); WriteTypeArguments(simpleType.TypeArguments); EndNode(simpleType); }
public override void VisitSimpleType(SimpleType simpleType) { CheckType(simpleType, simpleType.TypeArguments.FirstOrDefault()); }
private static CFuncPtrType GetFunctionType(CodeContext context, int flags) { // Ideally we should cache these... SimpleType resType = new SimpleType( context, "int", PythonTuple.MakeTuple(DynamicHelpers.GetPythonTypeFromType(typeof(SimpleCData))), PythonOps.MakeHomogeneousDictFromItems(new object[] { "i", "_type_" })); CFuncPtrType funcType = new CFuncPtrType( context, "func", PythonTuple.MakeTuple(DynamicHelpers.GetPythonTypeFromType(typeof(_CFuncPtr))), PythonOps.MakeHomogeneousDictFromItems(new object[] { FUNCFLAG_STDCALL, "_flags_", resType, "_restype_" })); return funcType; }
public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration) { Guard.AgainstNullArgument("methodDeclaration", methodDeclaration); IEnumerable <ParameterDeclaration> parameters = methodDeclaration .GetChildrenByRole(Roles.Parameter) .Select(x => (ParameterDeclaration)x.Clone()); var isVoid = false; var isAsync = methodDeclaration.Modifiers.HasFlag(Modifiers.Async); AstType returnType = methodDeclaration.GetChildByRole(Roles.Type).Clone(); var type = returnType as PrimitiveType; if (type != null) { isVoid = string.Compare( type.Keyword, "void", StringComparison.OrdinalIgnoreCase) == 0; } var methodType = new SimpleType(Identifier.Create(isVoid ? "Action" : "Func")); IEnumerable <AstType> types = parameters.Select( x => x.GetChildByRole(Roles.Type).Clone()); methodType .TypeArguments .AddRange(types); if (!isVoid) { methodType.TypeArguments.Add(returnType); } var methodName = GetIdentifierName(methodDeclaration); var methodBody = methodDeclaration .GetChildrenByRole(Roles.Body) .FirstOrDefault(); if (methodBody == null) { // method has no method body return; } methodBody = (BlockStatement)methodBody.Clone(); var prototype = new VariableDeclarationStatement { Type = methodType }; prototype.Variables.Add(new VariableInitializer(methodName)); var anonymousMethod = new AnonymousMethodExpression(methodBody, parameters) { IsAsync = isAsync }; var expression = new ExpressionStatement { Expression = new AssignmentExpression( new IdentifierExpression(methodName), anonymousMethod) }; _methods.Add(new MethodVisitorResult { MethodDefinition = methodDeclaration, MethodPrototype = prototype, MethodExpression = expression }); }