using System.Text.RegularExpressions; using CodePlay.Core.Interfaces; using CodePlay.Core.Models; namespace CodePlay.Core.Pipeline.Converters; /// /// 模式匹配转换器 - is 表达式、关系模式等 /// public class PatternMatchingConverter : ILineConverter { public int Priority => 60; public string Convert(string line, ConversionContext context) { var result = line; // 类型模式:obj is string s → obj instanceof String result = Regex.Replace(result, @"(\w+)\s+is\s+(\w+)\s+(\w+)", "$1 instanceof $2"); // null 模式:is null / is not null result = Regex.Replace(result, @"\s+is\s+null\b", " == null"); result = Regex.Replace(result, @"\s+is\s+not\s+null\b", " != null"); // 关系模式:is (> 0 and < 10) → > 0 && < 10 (简化处理) result = ConvertRelationalPatterns(result); return result; } private string ConvertRelationalPatterns(string line) { var result = line; // and 模式 result = Regex.Replace(result, @"is\s*\(\s*>\s*([\d.]+)\s+and\s+<\s*([\d.]+)\s*\)", "> $1 && < $2"); result = Regex.Replace(result, @"is\s*\(\s*>=\s*([\d.]+)\s+and\s+<=\s*([\d.]+)\s*\)", ">= $1 && <= $2"); // or 模式 result = Regex.Replace(result, @"is\s*\(\s*<\s*([\d.]+)\s+or\s+>\s*([\d.]+)\s*\)", "< $1 || > $2"); // 单独的关系运算符 result = Regex.Replace(result, @"is\s*>\s*([\d.]+)", "> $1"); result = Regex.Replace(result, @"is\s*<\s*([\d.]+)", "< $1"); result = Regex.Replace(result, @"is\s*>=\s*([\d.]+)", ">= $1"); result = Regex.Replace(result, @"is\s*<=\s*([\d.]+)", "<= $1"); return result; } }