我需要将用户类型的表达式编译成可以调用的.NET程序集.表达式语言(从应用程序的版本1继承)非常有限,几乎是有效的C#,但它确实有一些不寻常的属性.
我想在版本2中切换到完整的C#,但是我在使用Roslyn将特性转换为可编译的SyntaxTree时遇到了麻烦.目前我正试图弄清楚如何获得权力和因子来编译,即
double n = 1.5² / 0.9³ + 6!;
Run Code Online (Sandbox Code Playgroud)
必须转换成类似的东西:
double n = Pow(1.5, 2) / Pow(0.9, 3) + Factorial(6);
Run Code Online (Sandbox Code Playgroud)
但是,当我解析原始表达式时,它会立即在²字符处分解:
public static void TestLanguageAdditions()
{
const string code = "double n = 1.5² / 0.9³ + 6!;";
var syntaxTree = CSharpSyntaxTree.ParseText(code);
var syntaxRoot = syntaxTree.GetRoot();
var sb = new StringBuilder();
sb.AppendLine(code);
sb.AppendLine();
foreach (var node in syntaxRoot.DescendantNodes())
{
var span = node.FullSpan;
var spanLine =
new string(' ', span.Start) +
new string('?', span.Length);
spanLine = spanLine.PadRight(30);
spanLine += ((CSharpSyntaxNode)node).Kind();
sb.AppendLine(spanLine);
}
string report = sb.ToString();
Console.Write(report);
}
Run Code Online (Sandbox Code Playgroud)
产量:
double n = 1.5² / 0.9³ + 6!;
???????????????????????????? FieldDeclaration
?????????????? VariableDeclaration
??????? PredefinedType
??????? VariableDeclarator
????? EqualsValueClause
??? NumericLiteralExpression
Run Code Online (Sandbox Code Playgroud)
我想知道是否有任何方法可以哄骗Roslyn按原样解析其余的字符串,或者如果没有,那么准备字符串的好策略是什么.显然我可以用一些可解析的占位符替换²和³字符,但不能在字符串或字符文字中出现这些字符时.
-----------------------------------编辑-------------- ---------------------
将非法字符转换为块注释允许解析,但奇怪的是它们在许多节点之后显示为琐事:
double n = 1.50/*²*/ / (0.90)/*³*/ + 6/*!*/;
???????????????????????????????????????????? CompilationUnit
???????????????????????????????????????????? FieldDeclaration
???????????????????????????????????????????· VariableDeclaration
······································?????· ? trivia: /*!*/
???????····································· PredefinedType
·······????????????????????????????????????· VariableDeclarator
······································?????· ? trivia: /*!*/
·········??????????????????????????????????· EqualsValueClause
······································?????· ? trivia: /*!*/
···········????????????????????????????????· AddExpression
······································?????· ? trivia: /*!*/
···········????????????????????????········· DivideExpression
·····························?????·········· ? trivia: /*³*/
···········??????????······················· NumericLiteralExpression
···············?????························ ? trivia: /*²*/
·······················????????????········· ParenthesizedExpression
·····························?????·········· ? trivia: /*³*/
························????················ NumericLiteralExpression
·····································??????· NumericLiteralExpression
······································?????· ? trivia: /*!*/
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
145 次 |
| 最近记录: |