public List <EnumDirection> GetEmptySides(MazeMap map, MapPos pos, EnumDirection?lastDir) { List <EnumDirection> list = new List <EnumDirection>(); int curMask = map.GetSegment(pos); Predicate <EnumDirection> dirPre = delegate(EnumDirection d) { MapPos off = pos.Offset(d); if ((curMask & d.BitMask()) != 0) { return(false); } else if (map.IsValid(off) && (map.GetSegment(off) <= 0 || rand.NextDouble() < lpChance)) { return(true); } return(false); }; list.AddAll(MethodExtensions.AllDirections(), dirPre); if (lastDir.HasValue && rand.NextDouble() < strBias && list.Contains(lastDir.Value)) { for (int n = list.Count - 1; n >= 0; n--) { list[n] = lastDir.Value; } } return(list); }
protected void ProcessMethodDeclaration <T>(T node, string simpleName, string fqName, string returnType, Action <string> runWithCurrent, IList <TypeParameterSyntax> typeParameters = null) where T : BaseMethodDeclarationSyntax { typeParameters = typeParameters ?? Array.Empty <TypeParameterSyntax>(); var declaringTypeName = DeclaringTypeNameFor(node); var methodVar = MethodExtensions.LocalVariableNameFor(declaringTypeName, simpleName, node.MangleName(Context.SemanticModel)); AddOrUpdateMethodDefinition(methodVar, fqName, node.Modifiers.MethodModifiersToCecil(ModifiersToCecil, GetSpecificModifiers(), DeclaredSymbolFor(node)), returnType, typeParameters); AddCecilExpression("{0}.Methods.Add({1});", Context.DefinitionVariables.GetLastOf(MemberKind.Type).VariableName, methodVar); HandleAttributesInMemberDeclaration(node.AttributeLists, TargetDoesNotMatch, SyntaxKind.ReturnKeyword, methodVar); // Normal method attrs. HandleAttributesInMemberDeclaration(node.AttributeLists, TargetMatches, SyntaxKind.ReturnKeyword, $"{methodVar}.MethodReturnType"); // [return:Attr] var isAbstract = DeclaredSymbolFor(node).IsAbstract; if (!isAbstract) { ilVar = MethodExtensions.LocalVariableNameFor("il", declaringTypeName, simpleName, node.MangleName(Context.SemanticModel)); AddCecilExpression(@"var {0} = {1}.Body.GetILProcessor();", ilVar, methodVar); } WithCurrentMethod(declaringTypeName, methodVar, fqName, node.ParameterList.Parameters.Select(p => Context.GetTypeInfo(p.Type).Type.Name).ToArray(), runWithCurrent); //TODO: Move this to default ctor handling and rely on VisitReturnStatement here instead if (!isAbstract && !node.DescendantNodes().Any(n => n.Kind() == SyntaxKind.ReturnStatement)) { AddCilInstruction(ilVar, OpCodes.Ret); } }
public override void VisitEnumDeclaration(EnumDeclarationSyntax node) { _memberCollector = new EnumMemberValueCollector(); node.Accept(_memberCollector); var enumType = TempLocalVar(node.Identifier.ValueText); var attrs = ModifiersToCecil("TypeAttributes", node.Modifiers, "Private"); var typeDef = CecilDefinitionsFactory.Type(Context, enumType, node.Identifier.ValueText, attrs + " | TypeAttributes.Sealed", Context.TypeResolver.Resolve("System.Enum"), false, Array.Empty <string>()); AddCecilExpressions(typeDef); using (Context.DefinitionVariables.WithCurrent(node.Parent.IsKind(SyntaxKind.CompilationUnit) ? "" : node.Parent.ResolveDeclaringType().Identifier.ValueText, node.Identifier.ValueText, MemberKind.Type, enumType)) { //.class private auto ansi MyEnum //TODO: introduce TypeSystem.CoreLib.Enum/Action/etc... var fieldVar = MethodExtensions.LocalVariableNameFor("valueField", node.Identifier.ValueText); var valueFieldExp = CecilDefinitionsFactory.Field(enumType, fieldVar, "value__", "assembly.MainModule.TypeSystem.Int32", "FieldAttributes.SpecialName | FieldAttributes.RTSpecialName | FieldAttributes.Public"); AddCecilExpressions(valueFieldExp); HandleAttributesInMemberDeclaration(node.AttributeLists, enumType); base.VisitEnumDeclaration(node); } }
public Fixture() { _grammars.OnAddition = readGrammar; MethodExtensions.ForAttribute <HiddenAttribute>(GetType(), x => Policies.IsPrivate = true); MethodExtensions.ForAttribute <TagAttribute>(GetType(), x => x.Tags.Each(t => Policies.Tag(t))); GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(methodFromThis).Each(method => { string grammarKey = method.GetKey(); try { IGrammar grammar = GrammarBuilder.BuildGrammar(method, this); this[grammarKey] = grammar; MethodExtensions.ForAttribute <HiddenAttribute>(method, x => _policies.HideGrammar(grammarKey)); MethodExtensions.ForAttribute <TagAttribute>(method, x => x.Tags.Each(t => _policies.Tag(grammarKey, t))); } catch (Exception e) { _errors.Add(new GrammarError { ErrorText = e.ToString(), Message = "Could not create Grammar '{0}' of Fixture '{1}'".ToFormat(grammarKey, GetType().GetFixtureAlias()) }); } }); }
public IEnumerable <string> GetErrorMessages() { IList <string> errors = new List <string>(); try { int hash1 = (int)this.Method.Invoke(this.TargetInstance, new object[0]); int hash2 = (int)this.Method.Invoke(this.OtherObject, new object[0]); if (hash1 != hash2) { errors.Add($"{MethodExtensions.GetSignature(this.Method)} returned distinct values on equal objects."); } } catch (TargetInvocationException invocationExc) { errors.Add($"{MethodExtensions.GetSignature(this.Method)} failed - {invocationExc.Message}."); } catch (Exception exc) { errors.Add($"{MethodExtensions.GetSignature(this.Method)} failed - {exc.Message}."); } return(errors); }
static void Main(string[] args) { container = ConfigureContainer(); var revinueService = container.Resolve <IRevenueService>(); DateTime reference = DateTime.Now; Calendar calendar = CultureInfo.CurrentCulture.Calendar; var endDate = DateTime.Now; var startDate = DateTime.Now.AddDays(-30); startDate = startDate.Date.DayOfWeek == DayOfWeek.Sunday? startDate.AddDays(1): startDate; IEnumerable <DateTime> daysInMonth = MethodExtensions.EachDay(startDate, endDate); List <Tuple <DateTime, DateTime> > weeks = daysInMonth.GroupBy(d => calendar.GetWeekOfYear(d, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday)) .Select(g => new Tuple <DateTime, DateTime>(g.First(), (g.Last().DayOfWeek == DayOfWeek.Sunday) ? g.Last().AddDays(-1) : g.Last())) .ToList(); Console.WriteLine("Weekly revenue report with immobilized money from {0:MM/dd/yyyy} to {1:MM/dd/yyyy}\n", startDate, endDate); weeks.ForEach(x => { Console.WriteLine("From {0:MM/dd/yyyy} to {1:MM/dd/yyyy}", x.Item1, x.Item2); var rev = revinueService.GetRevinueBetween(x.Item1, x.Item2); Console.WriteLine($"Revinue => {rev.Revenue} Immobilized money => {rev.Immobilized}\n"); }); Console.ReadKey(); }
private IEnumerable <string> HandleFieldDeclaration(MemberDeclarationSyntax node, VariableDeclarationSyntax variableDeclarationSyntax, SyntaxTokenList modifiers, BaseTypeDeclarationSyntax declaringType) { var declaringTypeVar = Context.DefinitionVariables.GetLastOf(MemberKind.Type).VariableName; var fieldDefVars = new List <string>(variableDeclarationSyntax.Variables.Count); var type = ResolveType(variableDeclarationSyntax.Type); var fieldType = ProcessRequiredModifiers(modifiers, type) ?? type; var fieldAttributes = MapAttributes(modifiers); foreach (var field in variableDeclarationSyntax.Variables) { var fieldVar = MethodExtensions.LocalVariableNameFor("fld", declaringType.Identifier.ValueText, field.Identifier.ValueText.CamelCase()); fieldDefVars.Add(fieldVar); var exps = CecilDefinitionsFactory.Field(declaringTypeVar, fieldVar, field.Identifier.ValueText, fieldType, fieldAttributes); AddCecilExpressions(exps); HandleAttributesInMemberDeclaration(node.AttributeLists, fieldVar); Context.DefinitionVariables.RegisterNonMethod(declaringType.Identifier.Text, field.Identifier.ValueText, MemberKind.Field, fieldVar); } return(fieldDefVars); }
private void readAttributes(ICustomAttributeProvider parameter) { parameter.ForAttributes <ICellModifier>(x => x.Modify(this)); MethodExtensions.ForAttribute <SelectionValuesAttribute>(parameter, att => _selectionAttribute = att); readType(); }
public void CallMethod_By_Delegate() { var getAreaInvoker = MethodExtensions.DelegateForCallMethod(widgetType, "GetArea"); foreach (var widget in _widgets) { var area = (double)getAreaInvoker.Invoke(widget); Assert.AreEqual(widget.GetArea(), area); } }
private void ProcessPrefixPostfixOperators(ExpressionSyntax operand, OpCode opCode, bool isPrefix) { Visit(operand); InjectRequiredConversions(operand); var assignmentVisitor = new AssignmentVisitor(Context, ilVar); var operandInfo = Context.SemanticModel.GetSymbolInfo(operand); if (operandInfo.Symbol != null && operandInfo.Symbol.Kind != SymbolKind.Field && operandInfo.Symbol.Kind != SymbolKind.Property) // Fields / Properties requires more complex handling to load the owning reference. { if (!isPrefix) // For *postfix* operators we duplicate the value *before* applying the operator... { AddCilInstruction(ilVar, OpCodes.Dup); } AddCilInstruction(ilVar, OpCodes.Ldc_I4_1); AddCilInstruction(ilVar, opCode); if (isPrefix) // For prefix operators we duplicate the value *after* applying the operator... { AddCilInstruction(ilVar, OpCodes.Dup); } //assign (top of stack to the operand) assignmentVisitor.InstructionPrecedingValueToLoad = Context.CurrentLine; operand.Accept(assignmentVisitor); return; } var tempLocalName = MethodExtensions.LocalVariableNameFor("tmp_", "tmp_".UniqueId().ToString()); AddCecilExpression($"var {tempLocalName} = new VariableDefinition({Context.TypeResolver.Resolve(Context.SemanticModel.GetTypeInfo(operand).Type)});"); AddCecilExpression($"{Context.DefinitionVariables.GetLastOf(MemberKind.Method).VariableName}.Body.Variables.Add({tempLocalName});"); if (isPrefix) { AddCilInstruction(ilVar, OpCodes.Ldc_I4_1); AddCilInstruction(ilVar, opCode); } AddCilInstruction(ilVar, OpCodes.Stloc, tempLocalName); AddCilInstruction(ilVar, OpCodes.Ldloc, tempLocalName); assignmentVisitor.InstructionPrecedingValueToLoad = Context.CurrentLine; AddCilInstruction(ilVar, OpCodes.Ldloc, tempLocalName); if (!isPrefix) { AddCilInstruction(ilVar, OpCodes.Ldc_I4_1); AddCilInstruction(ilVar, opCode); } // assign (top of stack to the operand) operand.Accept(assignmentVisitor); }
public static T GetOrAddComponent <T>() where T : Component { Component c; if (Instance.cache.TryGetValue(typeof(T), out c)) { return((T)c); } T component = MethodExtensions.GetOrAddComponent <T>(Instance); Instance.cache.Add(typeof(T), component); return(component); }
private void DeclareAndInitializeValueTypeLocalVariable() { var resolvedVarType = Context.TypeResolver.Resolve(ctorInfo.Symbol.ContainingType); var tempLocalName = MethodExtensions.LocalVariableNameFor("tmp_", "tmp_".UniqueId().ToString()); AddCecilExpression("var {0} = new VariableDefinition({1});", tempLocalName, resolvedVarType); AddCecilExpression("{0}.Body.Variables.Add({1});", Context.DefinitionVariables.GetLastOf(MemberKind.Method).VariableName, tempLocalName); AddCilInstruction(ilVar, OpCodes.Ldloca_S, tempLocalName); AddCilInstruction(ilVar, OpCodes.Initobj, ctorInfo.Symbol.ContainingType.ResolveExpression(Context)); AddCilInstruction(ilVar, OpCodes.Ldloc, tempLocalName); }
/// <summary> /// 특정 수형의 특정 메소드를 호출할 수 있는 델리게이트를 제공합니다. /// </summary> /// <seealso cref="MethodExtensions.DelegateForCallMethod(System.Type,string,System.Type[])"/> public static MethodInvoker GetMethodInvoker(this Type instanceType, string methodName, params Type[] parameterTypes) { instanceType.ShouldNotBeNull("instanceType"); methodName.ShouldNotBeWhiteSpace("methodName"); if (IsDebugEnabled) { log.Debug("Get CallMethod for Delegate... instanceType=[{0}], methodName=[{1}], parameterTypes=[{2}]", instanceType, methodName, parameterTypes.CollectionToString()); } return(MethodExtensions.DelegateForCallMethod(instanceType, methodName, parameterTypes)); }
public static string Constructor(IVisitorContext context, out string ctorLocalVar, string typeName, string methodAccessibility, string[] paramTypes, string methodDefinitionPropertyValues = null) { ctorLocalVar = MethodExtensions.LocalVariableNameFor(typeName, "ctor", ""); context.DefinitionVariables.RegisterMethod(typeName, ".ctor", paramTypes, ctorLocalVar); var exp = $@"var {ctorLocalVar} = new MethodDefinition("".ctor"", {methodAccessibility} | MethodAttributes.HideBySig | {ConstructorDeclarationVisitor.CtorFlags}, assembly.MainModule.TypeSystem.Void)"; if (methodDefinitionPropertyValues != null) { exp = exp + $"{{ {methodDefinitionPropertyValues} }}"; } return(exp + ";"); }
public static MethodInfo GetOperatorOverload(string name, ArgumentConversions conversions, params Type[] types) { for (int i = 0; i < types.Length; i++) { var members = types[i].GetMember(name, PublicStatic); foreach (MethodInfo m in members) { if (MethodExtensions.MatchesArgumentTypes(m, types, conversions)) { return(m); } } } return(null); }
public static MethodInfo BindToMethod(MemberInfo[] members, Type[] types, out ArgumentConversions bindings) { bindings = new ArgumentConversions(types.Length); foreach (var m in members) { if (m.MemberType == MemberTypes.Method) { if (MethodExtensions.MatchesArgumentTypes((MethodInfo)m, types, bindings)) { return((MethodInfo)m); } } } return(null); }
public Cell(ParameterInfo parameter) { _key = parameter.Name; _type = parameter.ParameterType; if (parameter.Name.IsEmpty()) { _key = "returnValue"; MethodExtensions.ForAttribute <AliasAsAttribute>(parameter, att => _key = att.Alias); IsResult = true; } readAttributes(parameter); }
public override void VisitParenthesizedExpression(ParenthesizedExpressionSyntax node) { base.VisitParenthesizedExpression(node); var localVarParent = (CSharpSyntaxNode)node.Parent; if (localVarParent.Accept(new UsageVisitor()) == UsageKind.CallTarget) { var tempLocalName = MethodExtensions.LocalVariableNameFor("tmp_", "tmp_".UniqueId().ToString()); AddCecilExpression("var {0} = new VariableDefinition(assembly.MainModule.TypeSystem.Int32);", tempLocalName); AddCecilExpression("{0}.Body.Variables.Add({1});", Context.DefinitionVariables.GetLastOf(MemberKind.Method).VariableName, tempLocalName); AddCilInstruction(ilVar, OpCodes.Stloc, tempLocalName); AddCilInstruction(ilVar, OpCodes.Ldloca_S, tempLocalName); } }
public override void VisitEnumMemberDeclaration(EnumMemberDeclarationSyntax node) { // Adds a field like: // .field public static literal valuetype xxx.MyEnum Second = int32(1) var enumMemberValue = _memberCollector[node]; var enumVarDef = Context.DefinitionVariables.GetLastOf(MemberKind.Type); var fieldVar = MethodExtensions.LocalVariableNameFor($"em_{enumVarDef.MemberName}_{NextLocalVariableId()}", node.Identifier.ValueText); var exp = CecilDefinitionsFactory.Field(enumVarDef.VariableName, fieldVar, node.Identifier.ValueText, enumVarDef.VariableName, "FieldAttributes.Static | FieldAttributes.Literal | FieldAttributes.Public | FieldAttributes.HasDefault", $"Constant = {enumMemberValue}"); AddCecilExpressions(exp); HandleAttributesInMemberDeclaration(node.AttributeLists, fieldVar); base.VisitEnumMemberDeclaration(node); }
public override void VisitLiteralExpression(LiteralExpressionSyntax node) { switch (node.Kind()) { case SyntaxKind.NullLiteralExpression: AddCilInstruction(ilVar, OpCodes.Ldnull); break; case SyntaxKind.StringLiteralExpression: AddCilInstruction(ilVar, OpCodes.Ldstr, node.ToFullString()); break; case SyntaxKind.CharacterLiteralExpression: case SyntaxKind.NumericLiteralExpression: AddLocalVariableAndHandleCallOnValueTypeLiterals(node, "assembly.MainModule.TypeSystem.Int32", node.ToString()); break; case SyntaxKind.TrueLiteralExpression: case SyntaxKind.FalseLiteralExpression: AddLocalVariableAndHandleCallOnValueTypeLiterals(node, "assembly.MainModule.TypeSystem.Boolean", bool.Parse(node.ToString()) ? 1 : 0); break; default: throw new ArgumentException($"Literal ( {node}) of type {node.Kind()} not supported yet."); } void AddLocalVariableAndHandleCallOnValueTypeLiterals(LiteralExpressionSyntax literalNode, string cecilTypeSystemReference, object literalValue) { AddCilInstruction(ilVar, LoadOpCodeFor(literalNode), literalValue); var localVarParent = (CSharpSyntaxNode)literalNode.Parent; if (localVarParent.Accept(new UsageVisitor()) == UsageKind.CallTarget) { var tempLocalName = MethodExtensions.LocalVariableNameFor("tmp_", "tmp_".UniqueId().ToString()); AddCecilExpression("var {0} = new VariableDefinition({1});", tempLocalName, cecilTypeSystemReference); AddCecilExpression("{0}.Body.Variables.Add({1});", Context.DefinitionVariables.GetLastOf(MemberKind.Method).VariableName, tempLocalName); AddCilInstruction(ilVar, OpCodes.Stloc, $"{tempLocalName}"); AddCilInstruction(ilVar, OpCodes.Ldloca_S, $"{tempLocalName}"); } } }
private async Task Load(Action action) { //Run main script await Task.Run(action).ConfigureAwait(true); //Load scene MethodExtensions.LogWithElapsedTime("Load main scene"); await this.StartCoroutineAsync(PreLoadScene()).ConfigureAwait(true); MethodExtensions.LogWithElapsedTime(""); //Done #if DEBUG StartGame(); #else _loading = false; LoadingText.text = "Press any key to start"; LoadingText.color = Color.magenta; #endif }
private void DoPass(CellMap map) { List <KeyValuePair <MapPos, EnumCellState> > baseList = new List <KeyValuePair <MapPos, EnumCellState> >(); (from e in MethodExtensions.MapToKeyPairs(map) where map.IsValid(e.Key) && !e.Value.IsLocked() select e).ToList().ForEach(x => baseList.Add(x)); foreach (KeyValuePair <MapPos, EnumCellState> pair in baseList) { MapPos p1 = pair.Key; int neighbours = GetNeighbours(map, p1); if (neighbours < minCells) { map.SetSegment(p1, EnumCellState.OPEN); } else if (neighbours > maxCells) { map.SetSegment(p1, EnumCellState.CLOSED); } } }
public IEnumerable <string> GetErrorMessages() { IList <string> errors = new List <string>(); try { TResult actualResult = (TResult)this.Method.Invoke(this.TargetObject, this.MethodParameters); if (!actualResult.Equals(this.ExpectedResult)) { errors.Add( $"{MethodExtensions.GetSignature(this.Method, this.MethodLabel)} returned {actualResult} when expecting {this.ExpectedResult} - {this.TestCase}"); } } catch (TargetInvocationException invocationExc) { errors.Add($"{MethodExtensions.GetSignature(this.Method)} failed - {invocationExc.Message}."); } catch (Exception exc) { errors.Add($"{MethodExtensions.GetSignature(this.Method)} failed - {exc.Message}."); } return(errors); }
public void CanInvokeProcedureMethodByReflection() { var result = MethodExtensions.CallMethod(_widget, ProcedureMethod); Assert.IsNotNull(result); }