public void CanAddAndGetKey() { var lex = new Lexicon<object, object> {{"foo", "bar"}}; var testValue = lex["foo"]; Assert.AreEqual("bar", testValue); }
public void CanAddAndGetKey() { var lex = new Lexicon {{new StringValue("foo"), new StringValue("bar")}}; var testValue = lex[new StringValue("foo")]; Assert.AreEqual(new StringValue("bar"), testValue); }
private Lexicon GetResourceDictionary() { var resources = shared.Vessel.GetActiveResources(); var toReturn = new Lexicon(); foreach (var resource in resources) { toReturn.Add(new StringValue(resource.info.name), new ActiveResourceValue(resource, shared)); } return toReturn; }
/// <summary> /// Recursively builds a phrase structure tree from the given word. /// </summary> /// <param name="words">The array of words that make up the phrase</param> /// <returns>The sentence structured into a hierarchical tree</returns> public static Phrase buildTree(string InputPhrase, Lexicon d) { String[] words = processPhrase(InputPhrase); Terminal[] terminals = new Terminal[words.Length]; for (int i = 0; i < words.Length; i++) { terminals[i] = new Terminal(words[i], d.lookupCategory(words[i])); } return merge(terminals); }
private DFAModel(Lexicon lexicon) { m_lexicon = lexicon; m_dfaStates = new List<DFAState>(); //initialize accept table int stateCount = lexicon.LexerStateCount; m_acceptTables = new List<int>[stateCount]; for (int i = 0; i < stateCount; i++) { m_acceptTables[i] = new List<int>(); } }
public static DFAModel Create(Lexicon lexicon) { if (lexicon == null) { return null; } DFAModel newDFA = new DFAModel(lexicon); newDFA.ConvertLexcionToNFA(); newDFA.ConvertNFAToDFA(); return newDFA; }
public void CanGetLexiconIndex() { var list = new Lexicon<object,object>(); list.Add("foo", "bar"); cpu.PushStack(list); const string INDEX = "foo"; cpu.PushStack(INDEX); var opcode = new OpcodeGetIndex(); opcode.Execute(cpu); Assert.AreEqual(1, list.Count); Assert.AreEqual("bar", cpu.PopStack()); }
public void CanGetLexiconIndex() { var list = new Lexicon(); list.Add(new StringValue("foo"), new StringValue("bar")); cpu.PushStack(list); const string INDEX = "foo"; cpu.PushStack(INDEX); var opcode = new OpcodeGetIndex(); opcode.Execute(cpu); Assert.AreEqual(1, list.Count); Assert.AreEqual(new StringValue("bar"), cpu.PopStack()); }
public void CanShallowPrintListInLexicon() { var list = new ListValue(); list.Add("First In List"); list.Add("Second In List"); list.Add("Last In List"); var lexicon = new Lexicon<object, object>(); lexicon.Add("list", list); lexicon.Add("not list", 2); var result = lexicon.ToString(); Assert.IsTrue(result.Contains("LEXICON of 2 items")); Assert.IsTrue(result.Contains(" [\"list\"]= LIST of 3 items")); Assert.IsFalse(result.Contains("Last In List")); }
public void CanSerializeLexicons() { var lex = new Lexicon(); var nested = new Lexicon(); lex[new StringValue("key1")] = new StringValue("value1"); lex[new StringValue("2")] = new ScalarIntValue(10); lex[new ScalarIntValue(2)] = new ScalarIntValue(11); // make sure int 2 is different than string "2" lex[new StringValue("key3")] = nested; nested[new StringValue("nested1")] = new StringValue("nested1value"); nested[new StringValue("nested2")] = new StringValue("nested2value"); var lines = new string[] { "LEXICON of 4 items:", "[\"key1\"] = \"value1\"", "[\"2\"] = 10", "[2] = 11", "[\"key3\"] = LEXICON of 2 items:", " [\"nested1\"] = \"nested1value\"", " [\"nested2\"] = \"nested2value\""}; Assert.AreEqual(string.Join(Environment.NewLine, lines), Serialize(lex)); }
public void ExtractAllExceptMap(string path, HashSet<uint> stuff, ref Lexicon<uint, VideoBag.SpriteSheetInfo> ssilist) { uint i = 0; Section.SectionEntry entry = null; Section sct = null; foreach (Section s in sections) { foreach (Section.SectionEntry e in s.Entries) { entry = e; sct = s; if (!stuff.Contains(i)) { BinaryReader rdr = new BinaryReader(bag); rdr.BaseStream.Seek(sct.Offset, SeekOrigin.Begin); byte[] nxzData = rdr.ReadBytes((int)sct.SizeCompressed); byte[] mapData = new byte[sct.SizeUncompressed]; if (!NoxShared.CryptApi.NxzDecrypt(nxzData, mapData)) { Debug.WriteLine("ExtractOne: Couldn't NxzDecrypt"); } MemoryStream nxzStream = new MemoryStream(mapData); nxzStream.Seek(entry.Offset, SeekOrigin.Begin); VideoBag.SpriteSheetInfo ssi = new VideoBag.SpriteSheetInfo(); ssi.imageID = i; ssi.file = path + "/" + i.ToString() + ".png"; var bitmap = entry.GetBitmap(nxzStream, header.bits8, i, ref ssi.offsetX, ref ssi.offsetY); ssi.X = 0; ssi.Y = 0; ssi.width = bitmap.Width; ssi.height = bitmap.Height; bitmap.Save(ssi.file); ssilist.Add(ssi.imageID, ssi); } i++; } } }
public void CanSerializeLexicons() { var lex = new Lexicon(); var nested = new Lexicon(); lex[new StringValue("key1")] = new StringValue("value1"); lex[new StringValue("key2")] = new ScalarIntValue(1); lex[new StringValue("key3")] = nested; nested[new StringValue("nested1")] = new StringValue("nested1value"); nested[new StringValue("nested2")] = new StringValue("nested2value"); Lexicon deserialized = Deserialize(Serialize(lex)) as Lexicon; Assert.AreEqual(new StringValue("value1"), deserialized[new StringValue("key1")]); Assert.AreEqual(new ScalarIntValue(1), deserialized[new StringValue("key2")]); Assert.IsTrue(deserialized[new StringValue("key3")] is Lexicon); Assert.AreEqual(new StringValue("nested1value"), (deserialized[new StringValue("key3")] as Lexicon)[new StringValue("nested1")]); }
public void CanSetLexiconIndex() { Encapsulation.Structure index = new StringValue("foo"); var lex = new Lexicon(); lex.Add(index, new StringValue("bar")); cpu.PushStack(lex); cpu.PushStack(index); const string VALUE = "fizz"; cpu.PushStack(VALUE); var opcode = new OpcodeSetIndex(); opcode.Execute(cpu); Assert.AreEqual(1, lex.Count); Assert.AreNotEqual("bar", lex[new StringValue("foo")]); }
public void DoesNotContainInvalidToString() { var list = new ListValue { "First In List", "Second In List", "Last In List" }; var lexicon = new Lexicon<object, object> { {"list", list}, {"not list", 2} }; var result = (string)InvokeDelegate(lexicon, "DUMP"); Assert.IsFalse(result.Contains("System")); Assert.IsFalse(result.Contains("string[]")); }
public void DoesNotContainInvalidToString() { var list = new ListValue { new StringValue("First In List"), new StringValue("Second In List"), new StringValue("Last In List") }; var lexicon = new Lexicon { {new StringValue("list"), list}, {new StringValue("not list"), new ScalarIntValue(2)} }; var result = (StringValue)InvokeDelegate(lexicon, "DUMP"); Assert.IsFalse(result.Contains("System")); Assert.IsFalse(result.Contains("string[]")); }
public void CanDeepPrintListInLexicon() { var list = new ListValue { "First In List", "Second In List", "Last In List" }; var lexicon = new Lexicon<object, object> { {"list", list}, {"not list", 2} }; var result = (string)InvokeDelegate(lexicon, "DUMP"); Assert.IsTrue(result.Contains("LEXICON of 2 items")); Assert.IsTrue(result.Contains(" [\"list\"]= LIST of 3 items")); Assert.IsTrue(result.Contains("Last In List")); }
public void CanRemoveKeyOfDifferentCase() { var lex = new Lexicon<object, object> {{"foo", "bar"}}; Assert.AreEqual(1, lex.Count); lex.Remove("foo"); Assert.AreEqual(0, lex.Count); lex.Add("foo", "bar"); Assert.AreEqual(1, lex.Count); lex.Remove("FOO"); Assert.AreEqual(0, lex.Count); lex.Add("foo", "bar"); Assert.AreEqual(1, lex.Count); lex.Remove("Foo"); Assert.AreEqual(0, lex.Count); }
public void CanPrintListInLexicon() { var list = new ListValue { new StringValue("First In List"), new StringValue("Second In List"), new StringValue("Last In List") }; var lexicon = new Lexicon { {new StringValue("list"), list}, {new StringValue("not list"), new ScalarIntValue(2)} }; var result = (StringValue)InvokeDelegate(lexicon, "DUMP"); Assert.IsTrue(result.Contains("LEXICON of 2 items")); Assert.IsTrue(result.Contains("[\"list\"] = LIST of 3 items")); Assert.IsTrue(result.Contains("Last In List")); }
private Lexicon MakeNestedExample() { const string OUTER_STRING = "String, outer value"; var map = new Lexicon(); var innerMap1 = new Lexicon(); var innerMap2 = new Lexicon(); var innerInnerMap = new Lexicon { {new StringValue("inner"), new StringValue("inner string 1")}, {new ScalarIntValue(2), new ScalarIntValue(2)} }; innerMap1.Add(new StringValue("map"), innerInnerMap); innerMap1.Add(new StringValue("2"), new StringValue("string,one.two")); innerMap1.Add(new ScalarIntValue(3), new StringValue("string,one.three")); innerMap2.Add(new StringValue("testing"), new StringValue("string,two.one") ); innerMap2.Add(new StringValue("2"), new StringValue("string,two.two") ); InvokeDelegate(map,"ADD", new StringValue("first"), new ScalarIntValue(100)); InvokeDelegate(map,"ADD", new StringValue("second"), new ScalarIntValue(200)); InvokeDelegate(map,"ADD", new StringValue("inner"), innerMap1); InvokeDelegate(map,"ADD", new StringValue("inner2"), innerMap2); InvokeDelegate(map,"ADD", new StringValue("last"), new StringValue(OUTER_STRING)); return map; }
public void HashMissOnDifferentValues() { var lex = new Lexicon {{ScalarDoubleValue.MinValue(), new StringValue("bar")}}; Assert.AreNotEqual("bar", lex[ScalarDoubleValue.MaxValue()]); }
public void HasCaseInsensitiveKeys() { var lex = new Lexicon {{new StringValue("foo"), new StringValue("bar")}}; Assert.AreEqual(new StringValue("bar"), lex[new StringValue("FOO")]); }
static HebrewPromptNumberReader() { HebrewLexicon = new Lexicon("hebrew-numbers.pls"); }
public override void behaviorOnCollisionWithMonster(NPC n, GameLocation location) { if (!damagesMonsters) { return; } explosionAnimation(location); if (n is Monster) { location.damageMonster(n.GetBoundingBox(), damageToFarmer, (int)damageToFarmer + 1, isBomb: false, (theOneWhoFiredMe.Get(location) is Farmer) ? (theOneWhoFiredMe.Get(location) as Farmer) : Game1.player); return; } n.getHitByPlayer((theOneWhoFiredMe.Get(location) == null || !(theOneWhoFiredMe.Get(location) is Farmer)) ? Game1.player : (theOneWhoFiredMe.Get(location) as Farmer), location); string projectileName = ""; if (Game1.objectInformation.ContainsKey(currentTileSheetIndex.Value)) { projectileName = Game1.objectInformation[currentTileSheetIndex.Value].Split('/')[4]; } else if (Game1.objectInformation.ContainsKey(currentTileSheetIndex.Value - 1)) { projectileName = Game1.objectInformation[currentTileSheetIndex.Value - 1].Split('/')[4]; } Game1.multiplayer.globalChatInfoMessage("Slingshot_Hit", ((theOneWhoFiredMe.Get(location) == null || !(theOneWhoFiredMe.Get(location) is Farmer)) ? Game1.player : (theOneWhoFiredMe.Get(location) as Farmer)).Name, (n.Name == null) ? "???" : n.Name, Lexicon.prependArticle(projectileName)); }
private static string GetExpectedTokenExceptionMessage(Lexicon expected, Lexicon previous, Lexicon actual) { return($"Expected to find {expected} after {previous} but found: {actual}"); }
public string getPurchasedItemDialogueForNPC(StardewValley.Object i, NPC n) { string result = "..."; string[] array = Game1.content.LoadString("Strings\\Lexicon:GenericPlayerTerm", new object[0]).Split(new char[] { '^' }); string text = array[0]; if (array.Length > 1 && !Game1.player.isMale) { text = array[1]; } string text2 = (Game1.random.NextDouble() < (double)(Game1.player.getFriendshipLevelForNPC(n.name) / 1250)) ? Game1.player.name : text; if (n.age != 0) { text2 = Game1.player.name; } string text3 = (LocalizedContentManager.CurrentLanguageCode == LocalizedContentManager.LanguageCode.en) ? Game1.getProperArticleForWord(i.name) : ""; if ((i.category == -4 || i.category == -75 || i.category == -79) && Game1.random.NextDouble() < 0.5) { text3 = Game1.content.LoadString("Strings\\StringsFromCSFiles:SeedShop.cs.9701", new object[0]); } int num = Game1.random.Next(5); if (n.manners == 2) { num = 2; } switch (num) { case 0: if (Game1.random.NextDouble() < (double)i.quality * 0.5 + 0.2) { result = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_1_QualityHigh", new object[] { text2, text3, i.DisplayName, Lexicon.getRandomDeliciousAdjective(n) }); } else { result = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_1_QualityLow", new object[] { text2, text3, i.DisplayName, Lexicon.getRandomNegativeFoodAdjective(n) }); } break; case 1: if (i.quality == 0) { result = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_2_QualityLow", new object[] { text2, text3, i.DisplayName }); } else if (n.name.Equals("Jodi")) { result = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_2_QualityHigh_Jodi", new object[] { text2, text3, i.DisplayName }); } else { result = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_2_QualityHigh", new object[] { text2, text3, i.DisplayName }); } break; case 2: if (n.manners == 2) { if (i.quality != 2) { result = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_3_QualityLow_Rude", new object[] { text2, text3, i.DisplayName, i.salePrice() / 2, Lexicon.getRandomNegativeFoodAdjective(n), Lexicon.getRandomNegativeItemSlanderNoun() }); } else { Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_3_QualityHigh_Rude", new object[] { text2, text3, i.DisplayName, i.salePrice() / 2, Lexicon.getRandomSlightlyPositiveAdjectiveForEdibleNoun(n) }); } } else { Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_3_NonRude", new object[] { text2, text3, i.DisplayName, i.salePrice() / 2 }); } break; case 3: result = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_4", new object[] { text2, text3, i.DisplayName }); break; case 4: if (i.category == -75 || i.category == -79) { result = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_5_VegetableOrFruit", new object[] { text2, text3, i.DisplayName }); } else if (i.category == -7) { string randomPositiveAdjectiveForEventOrPerson = Lexicon.getRandomPositiveAdjectiveForEventOrPerson(n); result = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_5_Cooking", new object[] { text2, text3, i.DisplayName, Game1.getProperArticleForWord(randomPositiveAdjectiveForEventOrPerson), randomPositiveAdjectiveForEventOrPerson }); } else { result = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_5_Foraged", new object[] { text2, text3, i.DisplayName }); } break; } if (n.age == 1 && Game1.random.NextDouble() < 0.6) { result = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Teen", new object[] { text2, text3, i.DisplayName }); } string name = n.name; uint num2 = < PrivateImplementationDetails >.ComputeStringHash(name); if (num2 <= 1708213605u) { if (num2 != 208794864u) { if (num2 != 786557384u) { if (num2 == 1708213605u) { if (name == "Alex") { result = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Alex", new object[] { text2, text3, i.DisplayName }); } } } else if (name == "Caroline") { if (i.quality == 0) { result = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Caroline_QualityLow", new object[] { text2, text3, i.DisplayName }); } else { result = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Caroline_QualityHigh", new object[] { text2, text3, i.DisplayName }); } } } else if (name == "Pierre") { if (i.quality == 0) { result = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Pierre_QualityLow", new object[] { text2, text3, i.DisplayName }); } else { result = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Pierre_QualityHigh", new object[] { text2, text3, i.DisplayName }); } } } else if (num2 <= 2732913340u) { if (num2 != 2434294092u) { if (num2 == 2732913340u) { if (name == "Abigail") { if (i.quality == 0) { result = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Abigail_QualityLow", new object[] { text2, text3, i.DisplayName, Lexicon.getRandomNegativeItemSlanderNoun() }); } else { result = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Abigail_QualityHigh", new object[] { text2, text3, i.DisplayName }); } } } } else if (name == "Haley") { result = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Haley", new object[] { text2, text3, i.DisplayName }); } } else if (num2 != 2826247323u) { if (num2 == 3066176300u) { if (name == "Elliott") { result = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Elliott", new object[] { text2, text3, i.DisplayName }); } } } else if (name == "Leah") { result = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Leah", new object[] { text2, text3, i.DisplayName }); } return(result); }
public RuleToken(Lexicon lexicon, string value) { Lexicon = lexicon; Value = value; }
public RuleToken(Lexicon lexicon) : this(lexicon, string.Empty) { }
/// <summary> /// Check if an input has the required stack for the producer rule. /// </summary> /// <param name="producerRule">the producer rule to check</param> /// <param name="input">The input to check</param> public static void ValidateIfInputStackLessThanRequired(ProducerRule producerRule, Object input) { int requiredStack = producerRule.InputStack; if (input.Stack < requiredStack) { throw new RestrictionException(DataLoader.Helper.Translation.Get( "Message.Requirement.Amount" , new { amount = requiredStack, objectName = Lexicon.makePlural(input.DisplayName, requiredStack == 1) } )); } }
public override string getPurchasedItemDialogueForNPC(Object i, NPC n) { string response = "..."; string[] split = Game1.content.LoadString("Strings\\Lexicon:GenericPlayerTerm").Split('^'); string genderName = split[0]; if (split.Length > 1 && !Game1.player.isMale) { genderName = split[1]; } string whatToCallPlayer = (Game1.random.NextDouble() < (double)(Game1.player.getFriendshipLevelForNPC(n.Name) / 1250)) ? Game1.player.Name : genderName; if (n.Age != 0) { whatToCallPlayer = Game1.player.Name; } string particle = (LocalizedContentManager.CurrentLanguageCode == LocalizedContentManager.LanguageCode.en) ? Lexicon.getProperArticleForWord(i.name) : ""; if ((i.Category == -4 || i.Category == -75 || i.Category == -79) && Game1.random.NextDouble() < 0.5) { particle = Game1.content.LoadString("Strings\\StringsFromCSFiles:SeedShop.cs.9701"); } int whichDialogue = Game1.random.Next(5); if (n.Manners == 2) { whichDialogue = 2; } switch (whichDialogue) { case 0: response = ((!(Game1.random.NextDouble() < (double)(int)i.quality * 0.5 + 0.2)) ? Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_1_QualityLow", whatToCallPlayer, particle, i.DisplayName, Lexicon.getRandomNegativeFoodAdjective(n)) : Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_1_QualityHigh", whatToCallPlayer, particle, i.DisplayName, Lexicon.getRandomDeliciousAdjective(n))); break; case 1: response = (((int)i.quality != 0) ? ((!n.Name.Equals("Jodi")) ? Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_2_QualityHigh", whatToCallPlayer, particle, i.DisplayName) : Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_2_QualityHigh_Jodi", whatToCallPlayer, particle, i.DisplayName)) : Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_2_QualityLow", whatToCallPlayer, particle, i.DisplayName)); break; case 2: if (n.Manners == 2) { if ((int)i.quality != 2) { response = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_3_QualityLow_Rude", whatToCallPlayer, particle, i.DisplayName, i.salePrice() / 2, Lexicon.getRandomNegativeFoodAdjective(n), Lexicon.getRandomNegativeItemSlanderNoun()); } else { Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_3_QualityHigh_Rude", whatToCallPlayer, particle, i.DisplayName, i.salePrice() / 2, Lexicon.getRandomSlightlyPositiveAdjectiveForEdibleNoun(n)); } } else { Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_3_NonRude", whatToCallPlayer, particle, i.DisplayName, i.salePrice() / 2); } break; case 3: response = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_4", whatToCallPlayer, particle, i.DisplayName); break; case 4: if (i.Category == -75 || i.Category == -79) { response = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_5_VegetableOrFruit", whatToCallPlayer, particle, i.DisplayName); } else if (i.Category == -7) { string adjective = Lexicon.getRandomPositiveAdjectiveForEventOrPerson(n); response = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_5_Cooking", whatToCallPlayer, particle, i.DisplayName, Lexicon.getProperArticleForWord(adjective), adjective); } else { response = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_5_Foraged", whatToCallPlayer, particle, i.DisplayName); } break; } if (n.Age == 1 && Game1.random.NextDouble() < 0.6) { response = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Teen", whatToCallPlayer, particle, i.DisplayName); } switch (n.Name) { case "Abigail": response = (((int)i.quality != 0) ? Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Abigail_QualityHigh", whatToCallPlayer, particle, i.DisplayName) : Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Abigail_QualityLow", whatToCallPlayer, particle, i.DisplayName, Lexicon.getRandomNegativeItemSlanderNoun())); break; case "Caroline": response = (((int)i.quality != 0) ? Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Caroline_QualityHigh", whatToCallPlayer, particle, i.DisplayName) : Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Caroline_QualityLow", whatToCallPlayer, particle, i.DisplayName)); break; case "Pierre": response = (((int)i.quality != 0) ? Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Pierre_QualityHigh", whatToCallPlayer, particle, i.DisplayName) : Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Pierre_QualityLow", whatToCallPlayer, particle, i.DisplayName)); break; case "Haley": response = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Haley", whatToCallPlayer, particle, i.DisplayName); break; case "Elliott": response = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Elliott", whatToCallPlayer, particle, i.DisplayName); break; case "Alex": response = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Alex", whatToCallPlayer, particle, i.DisplayName); break; case "Leah": response = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Leah", whatToCallPlayer, particle, i.DisplayName); break; } return(response); }
public Agreement(string sense, string word, bool b //New ,WSD wsd ) { if (b) { switch (word) { case "ANYBODY": case "NOBODY": case "ANYONE": case "NO_ONE": case "NONE": case "SHE": case "HE": case "ONESELF": case "HER": case "HERSELF": case "HIM": case "HIMSELF": case "HERS": case "HIS": this.Type = 1; this.Person = 3; break; case "THOSE": case "THESE": case "THEY": case "THEM": case "THEMSELVES": case "EVERYBODY": case "EVERYONE": case "EVERYTHING": case "THEIR": case "THEIRS": this.Type = 3; this.Person = 3; break; case "IT": case "ITSELF": case "ITS": this.Type = 2; this.Person = 3; break; case "I": case "WE": case "ME": case "MYSELF": case "MINE": case "MY": this.Type = 1; this.Person = 1; break; case "YOU": case "YOURSELF": case "YOURSELVES": case "YOUR": case "YOURS": this.Type = 1; this.Person = 2; break; case "EACHO": case "ONEAN": this.Type = 3; this.Person = 0; break; case "OUR": case "OURS": case "US": case "OURSELVES": case "OURSELF": this.Type = 3; this.Person = 1; break; case "THIS": case "THAT": this.Type = 0; this.Person = 3; break; } } else { this.Person = 3; if (Lexicon.IsPlural(word)) { this.Type = 3; } else { this.Type = WSDReplace.GetType(sense); //here we will send the sense //New } } }
static void Main(string[] arguments) { #region Classic Space Object Collision Example /* * See https://en.wikipedia.org/wiki/Multiple_dispatch#Examples */ var planet1 = new Planet(); var planet2 = new Planet(); var asteroid1 = new Asteroid(); var asteroid2 = new Asteroid(); var spaceship1 = new Spaceship(); var spaceship2 = new Spaceship(); var satellite1 = new TelecomSatellite(); var satellite2 = new TelecomSatellite(); System.Diagnostics.Debug.Assert(planet1.CollideWith(planet2) == "the planets destroy each other"); System.Diagnostics.Debug.Assert(planet1.CollideWith(asteroid1) == "the planet obliterates the asteroid"); System.Diagnostics.Debug.Assert(asteroid1.CollideWith(planet1) == "the planet obliterates the asteroid"); System.Diagnostics.Debug.Assert(planet1.CollideWith(spaceship1) == "the planet obliterates the spaceship"); System.Diagnostics.Debug.Assert(spaceship1.CollideWith(planet1) == "the planet obliterates the spaceship"); System.Diagnostics.Debug.Assert(planet1.CollideWith(satellite1) == "the planet obliterates the satellite"); System.Diagnostics.Debug.Assert(satellite1.CollideWith(planet1) == "the planet obliterates the satellite"); System.Diagnostics.Debug.Assert(asteroid1.CollideWith(asteroid2) == "the asteroids destroy each other"); System.Diagnostics.Debug.Assert(asteroid1.CollideWith(spaceship1) == "the asteroid obliterates the spaceship"); System.Diagnostics.Debug.Assert(spaceship1.CollideWith(asteroid1) == "the asteroid obliterates the spaceship"); System.Diagnostics.Debug.Assert(asteroid1.CollideWith(satellite1) == "the asteroid obliterates the satellite"); System.Diagnostics.Debug.Assert(satellite1.CollideWith(asteroid1) == "the asteroid obliterates the satellite"); System.Diagnostics.Debug.Assert(spaceship1.CollideWith(spaceship2) == "the spaceships destroy each other"); System.Diagnostics.Debug.Assert(spaceship1.CollideWith(satellite1) == "the spaceship obliterates the satellite"); System.Diagnostics.Debug.Assert(satellite1.CollideWith(spaceship1) == "the spaceship obliterates the satellite"); System.Diagnostics.Debug.Assert(satellite1.CollideWith(satellite2) == "the satellites destroy each other"); #endregion var testLexicon = new Lexicon ( new[] { new TokenType("identifier", "[A-Za-z_][A-Za-z_0-9]*", token => token.Match != "null" ? token.Match : null), new TokenType("text", "\"[^\"]*\"", token => token.Match), new TokenType("number", "[0-9]+", token => int.Parse(token.Match)) } ); // Anonymous goodness... var AnonymousModel = new { Content = default(object) }; var AnonymousReducer = Reducer(default(object), AnonymousModel); var toAnonymousModel = NewReducer ( AnonymousReducer, (context, outer, expression, value) => expression ?? new { Content = value } ); var aParser = SExpressionParser.Create(testLexicon, AnonymousReducer); var aModel = aParser.Parse(" ( a 123 ( \"foo\" bar ( ) c ) ( null ) ) ", toAnonymousModel); System.Diagnostics.Debug.Assert(Is(AnonymousModel, aModel)); System.Diagnostics.Debug.Assert(Is(ListOf(AnonymousModel), As(AnonymousModel, aModel).Content)); System.Diagnostics.Debug.Assert(As(ListOf(AnonymousModel), As(AnonymousModel, aModel).Content)[0].Content is string); System.Diagnostics.Debug.Assert(As(ListOf(AnonymousModel), As(AnonymousModel, aModel).Content)[0].Content as string == "a"); System.Diagnostics.Debug.Assert(As(ListOf(AnonymousModel), As(AnonymousModel, aModel).Content)[1].Content is int); System.Diagnostics.Debug.Assert((int)As(ListOf(AnonymousModel), As(AnonymousModel, aModel).Content)[1].Content == 123); Console.WriteLine(); Console.Write("Press a key>"); Console.ReadKey(); // via extension method : SExpressionBuilder SExpressionBuilder(this object anchor) var S = default(object).SExpressionBuilder(); // loosely typed use cases (ie, object / object[] S-Exprs) // via extension method : SExpressionBuilder<TExpression> SExpressionBuilder<TExpression>(this TExpression anchor) var P = default(PicoNode).SExpressionBuilder(); // strongly typed use cases (ie, PicoNode S-Exprs) // equiv S-Expr: ( 123 abc ( x y null z ( null ) ) 456 ( ) ) // fluently built var test1 = S(123, "abc", S("x", "y", null, "z", S(null)), 456, S()); System.Diagnostics.Debug.Assert(test1 is object[]); System.Diagnostics.Debug.Assert((int)(test1 as object[])[0] == 123); // ( 123 <- System.Diagnostics.Debug.Assert((string)(test1 as object[])[1] == "abc"); // ( ... abc <- System.Diagnostics.Debug.Assert((string)((test1 as object[])[2] as object[])[1] == "y"); // ( ... ( ... y <- System.Diagnostics.Debug.Assert((int)(test1 as object[])[3] == 456); // ( ... ( ... ) 456 <- System.Diagnostics.Debug.Assert(((object[])(test1 as object[])[4]).Length == 0); // ( ... ( ... ) ... ( ) <- // equiv S-Expr: ( ( html ) ( ( body ) ( ( p ) "Hello, world!" ( ( br ) ) "Ciao!" ) ) ) // fluently built var test2 = P( P("html"), P( P("body"), P ( P("p"), "\"Hello, world!\"", P(P("br")), "\"Ciao!\"" ) ) ); System.Diagnostics.Debug.Assert(test2 is PicoNode); System.Diagnostics.Debug.Assert(test2.IsAtom == false); System.Diagnostics.Debug.Assert(test2 is IReadOnlyList <PicoNode>); System.Diagnostics.Debug.Assert(test2[0].IsAtom == false); System.Diagnostics.Debug.Assert(test2[0][0].IsAtom == true); System.Diagnostics.Debug.Assert(test2[0][0].Value == "html"); System.Diagnostics.Debug.Assert(test2[1][1][1].IsAtom == true); System.Diagnostics.Debug.Assert(test2[1][1][1].Value == "\"Hello, world!\""); System.Diagnostics.Debug.Assert ( test2.ToString() == "( ( System.String{html} ) ( ( System.String{body} ) ( ( System.String{p} ) System.String{\"Hello, world!\"} ( ( System.String{br} ) ) System.String{\"Ciao!\"} ) ) )" ); Console.WriteLine(); Console.WriteLine($"{nameof(test2)}: {test2}"); // Now for some parsing... var parse1 = new SExpressionParser(testLexicon) .Parse(" ( 123 abc ( x y null z ( null ) ) 456 ( ) ) "); System.Diagnostics.Debug.Assert(parse1 is SExpression); System.Diagnostics.Debug.Assert((int)parse1[0].Value == 123); // ( 123 <- System.Diagnostics.Debug.Assert((string)parse1[1].Value == "abc"); // ( ... abc <- System.Diagnostics.Debug.Assert((string)parse1[2][1].Value == "y"); // ( ... ( ... y <- System.Diagnostics.Debug.Assert((string)parse1[2][2].Value == null); // ( ... ( ... null <- System.Diagnostics.Debug.Assert((int)parse1[3].Value == 456); // ( ... ( ... ) 456 <- System.Diagnostics.Debug.Assert(parse1[4].Count == 0); // ( ... ( ... ) ... ( ) <- System.Diagnostics.Debug.Assert ( parse1.ToString() == "( System.Int32{123} System.String{abc} ( System.String{x} System.String{y} System.Object{null} System.String{z} ( System.Object{null} ) ) System.Int32{456} ( ) )" ); Console.WriteLine(); Console.WriteLine($"{nameof(parse1)}: {parse1}"); var parse2 = new SExpressionParser <PicoNode>(testLexicon) .Parse(" ( ( html ) ( ( body ) ( ( p ) \"Hello, world!\" ( ( br ) ) \"Ciao!\" ) ) ) "); System.Diagnostics.Debug.Assert(parse2 is PicoNode); // Duh. System.Diagnostics.Debug.Assert(parse2.IsAtom == false); System.Diagnostics.Debug.Assert(parse2 is IReadOnlyList <PicoNode>); System.Diagnostics.Debug.Assert(parse2[0].IsAtom == false); System.Diagnostics.Debug.Assert(parse2[0][0].IsAtom == true); System.Diagnostics.Debug.Assert(parse2[0][0].Value == "html"); System.Diagnostics.Debug.Assert(parse2[1][1][1].IsAtom == true); System.Diagnostics.Debug.Assert(parse2[1][1][1].Value == "\"Hello, world!\""); System.Diagnostics.Debug.Assert(parse2.ToString() == test2.ToString()); // Yup. Console.WriteLine(); Console.WriteLine($"{nameof(parse2)}: {parse2}"); // Parse errors reporting... string error1 = null; try { new SExpressionParser(testLexicon).Parse(@" ( 123 ( 456 ) ) garbage"); } catch (Exception ex) { error1 = ex.Message; } System.Diagnostics.Debug.Assert(error1.StartsWith("syntax error: end of input expected but found identifier garbage at line 4, column 2")); string error2 = null; try { new SExpressionParser(testLexicon).Parse(@" ( 123 abc 456 "); } catch (Exception ex) { error2 = ex.Message; } System.Diagnostics.Debug.Assert(error2.StartsWith("syntax error: ) expected but found end of input at line 2, column 6")); string error3 = null; try { new SExpressionParser(testLexicon).Parse(@" ( abc ( ?!? ) ) "); } catch (Exception ex) { error3 = ex.Message; } System.Diagnostics.Debug.Assert(error3.StartsWith("syntax error: ) expected but found unexpected ?!? at line 3, column 11")); // And last but not least... // via extension method: // Reducer<TContext, TExpression> SExpressionReducer<TContext, TExpression>(this TExpression anchor, TContext prototype, Reducer<TContext, TExpression> reducer) var reducer = default(PicoNode) // expression type .SExpressionReducer ( default(object), // optional context (ignored) (ignored, outer, expression, value) => ( expression != null ? ( !expression.IsAtom && (expression.Count > 0) && !expression[0].IsAtom && // all this to detect the "(tagName)" in "... ( (tagName) ... ) ..." expression[0].Count == 1 && expression[0][0].IsAtom ? ( outer == null ? new PicoDocument(new PicoElement(expression[0][0].Value, expression.Skip(1))) : (PicoNode) new PicoElement(expression[0][0].Value, expression.Skip(1)) ) : ( expression.IsAtom && expression.Value.StartsWith("\"") && expression.Value.EndsWith("\"") ? new PicoText(expression.Value) : expression ) ) : ( value is IEnumerable <PicoNode>? new PicoNode((IEnumerable <PicoNode>)value) : new PicoNode((string)value) ) ) ); /* * compare to: * <html> * <body> * <p> * Hello, world! * <br/> * Ciao! * </p> * </html> * ... */ var parse3 = new SExpressionParser <PicoNode>(testLexicon) .Parse(@" ( ( html ) ( ( body ) ( ( p ) ""Hello, world!"" ( ( br ) ) ""Ciao!"" ) ) ) ", reducer); // <- note the passing of the reducer System.Diagnostics.Debug.Assert(parse3 is PicoDocument); var documentElement = ((PicoDocument)parse3).DocumentElement; System.Diagnostics.Debug.Assert(documentElement.TagName == "html"); System.Diagnostics.Debug.Assert(documentElement[0] is PicoElement); System.Diagnostics.Debug.Assert((documentElement[0] as PicoElement).TagName == "body"); System.Diagnostics.Debug.Assert(documentElement[0][0] is PicoElement); System.Diagnostics.Debug.Assert((documentElement[0][0] as PicoElement).TagName == "p"); System.Diagnostics.Debug.Assert(documentElement[0][0][0] is PicoText); System.Diagnostics.Debug.Assert((documentElement[0][0][0] as PicoText).Value == "\"Hello, world!\""); System.Diagnostics.Debug.Assert ( parse3.ToString() == "(<html><body><p>Hello, world!<br/>Ciao!</p></body></html>)" ); Console.WriteLine(); Console.WriteLine($"{nameof(parse3)}: {parse3}"); //var input = System.IO.File.ReadAllText(TEST_SEXPR_FILE_PATH); //var parser = new SExpressionParser<PicoNode>(); //Console.WriteLine(); //Console.Write("Press a key>"); //Console.ReadKey(); //var sw = new System.Diagnostics.Stopwatch(); //sw.Start(); //var parse4 = parser.Parse(input, new FastLexer(), reducer); //sw.Stop(); //Console.WriteLine(); //Console.WriteLine($"{nameof(parse4)}: elapsed: {sw.ElapsedMilliseconds.ToString("0,0")} ms."); //Console.WriteLine(); //Console.Write("Press a key>"); //Console.ReadKey(); //var body = (PicoElement)((PicoDocument)parse4).DocumentElement[0]; //var firstParagraph = (PicoElement)body[0]; //Console.WriteLine(); //Console.WriteLine($"{nameof(parse4)}: '{body.TagName}' has {body.Count} child nodes '{firstParagraph.TagName}'"); //Console.WriteLine(); //Console.Write("Press a key>"); //Console.ReadKey(); //Console.WriteLine(); //Console.WriteLine($"{nameof(parse4)}: {parse4}"); Console.WriteLine(); Console.Write("The end>"); Console.ReadKey(); }
/// <summary> /// Packs a collection of images into a single image. /// </summary> /// <param name="imageFiles">The list of file paths of the images to be combined.</param> /// <param name="requirePowerOfTwo">Whether or not the output image must have a power of two size.</param> /// <param name="requireSquareImage">Whether or not the output image must be a square.</param> /// <param name="maximumWidth">The maximum width of the output image.</param> /// <param name="maximumHeight">The maximum height of the output image.</param> /// <param name="imagePadding">The amount of blank space to insert in between individual images.</param> /// <param name="generateMap">Whether or not to generate the map dictionary.</param> /// <param name="outputImage">The resulting output image.</param> /// <param name="outputMap">The resulting output map of placement rectangles for the images.</param> /// <returns>0 if the packing was successful, error code otherwise.</returns> /* public int PackImage( IEnumerable<string> imageFiles, bool requirePowerOfTwo, bool requireSquareImage, int maximumWidth, int maximumHeight, int imagePadding, bool generateMap, out Bitmap outputImage, out Dictionary<string, Rectangle> outputMap) { files = new List<string>(imageFiles); requirePow2 = requirePowerOfTwo; requireSquare = requireSquareImage; outputWidth = maximumWidth; outputHeight = maximumHeight; padding = imagePadding; outputImage = null; outputMap = null; // make sure our dictionaries are cleared before starting imageSizes.Clear(); imagePlacement.Clear(); // get the sizes of all the images foreach (var image in files) { Bitmap bitmap = Bitmap.FromFile(image) as Bitmap; if (bitmap == null) return (int)FailCode.FailedToLoadImage; imageSizes.Add(image, bitmap.Size); } // sort our files by file size so we place large sprites first files.Sort( (f1, f2) => { Size b1 = imageSizes[f1]; Size b2 = imageSizes[f2]; int c = -b1.Width.CompareTo(b2.Width); if (c != 0) return c; c = -b1.Height.CompareTo(b2.Height); if (c != 0) return c; return f1.CompareTo(f2); }); // try to pack the images if (!PackImageRectangles()) return (int)FailCode.FailedToPackImage; // make our output image outputImage = CreateOutputImage(); if (outputImage == null) return (int)FailCode.FailedToSaveImage; if (generateMap) { // go through our image placements and replace the width/height found in there with // each image's actual width/height (since the ones in imagePlacement will have padding) string[] keys = new string[imagePlacement.Keys.Count]; imagePlacement.Keys.CopyTo(keys, 0); foreach (var k in keys) { // get the actual size Size s = imageSizes[k]; // get the placement rectangle Rectangle r = imagePlacement[k]; // set the proper size r.Width = s.Width; r.Height = s.Height; // insert back into the dictionary imagePlacement[k] = r; } // copy the placement dictionary to the output outputMap = new Dictionary<string, Rectangle>(); foreach (var pair in imagePlacement) { outputMap.Add(pair.Key, pair.Value); } } // clear our dictionaries just to free up some memory imageSizes.Clear(); imagePlacement.Clear(); return 0; }*/ // This method does some trickery type stuff where we perform the TestPackingImages method over and over, // trying to reduce the image size until we have found the smallest possible image we can fit. private bool PackImageRectangles() { // create a dictionary for our test image placements Lexicon<string, Rectangle> testImagePlacement = new Lexicon<string, Rectangle>(); // get the size of our smallest image int smallestWidth = int.MaxValue; int smallestHeight = int.MaxValue; foreach (var size in imageSizes) { smallestWidth = Math.Min(smallestWidth, size.Value.Width); smallestHeight = Math.Min(smallestHeight, size.Value.Height); } // we need a couple values for testing int testWidth = outputWidth; int testHeight = outputHeight; bool shrinkVertical = false; // just keep looping... while (true) { // make sure our test dictionary is empty testImagePlacement.Clear(); // try to pack the images into our current test size if (!TestPackingImages(testWidth, testHeight, testImagePlacement)) { // if that failed... // if we have no images in imagePlacement, i.e. we've never succeeded at PackImages, // show an error and return false since there is no way to fit the images into our // maximum size texture if (testWidth == 2048) goto test; if (imagePlacement.Count == 0) return false; // otherwise return true to use our last good results if (shrinkVertical) return true; shrinkVertical = true; testWidth += smallestWidth + padding + padding; testHeight += smallestHeight + padding + padding; continue; } test: // clear the imagePlacement dictionary and add our test results in imagePlacement.Clear(); foreach (var pair in testImagePlacement) imagePlacement.Add(pair.Key, pair.Value); // figure out the smallest bitmap that will hold all the images testWidth = testHeight = 0; foreach (var pair in imagePlacement) { testWidth = Math.Max(testWidth, pair.Value.Right); testHeight = Math.Max(testHeight, pair.Value.Bottom); } // subtract the extra padding on the right and bottom if (!shrinkVertical) testWidth -= padding; testHeight -= padding; // if we require a power of two texture, find the next power of two that can fit this image if (requirePow2) { testWidth = MiscHelper.FindNextPowerOfTwo(testWidth); testHeight = MiscHelper.FindNextPowerOfTwo(testHeight); } // if we require a square texture, set the width and height to the larger of the two if (requireSquare) { int max = Math.Max(testWidth, testHeight); testWidth = testHeight = max; } // if the test results are the same as our last output results, we've reached an optimal size, // so we can just be done if (testWidth == outputWidth && testHeight == outputHeight) { if (shrinkVertical) return true; shrinkVertical = true; } // save the test results as our last known good results outputWidth = testWidth; outputHeight = testHeight; // subtract the smallest image size out for the next test iteration if (!shrinkVertical) testWidth -= smallestWidth; testHeight -= smallestHeight; } }
public void LexerStateToDFATest() { Lexicon lexicon = new Lexicon(); Lexer global = lexicon.Lexer; Lexer keywords = global.CreateSubLexer(); Lexer xml = keywords.CreateSubLexer(); var ID = global.DefineToken(RE.Range('a', 'z').Concat( (RE.Range('a', 'z') | RE.Range('0', '9')).Many())); var NUM = global.DefineToken(RE.Range('0', '9').Many1()); var ERROR = global.DefineToken(RE.Range(Char.MinValue, (char)255)); var IF = keywords.DefineToken(RE.Literal("if")); var ELSE = keywords.DefineToken(RE.Literal("else")); var XMLNS = xml.DefineToken(RE.Literal("xmlns")); DFAModel dfa = DFAModel.Create(lexicon); CompressedTransitionTable tc = CompressedTransitionTable.Compress(dfa); ScannerInfo si = lexicon.CreateScannerInfo(); FiniteAutomationEngine engine = new FiniteAutomationEngine(si.TransitionTable, si.CharClassTable); engine.InputString("if"); Assert.AreEqual(ID.Index, si.GetTokenIndex(engine.CurrentState)); engine.Reset(); engine.InputString("12345"); Assert.AreEqual(NUM.Index, si.GetTokenIndex(engine.CurrentState)); engine.Reset(); engine.InputString("asdf12dd"); Assert.AreEqual(ID.Index, si.GetTokenIndex(engine.CurrentState)); engine.Reset(); engine.InputString("A"); Assert.AreEqual(ERROR.Index, si.GetTokenIndex(engine.CurrentState)); engine.Reset(); engine.InputString("AAA"); Assert.IsTrue(engine.IsAtStoppedState); engine.Reset(); engine.InputString("if "); Assert.IsTrue(engine.IsAtStoppedState); engine.Reset(); si.CurrentLexerIndex = keywords.Index; engine.InputString("if"); Assert.AreEqual(IF.Index, si.GetTokenIndex(engine.CurrentState)); engine.Reset(); engine.InputString("else"); Assert.AreEqual(ELSE.Index, si.GetTokenIndex(engine.CurrentState)); engine.Reset(); engine.InputString("xmlns"); Assert.AreEqual(ID.Index, si.GetTokenIndex(engine.CurrentState)); engine.Reset(); si.CurrentLexerIndex = xml.Index; engine.InputString("if"); Assert.AreEqual(IF.Index, si.GetTokenIndex(engine.CurrentState)); engine.Reset(); engine.InputString("xml"); Assert.IsFalse(engine.IsAtStoppedState); engine.Reset(); engine.InputString("xmlns"); Assert.AreEqual(XMLNS.Index, si.GetTokenIndex(engine.CurrentState)); ; }
public virtual bool actionWhenPurchased() { if (isLostItem) { Game1.player.itemsLostLastDeath.Clear(); isLostItem = false; Game1.player.recoveredItem = this; Game1.player.mailReceived.Remove("MarlonRecovery"); Game1.addMailForTomorrow("MarlonRecovery"); Game1.playSound("newArtifact"); Game1.exitActiveMenu(); bool use_plural = Stack > 1; Game1.drawDialogue(Game1.getCharacterFromName("Marlon"), Game1.content.LoadString(use_plural ? "Strings\\StringsFromCSFiles:ItemRecovery_Engaged_Stack" : "Strings\\StringsFromCSFiles:ItemRecovery_Engaged", Lexicon.makePlural(DisplayName, !use_plural))); return(true); } return(false); }
private static string GetExpectedTokenExceptionMessage(IEnumerable expected, Lexicon previous, Lexicon actual) { return($"Expected to find {string.Join(", ", expected)} after {previous} but found: {actual}"); }
public override string getPurchasedItemDialogueForNPC(Object i, NPC n) { string response = "..."; string[] split = Game1.content.LoadString("Strings\\Lexicon:GenericPlayerTerm").Split('^'); string genderName = split[0]; if (split.Length > 1 && !Game1.player.isMale) { genderName = split[1]; } string whatToCallPlayer = ((Game1.random.NextDouble() < (double)(Game1.player.getFriendshipLevelForNPC(n.Name) / 1250)) ? Game1.player.Name : genderName); if (n.Age != 0) { whatToCallPlayer = Game1.player.Name; } string particle = ((LocalizedContentManager.CurrentLanguageCode == LocalizedContentManager.LanguageCode.en) ? Lexicon.getProperArticleForWord(i.name) : ""); if ((i.Category == -4 || i.Category == -75 || i.Category == -79) && Game1.random.NextDouble() < 0.5) { particle = Game1.content.LoadString("Strings\\StringsFromCSFiles:SeedShop.cs.9701"); } int whichDialogue = Game1.random.Next(5); if (n.Manners == 2) { whichDialogue = 2; } switch (whichDialogue) { case 0: case 4: response = ((!(Game1.random.NextDouble() < (double)(int)i.quality * 0.5 + 0.2)) ? Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_1_QualityLow_Willy", whatToCallPlayer, particle, i.DisplayName, Lexicon.getRandomNegativeFoodAdjective(n)) : Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_1_QualityHigh_Willy", whatToCallPlayer, particle, i.DisplayName, Lexicon.getRandomDeliciousAdjective(n))); break; case 1: response = (((int)i.quality != 0) ? ((!n.Name.Equals("Jodi")) ? Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_2_QualityHigh_Willy", whatToCallPlayer, particle, i.DisplayName) : Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_2_QualityHigh_Jodi_Willy", whatToCallPlayer, particle, i.DisplayName)) : Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_2_QualityLow_Willy", whatToCallPlayer, particle, i.DisplayName)); break; case 2: if (n.Manners == 2) { if ((int)i.quality != 2) { response = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_3_QualityLow_Rude_Willy", whatToCallPlayer, particle, i.DisplayName, i.salePrice() / 2, Lexicon.getRandomNegativeFoodAdjective(n), Lexicon.getRandomNegativeItemSlanderNoun()); } else { Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_3_QualityHigh_Rude_Willy", whatToCallPlayer, particle, i.DisplayName, i.salePrice() / 2, Lexicon.getRandomSlightlyPositiveAdjectiveForEdibleNoun(n)); } } else { Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_3_NonRude_Willy", whatToCallPlayer, particle, i.DisplayName, i.salePrice() / 2); } break; case 3: response = Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_4_Willy", whatToCallPlayer, particle, i.DisplayName); break; } string name = n.Name; if (name == "Willy") { response = (((int)i.quality != 0) ? Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Pierre_QualityHigh_Willy", whatToCallPlayer, particle, i.DisplayName) : Game1.content.LoadString("Data\\ExtraDialogue:PurchasedItem_Pierre_QualityLow_Willy", whatToCallPlayer, particle, i.DisplayName)); } return(response); }
public static bool Handle_ArticleFor(string input, IGameState state, out string result) { result = Lexicon.getProperArticleForWord(input); return(true); }
public void DoesNotErrorOnRemoveNullKey() { var lex = new Lexicon(); lex.Remove(new StringValue("foo")); }
public void MultipleLexerParsingTest() { Lexicon lexicon = new Lexicon(); Lexer global = lexicon.Lexer; Lexer keywords = global.CreateSubLexer(); var PROPERTY = global.DefineToken(RE.Literal("property")); var ID = global.DefineToken(RE.Range('a', 'z').Concat( (RE.Range('a', 'z') | RE.Range('0', '9')).Many()), "ID"); var NUM = global.DefineToken(RE.Range('0', '9').Many1(), "NUM"); var EQ = global.DefineToken(RE.Symbol('=')); var SEMICOLON = global.DefineToken(RE.Symbol(';')); var LB = global.DefineToken(RE.Symbol('{')); var RB = global.DefineToken(RE.Symbol('}')); var WHITESPACE = global.DefineToken(RE.Symbol(' ').Union(RE.Symbol('\t')), "[ ]"); var GET = keywords.DefineToken(RE.Literal("get")); var assignStatement = from id in ID from eq in EQ from value in NUM from st in SEMICOLON select id.Value + "=" + value.Value; var getDef = from _get in GET from lb in LB from statements in assignStatement.Many() from rb in RB select new GetDef { Statements = statements }; var propDef = from _prop in PROPERTY from id in ID from lb in LB from getdef in getDef from rb in RB select new PropDef { PropName = id.Value.Content, GetDef = getdef }; string source = "property get { get { get = 1; } }"; SourceReader sr = new SourceReader( new StringReader(source)); var info = lexicon.CreateScannerInfo(); Scanner scanner = new Scanner(info); scanner.SetTriviaTokens(WHITESPACE.Index); scanner.SetSource(sr); CompilationErrorManager errorManager = new CompilationErrorManager(); errorManager.DefineError(1, 0, CompilationStage.Parsing, "Unexpected token '{0}'"); errorManager.DefineError(2, 0, CompilationStage.Parsing, "Missing token '{0}'"); errorManager.DefineError(3, 0, CompilationStage.Parsing, "Syntax error"); ProductionInfoManager pim = new ProductionInfoManager(propDef.SuffixedBy(Grammar.Eos())); LR0Model lr0 = new LR0Model(pim); lr0.BuildModel(); string dot = lr0.ToString(); TransitionTable tt = TransitionTable.Create(lr0, info); SyntaxErrors errDef = new SyntaxErrors() { TokenUnexpectedId = 1, TokenMissingId = 2, OtherErrorId = 3 }; ParserEngine driver = new ParserEngine(tt, errDef); Lexeme r; do { r = scanner.Read(); driver.Input(r); } while (!r.IsEndOfStream); var result = (PropDef)driver.GetResult(0, errorManager); Assert.AreEqual(0, errorManager.Errors.Count); Assert.AreEqual("get", result.PropName); Assert.AreEqual("get=1", result.GetDef.Statements.First()); }
private void DiscardToken(Lexicon lexicon) { CheckThatCurrentTokenIs(lexicon); DiscardToken(); }
public void ParserDriverConflictTest() { Lexicon test = new Lexicon(); var X = test.Lexer.DefineToken(RE.Symbol('x')); var PLUS = test.Lexer.DefineToken(RE.Symbol('+')); var ASTERISK = test.Lexer.DefineToken(RE.Symbol('*')); var scannerinfo = test.CreateScannerInfo(); Production <object> E = new Production <object>(), T = new Production <object>(); E.Rule = (from e1 in E from plus in PLUS from e2 in E select(object)(((int)e1) + ((int)e2))) | (from e1 in E from mul in ASTERISK from e2 in E select(object)(((int)e1) * ((int)e2))) | T; T.Rule = from x in X select(object) 2; ProductionInfoManager pim = new ProductionInfoManager(E.SuffixedBy(Grammar.Eos())); LR0Model lr0 = new LR0Model(pim); lr0.BuildModel(); string dot = lr0.ToString(); TransitionTable tt = TransitionTable.Create(lr0, scannerinfo); ParserEngine driver = new ParserEngine(tt, new SyntaxErrors()); ForkableScannerBuilder builder = new ForkableScannerBuilder(scannerinfo); builder.ErrorManager = new VBF.Compilers.CompilationErrorManager(); var scanner = builder.Create(new VBF.Compilers.SourceReader(new StringReader("x+x*x"))); var z1 = scanner.Read(); driver.Input(z1); var z2 = scanner.Read(); driver.Input(z2); var z3 = scanner.Read(); driver.Input(z3); var z4 = scanner.Read(); driver.Input(z4); var z5 = scanner.Read(); driver.Input(z5); var z6 = scanner.Read(); driver.Input(z6); Assert.AreEqual(0, driver.CurrentStackCount); Assert.AreEqual(2, driver.AcceptedCount); var results = new[] { (int)driver.GetResult(0, null), (int)driver.GetResult(1, null) }; Assert.IsTrue(results.Contains(8)); Assert.IsTrue(results.Contains(6)); }
//I should probably remove most of the below code as it's not neccessary for weapon tooltips, but I don't want to risk bugs public static void drawHoverTextPostfix(IClickableMenu __instance, SpriteBatch b, StringBuilder text, SpriteFont font, int xOffset, int yOffset, int moneyAmountToDisplayAtBottom, string boldTitleText, int healAmountToDisplay, string[] buffIconsToDisplay, Item hoveredItem, int currencySymbol, int extraItemToShowIndex, int extraItemToShowAmount, int overrideX, int overrideY, float alpha, CraftingRecipe craftingIngredients, IList <Item> additional_craft_materials) { try { if (hoveredItem is object) { if (ModEntry.umbrellaNames.Contains(hoveredItem.Name)) { if (text == null || text.Length == 0) { return; } string bold_title_subtext = null; if (boldTitleText != null && boldTitleText.Length == 0) { boldTitleText = null; } int width = Math.Max((healAmountToDisplay != -1) ? ((int)font.MeasureString(healAmountToDisplay + "+ Energy" + 32).X) : 0, Math.Max((int)font.MeasureString(text).X, (boldTitleText != null) ? ((int)Game1.dialogueFont.MeasureString(boldTitleText).X) : 0)) + 32; int height2 = Math.Max(20 * 3, (int)font.MeasureString(text).Y + 32 + (int)((moneyAmountToDisplayAtBottom > -1) ? (font.MeasureString(string.Concat(moneyAmountToDisplayAtBottom)).Y + 4f) : 8f) + (int)((boldTitleText != null) ? (Game1.dialogueFont.MeasureString(boldTitleText).Y + 16f) : 0f)); if (extraItemToShowIndex != -1) { string[] split = Game1.objectInformation[extraItemToShowIndex].Split('/'); string objName = split[0]; if (LocalizedContentManager.CurrentLanguageCode != 0) { objName = split[4]; } string requirement2 = Game1.content.LoadString("Strings\\UI:ItemHover_Requirements", extraItemToShowAmount, (extraItemToShowAmount > 1) ? Lexicon.makePlural(objName) : objName); int spriteWidth = Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, extraItemToShowIndex, 16, 16).Width * 2 * 4; width = Math.Max(width, spriteWidth + (int)font.MeasureString(requirement2).X); } if (buffIconsToDisplay != null) { for (int k = 0; k < buffIconsToDisplay.Length; k++) { if (!buffIconsToDisplay[k].Equals("0")) { height2 += 34; } } height2 += 4; } if (craftingIngredients != null && Game1.options.showAdvancedCraftingInformation && craftingIngredients.getCraftCountText() != null) { height2 += (int)font.MeasureString("T").Y; } string categoryName = "Tool"; if (hoveredItem != null) { height2 += 68 * hoveredItem.attachmentSlots(); if (categoryName.Length > 0) { width = Math.Max(width, (int)font.MeasureString(categoryName).X + 32); height2 += (int)font.MeasureString("T").Y; } int maxStat = 9999; int buffer = 92; Point p = hoveredItem.getExtraSpaceNeededForTooltipSpecialIcons(font, width, buffer, height2, text, boldTitleText, moneyAmountToDisplayAtBottom); width = ((p.X != 0) ? p.X : width); height2 = ((p.Y != 0) ? p.Y : height2); if (hoveredItem is MeleeWeapon && (hoveredItem as MeleeWeapon).GetTotalForgeLevels() > 0) { height2 += (int)font.MeasureString("T").Y; } if (hoveredItem is MeleeWeapon && (hoveredItem as MeleeWeapon).GetEnchantmentLevel <GalaxySoulEnchantment>() > 0) { height2 += (int)font.MeasureString("T").Y; } if (buffIconsToDisplay != null) { for (int j = 0; j < buffIconsToDisplay.Length; j++) { if (!buffIconsToDisplay[j].Equals("0") && j <= 11) { width = (int)Math.Max(width, font.MeasureString(Game1.content.LoadString("Strings\\UI:ItemHover_Buff" + j, maxStat)).X + (float)buffer); } } } } Vector2 small_text_size = Vector2.Zero; if (craftingIngredients != null) { if (Game1.options.showAdvancedCraftingInformation) { int craftable_count = craftingIngredients.getCraftableCount(additional_craft_materials); if (craftable_count > 1) { bold_title_subtext = " (" + craftable_count + ")"; small_text_size = Game1.smallFont.MeasureString(bold_title_subtext); } } width = (int)Math.Max(Game1.dialogueFont.MeasureString(boldTitleText).X + small_text_size.X + 12f, 384f); height2 += craftingIngredients.getDescriptionHeight(width - 8) + ((healAmountToDisplay == -1) ? (-32) : 0); } else if (bold_title_subtext != null && boldTitleText != null) { small_text_size = Game1.smallFont.MeasureString(bold_title_subtext); width = (int)Math.Max(width, Game1.dialogueFont.MeasureString(boldTitleText).X + small_text_size.X + 12f); } int x = Game1.getOldMouseX() + 32 + xOffset; int y4 = Game1.getOldMouseY() + 32 + yOffset; if (overrideX != -1) { x = overrideX; } if (overrideY != -1) { y4 = overrideY; } if (x + width > Utility.getSafeArea().Right) { x = Utility.getSafeArea().Right - width; y4 += 16; } height2 = height2 - 40; // Deal with tooltip offset if (y4 + height2 > Utility.getSafeArea().Bottom) { x += 16; if (x + width > Utility.getSafeArea().Right) { x = Utility.getSafeArea().Right - width; } y4 = Utility.getSafeArea().Bottom - height2; } StardewValley.Menus.IClickableMenu.drawTextureBox(b, Game1.menuTexture, new Rectangle(0, 256, 60, 60), x, y4, width + ((craftingIngredients != null) ? 21 : 0), height2, Color.White * alpha); if (boldTitleText != null) { Vector2 bold_text_size = Game1.dialogueFont.MeasureString(boldTitleText); StardewValley.Menus.IClickableMenu.drawTextureBox(b, Game1.menuTexture, new Rectangle(0, 256, 60, 60), x, y4, width + ((craftingIngredients != null) ? 21 : 0), (int)Game1.dialogueFont.MeasureString(boldTitleText).Y + 32 + (int)((hoveredItem != null && categoryName.Length > 0) ? font.MeasureString("asd").Y : 0f) - 4, Color.White * alpha, 1f, drawShadow: false); b.Draw(Game1.menuTexture, new Rectangle(x + 12, y4 + (int)Game1.dialogueFont.MeasureString(boldTitleText).Y + 32 + (int)((hoveredItem != null && categoryName.Length > 0) ? font.MeasureString("asd").Y : 0f) - 4, width - 4 * ((craftingIngredients != null) ? 1 : 6), 4), new Rectangle(44, 300, 4, 4), Color.White); b.DrawString(Game1.dialogueFont, boldTitleText, new Vector2(x + 16, y4 + 16 + 4) + new Vector2(2f, 2f), Game1.textShadowColor); b.DrawString(Game1.dialogueFont, boldTitleText, new Vector2(x + 16, y4 + 16 + 4) + new Vector2(0f, 2f), Game1.textShadowColor); b.DrawString(Game1.dialogueFont, boldTitleText, new Vector2(x + 16, y4 + 16 + 4), Game1.textColor); if (bold_title_subtext != null) { Utility.drawTextWithShadow(b, bold_title_subtext, Game1.smallFont, new Vector2((float)(x + 16) + bold_text_size.X, (int)((float)(y4 + 16 + 4) + bold_text_size.Y / 2f - small_text_size.Y / 2f)), Game1.textColor); } y4 += (int)Game1.dialogueFont.MeasureString(boldTitleText).Y; } if (hoveredItem != null && categoryName.Length > 0) { y4 -= 4; Utility.drawTextWithShadow(b, categoryName, font, new Vector2(x + 16, y4 + 16 + 4), hoveredItem.getCategoryColor(), 1f, -1f, 2, 2); y4 += (int)font.MeasureString("T").Y + ((boldTitleText != null) ? 16 : 0) + 4; if (hoveredItem is Tool && (hoveredItem as Tool).GetTotalForgeLevels() > 0) { string forged_string2 = Game1.content.LoadString("Strings\\UI:Item_Tooltip_Forged"); Utility.drawTextWithShadow(b, forged_string2, font, new Vector2(x + 16, y4 + 16 + 4), Color.DarkRed, 1f, -1f, 2, 2); int forges = (hoveredItem as Tool).GetTotalForgeLevels(); if (forges < (hoveredItem as Tool).GetMaxForges() && !(hoveredItem as Tool).hasEnchantmentOfType <DiamondEnchantment>()) { Utility.drawTextWithShadow(b, " (" + forges + "/" + (hoveredItem as Tool).GetMaxForges() + ")", font, new Vector2((float)(x + 16) + font.MeasureString(forged_string2).X, y4 + 16 + 4), Color.DimGray, 1f, -1f, 2, 2); } y4 += (int)font.MeasureString("T").Y; } if (hoveredItem is MeleeWeapon && (hoveredItem as MeleeWeapon).GetEnchantmentLevel <GalaxySoulEnchantment>() > 0) { GalaxySoulEnchantment enchantment = (hoveredItem as MeleeWeapon).GetEnchantmentOfType <GalaxySoulEnchantment>(); string forged_string = Game1.content.LoadString("Strings\\UI:Item_Tooltip_GalaxyForged"); Utility.drawTextWithShadow(b, forged_string, font, new Vector2(x + 16, y4 + 16 + 4), Color.DarkRed, 1f, -1f, 2, 2); int level = enchantment.GetLevel(); if (level < enchantment.GetMaximumLevel()) { Utility.drawTextWithShadow(b, " (" + level + "/" + enchantment.GetMaximumLevel() + ")", font, new Vector2((float)(x + 16) + font.MeasureString(forged_string).X, y4 + 16 + 4), Color.DimGray, 1f, -1f, 2, 2); } y4 += (int)font.MeasureString("T").Y; } } else { y4 += ((boldTitleText != null) ? 16 : 0); } if (hoveredItem != null && craftingIngredients == null) { int descriptionWidth; int minimum_size = 272; if (LocalizedContentManager.CurrentLanguageCode == LocalizedContentManager.LanguageCode.fr) { minimum_size = 384; } descriptionWidth = Math.Max(minimum_size, (int)Game1.dialogueFont.MeasureString((boldTitleText == null) ? "" : boldTitleText).X); // Hide the weapon tooltip Utility.drawTextWithShadow(b, text.ToString().Split('#')[0], font, new Vector2(x + 16, y4 + 16 + 4), Game1.textColor);; //hoveredItem.drawTooltip(b, ref x, ref y4, font, alpha, text); } else if (text != null && text.Length != 0 && (text.Length != 1 || text[0] != ' ')) { b.DrawString(font, text, new Vector2(x + 16, y4 + 16 + 4) + new Vector2(2f, 2f), Game1.textShadowColor * alpha); b.DrawString(font, text, new Vector2(x + 16, y4 + 16 + 4) + new Vector2(0f, 2f), Game1.textShadowColor * alpha); b.DrawString(font, text, new Vector2(x + 16, y4 + 16 + 4) + new Vector2(2f, 0f), Game1.textShadowColor * alpha); b.DrawString(font, text, new Vector2(x + 16, y4 + 16 + 4), Game1.textColor * 0.9f * alpha); y4 += (int)font.MeasureString(text).Y + 4; } if (craftingIngredients != null) { craftingIngredients.drawRecipeDescription(b, new Vector2(x + 16, y4 - 8), width, additional_craft_materials); y4 += craftingIngredients.getDescriptionHeight(width - 8); } if (buffIconsToDisplay != null) { for (int i = 0; i < buffIconsToDisplay.Length; i++) { if (!buffIconsToDisplay[i].Equals("0")) { Utility.drawWithShadow(b, Game1.mouseCursors, new Vector2(x + 16 + 4, y4 + 16), new Rectangle(10 + i * 10, 428, 10, 10), Color.White, 0f, Vector2.Zero, 3f, flipped: false, 0.95f); string buffName = ((Convert.ToInt32(buffIconsToDisplay[i]) > 0) ? "+" : "") + buffIconsToDisplay[i] + " "; if (i <= 11) { buffName = Game1.content.LoadString("Strings\\UI:ItemHover_Buff" + i, buffName); } Utility.drawTextWithShadow(b, buffName, font, new Vector2(x + 16 + 34 + 4, y4 + 16), Game1.textColor); y4 += 34; } } } if (hoveredItem != null && hoveredItem.attachmentSlots() > 0) { hoveredItem.drawAttachments(b, x + 16, y4 + 16); if (moneyAmountToDisplayAtBottom > -1) { y4 += 68 * hoveredItem.attachmentSlots(); } } y4 = y4 + 72; // Deal with tooltip offset if (moneyAmountToDisplayAtBottom > -1) { b.DrawString(font, string.Concat(moneyAmountToDisplayAtBottom), new Vector2(x + 16, y4 + 16 + 4) + new Vector2(2f, 2f), Game1.textShadowColor); b.DrawString(font, string.Concat(moneyAmountToDisplayAtBottom), new Vector2(x + 16, y4 + 16 + 4) + new Vector2(0f, 2f), Game1.textShadowColor); b.DrawString(font, string.Concat(moneyAmountToDisplayAtBottom), new Vector2(x + 16, y4 + 16 + 4) + new Vector2(2f, 0f), Game1.textShadowColor); b.DrawString(font, string.Concat(moneyAmountToDisplayAtBottom), new Vector2(x + 16, y4 + 16 + 4), Game1.textColor); switch (currencySymbol) { case 0: b.Draw(Game1.debrisSpriteSheet, new Vector2((float)(x + 16) + font.MeasureString(string.Concat(moneyAmountToDisplayAtBottom)).X + 20f, y4 + 16 + 16), Game1.getSourceRectForStandardTileSheet(Game1.debrisSpriteSheet, 8, 16, 16), Color.White, 0f, new Vector2(8f, 8f), 4f, SpriteEffects.None, 0.95f); break; case 1: b.Draw(Game1.mouseCursors, new Vector2((float)(x + 8) + font.MeasureString(string.Concat(moneyAmountToDisplayAtBottom)).X + 20f, y4 + 16 - 5), new Rectangle(338, 400, 8, 8), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, 1f); break; case 2: b.Draw(Game1.mouseCursors, new Vector2((float)(x + 8) + font.MeasureString(string.Concat(moneyAmountToDisplayAtBottom)).X + 20f, y4 + 16 - 7), new Rectangle(211, 373, 9, 10), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, 1f); break; case 4: b.Draw(Game1.objectSpriteSheet, new Vector2((float)(x + 8) + font.MeasureString(string.Concat(moneyAmountToDisplayAtBottom)).X + 20f, y4 + 16 - 7), Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, 858, 16, 16), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, 1f); break; } y4 += 48; } if (extraItemToShowIndex != -1) { if (moneyAmountToDisplayAtBottom == -1) { y4 += 8; } string displayName = Game1.objectInformation[extraItemToShowIndex].Split('/')[4]; string requirement = Game1.content.LoadString("Strings\\UI:ItemHover_Requirements", extraItemToShowAmount, displayName); float minimum_box_height = Math.Max(font.MeasureString(requirement).Y + 21f, 96f); StardewValley.Menus.IClickableMenu.drawTextureBox(b, Game1.menuTexture, new Rectangle(0, 256, 60, 60), x, y4 + 4, width + ((craftingIngredients != null) ? 21 : 0), (int)minimum_box_height, Color.White); y4 += 20; b.DrawString(font, requirement, new Vector2(x + 16, y4 + 4) + new Vector2(2f, 2f), Game1.textShadowColor); b.DrawString(font, requirement, new Vector2(x + 16, y4 + 4) + new Vector2(0f, 2f), Game1.textShadowColor); b.DrawString(font, requirement, new Vector2(x + 16, y4 + 4) + new Vector2(2f, 0f), Game1.textShadowColor); b.DrawString(Game1.smallFont, requirement, new Vector2(x + 16, y4 + 4), Game1.textColor); b.Draw(Game1.objectSpriteSheet, new Vector2(x + 16 + (int)font.MeasureString(requirement).X + 21, y4), Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, extraItemToShowIndex, 16, 16), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, 1f); } if (craftingIngredients != null && Game1.options.showAdvancedCraftingInformation) { Utility.drawTextWithShadow(b, craftingIngredients.getCraftCountText(), font, new Vector2(x + 16, y4 + 16 + 4), Game1.textColor, 1f, -1f, 2, 2); y4 += (int)font.MeasureString("T").Y + 4; } } } } catch (Exception ex) { Monitor.Log($"Failed in {nameof(drawHoverTextPostfix)}:\n{ex}", LogLevel.Error); } }
private void DrawTextList() { EditorGUILayoutUtil.DrawSeparator(); if (!locked && !Selection.gameObjects.IsEmpty() && (roots == null || !Enumerable.SequenceEqual(roots, Selection.gameObjects))) { Clear(); // search labels roots = Selection.gameObjects; foreach (GameObject o in roots) { tabs.Clear(); foreach (UITabHandler t in o.GetComponentsInChildren <UITabHandler>(true)) { tabs.Add(new UITabHandlerInspectorImpl(t)); } } foreach (GameObject o in roots) { // remove number labels HashSet <UIText> ignore = new HashSet <UIText>(); foreach (DropDown dropdown in o.GetComponentsInChildren <DropDown>(true)) { foreach (UIText l in dropdown.GetComponentsInChildren <UIText>(true)) { ignore.Add(l); } } foreach (UIText l in o.GetComponentsInChildren <UIText>(true)) { if (l.text.IsEmpty()) { continue; } if (ignore.Contains(l)) { continue; } if (visibleOnly && (!l.gameObject.activeInHierarchy || !l.enabled)) { continue; } foreach (char c in l.text) { if (char.IsLetter(c) && !char.IsWhiteSpace(c) && !char.IsPunctuation(c)) { labels.Add(l); break; } } } } } foreach (UITabHandlerInspectorImpl inspector in tabs) { if (inspector.OnInspectorGUI()) { Save(); roots = null; } } // draw trigger list EditorGUILayout.BeginVertical(); foreach (UIText l in labels) { if (!mod.ContainsKey(l)) { FindKey(l); } EditorGUILayout.BeginHorizontal(); EditorGUILayout.ObjectField(l, typeof(UIText), true); Color oldColor = GUI.backgroundColor; string srcKey = mod.Get(l); if (srcKey == null) { srcKey = l.textKey; } if (!Lexicon.ContainsKey(srcKey)) { GUI.backgroundColor = Color.red; } string dstKey = EditorGUILayout.TextField(srcKey); GUI.backgroundColor = oldColor; string text = EditorGUILayout.TextField(l.text); if (srcKey != dstKey) { mod[l] = dstKey; } if (text != l.text) { l.SetText(text); EditorUtil.SetDirty(l); } EditorGUILayout.EndHorizontal(); } EditorGUILayout.EndVertical(); if (GUILayout.Button("Save")) { Save(); } }
public override void Execute(SharedObjects shared) { Structure[] argArray = new Structure[CountRemainingArgs(shared)]; for (int i = argArray.Length - 1 ; i >= 0 ; --i) argArray[i] = PopStructureAssertEncapsulated(shared); // fill array in reverse order because .. stack args. AssertArgBottomAndConsume(shared); var lexicon = new Lexicon(argArray.ToList()); ReturnValue = lexicon; }
public void ErrorsOnGetEmptyKey() { var lex = new Lexicon(); var val = lex[new StringValue("fizz")]; }
public NamedStep(Lexicon <TContext> lexicon, string refName) : this(refName, lexicon, refName) { }
public void HashHitOnEqualValues() { var lex = new Lexicon {{ScalarDoubleValue.MaxValue(), new StringValue("bar")}}; Assert.AreEqual(new StringValue("bar"), lex[ScalarDoubleValue.MaxValue()]); }
public void ParserErrorRecoveryTest() { Lexicon binaryTreeSyntax = new Lexicon(); var lex = binaryTreeSyntax.Lexer; //lex Token LEFTPH = lex.DefineToken(RE.Symbol('(')); Token RIGHTPH = lex.DefineToken(RE.Symbol(')')); Token COMMA = lex.DefineToken(RE.Symbol(',')); Token LETTER = lex.DefineToken(RE.Range('a', 'z') | RE.Range('A', 'Z'), "ID"); //grammar Production <Node> NodeParser = new Production <Node>(); NodeParser.Rule = (from a in LETTER from _1 in LEFTPH from left in NodeParser from _2 in COMMA from right in NodeParser from _3 in RIGHTPH select new Node(a.Value.Content, left, right)) | Grammar.Empty <Node>(null); var builder = new ForkableScannerBuilder(binaryTreeSyntax.CreateScannerInfo()); const string correct = "A(B(,),C(,))"; string source = "A((B(,),C(,)"; SourceReader sr = new SourceReader( new StringReader(source)); var info = binaryTreeSyntax.CreateScannerInfo(); Scanner scanner = new Scanner(info); scanner.SetSource(sr); CompilationErrorManager errorManager = new CompilationErrorManager(); errorManager.DefineError(1, 0, CompilationStage.Parsing, "Unexpected token '{0}'"); errorManager.DefineError(2, 0, CompilationStage.Parsing, "Missing token '{0}'"); errorManager.DefineError(3, 0, CompilationStage.Parsing, "Invalid token found, did you mean '{0}' ?"); errorManager.DefineError(4, 0, CompilationStage.Parsing, "Syntax error"); ProductionInfoManager pim = new ProductionInfoManager(NodeParser.SuffixedBy(Grammar.Eos())); LR0Model lr0 = new LR0Model(pim); lr0.BuildModel(); string dot = lr0.ToString(); TransitionTable tt = TransitionTable.Create(lr0, info); SyntaxErrors errDef = new SyntaxErrors() { TokenUnexpectedId = 1, TokenMissingId = 2, OtherErrorId = 4, TokenMistakeId = 3 }; ParserEngine driver = new ParserEngine(tt, errDef); Lexeme r; do { r = scanner.Read(); driver.Input(r); } while (!r.IsEndOfStream); var result = driver.GetResult(0, errorManager.CreateErrorList()); ; }
private Encapsulation.Structure InvokeDelegate(Lexicon map, string suffixName, params Encapsulation.Structure[] parameters) { ISuffixResult lengthResult = map.GetSuffix(suffixName); Assert.IsNotNull(lengthResult); if (!lengthResult.HasValue) { var delegateResult = lengthResult as DelegateSuffixResult; if (delegateResult != null) { var temp = delegateResult.Del.DynamicInvoke(parameters); return temp as Encapsulation.Structure; } } return lengthResult.Value; }
public int PackImage( IEnumerable<KeyValuePair<string, Bitmap>> input, bool requirePowerOfTwo, bool requireSquareImage, int maximumWidth, int maximumHeight, int imagePadding, bool generateMap, out Bitmap outputImage, out Lexicon<string, Rectangle> outputMap, out List<uint> outFailedPlacements) { files = new List<KeyValuePair<string, Bitmap>>(input);//new List<string>();// (imageFiles); requirePow2 = requirePowerOfTwo; requireSquare = requireSquareImage; outputWidth = maximumWidth; outputHeight = maximumHeight; padding = imagePadding; outputImage = null; outputMap = null; outFailedPlacements = null; // make sure our dictionaries are cleared before starting imageSizes.Clear(); imagePlacement.Clear(); // get the sizes of all the images foreach(KeyValuePair<string, Bitmap> kv in input) { imageSizes.Add(kv.Key, kv.Value.Size); } /*foreach (var image in files) { Bitmap bitmap = Bitmap.FromFile(image) as Bitmap; if (bitmap == null) return (int)FailCode.FailedToLoadImage; imageSizes.Add(image, bitmap.Size); }*/ // sort our files by file size so we place large sprites first files.Sort( (f1, f2) => { Size b1 = imageSizes[f1.Key][0]; Size b2 = imageSizes[f2.Key][0]; int c = -b1.Width.CompareTo(b2.Width); if (c != 0) return c; c = -b1.Height.CompareTo(b2.Height); if (c != 0) return c; return f1.Key.CompareTo(f2.Key); }); // try to pack the images if (!PackImageRectangles()) return (int)FailCode.FailedToPackImage; // make our output image outputImage = CreateOutputImage(); if (outputImage == null) return (int)FailCode.FailedToSaveImage; if (generateMap) { // go through our image placements and replace the width/height found in there with // each image's actual width/height (since the ones in imagePlacement will have padding) string[] keys = new string[imagePlacement.Keys.Count]; imagePlacement.Keys.CopyTo(keys, 0); foreach (var k in keys) { // get the actual size Size s = imageSizes[k][0]; // get the placement rectangle Rectangle r = imagePlacement[k][0]; // set the proper size r.Width = s.Width; r.Height = s.Height; // insert back into the dictionary imagePlacement[k][0] = r; } // copy the placement dictionary to the output outputMap = new Lexicon<string, Rectangle>(); foreach (var pair in imagePlacement) { outputMap.Add(pair.Key, pair.Value); } } // clear our dictionaries just to free up some memory imageSizes.Clear(); imagePlacement.Clear(); outFailedPlacements = FailedPlacements; return 0; }
public void CanFindObjectsForWord() { long siteId = 0; string culture = "en-US"; // Setup Words Lexicon lexicon = new Lexicon(new StaticLexicon()); long thi_id = lexicon.AddOrCreateWord("thi", culture); long test_id = lexicon.AddOrCreateWord("test", culture); long sampl_id = lexicon.AddOrCreateWord("sampl", culture); // Setup Search Objects SearchObject s1 = new SearchObject(); s1.ObjectType = 0; s1.ObjectId = "1"; SearchObject s2 = new SearchObject(); s2.ObjectType = 0; s2.ObjectId = "2"; // Setup Searcher Searcher searcher = new Searcher(lexicon, new StaticSearcher()); // Record Objects long sid1 = searcher.ObjectIndexAddOrUpdate(s1); long sid2 = searcher.ObjectIndexAddOrUpdate(s2); // Index Words for Objects SearchObjectWord w1_1 = new SearchObjectWord() { SearchObjectId = s1.Id, WordId = thi_id, Score = 1, SiteId = siteId }; SearchObjectWord w1_2 = new SearchObjectWord() { SearchObjectId = s1.Id, WordId = test_id, Score = 1, SiteId = siteId }; SearchObjectWord w2_1 = new SearchObjectWord() { SearchObjectId = s2.Id, WordId = thi_id, Score = 1, SiteId = siteId }; SearchObjectWord w2_2 = new SearchObjectWord() { SearchObjectId = s2.Id, WordId = sampl_id, Score = 1, SiteId = siteId }; searcher.ObjectWordIndexUpdate(w1_1); searcher.ObjectWordIndexUpdate(w1_2); searcher.ObjectWordIndexUpdate(w2_1); searcher.ObjectWordIndexUpdate(w2_2); // Test List <SearchObjectWord> actual = searcher.ObjectWordIndexFindByWordId(siteId, thi_id); Assert.IsNotNull(actual); Assert.AreEqual(2, actual.Count); List <SearchObjectWord> actual2 = searcher.ObjectWordIndexFindByWordId(siteId, test_id); Assert.IsNotNull(actual2); Assert.AreEqual(1, actual2.Count); List <SearchObjectWord> actual3 = searcher.ObjectWordIndexFindByWordId(siteId, 99); Assert.IsNotNull(actual3); Assert.AreEqual(0, actual3.Count); }
public void SkipTokenTest() { Lexicon lexicon = new Lexicon(); Lexer global = lexicon.Lexer; Lexer keywords = global.CreateSubLexer(); Lexer xml = keywords.CreateSubLexer(); var ID = global.DefineToken(RE.Range('a', 'z').Concat( (RE.Range('a', 'z') | RE.Range('0', '9')).Many())); var NUM = global.DefineToken(RE.Range('0', '9').Many1()); var WHITESPACE = global.DefineToken(RE.Symbol(' ').Many()); var ERROR = global.DefineToken(RE.Range(Char.MinValue, (char)255)); var IF = keywords.DefineToken(RE.Literal("if")); var ELSE = keywords.DefineToken(RE.Literal("else")); var XMLNS = xml.DefineToken(RE.Literal("xmlns")); ScannerInfo info = lexicon.CreateScannerInfo(); PeekableScanner scanner = new PeekableScanner(info); string source = "asdf04a 1107 else Z if vvv xmlns 772737"; StringReader sr = new StringReader(source); scanner.SetSource(new SourceReader(sr)); scanner.SetTriviaTokens(WHITESPACE.Index, ERROR.Index); info.CurrentLexerIndex = xml.Index; Lexeme l1 = scanner.Read(); Assert.AreEqual(ID.Index, l1.TokenIndex); Assert.AreEqual("asdf04a", l1.Value); Assert.AreEqual(0, l1.PrefixTrivia.Count); Lexeme l2 = scanner.Read(); Assert.AreEqual(NUM.Index, l2.TokenIndex); Assert.AreEqual("1107", l2.Value); Assert.AreEqual(1, l2.PrefixTrivia.Count); Lexeme l3 = scanner.Read(); Assert.AreEqual(ELSE.Index, l3.TokenIndex); Assert.AreEqual("else", l3.Value); Assert.AreEqual(1, l2.PrefixTrivia.Count); Lexeme l4 = scanner.Read(); Assert.AreEqual(IF.Index, l4.TokenIndex); Assert.AreEqual("if", l4.Value); Assert.AreEqual(3, l4.PrefixTrivia.Count); int p1 = scanner.Peek(); Assert.AreEqual(ID.Index, p1); int p2 = scanner.Peek2(); int p3 = scanner.Peek(3); int peof = scanner.Peek(4); Assert.AreEqual(info.EndOfStreamTokenIndex, peof); Lexeme l6 = scanner.Read(); Lexeme l7 = scanner.Read(); Assert.AreEqual(XMLNS.Index, l7.TokenIndex); Lexeme l8 = scanner.Read(); Assert.AreEqual(NUM.Index, l8.TokenIndex); Lexeme leof = scanner.Read(); Assert.AreEqual(info.EndOfStreamTokenIndex, leof.TokenIndex); Assert.AreEqual(leof.Span.StartLocation.CharIndex, leof.Span.EndLocation.CharIndex); Assert.AreEqual(source.Length, leof.Span.StartLocation.CharIndex); }
private bool TestPackingImages(int testWidth, int testHeight, Lexicon<string, Rectangle> testImagePlacement) { // create the rectangle packer ArevaloRectanglePacker rectanglePacker = new ArevaloRectanglePacker(testWidth, testHeight); foreach (var image in files) { // get the bitmap for this file Size size = imageSizes[image.Key][0]; // pack the image Point origin; if (!rectanglePacker.TryPack(size.Width + padding, size.Height + padding, out origin)) { return false; } // add the destination rectangle to our dictionary testImagePlacement.Add(image.Key, new Rectangle(origin.X, origin.Y, size.Width + padding, size.Height + padding)); } return true; }
public void CompactCharSetTest() { Lexicon lexicon = new Lexicon(); Lexer global = lexicon.Lexer; Lexer keywords = global.CreateSubLexer(); Lexer xml = keywords.CreateSubLexer(); var lettersCategories = new[] { UnicodeCategory.LetterNumber, UnicodeCategory.LowercaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.UppercaseLetter }; var RE_IDCHAR = RE.CharsOf(c => lettersCategories.Contains(Char.GetUnicodeCategory(c))); var ID = global.DefineToken(RE_IDCHAR.Concat( (RE_IDCHAR | RE.Range('0', '9')).Many())); var NUM = global.DefineToken(RE.Range('0', '9').Many1()); var WHITESPACE = global.DefineToken(RE.Symbol(' ').Many()); var IF = keywords.DefineToken(RE.Literal("if")); var ELSE = keywords.DefineToken(RE.Literal("else")); var XMLNS = xml.DefineToken(RE.Literal("xmlns")); var scannerInfo = lexicon.CreateScannerInfo(); scannerInfo.CurrentLexerIndex = xml.Index; Scanner s = new Scanner(scannerInfo); string source = "xmlns 你好吗1 123 蘏臦囧綗 ABCD if"; SourceReader sr = new SourceReader(new StringReader(source)); s.SetSource(sr); s.SetTriviaTokens(WHITESPACE.Index); var l1 = s.Read(); Assert.AreEqual(XMLNS.Index, l1.TokenIndex); var l2 = s.Read(); Assert.AreEqual(ID.Index, l2.TokenIndex); var l3 = s.Read(); Assert.AreEqual(NUM.Index, l3.TokenIndex); var l4 = s.Read(); Assert.AreEqual(ID.Index, l4.TokenIndex); var l5 = s.Read(); Assert.AreEqual(ID.Index, l5.TokenIndex); var l6 = s.Read(); Assert.AreEqual(IF.Index, l6.TokenIndex); }
public void ParserDriverSimpleTest() { Lexicon test = new Lexicon(); var X = test.Lexer.DefineToken(RE.Symbol('x')); var PLUS = test.Lexer.DefineToken(RE.Symbol('+')); var scannerinfo = test.CreateScannerInfo(); Production <object> E = new Production <object>(), T = new Production <object>(); E.Rule = (from t in T from plus in PLUS from e in E select(object)(((int)t) + ((int)e))) | T; T.Rule = from x in X select(object) 1; ProductionInfoManager pim = new ProductionInfoManager(E.SuffixedBy(Grammar.Eos())); LR0Model lr0 = new LR0Model(pim); lr0.BuildModel(); string dot = lr0.ToString(); TransitionTable tt = TransitionTable.Create(lr0, scannerinfo); ParserEngine driver = new ParserEngine(tt, new SyntaxErrors() { TokenUnexpectedId = 1 }); ForkableScannerBuilder builder = new ForkableScannerBuilder(scannerinfo); var em = new VBF.Compilers.CompilationErrorManager();; var el = em.CreateErrorList(); builder.ErrorList = el; var scanner = builder.Create(new VBF.Compilers.SourceReader(new StringReader("x+x+x"))); var z1 = scanner.Read(); driver.Input(z1); var z2 = scanner.Read(); driver.Input(z2); var z3 = scanner.Read(); driver.Input(z3); var z4 = scanner.Read(); driver.Input(z4); var z5 = scanner.Read(); driver.Input(z5); var z6 = scanner.Read(); driver.Input(z6); Assert.AreEqual(0, driver.CurrentStackCount); Assert.AreEqual(1, driver.AcceptedCount); Assert.AreEqual(3, driver.GetResult(0, null)); }
public void ScannerTest() { Lexicon lexicon = new Lexicon(); Lexer global = lexicon.Lexer; Lexer keywords = global.CreateSubLexer(); Lexer xml = keywords.CreateSubLexer(); var ID = global.DefineToken(RE.Range('a', 'z').Concat( (RE.Range('a', 'z') | RE.Range('0', '9')).Many())); var NUM = global.DefineToken(RE.Range('0', '9').Many1()); var WHITESPACE = global.DefineToken(RE.Symbol(' ').Many()); var ERROR = global.DefineToken(RE.Range(Char.MinValue, (char)255)); var IF = keywords.DefineToken(RE.Literal("if")); var ELSE = keywords.DefineToken(RE.Literal("else")); var XMLNS = xml.DefineToken(RE.Literal("xmlns")); ScannerInfo info = lexicon.CreateScannerInfo(); PeekableScanner scanner = new PeekableScanner(info); string source = "asdf04a 1107 else Z if vvv xmlns 772737"; StringReader sr = new StringReader(source); scanner.SetSource(new SourceReader(sr)); Lexeme l1 = scanner.Read(); Assert.AreEqual(ID.Index, l1.TokenIndex); Assert.AreEqual("asdf04a", l1.Value); Assert.AreEqual(0, l1.Span.StartLocation.Column); Assert.AreEqual(6, l1.Span.EndLocation.Column); Lexeme l2 = scanner.Read(); Assert.AreEqual(WHITESPACE.Index, l2.TokenIndex); Assert.AreEqual(" ", l2.Value); Lexeme l3 = scanner.Read(); Assert.AreEqual(NUM.Index, l3.TokenIndex); Assert.AreEqual("1107", l3.Value); Lexeme l4 = scanner.Read(); Assert.AreEqual(WHITESPACE.Index, l4.TokenIndex); Lexeme l5 = scanner.Read(); Assert.AreEqual(ID.Index, l5.TokenIndex); int p1 = scanner.Peek(); Assert.AreEqual(WHITESPACE.Index, p1); int p2 = scanner.Peek2(); Assert.AreEqual(ERROR.Index, p2); int p3 = scanner.Peek(3); Assert.AreEqual(WHITESPACE.Index, p3); int p4 = scanner.Peek(4); Assert.AreEqual(ID.Index, p4); int p5 = scanner.Peek(5); Assert.AreEqual(WHITESPACE.Index, p5); Lexeme l6 = scanner.Read(); Lexeme l7 = scanner.Read(); Assert.AreEqual(ERROR.Index, l7.TokenIndex); int p3_2 = scanner.Peek(); Assert.AreEqual(p3, p3_2); Lexeme l8 = scanner.Read(); // whitespace Lexeme l9 = scanner.Read(); // ID:if Lexeme l10 = scanner.Read(); // whitespace Lexeme l11 = scanner.Read(); // ID:vvv Lexeme l12 = scanner.Read(); // whitespace Lexeme l13 = scanner.Read(); // ID:xmlns Lexeme l14 = scanner.Read(); // whitespace Lexeme l15 = scanner.Read(); // NUM:772737 Lexeme leof = scanner.Read(); // eof Assert.AreEqual(info.EndOfStreamTokenIndex, leof.TokenIndex); Assert.AreEqual(leof.Span.StartLocation.CharIndex, leof.Span.EndLocation.CharIndex); Assert.AreEqual(source.Length, leof.Span.StartLocation.CharIndex); Lexeme leof2 = scanner.Read(); //after eof, should return eof again Assert.AreEqual(info.EndOfStreamTokenIndex, leof2.TokenIndex); Assert.AreEqual(leof.Span.StartLocation.CharIndex, leof2.Span.StartLocation.CharIndex); }
public void ProductionInfoManagerTest() { Lexicon test = new Lexicon(); var A = test.Lexer.DefineToken(RE.Symbol('a')); var D = test.Lexer.DefineToken(RE.Symbol('d')); var C = test.Lexer.DefineToken(RE.Symbol('c')); Production <object> X = new Production <object>(), Y = new Production <object>(), Z = new Production <object>(); Z.Rule = (from d in D select d as object) | (from x in X from y in Y from z in Z select new { x, y, z } as object); Y.Rule = Grammar.Empty(new object()) | (from c in C select c as object); X.Rule = Y | (from a in A select a as object); ProductionInfoManager pis = new ProductionInfoManager(Z); var xInfo = pis.GetInfo(X); var yInfo = pis.GetInfo(Y); var zInfo = pis.GetInfo(Z); Assert.IsTrue(xInfo.IsNullable, "X should be nullable"); Assert.IsTrue(yInfo.IsNullable, "Y should be nullable"); Assert.IsFalse(zInfo.IsNullable, "Z should not be nullable"); Assert.AreEqual(xInfo.First.Count, 2); Assert.AreEqual(xInfo.Follow.Count, 3); Assert.IsTrue(xInfo.First.Contains(A.AsTerminal())); Assert.IsTrue(xInfo.First.Contains(C.AsTerminal())); Assert.IsTrue(xInfo.Follow.Contains(A.AsTerminal())); Assert.IsTrue(xInfo.Follow.Contains(C.AsTerminal())); Assert.IsTrue(xInfo.Follow.Contains(D.AsTerminal())); Assert.AreEqual(yInfo.First.Count, 1); Assert.AreEqual(yInfo.Follow.Count, 3); Assert.IsTrue(yInfo.First.Contains(C.AsTerminal())); Assert.IsTrue(yInfo.Follow.Contains(A.AsTerminal())); Assert.IsTrue(yInfo.Follow.Contains(C.AsTerminal())); Assert.IsTrue(yInfo.Follow.Contains(D.AsTerminal())); Assert.AreEqual(zInfo.First.Count, 3); Assert.AreEqual(zInfo.Follow.Count, 0); Assert.IsTrue(zInfo.First.Contains(A.AsTerminal())); Assert.IsTrue(zInfo.First.Contains(C.AsTerminal())); Assert.IsTrue(zInfo.First.Contains(D.AsTerminal())); }
public void WhereGrammaTest() { Lexicon test = new Lexicon(); var ID = test.Lexer.DefineToken(RE.Range('a', 'z').Concat( (RE.Range('a', 'z') | RE.Range('0', '9')).Many()), "ID"); var NUM = test.Lexer.DefineToken(RE.Range('0', '9').Many1(), "NUM"); var GREATER = test.Lexer.DefineToken(RE.Symbol('>')); var WHITESPACE = test.Lexer.DefineToken(RE.Symbol(' ').Union(RE.Symbol('\t')), "[ ]"); var p1 = from i in ID from g in GREATER from g2 in GREATER where Grammar.Check(g2.PrefixTrivia.Count == 0, 4, g2.Value.Span) from n in NUM select "A"; var p2 = from i in ID from g in GREATER from g2 in GREATER from n in NUM select "B"; var parser1 = p1 | p2; parser1.AmbiguityAggregator = (a, b) => a == "A" ? a : b; var info = test.CreateScannerInfo(); var errorManager = new CompilationErrorManager(); errorManager.DefineError(1, 0, CompilationStage.Parsing, "Unexpected token '{0}'"); errorManager.DefineError(2, 0, CompilationStage.Parsing, "Missing token '{0}'"); errorManager.DefineError(3, 0, CompilationStage.Parsing, "Syntax error"); errorManager.DefineError(4, 0, CompilationStage.Parsing, "White spaces between >> are not allowed"); var el = errorManager.CreateErrorList(); ProductionInfoManager pim = new ProductionInfoManager(parser1.SuffixedBy(Grammar.Eos())); LR0Model lr0 = new LR0Model(pim); lr0.BuildModel(); string dot = lr0.ToString(); TransitionTable tt = TransitionTable.Create(lr0, info); var errdef = new SyntaxErrors() { TokenUnexpectedId = 1, TokenMissingId = 2, OtherErrorId = 3 }; ParserEngine driver = new ParserEngine(tt, errdef); string source1 = "abc >> 123"; var sr1 = new SourceReader(new StringReader(source1)); Scanner scanner = new Scanner(info); scanner.SetTriviaTokens(WHITESPACE.Index); scanner.SetSource(sr1); Lexeme r; do { r = scanner.Read(); driver.Input(r); } while (!r.IsEndOfStream); Assert.AreEqual(1, driver.AcceptedCount); Assert.AreEqual("A", driver.GetResult(0, el)); Assert.AreEqual(0, el.Count); ParserEngine driver2 = new ParserEngine(tt, errdef); string source2 = "abc > > 123"; var sr2 = new SourceReader(new StringReader(source2)); scanner.SetSource(sr2); do { r = scanner.Read(); driver2.Input(r); } while (!r.IsEndOfStream); var el2 = errorManager.CreateErrorList(); Assert.AreEqual(1, driver2.AcceptedCount); Assert.AreEqual("B", driver2.GetResult(0, el2)); Assert.AreEqual(0, el2.Count); }
public void CanHandleSerializableStructures() { Lexicon lex = new Lexicon(); lex.Add(new StringValue("key1"), new StringValue("value1")); queue.Push(new BaseMessage(new SafeSerializationMgr(null).Dump(lex), 0, 0)); Lexicon read = new SafeSerializationMgr(null).CreateFromDump(queue.Pop().Content as Dump) as Lexicon; Assert.AreEqual(new StringValue("value1"), read[new StringValue("key1")]); }
public NamedStep(string name, Lexicon <TContext> lexicon, string refName) : base(name) { steps = lexicon; this.refName = refName; }