public void Simple() { var hashList = new HashList <int, string> { { 2, "a" } }; Assert.AreEqual(hashList.ValueCount, 1); Assert.AreEqual(hashList.KeyCount, 1); hashList.Add(4, new List <string>(new[] { "2", "3", "4", "5" })); Assert.AreEqual(hashList.ValueCount, 5); Assert.AreEqual(hashList.KeyCount, 2); var enumerator = hashList.GetValueEnumerator(); var list = new List <string>(); while (enumerator.MoveNext()) { list.Add(enumerator.Current); } Assert.AreEqual(list.Count, 5); Assert.IsTrue(list.Contains("a")); Assert.IsTrue(list.Contains("2")); Assert.IsTrue(list.Contains("3")); Assert.IsTrue(list.Contains("4")); Assert.IsTrue(list.Contains("5")); }
public void ExceptionInvalidRange() { var hashList = new HashList<int, string> { {3, (List<string>) null} }; }
public void Simple() { var hashList = new HashList<int, string> {{2, "a"}}; Assert.AreEqual(hashList.ValueCount, 1); Assert.AreEqual(hashList.KeyCount, 1); hashList.Add(4, new List<string>(new[] { "2", "3", "4", "5" })); Assert.AreEqual(hashList.ValueCount, 5); Assert.AreEqual(hashList.KeyCount, 2); var enumerator = hashList.GetValueEnumerator(); var list = new List<string>(); while (enumerator.MoveNext()) { list.Add(enumerator.Current); } Assert.AreEqual(list.Count, 5); Assert.IsTrue(list.Contains("a")); Assert.IsTrue(list.Contains("2")); Assert.IsTrue(list.Contains("3")); Assert.IsTrue(list.Contains("4")); Assert.IsTrue(list.Contains("5")); }
public void TestSuccesfulInit() { HashList <string, int> h = new HashList <string, int>(); Assert.AreEqual(h.Count, 0); Dictionary <string, IList <int> > dict = new Dictionary <string, IList <int> >(); dict.Add("aa", new List <int>()); dict.Add("bb", new List <int>()); dict.Add("cc", new List <int>()); dict["bb"].Add(5); dict["bb"].Add(6); dict["cc"].Add(2); h = new HashList <string, int>(dict); Assert.AreEqual(h.Count, 3); Assert.AreEqual(h.ValueCount, 3); Assert.AreEqual(h["aa"].Count, 0); Assert.AreEqual(h["bb"].Count, 2); Assert.AreEqual(h["cc"].Count, 1); Assert.AreEqual(h["bb"][0], 5); Assert.AreEqual(h["bb"][1], 6); Assert.AreEqual(h["cc"][0], 2); h = new HashList <string, int>(50); Assert.AreEqual(h.Count, 0); Assert.AreEqual(h.ValueCount, 0); }
public void TestGetValueEnumerator() { HashList <int, string> h = new HashList <int, string>(); h.Add(2, "a"); Assert.AreEqual(h.ValueCount, 1); Assert.AreEqual(h.KeyCount, 1); h.Add(4, new List <string>(new string[] { "2", "3", "4", "5" })); Assert.AreEqual(h.ValueCount, 5); Assert.AreEqual(h.KeyCount, 2); IEnumerator <string> enumerator = h.GetValueEnumerator(); List <string> list = new List <string>(); while (enumerator.MoveNext()) { list.Add(enumerator.Current); } Assert.AreEqual(list.Count, 5); Assert.AreEqual(list.Contains("a"), true); Assert.AreEqual(list.Contains("2"), true); Assert.AreEqual(list.Contains("3"), true); Assert.AreEqual(list.Contains("4"), true); Assert.AreEqual(list.Contains("5"), true); }
public void SetItem_IList_OutOfRange() { IList <string> list = new HashList <string> { [0] = "foo" }; }
public void ExceptionInvalidRange() { var hashList = new HashList <int, string> { { 3, (List <string>)null } }; }
public void VersionCheck_RemoveAt() { var list = new HashList <int> { 5 }; IEnumerator enumerator = list.GetEnumerator(); list.RemoveAt(0); try { enumerator.MoveNext(); Assert.Fail("#1"); } catch (InvalidOperationException) { } try { enumerator.Reset(); Assert.Fail("#2"); } catch (InvalidOperationException) { } enumerator = list.GetEnumerator(); enumerator.MoveNext(); }
public void VersionCheck_Remove() { var list = new HashList <int> { 5 }; IEnumerator enumerator = list.GetEnumerator(); // version number is not incremented if item does not exist in list list.Remove(7); enumerator.MoveNext(); list.Remove(5); try { enumerator.MoveNext(); Assert.Fail("#1"); } catch (InvalidOperationException) { } try { enumerator.Reset(); Assert.Fail("#2"); } catch (InvalidOperationException) { } enumerator = list.GetEnumerator(); enumerator.MoveNext(); }
public void VersionCheck_AddRange() { var list = new HashList <int>(); IEnumerator enumerator = list.GetEnumerator(); list.AddRange(new int[] { 5, 7 }); try { enumerator.MoveNext(); Assert.Fail("#1"); } catch (InvalidOperationException) { } try { enumerator.Reset(); Assert.Fail("#2"); } catch (InvalidOperationException) { } enumerator = list.GetEnumerator(); enumerator.MoveNext(); }
protected MethodEntityBase(TypeEntity type, bool isImported = false) : base(type) { Arguments = new HashList<FunctionArgument>(); IsImported = isImported; }
public override PathCond Or(PathCond other) { if (other is CachedAtom && conds.Contains(((CachedAtom)other).Negate())) { // Reduce Or(OR(...,e,...), NOT(e)) and Or(OR(...,NOT(e),...), e) to TRUE return TRUE; } else if (other is Disj) { HashList<PathCond> result = new HashList<PathCond>(); result.AddAll(conds); foreach (PathCond cond in ((Disj)other).conds) { if (cond is CachedAtom && conds.Contains((cond as CachedAtom).Negate())) { // Reduce Or(OR(...,e,...),OR(...,NOT(e),...)) to TRUE // and Or(OR(...,NOT(e),...),OR(...,e,...)) to TRUE return TRUE; } result.Add(cond); } return Disj.Make(result.ToArray()); } else if (other is Conj) { if (((Conj)other).conds.Contains(this)) { // Reduce (pi | (p1 & ... & pn)) to pi return this; } else { if (((Conj)other).conds.Any(cond => conds.Contains(cond))) { return this; } } return Disj.Make(AddItem(this.conds, other)); } else { return Disj.Make(AddItem(this.conds, other)); } }
public static void ClearAllCachedAttributes() { try { BaseClass = string.Empty; ClassName = string.Empty; if (HashClassGUID != null) { HashClassGUID.Clear(); } if (HashList != null) { HashList.Clear(); } if (HashTableBaseClass != null) { HashTableBaseClass.Clear(); } if (OMResultedQuery != null) { OMResultedQuery.Clear(); } QueryResultToolWindow = null; Tab_index = 0; ListofModifiedObjects.Instance.Clear(); } catch (Exception oEx) { LoggingHelper.ShowMessage(oEx); } }
public virtual HashList Range(IHashItem query, int range) { HashList r = RangeTraversal(query, range, Root, new HashList()); r.CustomSort(0, r.Count - 1); return(r); }
public void ConvertHashType() { if (!HashList.ContainsKey("Hash")) { return; } ProtoHashList = new Dictionary <string, List <KeyInfo> >(); foreach (var item in HashList?["Hash"]) { try { var type = (HashType)item.KeyObject.HashType; string typeStr = type.ToString(); if (!ProtoHashList.ContainsKey(typeStr)) { ProtoHashList.Add(typeStr, new List <KeyInfo>()); } ProtoHashList[typeStr].Add(item); } catch (Exception e) { Logger.WriteInfo($"Convert hash key exception: {item}"); } } }
public MemberNameGenerator(BuildLog log, Random random) { if (log == null) { throw new ArgumentNullException("log"); } if (random == null) { throw new ArgumentNullException("random"); } _random = random; _log = log; _charSet = AsciiCharSet; _charSet = _charSet.NewCopy(); _charSet.Shuffle(_random); _charSetLength = _charSet.Length; _stringLength = 1; _chars = new char[_stringLength]; _pointers = new int[_stringLength]; _strings = new HashList <string>(); _existingStrings = new HashList <string>(); foreach (string name in log.NewNames) { _existingStrings.Add(name); } }
private static IProductionRuleCaptureStructure BuildStructureFor(OilexerGrammarProductionRuleEntry entry, IProductionRuleSeries expressionSeries, IOilexerGrammarFile source) { IProductionRuleCaptureStructure result = null; HashList <HashList <string> > currentResultVariants = new HashList <HashList <string> >(); foreach (var expression in expressionSeries) { var current = BuildStructureFor(entry, expressionSeries, expression, source); if (result == null) { result = current; } else { result = result.Union(current); } var dataSet = new HashList <string>(current.Keys); if (!currentResultVariants.Any(k => k.SequenceEqual(dataSet))) { currentResultVariants.Add(dataSet); } } foreach (var variant in currentResultVariants) { result.Structures.Add(variant); } if (expressionSeries == entry) { ((ControlledCollection <IProductionRuleSource>)result.Sources).baseList.Add(entry); } result.ResultedTypeName = string.Format("{0}{1}{2}", source.Options.RulePrefix, entry.Name, source.Options.RuleSuffix); return(result); }
private HashList RangeTraversal(IHashItem query, int range, Node tNode, HashList results) { if (tNode != null) { int sortdistance = query.CalculateDistance(tNode.HashItem); if (sortdistance < range) { results.Add(tNode.HashItem); tNode.HashItem.SortDistance = sortdistance; } if (sortdistance + range < tNode.Distance) { RangeTraversal(query, range, tNode.Left, results); } else if (sortdistance - range > tNode.Distance) { RangeTraversal(query, range, tNode.Right, results); } else { RangeTraversal(query, range, tNode.Left, results); RangeTraversal(query, range, tNode.Right, results); } } return(results); }
public virtual HashList <T> Range(T query, int range) { HashList <T> r = RangeTraversal(query, range, Root, new HashList <T>()); r.CustomSort(0, r.Count - 1); return(r); }
private async Task <List <FileData> > EnumerateDownloadableFilesFromHashList(string path) { HashList = await SmartCopy.GetHashList(remote, true); List <FileData> workingList = HashList.Where(f => f.RelativePath.StartsWith(path)).ToList(); OnReportTotalFilesCount?.Invoke(workingList.Count); var retv = new List <FileData>(); foreach (var a in HashList) { string hash = ""; if (local.Exists(a.RelativePath)) { local.Read(a.RelativePath, async(stream) => { await Task.Yield(); hash = await GetHash(stream); }).Wait(); } var gzSuffix = ""; if (options.UseGZip) { gzSuffix = GZIP_FILE_SUFFIX; } while ((a.Hash != hash || !local.Exists(a.RelativePath))) { if (remote.Exists(a.RelativePath + gzSuffix)) { retv.Add(a); } } } return(retv); }
private void InitializeSpecialistCharacters() { specialistAliveList = new HashList <Spatial>(); if (specialistCharacters != null) { int specialistAmount = GetGlobal <int>("specialistAmount"); for (int i = 0; i < specialistCharacters.Length; i++) { if (i < specialistAmount && GetGlobal <int>("livesSpecialistIndex" + i) > -1) { specialistAliveList.Add(specialistCharacters[i]); specialistCharacters[i].Connect(this.GetGDSignalTreeExited(), this, nameof(OnSpecialistDead), this.CreateSingleBind(specialistCharacters[i])); } else { specialistCharacters[i].Visible = false; specialistCharacters[i].QueueFree(); } } } }
/// <summary> /// Build a list of all the Formula and ArrayFormula cells that the outputCell /// depends on, in calculation order. /// </summary> /// <returns>Cells sorted in calculation order; output cell last.</returns> public IList <FullCellAddr> PrecedentOrder() { HashList <FullCellAddr> sorted = new HashList <FullCellAddr>(); AddNode(sorted, outputCell); return(sorted.ToArray()); }
public static PathCond Make(params PathCond[] conjs) { HashList <PathCond> result = new HashList <PathCond>(); foreach (PathCond conj in conjs) { if (conj.Is(false)) { return(FALSE); } else if (!conj.Is(true)) { result.Add(conj); } } if (result.Count == 0) { return(TRUE); } else if (result.Count == 1) { return(result.Single()); } else { return(new Conj(result.ToArray())); } }
public static string NextUniqueString(this Random random, HashList <string> hash, int size, bool includeDigits = false) { char[] chars = new char[size]; char[] charSet = includeDigits ? StringGenerator.AsciiLetterOrDigit : StringGenerator.AsciiLetter; int charSetLength = charSet.Length; int count = 0; string s; do { if (count > 20) { count = 0; size++; chars = new char[size]; } for (int i = 0; i < size; i++) { chars[i] = charSet[random.Next(0, charSetLength)]; } s = new string(chars); count++; }while (hash.Contains(s)); return(s); }
public override PathCond Or(PathCond other) { if (this.Is(true) || other.Is(true)) { return(TRUE); } else if (this.Is(false)) { return(other); } else if (other.Is(false)) { return(this); } else if (conds.Contains(other)) { // Reduce ((p1 & ... & pn)) | pi to pi return(other); } else if (other is Disj) { // TODO: This doesn't preserve order of disjuncts: return(other.Or(this)); } else if (other is Conj) { if ((other as Conj).conds.Contains(this)) { // Reduce (pi | (p1 & ... & pn)) to pi return(this); } else { HashList <PathCond> intersect = HashList <PathCond> .Intersection(this.conds, (other as Conj).conds); if (intersect.Count > 0) { // Reduce (p1 & ... & pn & q1 & ... & qm) | (p1 & ... & pn & r1 & ... & rk) // to (p1 & ... & pn & (q1 & ... & qm | r1 & ... & rk). // The pi go in intersect, qi in thisRest, and ri in otherRest. HashList <PathCond> thisRest = HashList <PathCond> .Difference(this.conds, intersect); HashList <PathCond> otherRest = HashList <PathCond> .Difference((other as Conj).conds, intersect); // This recursion terminates because thisRest is smaller than this.conds intersect.Add(Conj.Make(thisRest.ToArray()).Or(Conj.Make(otherRest.ToArray()))); return(Conj.Make(intersect.ToArray())); } else { return(Disj.Make(AddItem(this.conds, other))); } } } else { return(Disj.Make(this, other)); } }
public override bool Equals(HashList <TypeModification> other) { if (other is ITypeModifierSetEntry) { return(this.Equals((ITypeModifierSetEntry)other)); } return(base.Equals(other)); }
protected static PathCond[] AddItem(IEnumerable <PathCond> set, PathCond item) { HashList <PathCond> result = new HashList <PathCond>(); result.AddAll(set); result.Add(item); return(result.ToArray()); }
internal LahPlayer(LahGame game, int id) { Game = game; Id = id; _hand = new HashList <WhiteCard>(); _selectedCards = new HashList <WhiteCard>(); _prevPlays = new List <RoundPlay>(); }
public HashList Range(IHashItem item, int d) { HashList rtn = new HashList(); RecursiveSearch(_root, rtn, item, d); rtn.CustomSort(0, rtn.Count - 1); return(rtn); }
protected MethodEntityBase(bool isImported = false) { Body = new CodeBlockNode(); Arguments = new HashList<FunctionArgument>(); Scope = new Scope(); IsImported = isImported; }
public virtual void DiscardTokenType(int ttype) { if (discardSet == null) { discardSet = new HashList(); } discardSet.Add(ttype.ToString(), ttype); }
public void AddRange_Bug77019() { var l = new HashList <int>(); var d = new Dictionary <string, int>(); l.AddRange(d.Values); Assert.AreEqual(0, l.Count, "Count"); }
/// <summary> /// Adds named services to the dependency map. /// </summary> /// <param name="map">The dependency map.</param> /// <param name="serviceList">The list of named services that will be added to the container.</param> internal static void RegisterNamedServices(this DependencyMap map, HashList<System.Type, IServiceInfo> serviceList) { // Register the named services foreach (var serviceType in serviceList.Keys) { var services = serviceList[serviceType]; Register(map, services); } }
public static HashList Concat(this HashList hashList1, HashList hashList2) { var hashes = hashList1.Values; hashes.AddRange(hashList2.Values); return(new HashList { Values = { hashes } }); }
/// <summary> /// Adds named services to the dependency map. /// </summary> /// <param name="map">The dependency map.</param> /// <param name="serviceList">The list of named services that will be added to the container.</param> internal static void RegisterNamedServices(this DependencyMap map, HashList <System.Type, IServiceInfo> serviceList) { // Register the named services foreach (var serviceType in serviceList.Keys) { var services = serviceList[serviceType]; Register(map, services); } }
[Test] // was bug in Mono 2.10.9 public void DotNetDoesntThrowObjectDisposedExceptionAfterSubsequentDisposes() { var enumerable = new HashList <Bar>(); var enumerator = enumerable.GetEnumerator(); Assert.AreEqual(false, enumerator.MoveNext()); enumerator.Dispose(); Assert.AreEqual(false, enumerator.MoveNext()); }
public void AddExample() { var whatAnimalEatHashList = new HashList<string, string>(); whatAnimalEatHashList.Add("cat", "milk"); whatAnimalEatHashList.Add("cat", "fish"); whatAnimalEatHashList.Add("dog", "dog food"); whatAnimalEatHashList.Add("dog", "bones"); whatAnimalEatHashList.Add("tiger", "people"); // There should be 3 items. Assert.AreEqual(3, whatAnimalEatHashList.Count); }
public void Simple() { var hashList = new HashList<int, string> {{2, "a"}}; Assert.AreEqual(hashList.ValueCount, 1); Assert.AreEqual(hashList.KeyCount, 1); hashList.Add(4, new List<string>(new[] { "2", "3", "4", "5" })); Assert.AreEqual(hashList.ValueCount, 5); Assert.AreEqual(hashList.KeyCount, 2); }
public void ConstructorCapacityExample() { // If you know how many items will initially be in the HashList it is // more efficient to set the initial capacity var whatAnimalEatHashList = new HashList<string, string>(3) { {"cat", "milk"}, {"cat", "fish"}, {"dog", "dog food"}, {"dog", "bones"}, {"tiger", "people"} }; }
public void AddParamsExample() { var whatAnimalEatHashList = new HashList<string, string>(); whatAnimalEatHashList.Add("cat", "milk", "fish"); whatAnimalEatHashList.Add("dog", "dog food", "bones"); whatAnimalEatHashList.Add("tiger", "people"); // There are 3 keys. Assert.AreEqual(3, whatAnimalEatHashList.KeyCount); // There are 5 values. Assert.AreEqual(5, whatAnimalEatHashList.ValueCount); }
public void Simple() { var hashList = new HashList<string, int>(); Assert.AreEqual(hashList.Count, 0); var dictionary = new Dictionary<string, IList<int>> { {"aa", new List<int>()}, {"bb", new List<int>()}, {"cc", new List<int>()} }; dictionary["bb"].Add(5); dictionary["bb"].Add(6); dictionary["cc"].Add(2); hashList = new HashList<string, int>(dictionary); Assert.AreEqual(hashList.Count, 3); Assert.AreEqual(hashList.ValueCount, 3); Assert.AreEqual(hashList["aa"].Count, 0); Assert.AreEqual(hashList["bb"].Count, 2); Assert.AreEqual(hashList["cc"].Count, 1); Assert.AreEqual(hashList["bb"][0], 5); Assert.AreEqual(hashList["bb"][1], 6); Assert.AreEqual(hashList["cc"][0], 2); hashList = new HashList<string, int>(50); Assert.AreEqual(hashList.Count, 0); Assert.AreEqual(hashList.ValueCount, 0); hashList = new HashList<string, int>(EqualityComparer<string>.Default); Assert.AreEqual(hashList.Count, 0); Assert.AreEqual(hashList.ValueCount, 0); hashList = new HashList<string, int>(20, EqualityComparer<string>.Default); Assert.AreEqual(hashList.Count, 0); Assert.AreEqual(hashList.ValueCount, 0); }
public WebServer(int port, int webPort, HostTopology topology) { buffer = new byte[WebManager.PACKET_SIZE]; ms = new MemoryStream(buffer); reader = new BinaryReader(ms); writer = new BinaryWriter(ms); players = new List<Player>(); connections = new Dictionary<int, Player>(); history = new Dictionary<Vint3, List<AreaHistory>>(); changes = new HashList<Vint3>(); channel = 0; movement = 1; host = NetworkTransport.AddHost(topology, port); webHost = NetworkTransport.AddWebsocketHost(topology, webPort, null); }
public void Params() { var hashList = new HashList<int, string> { {2, "a", "b"} }; Assert.AreEqual(hashList.ValueCount, 2); Assert.AreEqual(hashList.KeyCount, 1); hashList.Add(4, "2", "3", "4", "5"); Assert.AreEqual(hashList.ValueCount, 6); Assert.AreEqual(hashList.KeyCount, 2); hashList.Add(2, "2", "3", "4", "5"); Assert.AreEqual(hashList.ValueCount, 10); Assert.AreEqual(hashList.KeyCount, 2); }
public void ConstructorComparerExample() { var whatAnimalEatHashListIgnoreCase = new HashList<string, string>(StringComparer.OrdinalIgnoreCase) { {"cat", "milk"}, {"CAT", "fish"} }; // KeyCount is 1 because case is ignored Assert.AreEqual(1, whatAnimalEatHashListIgnoreCase.KeyCount); var whatAnimalEatHashListUseCase = new HashList<string, string>(StringComparer.Ordinal) { {"cat", "milk"}, {"CAT", "fish"} }; // KeyCount is 2 because case is not ignored Assert.AreEqual(2, whatAnimalEatHashListUseCase.KeyCount); }
public static PathCond Make(params PathCond[] conjs) { HashList<PathCond> result = new HashList<PathCond>(); foreach (PathCond conj in conjs) { if (conj.Is(false)) { return FALSE; } else if (!conj.Is(true)) { result.Add(conj); } } if (result.Count == 0) { return TRUE; } else if (result.Count == 1) { return result.Single(); } else { return new Conj(result.ToArray()); } }
public void Simple() { var hashList = new HashList<int, string> { {2, "a"}, {2, "b"}, {3, "b"}, {3, "c"}, {3, "d"}, {4, "c"} }; var newHash = SerializeUtil.BinarySerializeDeserialize(hashList); Assert.AreNotSame(hashList, newHash); Assert.AreEqual(hashList.Count, newHash.Count); var hashListEnumerator = hashList.GetEnumerator(); var newHashEnumerator = newHash.GetEnumerator(); while (hashListEnumerator.MoveNext()) { Assert.IsTrue(newHashEnumerator.MoveNext()); Assert.AreEqual(hashListEnumerator.Current.Key, newHashEnumerator.Current.Key); var l1 = hashListEnumerator.Current.Value; var l2 = newHashEnumerator.Current.Value; Assert.AreNotSame(l1, l2); Assert.AreEqual(l1.Count, l2.Count); for (var i = 0; i < l1.Count; i++) { Assert.AreEqual(l1[i], l2[i]); } } Assert.IsFalse(newHashEnumerator.MoveNext()); }
// Use this for initialization void Start () { list = new List<HashList<int>>(); for (int i = 0; i < 1000; i++) { var hash = new HashList<int>(15000); for (int j = 0; j < 10000; j++) { hash.Add(Random.Range(int.MinValue, int.MaxValue)); } } var set = new HashList<int>(); Debug.Log("Add 1 " + set.Add(1)); Debug.Log("Add 1 " + set.Add(1)); set.Add(30000); set.Add(444); Debug.Log("Add 5555 " + set.Add(5555)); set.Add(500000); set.Add(364892679); set.Remove(444); Debug.Log("Set contains 444 = " + set.Contains(444)); Debug.Log("Size = " + set.Count); foreach (var i in set) { Debug.Log("Set contains " + i + " = " + set.Contains(i)); } Debug.Log("Set contains 11 = " + set.Contains(11)); Debug.Log("Set contains 23 = " + set.Contains(23)); Debug.Log("Set contains 16 = " + set.Contains(16)); Debug.Log("Set contains 32 = " + set.Contains(32)); Debug.Log("Set contains 33 = " + set.Contains(33)); }
/// <summary> /// Creates a new method with argument types given by function arguments. /// </summary> internal MethodEntity CreateMethod(string name, TypeSignature returnType, IEnumerable<FunctionArgument> args = null, bool isStatic = false, bool isVirtual = false, bool prepare = false) { var argHash = new HashList<FunctionArgument>(); if(args != null) foreach (var curr in args) argHash.Add(curr.Name, curr); var me = createMethodCore(name, isStatic, isVirtual, prepare); me.ReturnTypeSignature = returnType; me.Arguments = argHash; return me; }
/// <summary> /// 初始化 /// </summary> private void init() { loadDic = new Dictionary<string, LoadInfo>(); unZipList = new HashList<string, LoadInfo>(); }
/// <summary> /// Create a method in a type /// </summary> /// <param name="owner">Owner type node</param> /// <param name="name">Method name</param> /// <param name="type">Method return value type signature</param> /// <param name="parameters">Method parameters list</param> /// <param name="isStatic">Static flag</param> /// <returns></returns> public MethodNode CreateMethod(TypeNode owner, string name, SignatureNode type, HashList<ParameterNode> parameters = null, bool isStatic = false, bool prepare = false) { // cannot add methods to built-in types if (owner.BuiltIn) throw new CompilerException(String.Format(Resources.errExtendBuiltInType, owner.Name)); // create method in assembly and in Mirelle Registry var method = new MethodNode(name, type, isStatic); method.SetParameters(parameters); // check if an identical method hasn't already been declared if (owner.Methods.Contains(method.Name)) { if(owner.Methods[method.Name].Exists(curr => curr.Signature == method.Signature)) throw new CompilerException(String.Format(Resources.errMethodRedefinition, method.Name, owner.Name)); } // register method in the parent type AddMethod(owner, method); method.Owner = owner; if (prepare) PrepareMethod(method); return method; }
/// <summary> /// Create type instance constructor /// </summary> /// <param name="owner">Owner type node</param> /// <param name="parameters">List of parameters</param> /// <returns></returns> public MethodNode CreateCtor(TypeNode owner, HashList<ParameterNode> parameters = null, bool prepare = false) { return CreateMethod(owner, ".ctor", new SignatureNode("void"), parameters, false, prepare); }
private void SaveSettings() { // We have to manually set this so we invoke the set {} ShownMessageNotifications = ShownMessageNotifications; }
public void DefineGetAllInstancesMethod(TypeDefinition containerType, ModuleDefinition module, IDictionary<IDependency, IImplementation> serviceMap) { var targetMethods = new List<MethodDefinition>(); foreach (MethodDefinition method in containerType.Methods) { if (method.Name != "GetAllInstances") continue; targetMethods.Add(method); } var getAllInstancesMethod = targetMethods[0]; // Remove the stub implementation var body = getAllInstancesMethod.Body; var IL = body.GetILProcessor(); body.InitLocals = true; body.Instructions.Clear(); var listVariable = getAllInstancesMethod.AddLocal<List<object>>(); var listCtor = module.ImportConstructor<List<object>>(); IL.Emit(OpCodes.Newobj, listCtor); IL.Emit(OpCodes.Stloc, listVariable); // Group the dependencies by type var dependenciesByType = new HashList<System.Type, IDependency>(); foreach (var dependency in serviceMap.Keys) { var serviceType = dependency.ServiceType; dependenciesByType.Add(serviceType, dependency); } var getTypeFromHandleMethod = typeof(System.Type).GetMethod("GetTypeFromHandle", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); var getTypeFromHandle = module.Import(getTypeFromHandleMethod); var addItem = module.ImportMethod<List<object>>("Add"); var currentService = getAllInstancesMethod.AddLocal<object>(); foreach (var currentType in dependenciesByType.Keys) { var currentTypeRef = module.Import(currentType); var currentList = dependenciesByType[currentType]; if (currentList.Count == 0) continue; var skipAdd = IL.Create(OpCodes.Nop); IL.Emit(OpCodes.Ldarg_1); IL.Emit(OpCodes.Ldtoken, currentTypeRef); IL.Emit(OpCodes.Call, getTypeFromHandle); IL.Emit(OpCodes.Ceq); IL.Emit(OpCodes.Brfalse, skipAdd); foreach (var dependency in currentList) { IL.Emit(OpCodes.Ldloc, listVariable); var implementation = serviceMap[dependency]; implementation.Emit(dependency, serviceMap, getAllInstancesMethod); IL.Emit(OpCodes.Stloc, currentService); // Call IInitialize.Initialize(container) on the current service type _initializer.Initialize(IL, module, currentService); IL.Emit(OpCodes.Ldloc, currentService); IL.Emit(OpCodes.Callvirt, addItem); } IL.Append(skipAdd); } var skipOtherContainerCall = IL.Create(OpCodes.Nop); var getNextContainer = module.ImportMethod<IMicroContainer>("get_NextContainer"); var otherContainer = getAllInstancesMethod.AddLocal<IMicroContainer>(); // var otherContainer = this.NextContainer; IL.Emit(OpCodes.Ldarg_0); IL.Emit(OpCodes.Callvirt, getNextContainer); IL.Emit(OpCodes.Stloc, otherContainer); // if (otherContainer != null && this != otherContainer) { IL.Emit(OpCodes.Ldloc, otherContainer); IL.Emit(OpCodes.Brfalse, skipOtherContainerCall); IL.Emit(OpCodes.Ldloc, otherContainer); IL.Emit(OpCodes.Ldarg_0); IL.Emit(OpCodes.Ceq); IL.Emit(OpCodes.Brtrue, skipOtherContainerCall); // var otherInstances = NextContainer.GetAllInstances(type); var otherGetAllInstancesMethod = module.ImportMethod<IMicroContainer>("GetAllInstances"); IL.Emit(OpCodes.Ldloc, listVariable); IL.Emit(OpCodes.Ldloc, otherContainer); IL.Emit(OpCodes.Ldarg_1); IL.Emit(OpCodes.Callvirt, otherGetAllInstancesMethod); // resultList.AddRange(otherInstances); var addRangeMethod = module.ImportMethod<List<object>>("AddRange"); IL.Emit(OpCodes.Callvirt, addRangeMethod); // } // Cast the results down to an IEnumerable<object> var enumerableType = module.ImportType<IEnumerable<object>>(); IL.Append(skipOtherContainerCall); IL.Emit(OpCodes.Ldloc, listVariable); IL.Emit(OpCodes.Isinst, enumerableType); IL.Emit(OpCodes.Ret); }
/// <summary> /// Set the list of parameters /// </summary> /// <param name="parameters"></param> public void SetParameters(HashList<ParameterNode> parameters = null) { if (parameters != null) { Parameters = parameters; var sb = new StringBuilder(Name); if (parameters != null) { foreach (var curr in parameters) sb.Append(" " + parameters[curr].Type.Signature); } Signature = sb.ToString(); } else { Parameters = new HashList<ParameterNode>(); Signature = Name; } }
private void AddNode(HashList<FullCellAddr> sorted, FullCellAddr node) { HashSet<FullCellAddr> precedents; if (GetPrecedents(node, out precedents)) { Cell cell; foreach (FullCellAddr precedent in precedents) { // By including only non-input Formula and ArrayFormula cells, we avoid that // constant cells get stored in local variables. The result will not contain // constants cells (and will contain an input cell only if it is also the // output cell), so must the raw graph to find all cells belonging to an SDF. if (!sorted.Contains(precedent) && precedent.TryGetCell(out cell) && (cell is Formula || cell is ArrayFormula) && !inputCellSet.Contains(precedent)) { AddNode(sorted, precedent); } } } sorted.Add(node); // Last in HashList }
/// <summary> /// Build a list of all the Formula and ArrayFormula cells that the outputCell /// depends on, in calculation order. /// </summary> /// <returns>Cells sorted in calculation order; output cell last.</returns> public IList<FullCellAddr> PrecedentOrder() { HashList<FullCellAddr> sorted = new HashList<FullCellAddr>(); AddNode(sorted, outputCell); return sorted.ToArray(); }
/// <summary> /// Create an automatic .Equal() method /// </summary> /// <param name="type">Type node</param> private void GenerateAutoComparator(TypeNode type) { var node = new MethodNode("equal", new SignatureNode("bool"), false); // define parameter var parameters = new HashList<ParameterNode>(); var param = new ParameterNode("_obj", new SignatureNode(type.Name), 0); parameters.Add(param.Name, param); // generate series of comparisons foreach(var curr in type.Fields) { // // if(@<name> != _obj.<name>) return false; // node.Body.Statements.Add( Expr.If( Expr.Compare( Expr.IdentifierGet(curr, true), Lexer.LexemType.NotEqual, Expr.IdentifierGet(curr, Expr.IdentifierGet("_obj")) ), Expr.Return( Expr.Bool(true) ) ) ); } // return true node.Body.Statements.Add( Expr.Return( Expr.Bool(true) ) ); node.SetParameters(parameters); node.Owner = type; AddMethod(type, node); }
/// <summary> /// type_method = [ "static" ], signature, method_name, [ ":", signature, identifier, { ",", signature, identifier } ], "{", { local_stmt }, "}" ; /// </summary> private void ParseTypeMethod() { // ? "static" bool isStatic = false; if (PeekLexem(LexemType.Static)) { SkipLexem(); isStatic = true; } // signature var methodType = ParseSignature(); // <method_name> if (!PeekLexem(LexemType.Identifier)) Error(Resources.errMethodNameExpected); var methodName = GetLexem(); if (ReservedMethods.ContainsKey(methodName.Data) && ReservedMethods[methodName.Data] != methodType.Signature) Error(String.Format(Resources.errSpecialIncorrectReturnType, methodName.Data, ReservedMethods[methodName.Data])); // validate static constructor if (methodName.Data == "construct" && isStatic) Error(String.Format(Resources.errStaticConstructor, Compiler.Emitter.CurrentType.Name)); SkipLexem(); HashList<ParameterNode> parameters = null; // ? "(", params, ")" if(PeekLexem(LexemType.ParenOpen)) { SkipLexem(); parameters = new HashList<ParameterNode>(); var idx = 0; while(!PeekLexem(LexemType.ParenClose, LexemType.EOF)) { // separator if(idx > 0) { if (!PeekLexem(LexemType.Comma)) Error(Resources.errCommaExpected); SkipLexem(); } // signature var paramType = ParseSignature(); // <name> if (!PeekLexem(LexemType.Identifier)) Error(Resources.errParameterNameExpected); var paramName = GetLexem(); if (parameters.Contains(paramName.Data)) Error(String.Format(Resources.errParameterNameDuplicated, paramName.Data)); parameters.Add(paramName.Data, new ParameterNode(paramName.Data, paramType, idx)); SkipLexem(); idx++; } // ")" if (!PeekLexem(LexemType.ParenClose)) Error(Resources.errParenExpected); SkipLexem(); } MethodNode method; if (methodName.Data == "construct") method = Compiler.Emitter.CreateCtor(Compiler.Emitter.CurrentType, parameters); else method = Compiler.Emitter.CreateMethod(Compiler.Emitter.CurrentType, methodName.Data, methodType, parameters, isStatic); method.Lexem = methodName; Compiler.Emitter.CurrentMethod = method; // lookahead "{" if (!PeekLexem(LexemType.CurlyOpen)) Error(Resources.errMethodCurlyBrace); method.Body = ParseCodeBlock(); Compiler.Emitter.CurrentMethod = null; }
/// <summary> /// Calculate the total distance between a list of possible and actual types /// </summary> /// <param name="actualTypes">Actual list of parameter types at invokation</param> /// <param name="possibleTypes">List of types in the current method</param> /// <returns></returns> public int TotalDistance(string[] actualTypes, HashList<ParameterNode> possibleTypes) { var totalDistance = 0; var idx = 0; foreach(var currType in actualTypes) { var currDistance = TypeDistance(possibleTypes[idx].Type.Signature, currType); // types do not relate if (currDistance == -1) return -1; else totalDistance += currDistance; idx++; } return totalDistance; }
/// <summary> /// Create an automatic constructor to set all fields /// </summary> /// <param name="type">Type node</param> private void GenerateAutoCtor(TypeNode type) { var node = new MethodNode(".ctor", new SignatureNode("void"), false); var parameters = new HashList<ParameterNode>(); int idx = 0; foreach(var curr in type.Fields) { var param = new ParameterNode("_" + curr, type.Fields[curr].Type, idx); parameters.Add("_" + curr, param); idx++; var assignNode = new IdentifierSetNode(curr, true); assignNode.Expression = new IdentifierGetNode("_" + curr); node.Body.Statements.Add(assignNode); } node.SetParameters(parameters); node.Owner = type; AddMethod(type, node); }