コード例 #1
0
ファイル: DecoratedMethod.cs プロジェクト: raydleemsc/Torch
        internal void Commit()
        {
            try
            {
                // non-greedy so they are all reset
                if (!Prefixes.HasChanges(true) & !Suffixes.HasChanges(true) & !Transpilers.HasChanges(true) & !PostTranspilers.HasChanges(true))
                {
                    return;
                }
                Revert();

                if (Prefixes.Count == 0 && Suffixes.Count == 0 && Transpilers.Count == 0 && PostTranspilers.Count == 0)
                {
                    return;
                }
                _log.Log(PrintMsil ? LogLevel.Info : LogLevel.Debug,
                         $"Begin patching {_method.DeclaringType?.FullName}#{_method.Name}({string.Join(", ", _method.GetParameters().Select(x => x.ParameterType.Name))})");
                var patch = ComposePatchedMethod();

                _revertAddress = AssemblyMemory.GetMethodBodyStart(_method);
                var newAddress = AssemblyMemory.GetMethodBodyStart(patch);
                _revertData  = AssemblyMemory.WriteJump(_revertAddress, newAddress);
                _pinnedPatch = GCHandle.Alloc(patch);
                _log.Log(PrintMsil ? LogLevel.Info : LogLevel.Debug,
                         $"Done patching {_method.DeclaringType?.FullName}#{_method.Name}({string.Join(", ", _method.GetParameters().Select(x => x.ParameterType.Name))})");
            }
            catch (Exception exception)
            {
                _log.Fatal(exception, $"Error patching {_method.DeclaringType?.FullName}#{_method}");
                throw;
            }
        }
コード例 #2
0
ファイル: LanguageReader.cs プロジェクト: KeliBox/nuve
        public Language Read()
        {
            var sw = new Stopwatch();

            sw.Start();

            _orthography = ReadOrthography();
            Debug.Print($"orthograpy: {sw.ElapsedMilliseconds} ms");
            sw.Restart();

            Morphotactics morphotactics = ReadMorphotactics();

            Debug.Print($"morphotactics: {sw.ElapsedMilliseconds} ms");
            sw.Restart();

            MorphemeSurfaceDictionary <Root> roots = ReadRoots();

            Debug.Print($"roots: {sw.ElapsedMilliseconds} ms");
            sw.Restart();

            Suffixes suffixes = ReadSuffixes();

            Debug.Print($"suffixes: {sw.ElapsedMilliseconds} ms");
            sw.Restart();


            int index = _dirPath.LastIndexOf("\\", StringComparison.Ordinal);

            string langCode = index > -1 ? _dirPath.Substring(index + 1) : _dirPath;

            return(new Language(langCode, morphotactics, roots, suffixes));
        }
コード例 #3
0
        private void GetAppFromDirectory(string path, List <Program> list, int depth)
        {
            if (MaxDepth != -1 && depth > MaxDepth)
            {
                return;
            }
            try
            {
                foreach (var file in Directory.GetFiles(path))
                {
                    if (Suffixes.Any(o => file.EndsWith("." + o)))
                    {
                        var p = CreateEntry(file);
                        p.Source = this;
                        list.Add(p);
                    }
                }

                foreach (var subDirectory in Directory.GetDirectories(path))
                {
                    GetAppFromDirectory(subDirectory, list, depth + 1);
                }
            }
            catch (Exception e)
            {
                var woxPluginException = new WoxPluginException("Program", $"GetAppFromDirectory failed: {path}", e);
                Log.Exception(woxPluginException);
            }
        }
コード例 #4
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        public NameParser()
        {
            // Populate CorpIDs list.
            CorpIDs.Add("&");
            CorpIDs.Add(" Corp.");
            CorpIDs.Add(" Corporation");
            CorpIDs.Add(" Llc.");
            CorpIDs.Add(" Llp.");
            CorpIDs.Add(" Limited");
            CorpIDs.Add(" Co.");
            CorpIDs.Add(" Company");
            CorpIDs.Add("Firm");
            CorpIDs.Add("Associates");

            // Populate Suffixes list.
            Suffixes.Add("I");
            Suffixes.Add("II");
            Suffixes.Add("III");
            Suffixes.Add("Jr.");
            Suffixes.Add("Sr.");

            // Populate Titles list.
            Titles.Add("Dr.");
            Titles.Add("Miss");
            Titles.Add("Mrs.");
            Titles.Add("Mr.");
            Titles.Add("Ms.");
            Titles.Add("Prof.");
        }
コード例 #5
0
ファイル: D2DMenu.cs プロジェクト: DeanReynolds/SharpXNA
 public void AddSuffix(string text, Color color)
 {
     if (Suffixes.Contains(text))
     {
         throw new Exception($"Suffix with name '{text}' already exists!");
     }
     Suffixes.Add(text, new Title(text, color)); VisibleItems++;
 }
コード例 #6
0
ファイル: D2DMenu.cs プロジェクト: DeanReynolds/SharpXNA
 public void RemoveSuffix(string text)
 {
     if (!Suffixes.Contains(text))
     {
         return;
     }
     Suffixes.Remove(text); VisibleItems--;
 }
コード例 #7
0
ファイル: Parser.cs プロジェクト: jamesrm9235/NameParserSharp
        /// <summary>
        /// Determines whether <see cref="piece"/> is a given name component as opposed to an affix, initial or title.
        /// </summary>
        /// <param name="piece">A single word from a name</param>
        /// <returns>False if <see cref="piece"/> is a prefix (de, abu, bin), suffix (jr, iv, cpa), title (mr, pope), or initial (x, e.); true otherwise</returns>
        private static bool IsRootname(string piece)
        {
            var lcPiece = piece.ToLower().Replace(".", string.Empty);

            return(!Suffixes.Contains(lcPiece) &&
                   !Prefixes.Contains(lcPiece) &&
                   !Titles.Contains(lcPiece) &&
                   !IsAnInitial(piece));
        }
コード例 #8
0
ファイル: Language.cs プロジェクト: KeliBox/nuve
 internal Language(string code,
                   Morphotactics morphotactics,
                   MorphemeSurfaceDictionary <Root> roots,
                   Suffixes suffixes)
 {
     _code         = code;
     Morphotactics = morphotactics;
     _roots        = roots;
     _suffixes     = suffixes;
 }
コード例 #9
0
ファイル: Spec.cs プロジェクト: vazgriz/VulkanGenerator
 void LoadTags(XmlNode root)
 {
     foreach (XmlNode node in root.ChildNodes)
     {
         if (node is XmlComment)
         {
             continue;
         }
         Suffixes.Add(node.Attributes["name"].Value);
     }
 }
コード例 #10
0
 /// <summary>
 /// Produz o nome completo da versão, na forma:
 /// -   X.X.X-sufixoX_rX
 /// Ou apenas a parte escolhida.
 /// Sendo:
 /// -   X
 ///         Um número qualquer.
 /// -   X.X.X
 ///         Obrigatório.
 ///         Número de versão do aplicativo.
 /// -   sufixoX
 ///         Opcional.
 ///         O nome da versão, como alfa, beta, trunk, etc.
 ///         Seguido opcionalmente de um número de revisão do sufixo.
 /// -   rX
 ///         Opcional.
 ///         O número de revisão no repositório de código fonte.
 /// </summary>
 /// <param name="parts">
 /// As partes extras de versão escolhidas.
 /// </param>
 public string ToString(Suffixes parts)
 {
   var text = string.Join(".", Major, Minor, Patch);
   if (parts.HasFlag(Suffixes.PreRelease) && PreRelease != null)
   {
     text += $"-{PreRelease}";
   }
   if (parts.HasFlag(Suffixes.Revision) && Revision > 0)
   {
     text += $"_r{Revision}";
   }
   return text;
 }
コード例 #11
0
        /// <summary>
        /// Produz o nome completo da versão, na forma:
        /// -   X.X.X-sufixoX_rX
        /// Ou apenas a parte escolhida.
        /// Sendo:
        /// -   X
        ///         Um número qualquer.
        /// -   X.X.X
        ///         Obrigatório.
        ///         Número de versão do aplicativo.
        /// -   sufixoX
        ///         Opcional.
        ///         O nome da versão, como alfa, beta, trunk, etc.
        ///         Seguido opcionalmente de um número de revisão do sufixo.
        /// -   rX
        ///         Opcional.
        ///         O número de revisão no repositório de código fonte.
        /// </summary>
        /// <param name="parts">
        /// As partes extras de versão escolhidas.
        /// </param>
        public string ToString(Suffixes parts)
        {
            var text = FormattedNumber;

            if (parts.HasFlag(Suffixes.PreRelease))
            {
                text += FormattedPreRelease;
            }
            if (parts.HasFlag(Suffixes.Revision))
            {
                text += FormattedRevision;
            }
            return(text);
        }
コード例 #12
0
ファイル: TestClass.cs プロジェクト: kcherr1/CSharp-Eval
		public TestClass() {
			AccModTest = new AccessModifierTest();
			ArrTest = new ArrayTest();
			ETest = new EnumTest();
			IdentTest = new IdentifierTest();
			MethTest = new MethodTest();
			SpecExpTest = new SpecialExpressionsTest();
			AssignTest = new AssignmentTest();
			OpEqTest = new OpEqTest();
			Suffixes = new Suffixes();
			Constants = new TermConstants();
			Override = new OverrideTest();
			OpOver1 = new OpOverload();
			OpOver2 = new OpOverload();
		}
コード例 #13
0
ファイル: TestClass.cs プロジェクト: lilasquared/CSharp-Eval
 public TestClass()
 {
     AccModTest  = new AccessModifierTest();
     ArrTest     = new ArrayTest();
     ETest       = new EnumTest();
     IdentTest   = new IdentifierTest();
     MethTest    = new MethodTest();
     SpecExpTest = new SpecialExpressionsTest();
     AssignTest  = new AssignmentTest();
     OpEqTest    = new OpEqTest();
     Suffixes    = new Suffixes();
     Constants   = new TermConstants();
     Override    = new OverrideTest();
     OpOver1     = new OpOverload();
     OpOver2     = new OpOverload();
 }
コード例 #14
0
        public override async Task Initialize()
        {
            FirstName        = Prospect.FirstName;
            LastName         = Prospect.LastName;
            MiddleName       = Prospect.MiddleName;
            NickName         = Prospect.NickName;
            StreetAddress    = Prospect.StreetAddress == null ? new StreetAddress() : Prospect.StreetAddress.ShallowCopy();
            FollowUpSettings = Prospect.FollowUpSettings.ShallowCopy();
            MobilePhone      = Prospect.MobilePhoneNumber == null ? new PhoneNumber() : Prospect.MobilePhoneNumber.ShallowCopy();
            WorkPhone        = Prospect.WorkPhoneNumber == null ? new PhoneNumber() : Prospect.WorkPhoneNumber.ShallowCopy();
            HomePhone        = Prospect.HomePhoneNumber == null ? new PhoneNumber() : Prospect.HomePhoneNumber.ShallowCopy();
            Email            = Prospect.Email == null ? new Email() : Prospect.Email.ShallowCopy();

            _originalProspect = Prospect.ShallowCopy();
            _originalProspect.FollowUpSettings  = FollowUpSettings.ShallowCopy();
            _originalProspect.StreetAddress     = StreetAddress.ShallowCopy();
            _originalProspect.MobilePhoneNumber = MobilePhone.ShallowCopy();
            _originalProspect.WorkPhoneNumber   = WorkPhone.ShallowCopy();
            _originalProspect.HomePhoneNumber   = HomePhone.ShallowCopy();
            _originalProspect.Email             = Email.ShallowCopy();

            Prefixes     = (await _userDefinedCodeService.GetPrefixUserDefinedCodes()).ToObservableCollection();
            ActivePrefix = Prefixes.FirstOrDefault(p => p.Description1 == Prospect.NamePrefix);

            Suffixes     = (await _userDefinedCodeService.GetSuffixUserDefinedCodes()).ToObservableCollection();
            ActiveSuffix = Suffixes.FirstOrDefault(p => p.Description1 == Prospect.NameSuffix);

            ContactPreferences      = (await _userDefinedCodeService.GetContactPreferenceUserDefinedCodes()).ToObservableCollection();
            ActiveContactPreference = ContactPreferences.FirstOrDefault(p => p.Description1 == Prospect.FollowUpSettings.PreferredContactMethod);

            ExcludeReasons      = (await _userDefinedCodeService.GetExcludeReasonUserDefinedCodes()).ToObservableCollection();
            ActiveExcludeReason = ExcludeReasons.FirstOrDefault(p => p.Code == Prospect.FollowUpSettings.ExcludeReason);

            States      = (await _userDefinedCodeService.GetStateUserDefinedCodes()).ToObservableCollection();
            ActiveState = Prospect.StreetAddress != null?States.FirstOrDefault(p => p.Code == Prospect.StreetAddress.State) : null;

            Countries     = (await _userDefinedCodeService.GetCountryUserDefinedCodes()).ToObservableCollection();
            ActiveCountry = Prospect.StreetAddress != null?Countries.FirstOrDefault(p => p.Code == Prospect.StreetAddress.Country) : null;

            TrafficSources      = (await _trafficSourceService.GetTrafficSourcesByDivision(Prospect.ProspectCommunity.Division)).ToObservableCollection();
            ActiveTrafficSource = TrafficSources.FirstOrDefault(t => t.TrafficSourceDetails.Any(td => td.CodeId == Prospect.TrafficSourceCodeId));
            if (ActiveTrafficSource != null)
            {
                ActiveTrafficSourceDetail = ActiveTrafficSource.TrafficSourceDetails.First(td => td.CodeId == Prospect.TrafficSourceCodeId);
            }
        }
コード例 #15
0
        /// <summary>
        /// Обновляет сборку.
        /// </summary>
        /// <param name="location">Новый путь.</param>
        /// <param name="number">Номер сборки.</param>
        /// <param name="releaseNumber">Номер релиза.</param>
        /// <param name="updatedSuffixes">Новые суффиксы.</param>
        /// <param name="changeDate">Дата изменения сборки.</param>
        public void Update(string location, VersionNumber releaseNumber, VersionNumber number, IList <string> updatedSuffixes, DateTime changeDate)
        {
            location.ThrowIsNullOrWhiteSpace(new UpdateBuildException("Location is null or empty."));
            number.ThrowIfNull(new UpdateBuildException("Number must not be null"));
            ValidateReleaseNumber(releaseNumber, number, location);

            IList <string> newSuffixes =
                Suffixes.ToHashSet().SetEquals(updatedSuffixes)
                    ? Suffixes
                    : updatedSuffixes;

            if (location == Location && newSuffixes.SequenceEqual(Suffixes))
            {
                return;
            }

            Apply(new BuildUpdated(location, number, releaseNumber, newSuffixes, CreateMetadata(changeDate)));
            UpdateArtifactState(ArtifactState.Updated);
        }
コード例 #16
0
        public override List <Program> LoadPrograms()
        {
            List <Program> list = new List <Program>();

            foreach (var Folder in Directory.GetDirectories(BaseDirectory))
            {
                list.Add(CreateEntry(Folder));
            }


            foreach (string file in Directory.GetFiles(base.BaseDirectory))
            {
                if (Suffixes.Any(o => file.EndsWith("." + o)))
                {
                    list.Add(CreateEntry(file));
                }
            }

            return(list);
        }
コード例 #17
0
        public override async Task Initialize()
        {
            _user = await _userService.GetLoggedInUser();

            _originalCobuyer = Cobuyer.ShallowCopy();
            _originalCobuyer.StreetAddress     = StreetAddress.ShallowCopy();
            _originalCobuyer.MobilePhoneNumber = MobilePhone.ShallowCopy();
            _originalCobuyer.WorkPhoneNumber   = WorkPhone.ShallowCopy();
            _originalCobuyer.HomePhoneNumber   = HomePhone.ShallowCopy();
            _originalCobuyer.Email             = Email.ShallowCopy();

            Prefixes     = (await _userDefinedCodeService.GetPrefixUserDefinedCodes()).ToObservableCollection();
            ActivePrefix = Prefixes.FirstOrDefault(p => p.Description1 == Cobuyer.NamePrefix);

            Suffixes     = (await _userDefinedCodeService.GetSuffixUserDefinedCodes()).ToObservableCollection();
            ActiveSuffix = Suffixes.FirstOrDefault(p => p.Description1 == Cobuyer.NameSuffix);

            States      = (await _userDefinedCodeService.GetStateUserDefinedCodes()).ToObservableCollection();
            ActiveState = Cobuyer.StreetAddress != null?States.FirstOrDefault(p => p.Code == Cobuyer.StreetAddress.State) : null;

            Countries     = (await _userDefinedCodeService.GetCountryUserDefinedCodes()).ToObservableCollection();
            ActiveCountry = Cobuyer.StreetAddress != null?Countries.FirstOrDefault(p => p.Code == Cobuyer.StreetAddress.Country) : null;
        }
コード例 #18
0
ファイル: NameParser.cs プロジェクト: rahodges/Amns
        /// <summary>
        /// Tests to see if the string is a suffix and returns true if it is. In addition,
        /// it will provide a Formatted Version of a suffix for abbreviations.
        /// </summary>
        /// <param name="s">String to test.</param>
        /// <param name="formattedSuffix">String reference to pass formatted suffix.</param>
        /// <returns>True if string is a suffix; false if not.</returns>
        private bool isSuffix(string s, out string formattedSuffix)
        {
            foreach (string suffix in SimpleSuffixes)
            {
                if (s.ToUpper() == suffix.ToUpper())
                {
                    formattedSuffix = suffix;
                    return(true);
                }
            }

            for (int x = 0; x <= Suffixes.GetUpperBound(0); x++)
            {
                if (s.ToUpper().Replace(".", string.Empty) == Suffixes[x, 0])
                {
                    formattedSuffix = Suffixes[x, 1];
                    return(true);
                }
            }

            formattedSuffix = s;

            return(false);
        }
コード例 #19
0
        public string Generate(uint modelId, string source)
        {
            var split = PreGenerate(modelId, source);

            if (split == null)
            {
                return(null);
            }

            split = Process(split);
            if (split == null)
            {
                return(null);
            }

            var last = split.Last();

            if (Suffixes.Any(t => t.Equals(last)) == true)
            {
                split = Trim(split);
            }

            return(PostProcess(split));
        }
コード例 #20
0
ファイル: Parser.cs プロジェクト: jamesrm9235/NameParserSharp
 private static bool IsSuffix(string piece)
 {
     return(Suffixes.Contains(piece.Replace(".", string.Empty).ToLower()) && !IsAnInitial(piece));
 }
コード例 #21
0
 public void AddSuffixCodes(string suffix, params TypeCode[] codes)
 {
     SuffixTypeCodes.Add(suffix, codes);
     Suffixes.Add(suffix);
 }
コード例 #22
0
        public override void Execute()
        {
            College = new College(ProgID).Object;

            string[] suffixes = Suffixes.Split(',');
            List <LocationWrapper> locs = new List <LocationWrapper>();
            double total = College.Locations.Count; double count = 0;

            foreach (var loc in College.Locations)
            {
                Progress = (int)Math.Round(100.0 * ++count / total);
                var suffix = suffixes.FirstOrDefault(s => loc.Name.EndsWith(s));
                if (suffix != null)
                {
                    locs.Add(new LocationWrapper(loc, suffix));
                }
            }
            count = 0;
            foreach (var loc in College.Locations)
            {
                Progress = (int)Math.Round(100.0 * ++count / total);
                string name = loc.Name;
                if (locs.Any(l => l.NamePart == name))
                {
                    locs.Add(new LocationWrapper(loc, ""));
                }
            }

            Func <string, dynamic> findLoc = part =>
            {
                string parentName = string.IsNullOrEmpty(MergeInto) ? part
                    : locs.First(l => l.NamePart == part && l.Suffix == MergeInto).Name;
                var pLocs = College.Locations.Find(null, parentName);
                if (pLocs.Count == 0)
                {
                    var zloc = locs.FirstOrDefault(l => l.NamePart == part && !l.HostKey.StartsWith("#"));
                    if (zloc == null)
                    {
                        zloc = locs.FirstOrDefault(l => l.NamePart == part);
                    }
                    pLocs = College.Locations.Find(null, zloc.Name);
                }
                return(pLocs[1]);
            };

            total = College.Activities.Count; count = 0;
            foreach (var act in College.Activities)
            {
                Progress = (int)Math.Round(100.0 * ++count / total);
                if (act.SchedulingStatus != 0)
                {
                    continue;
                }

                var res     = act.GetResourceAllocation(1);
                var resList = ToList(res);

                bool change = false;
                foreach (var loc in resList)
                {
                    string locName = loc.Name;
                    var    tl      = locs.FirstOrDefault(l => l.Name == locName);
                    if (tl == null)
                    {
                        continue;
                    }
                    var parentLoc = findLoc(tl.NamePart);
                    if (parentLoc.ObjectId == loc.ObjectId)
                    {
                        continue;
                    }
                    change = true;
                    res.Remove(loc);
                    res.Add(parentLoc);
                }
                if (!change)
                {
                    continue;
                }

                var setting = College.CreateSchedulingResourceSetting();
                setting.UseLocation = true;
                var reqType = act.GetLocationRequirementType;
                act.UnscheduleSpecialMany(setting);
                act.SetResourceRequirement(1, 1, res.Count, res);
                act.ScheduleSpecialMany(setting);
                if ((int)reqType != 1)
                {
                    act.SetResourceRequirement(1, 2, res.Count, res);
                }
                //Log.Add(Description, "Reschedule", act);
            }

            total = College.Activities.Count; count = 0;
            foreach (var act in College.Activities)
            {
                Progress = (int)Math.Round(100.0 * ++count / total);
                if (act.GetResourceRequirementType(1) != 1)
                {
                    continue;
                }

                var res     = act.GetResourceRequirement(1);
                var resList = ToList(res);

                bool change = false;
                foreach (var loc in resList)
                {
                    string locName = loc.Name;
                    var    tl      = locs.FirstOrDefault(l => l.Name == locName);
                    if (tl == null)
                    {
                        continue;
                    }
                    var parentLoc = findLoc(tl.NamePart);
                    if (loc.ObjectId == parentLoc.ObjectId)
                    {
                        continue;
                    }
                    change = true;
                    res.Remove(loc);
                    res.Add(parentLoc);
                }
                if (!change)
                {
                    continue;
                }

                //Log.Add(Description, "ChangePreset", act);
                act.SetResourceRequirement(1, 1, res.Count, res);
            }

            total = locs.Count; count = 0;
            foreach (var loc in locs)
            {
                Progress = (int)Math.Round(100.0 * ++count / total);
                var zloc = locs.FirstOrDefault(l => l.NamePart == loc.NamePart && !l.Name.EndsWith(")"));
                if (zloc == null)
                {
                    zloc = locs.First(l => l.NamePart == loc.NamePart);
                }
                if (DeleteOthers && ((MergeInto != null && loc.Suffix != MergeInto) || (MergeInto == null && loc != zloc)))
                {
                    College.DeleteLocation(loc.Location);
                }
                else if (RemoveSuffix)
                {
                    loc.Location.Name = loc.NamePart;
                }
            }
        }
コード例 #23
0
ファイル: DecoratedMethod.cs プロジェクト: raydleemsc/Torch
 internal bool HasChanged()
 {
     return(Prefixes.HasChanges() || Suffixes.HasChanges() || Transpilers.HasChanges() || PostTranspilers.HasChanges());
 }
コード例 #24
0
 public void AddSuffix(string suffix, params TypeCode[] typeCodes)
 {
     SuffixTypeCodes.Add(suffix, typeCodes);
     Suffixes.Add(suffix);
 }
コード例 #25
0
ファイル: DecoratedMethod.cs プロジェクト: raydleemsc/Torch
        private IEnumerable <MsilInstruction> EmitPatched(Func <Type, bool, MsilLocal> declareLocal)
        {
            var methodBody = _method.GetMethodBody();

            Debug.Assert(methodBody != null, "Method body is null");
            foreach (var localVar in methodBody.LocalVariables)
            {
                Debug.Assert(localVar.LocalType != null);
                declareLocal(localVar.LocalType, localVar.IsPinned);
            }

            var instructions     = new List <MsilInstruction>();
            var specialVariables = new Dictionary <string, MsilLocal>();

            var labelAfterOriginalContent = new MsilLabel();
            var labelSkipMethodContent    = new MsilLabel();


            Type      returnType     = _method is MethodInfo meth ? meth.ReturnType : typeof(void);
            MsilLocal resultVariable = null;

            if (returnType != typeof(void))
            {
                if (Prefixes.Concat(Suffixes).SelectMany(x => x.GetParameters()).Any(x => x.Name == RESULT_PARAMETER) ||
                    Prefixes.Any(x => x.ReturnType == typeof(bool)))
                {
                    resultVariable = declareLocal(returnType, false);
                }
            }

            if (resultVariable != null)
            {
                instructions.AddRange(resultVariable.SetToDefault());
            }
            MsilLocal prefixSkippedVariable = null;

            if (Prefixes.Count > 0 && Suffixes.Any(x => x.GetParameters()
                                                   .Any(y => y.Name.Equals(PREFIX_SKIPPED_PARAMETER))))
            {
                prefixSkippedVariable = declareLocal(typeof(bool), false);
                specialVariables.Add(PREFIX_SKIPPED_PARAMETER, prefixSkippedVariable);
            }

            if (resultVariable != null)
            {
                specialVariables.Add(RESULT_PARAMETER, resultVariable);
            }

            // Create special variables
            foreach (var m in Prefixes.Concat(Suffixes))
            {
                foreach (var param in m.GetParameters())
                {
                    if (param.Name.StartsWith(LOCAL_PARAMETER))
                    {
                        var requiredType = param.ParameterType.IsByRef ? param.ParameterType.GetElementType() : param.ParameterType;
                        if (specialVariables.TryGetValue(param.Name, out var existingParam))
                        {
                            if (existingParam.Type != requiredType)
                            {
                                throw new ArgumentException(
                                          $"Trying to use injected local {param.Name} for {m.DeclaringType?.FullName}#{m.ToString()} with type {requiredType} but a local with the same name already exists with type {existingParam.Type}",
                                          param.Name);
                            }
                        }
                        else
                        {
                            specialVariables.Add(param.Name, declareLocal(requiredType, false));
                        }
                    }
                }
            }

            foreach (MethodInfo prefix in Prefixes)
            {
                instructions.AddRange(EmitMonkeyCall(prefix, specialVariables));
                if (prefix.ReturnType == typeof(bool))
                {
                    instructions.Add(new MsilInstruction(OpCodes.Brfalse).InlineTarget(labelSkipMethodContent));
                }
                else if (prefix.ReturnType != typeof(void))
                {
                    throw new Exception(
                              $"Prefixes must return void or bool.  {prefix.DeclaringType?.FullName}.{prefix.Name} returns {prefix.ReturnType}");
                }
            }

            instructions.AddRange(MethodTranspiler.Transpile(_method, (x) => declareLocal(x, false), Transpilers, labelAfterOriginalContent));

            instructions.Add(new MsilInstruction(OpCodes.Nop).LabelWith(labelAfterOriginalContent));
            if (resultVariable != null)
            {
                instructions.Add(new MsilInstruction(OpCodes.Stloc).InlineValue(resultVariable));
            }
            var notSkip = new MsilLabel();

            instructions.Add(new MsilInstruction(OpCodes.Br).InlineTarget(notSkip));
            instructions.Add(new MsilInstruction(OpCodes.Nop).LabelWith(labelSkipMethodContent));
            if (prefixSkippedVariable != null)
            {
                instructions.Add(new MsilInstruction(OpCodes.Ldc_I4_1));
                instructions.Add(new MsilInstruction(OpCodes.Stloc).InlineValue(prefixSkippedVariable));
            }

            instructions.Add(new MsilInstruction(OpCodes.Nop).LabelWith(notSkip));

            foreach (MethodInfo suffix in Suffixes)
            {
                instructions.AddRange(EmitMonkeyCall(suffix, specialVariables));
                if (suffix.ReturnType != typeof(void))
                {
                    throw new Exception($"Suffixes must return void.  {suffix.DeclaringType?.FullName}.{suffix.Name} returns {suffix.ReturnType}");
                }
            }

            if (resultVariable != null)
            {
                instructions.Add(new MsilInstruction(OpCodes.Ldloc).InlineValue(resultVariable));
            }
            instructions.Add(new MsilInstruction(OpCodes.Ret));

            var result = MethodTranspiler.Transpile(_method, instructions, (x) => declareLocal(x, false), PostTranspilers, null).ToList();

            if (result.Last().OpCode != OpCodes.Ret)
            {
                result.Add(new MsilInstruction(OpCodes.Ret));
            }
            return(result);
        }
コード例 #26
0
ファイル: Config.cs プロジェクト: Cyberworm3285/DiscordBot
 public void AddSuffix(string s) => Suffixes.Add(s);
コード例 #27
0
 /// <summary>
 /// Takes a string and find out whether that's a suffix.
 /// </summary>
 /// <param name="suffix">String to analyze.</param>
 /// <returns>Boolean indicating whether it's a suffix or not.</returns>
 protected bool IsSuffix(string suffix)
 {
     suffix = suffix.ToLower(CultureInfo.InvariantCulture);
     return(Suffixes.Cast <object>().Any(t => t.ToString().ToLower(CultureInfo.InvariantCulture) == suffix));
 }
コード例 #28
0
ファイル: Config.cs プロジェクト: Cyberworm3285/DiscordBot
 public bool RemoveSuffix(string s) => Suffixes.Remove(s);