Пример #1
0
        public static CodeArea Parse(string text, out int length)
        {
            var attrs = MatchAttribute.GetMatchAttributes <CodeArea>()
                        .Select(x => new {
                match = x.GetRegex().IsMatch(text),
                attr  = x
            });

            var   result = new CodeArea();
            Match match  = attrs.Where(x => x.match)
                           .FirstOrDefault().attr
                           .GetRegex().Match(text);

            var   temp      = match.Value.Replace("\r", "").Trim();
            Match langMatch = new Regex(@"```.+\r?\n").Match(temp);

            result.Language = langMatch.Value.Substring(3);
            result.Language = result.Language.Substring(0, result.Language.Length - 1);

            result.Code = temp.Substring(langMatch.Index + langMatch.Length);
            result.Code = result.Code.Substring(0, result.Code.Length - 3);

            var codeLines = result.Code.Split('\n');

            if (codeLines.LastOrDefault()?.Length == 0)
            {
                result.Code =
                    string.Join("\n", codeLines.Take(codeLines.Length - 1));
            }

            length = match.Index + match.Length;
            return(result);
        }
Пример #2
0
        public static Italic Parse(string text, out int length)
        {
            var attrs = MatchAttribute.GetMatchAttributes <Italic>()
                        .Select(x => new {
                match = x.GetRegex().IsMatch(text),
                attr  = x
            });

            if (!attrs.Any(x => x.match))
            {
                throw new FormatException();
            }
            var temp  = attrs.Where(x => x.match).FirstOrDefault();
            var match = temp.attr.GetRegex()
                        .Match(text);

            if (temp.attr.Regex == @"^\*[^\*\r\n]+\*")
            {
                text = match.Value.Substring(1, match.Value.Length - 2);
            }
            else
            {
                text = match.Value.Substring(2, match.Value.Length - 4);
            }
            length = match.Index + match.Length;

            return(new Italic()
            {
                Children = MarkdownRaw.Parse(text).Children
            });
        }
Пример #3
0
        public static AutoLink Parse(string text, out int length)
        {
            var attrs = MatchAttribute.GetMatchAttributes <AutoLink>()
                        .Select(x => new {
                match = x.GetRegex().IsMatch(text),
                attr  = x
            });

            if (!attrs.Any(x => x.match))
            {
                throw new FormatException();
            }

            Match match = attrs.Where(x => x.match).FirstOrDefault().attr
                          .GetRegex().Match(text);

            string temp  = match.Value;
            var    value = temp.Substring(1, text.Length - 2);

            length = match.Index + match.Length;
            return(new AutoLink()
            {
                Text = value,
                URL = value
            });
        }
Пример #4
0
        public static Header Parse(string text, out int length)
        {
            try {
                var attrs = MatchAttribute.GetMatchAttributes <Header>()
                            .Select(x => new {
                    match = x.GetRegex().IsMatch(text),
                    attr  = x
                });

                Match match = attrs.Where(x => x.match)
                              .FirstOrDefault().attr
                              .GetRegex().Match(text);

                Regex regex      = new Regex(@"#+");
                var   headerText = regex.Match(match.Value).Value;

                length = match.Index + match.Length;
                return(new Header()
                {
                    Level = headerText.Length,
                    Children = MarkdownRaw.Parse(match.Value.Replace(headerText, "")
                                                 .Trim()).Children
                });
            }catch (Exception e) {
                throw new FormatException();
            }
        }
Пример #5
0
        public static SetextHeader Parse(string text, out int length)
        {
            try {
                var attrs = MatchAttribute.GetMatchAttributes <SetextHeader>()
                            .Select(x => new {
                    match = x.GetRegex().IsMatch(text),
                    attr  = x
                });

                Match match = attrs.Where(x => x.match)
                              .FirstOrDefault().attr
                              .GetRegex().Match(text);

                Regex regex      = new Regex(@"(\s*.+)\r?\n");
                Match title      = regex.Match(match.Value);
                var   headerText = title.Value.Trim();
                var   sy         = match.Value.Substring(title.Length)[0];
                length = match.Index + match.Length;
                return(new SetextHeader()
                {
                    Level = sy == '=' ? 1 : 0,
                    Children = MarkdownRaw.Parse(headerText).Children
                });
            }catch (Exception e) {
                throw new FormatException();
            }
        }
Пример #6
0
        public static Code Parse(string text, out int length)
        {
            var attrs = MatchAttribute
                        .GetMatchAttributes <Code>()
                        .Select(x => new {
                match = x.GetRegex().IsMatch(text),
                attr  = x
            });

            if (!attrs.Any(x => x.match))
            {
                throw new FormatException();
            }

            Match match = attrs.Where(x => x.match).FirstOrDefault()
                          .attr.GetRegex().Match(text);
            string temp   = match.Value;
            var    result = new Code()
            {
                Text = temp.Substring(1, temp.Length - 2)
            };

            length = match.Index + match.Length;
            return(result);
        }
Пример #7
0
        public static Blockquotes Parse(string text, out int length)
        {
            var attrs = MatchAttribute.GetMatchAttributes <Blockquotes>()
                        .Select(x => new {
                match = x.GetRegex().IsMatch(text),
                attr  = x
            });

            var   result = new Blockquotes();
            Match match  = attrs.Where(x => x.match)
                           .FirstOrDefault().attr
                           .GetRegex().Match(text);

            string text2 = string.Join("\n", match.Value.Replace("\r", "").Split('\n')
                                       .Select(x => {
                Regex regex = new Regex(@"\s*>\s?");
                var temp    = regex.Match(x);
                return(x.Substring(temp.Index + temp.Length));
            })).Trim();

            result.Children = Markdown.Parse(text2).Children;

            length = match.Index + match.Length;
            return(result);
        }
Пример #8
0
        public void MatchAttribute_ShouldThrowIfThereIsNoMatch()
        {
            var attr = new MatchAttribute("cica");

            Assert.Throws <ValidationException>(() => ((IParameterValidator)attr).Validate(GetDummyParamInfo(), "mica", null !), Errors.PARAM_NOT_MATCHES);

            ParameterInfo GetDummyParamInfo() => ((MethodInfo)MethodBase.GetCurrentMethod()).ReturnParameter;
        }
Пример #9
0
        public void MatchAttribute_ShouldThrowIfThereIsNoMatch()
        {
            var attr = new MatchAttribute("cica");

            PropertyInfo prop = GetType().GetProperty(nameof(EmptyValues), BindingFlags.Public | BindingFlags.Static);

            Assert.Throws <ValidationException>(() => ((IPropertyValidator)attr).Validate(prop, "mica", null !), Errors.PROPERTY_NOT_MATCHES);
        }
Пример #10
0
        /// <summary>
        /// 验证和正则表达式是否匹配
        /// </summary>
        /// <param name="box">验证框</param>
        /// <param name="regexPattern">表达式</param>
        /// <param name="errorMessage">提示信息</param>
        /// <returns></returns>
        public static ValidBox Match(this ValidBox box, string regexPattern, string errorMessage)
        {
            var newBox = new MatchAttribute(regexPattern)
            {
                ErrorMessage = errorMessage
            }.ToValidBox();

            return(ValidBox.Merge(box, newBox));
        }
Пример #11
0
 /// <summary>
 /// Creates a new assertion result
 /// </summary>
 public MatchVector(MatchAttribute attribute, String name, double score, bool evaluated, object aValue, object bValue)
 {
     this.Attribute = attribute;
     this.Name      = name;
     this.Score     = score;
     this.Evaluated = evaluated;
     this.A         = aValue;
     this.B         = bValue;
 }
Пример #12
0
    private static int Value(MatchAttribute matchAttribute)
    {
        switch (matchAttribute)
        {
        case (MatchAttribute.PlayerHealth): return(GetPlayerHealth());

        default: throw new AttributeNotImplementedException(matchAttribute.ToString());
        }
    }
Пример #13
0
 protected Match GetMatch(string text)
 {
     return(MatchAttribute.GetMatchAttributes(GetType())
            .Select(x => new {
         match = x.GetRegex().IsMatch(text),
         attr = x
     })
            .Where(x => x.match)
            .FirstOrDefault()
            ?.attr.GetRegex().Match(text));
 }
Пример #14
0
        public static Link Parse(string text, out int length)
        {
            var attrs = MatchAttribute.GetMatchAttributes <Link>()
                        .Select(x => new {
                match = x.GetRegex().IsMatch(text),
                attr  = x
            });

            if (!attrs.Any(x => x.match))
            {
                throw new FormatException();
            }

            try {
                Regex tagLink = new Regex(@"\[[^\]]+\]\s*\[[^\]]+\]");
                Regex urlLink = new Regex(@"\[[^\]]+\]\s*\([^\)]+\)");

                string linkText = tagLink.IsMatch(text) ?
                                  tagLink.Match(text)?.Value :
                                  urlLink.Match(text)?.Value;

                Regex t1Regex = new Regex(@"\[[^\]]+\]");
                Regex t2Regex = new Regex(@"\(.+\)");
                Link  result  = new Link();
                result.Text = t1Regex.Match(linkText).Value;
                result.Text = result.Text.Substring(1, result.Text.Length - 2);
                length      = 0;
                if (tagLink.IsMatch(text))
                {
                    var    match = t1Regex.Match(linkText).NextMatch();
                    string tagId = match.Value;
                    tagId = tagId.Substring(1, tagId.Length - 2);

                    result.ReferenceTag = new Tag()
                    {
                        Id = tagId.Trim(), IsRef = true
                    };
                    length = match.Index + match.Length;
                }
                else if (urlLink.IsMatch(text))
                {
                    var    match = t2Regex.Match(linkText);
                    string url   = t2Regex.Match(linkText).Value;
                    url = url.Substring(1, url.Length - 2);

                    result.URL = url.Trim();
                    length     = match.Index + match.Length;
                }
                return(result);
            }catch (Exception e) {
                throw new FormatException();
            }
        }
Пример #15
0
        public void Test()
        {
            var x  = new MatchAttribute("foo");   x.Bind(null, typeof(string));
            var x2 = new MatchAttribute("foo"); x2.Bind(null, typeof(string));
            var y  = new MatchAttribute("foo");   y.Bind(null, typeof(object));
            var y2 = new MatchAttribute("bar"); y2.Bind(null, typeof(string));

            var type = typeof(ScanBaseAttribute);

            FieldInfo[] fields     = type.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
            string[]    fieldNames = fields.Select(f => f.Name).ToArray();
            Assert.GreaterOrEqual(fields.Length, 2);

            Assert.AreEqual(x, x);
            Assert.AreEqual(x, x2);
            Assert.AreNotEqual(x, y);
            Assert.AreNotEqual(x, y2);
        }
Пример #16
0
        public static Tag Parse(string text, out int length)
        {
            try {
                var match = MatchAttribute.GetMatchAttributes <Tag>()
                            .Select(x => new {
                    match = x.GetRegex().IsMatch(text),
                    attr  = x
                }).Where(x => x.match).FirstOrDefault().attr
                            .GetRegex().Match(text);


                Regex idRegex       = new Regex(@"\[[^\]]+\]");
                Regex urlRegex      = new Regex(":[^\"\'\\(]+[\\n\\s]?");
                Regex optionalRegex = new Regex("[\"\'\\(].+[\"\'\\)]");
                var   temp          = match.Value;

                string idText = idRegex.Match(temp).Value.Trim();
                idText = idText.Substring(1, idText.Length - 2);

                string urlText = urlRegex.Match(temp).Value.Trim();
                urlText = urlText.Substring(1)
                          .Replace("<", "").Replace(">", "")
                          .Trim();

                var    optionalMatch = optionalRegex.Match(temp);
                string optionalText  = null;
                if (optionalMatch.Value.Length > 2)
                {
                    optionalText = optionalMatch.Value.Trim();
                    optionalText = optionalText.Substring(1, optionalText.Length - 2);
                }
                length = match.Index + match.Length;

                return(new Tag()
                {
                    Id = idText,
                    URL = urlText,
                    Optional = optionalText
                });
            }catch (Exception e) {
                throw new FormatException();
            }
        }
Пример #17
0
        public static Divider Parse(string text, out int length)
        {
            var attrs = MatchAttribute.GetMatchAttributes <Divider>()
                        .Select(x => new {
                match = x.GetRegex().IsMatch(text),
                attr  = x
            });

            if (!attrs.Any(x => x.match))
            {
                throw new FormatException();
            }


            Match match = attrs.Where(x => x.match)
                          .FirstOrDefault().attr
                          .GetRegex().Match(text);

            length = match.Index + match.Length;
            return(new Divider());
        }
Пример #18
0
        public static Bold Parse(string text, out int length)
        {
            var attrs = MatchAttribute.GetMatchAttributes <Bold>()
                        .Select(x => new {
                match = x.GetRegex().IsMatch(text),
                attr  = x
            });

            if (!attrs.Any(x => x.match))
            {
                throw new FormatException();
            }
            var match = attrs.Where(x => x.match).FirstOrDefault().attr.GetRegex()
                        .Match(text);

            length = match.Index + match.Length;
            text   = match.Value.Substring(2, match.Value.Length - 4);
            return(new Bold()
            {
                Children = MarkdownRaw.Parse(text).Children
            });
        }
Пример #19
0
        public static PlayerInfo CreateInstance(PlayerInfo info)
        {
            var playerInfo = new PlayerInfo {
                Id                 = info.Id,
                Name               = info.Name,
                TeamId             = info.TeamId,
                CustomPlayerStatus = info.CustomPlayerStatus,
                IsRobot            = info.IsRobot
            };

            switch (info.RelayNetworkState)
            {
            case NetworkState.RelayOffline:
                playerInfo.CommonNetworkState = NetworkState.RelayOffline;
                break;

            case NetworkState.RelayOnline:
                playerInfo.CommonNetworkState = NetworkState.RelayOnline;
                break;
            }
            switch (info.CommonNetworkState)
            {
            case NetworkState.CommonOffline:
                playerInfo.CommonNetworkState = NetworkState.CommonOffline;
                break;

            case NetworkState.CommonOnline:
                playerInfo.CommonNetworkState = NetworkState.CommonOnline;
                break;
            }
            foreach (var attr in info.MatchAttributes)
            {
                var matchAttribute = new MatchAttribute(attr);
                playerInfo.MatchAttributes.Add(matchAttribute);
            }
            ;
            return(playerInfo);
        }
Пример #20
0
        public static List Parse(string text, out int length)
        {
            var attrs = MatchAttribute.GetMatchAttributes <List>()
                        .Select(x => new {
                match = x.GetRegex().IsMatch(text),
                attr  = x
            });

            var   result = new List();
            Match match  = attrs.Where(x => x.match)
                           .FirstOrDefault().attr
                           .GetRegex().Match(text);
            bool?isNumber = null;
            var  items    = string.Join("\n",
                                        match.Value.Replace("\r", "")
                                        .Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)
                                        .Select(x => {
                Regex regex = new Regex(@"\s*((\d+\.)|\*+|\++|\-+)\s*");
                var temp    = regex.Match(x);
                if (!isNumber.HasValue)
                {
                    isNumber = new Regex(@"\d+").IsMatch(temp.Value.Trim());
                }
                return(x.Substring(temp.Index + temp.Length));
            })
                                        ).Trim().Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)
                            .Select(x => new Markdown()
            {
                Children = Markdown.Parse(x).Children
            })
                            .ToList <MarkdownRaw>();

            result.Children = items;
            result.Type     = isNumber.Value ? ListTypes.Number : ListTypes.Symbol;
            length          = match.Index + match.Length;
            return(result);
        }
Пример #21
0
        /// <summary>
        /// Get the null score
        /// </summary>
        private static double?GetNullScore(MatchAttribute attribute)
        {
            switch (attribute.WhenNull)
            {
            case MatchAttributeNullBehavior.Disqualify:
                return(-100);

            case MatchAttributeNullBehavior.Zero:
            case MatchAttributeNullBehavior.None:
                return(0.0);

            case MatchAttributeNullBehavior.Match:
                return(attribute.MatchWeight);

            case MatchAttributeNullBehavior.NonMatch:
                return(attribute.NonMatchWeight);

            case MatchAttributeNullBehavior.Ignore:
                return(null);

            default:
                throw new InvalidOperationException("Should not be here - Can't determine null behavior");
            }
        }
 /// <summary>
 /// Create match action info from block
 /// </summary>
 /// <param name="attribute">The attribute</param>
 public MatchActionDiagnosticInfo(MatchAttribute attribute) : this()
 {
     this.ActionType    = "evaluate-attribute";
     this.ActionData    = attribute.Property.Union(new string[] { attribute.Id }).ToArray();
     this.StartOfAction = DateTimeOffset.Now;
 }
Пример #23
0
        /// <summary>
        /// Execute an assertion
        /// </summary>
        /// <param name="assertion">The assertion to execute</param>
        /// <param name="aValue">The value of the A value</param>
        /// <param name="bValue">The value of the B value</param>
        /// <returns>True if the assertion passes, false if not, null if the execution was skipped</returns>
        internal static AssertionResult ExecuteAssertion(string propertyName, MatchAttributeAssertion assertion, MatchAttribute attribute, object aValue, object bValue)
        {
            try
            {
                // Apply all transforms first
                object a = aValue, b = bValue;
                object scope = null;
                foreach (var xform in assertion.Transforms)
                {
                    if (a == null || b == null)
                    {
                        break;
                    }
                    scope = ExecuteTransform(xform.Name, xform.Parameters.ToArray(), ref a, ref b) ?? scope;
                }
                if (a == null || b == null)
                {
                    return(new AssertionResult(propertyName, false, false, GetNullScore(attribute), aValue, bValue));
                }
                else if (a is IEnumerable enumA && !enumA.OfType <Object>().Any() || b is IEnumerable enumB && !enumB.OfType <Object>().Any())
                {
                    return(new AssertionResult(propertyName, false, false, GetNullScore(attribute), aValue, bValue));
                }

                // Scope as enum
                if (scope is IEnumerable enumScope)
                {
                    if (!enumScope.OfType <Object>().Any()) // No results - cannot evaluate
                    {
                        return(new AssertionResult(propertyName, false, false, GetNullScore(attribute), aValue, bValue));
                    }
                    else
                    {
                        scope = enumScope.OfType <Object>().Max();
                    }
                }

                var retVal = true;
                switch (assertion.Operator)
                {
                case BinaryOperatorType.AndAlso:     // There are sub-assertions
                {
                    foreach (var asrt in assertion.Assertions)
                    {
                        var subVal = ExecuteAssertion(propertyName, asrt, attribute, a, b);
                        retVal &= subVal.Result;
                    }
                    break;
                }

                case BinaryOperatorType.OrElse:
                {
                    foreach (var asrt in assertion.Assertions)
                    {
                        var subVal = ExecuteAssertion(propertyName, asrt, attribute, a, b);
                        retVal |= subVal.Result;
                    }
                    break;
                }

                case BinaryOperatorType.Equal:
                    if (assertion.ValueSpecified)
                    {
                        retVal = scope.Equals(assertion.Value);
                    }
                    else
                    {
                        if (a == b)     // reference equality
                        {
                            retVal = true;
                        }
                        else if (a is IEnumerable aEnum && b is IEnumerable bEnum)     // Run against sequence
                        {
                            retVal = aEnum.OfType <Object>().SequenceEqual(bEnum.OfType <Object>());
                        }
                        else
                        {
                            retVal = a.Equals(b);
                        }
                    }
Пример #24
0
        /// <summary>
        /// 將Markdown字串轉換為Markdown Content
        /// </summary>
        /// <param name="text">Markdown本文</param>
        /// <param name="inline">是否為單一行</param>
        /// <returns>Markdown Content</returns>
        public static Markdown Parse(string text, bool inline = false)
        {
            List <MarkdownRaw> result = new List <MarkdownRaw>();

            text = text.Replace("\r", "");

            var types = inline ? InlineTypes : AreaTypes.Concat(LineTypes);

            while (/*text.Trim().Length > 0 &&*/ text.Length > 0)
            {
                int skip = 0;
                //剖析引用參數
                object[] args = new object[] { text, 0 };

                //範圍樣式與行樣式檢查
                foreach (var type in types)
                {
                    if (!MatchAttribute.IsMatch(type, text))
                    {
                        continue;
                    }

                    var parseMethod = type.GetTypeInfo().GetMethod("Parse");
                    result.Add((MarkdownRaw)parseMethod.Invoke(null, args));


                    skip = (int)args[1];
                    break;
                }
                if (inline && skip == 0)  //行內檢驗
                {
                    skip = 1;
                    string addChar = text[0].ToString();
                    if (text[0] == '\\')
                    {
                        skip    = 2;
                        addChar = new string(text.Take(2).ToArray());
                    }
                    var lastChild = result.LastOrDefault();
                    if (lastChild?.GetType() == typeof(MarkdownRaw))
                    {
                        lastChild.OuterMarkdown += addChar;
                    }
                    else
                    {
                        result.Add(new MarkdownRaw()
                        {
                            OuterMarkdown = addChar
                        });
                    }
                }
                else if (text[0] == '\n')
                {
                    result.Add(new MarkdownRaw()
                    {
                        OuterMarkdown = "\n"
                    });
                    skip = 1;
                }
                text = new string(text.Skip(skip).ToArray());
            }
            var resultInstace = new Markdown()
            {
                Children = result
            };                                //.Where(x=>x.OuterMarkdown.Length != 0).ToList();

            if (!resultInstace.IsSingleLine)  //多行實體
            {
                resultInstace.Children = FilterNewLine(resultInstace.Children);
            }
            return(resultInstace);
        }