我有一個問題,而試圖在switch statement
重構的if/else statement
。所用的語法就是Java 8,根據下面的語法:UnexpectedType錯誤重構
syntax SwitchStatement = "switch" "(" Expression ")" SwitchBlock ;
syntax SwitchBlock = "{" SwitchBlockStatementGroup* SwitchLabel* "}" ;
syntax SwitchBlockStatementGroup = SwitchLabels BlockStatements ;
syntax SwitchLabels = SwitchLabel+ ;
syntax SwitchLabel = "case" ConstantExpression ":"
| "default" ":"
;
我用下面的代碼來執行
如果else語句
syntax IfThenStatement = "if" "(" Expression ")" Statement ;
syntax IfThenElseStatement = "if" "(" Expression ")" StatementNoShortIf "else" Statement ;
syntax IfThenElseStatementNoShortIf = "if" "(" Expression ")" StatementNoShortIf "else" StatementNoShortIf ;
switch語句重構:
CompilationUnit refactorIfElseStatement(CompilationUnit unit) = visit(unit) {
case (IfThenElseStatement) `if (<Identifier idIf>.equals(<StringLiteral stringCompare>)) <StatementNoShortIf stmtIf> else <Statement stmtElse>` =>
(SwitchStatement) `switch (<Identifier idIf>) {<SwitchBlockStatementGroup switchBlock>}`
when switchBlock := generateCaseFromIfElseStatement(stmtElse, idIf)
};
SwitchBlockStatementGroup generateCaseFromIfElseStatement(Statement stmt, Identifier idIf) = visit(stmt){
case (StatementNoShortIf) `<StatementNoShortIf stmt1>` =>
(SwitchBlockStatementGroup) `default: <BlockStatements stmt1>`
case (IfThenElseStatement) `if (idIf.equals(<StringLiteral stringCompare>)) <StatementNoShortIf stmtIf> else <Statement stmtElse>` =>
(SwitchBlockStatementGroup) `case <ConstantExpression stringCompare> : { <BlockStatements stmtIf> }`
};
然而,當運行重構碼,則顯示以下錯誤:
Expected SwitchBlockStatementGroup, but got Statement Advice: |http://tutor.rascal-mpl.org/Errors/Static/UnexpectedType/UnexpectedType.html|
首先,重構是簡單如可以在下面的代碼塊中可以看出。隨後,我打算增加其複雜性以滿足其他情況。
if (string.equals("boo")){
System.out.println("is a boo");
}
else if (string.equals("blah")){
System.out.println("is a blah");
}
else if (string.equals("foo")){
System.out.println("is a foo");
}
else{
System.out.print("is a default");
}
您可以通過使用以下限制來簡化語法,即「」if「」(「Expression」()「Statement!>>」else「Statement」不需要StatementNoShortIf,並且您擁有更少的非終端/類型擔心。 – jurgenv