Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add on directive to switch as an alternative to case #114

Merged
merged 3 commits into from
Aug 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 95 additions & 0 deletions freemarker-core/src/main/java/freemarker/core/On.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package freemarker.core;

import java.util.List;

/**
* Represents an "on" in a switch statement.
* This is alternative to case that does not fall-though
* and instead supports multiple conditions.
*/
final class On extends TemplateElement {

List<Expression> conditions;

On(List<Expression> matchingValues, TemplateElements children) {
this.conditions = matchingValues;
setChildren(children);
}

@Override
TemplateElement[] accept(Environment env) {
return getChildBuffer();
}

@Override
protected String dump(boolean canonical) {
StringBuilder sb = new StringBuilder();
if (canonical) sb.append('<');
sb.append(getNodeTypeSymbol());
for (int i = 0; i < conditions.size(); i++) {
if (i != 0) {
sb.append(',');
}
sb.append(' ');
sb.append((conditions.get(i)).getCanonicalForm());
}
if (canonical) {
sb.append('>');
sb.append(getChildrenCanonicalForm());
}
return sb.toString();
}

@Override
String getNodeTypeSymbol() {
return "#on";
}

@Override
int getParameterCount() {
return conditions.size();
}

@Override
Object getParameterValue(int idx) {
checkIndex(idx);
return conditions.get(idx);
}

@Override
ParameterRole getParameterRole(int idx) {
checkIndex(idx);
return ParameterRole.CONDITION;
}

private void checkIndex(int idx) {
if (conditions == null || idx >= conditions.size()) {
throw new IndexOutOfBoundsException();
}
}

@Override
boolean isNestedBlockRepeater() {
return false;
}

}
85 changes: 61 additions & 24 deletions freemarker-core/src/main/java/freemarker/core/SwitchBlock.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@
import freemarker.template.TemplateException;

/**
* An instruction representing a switch-case structure.
* An instruction representing a switch-case or switch-on structure.
*/
final class SwitchBlock extends TemplateElement {

private Case defaultCase;
private final Expression searched;
private int firstCaseIndex;
private int firstCaseOrOnIndex;

/**
* @param searched the expression to be tested.
Expand All @@ -43,7 +43,7 @@ final class SwitchBlock extends TemplateElement {
for (int i = 0; i < ignoredCnt; i++) {
addChild(ignoredSectionBeforeFirstCase.getChild(i));
}
firstCaseIndex = ignoredCnt; // Note that normally postParseCleanup will overwrite this
firstCaseOrOnIndex = ignoredCnt; // Note that normally postParseCleanup will overwrite this
}

/**
Expand All @@ -56,37 +56,72 @@ void addCase(Case cas) {
addChild(cas);
}

/**
* @param on an On element.
*/
void addOn(On on) {
addChild(on);
}

@Override
TemplateElement[] accept(Environment env)
throws TemplateException, IOException {
boolean processedCase = false;
boolean processedCaseOrOn = false;
boolean usingOn = false;
int ln = getChildCount();
try {
for (int i = firstCaseIndex; i < ln; i++) {
Case cas = (Case) getChild(i);
boolean processCase = false;

// Fall through if a previous case tested true.
if (processedCase) {
processCase = true;
} else if (cas.condition != null) {
// Otherwise, if this case isn't the default, test it.
processCase = EvalUtil.compare(
searched,
EvalUtil.CMP_OP_EQUALS, "case==", cas.condition, cas.condition, env);
}
if (processCase) {
env.visit(cas);
processedCase = true;
for (int i = firstCaseOrOnIndex; i < ln; i++) {
TemplateElement tel = getChild(i);

if (tel instanceof On) {
usingOn = true;

for (Expression condition : ((On) tel).conditions) {
boolean processOn = EvalUtil.compare(
searched,
EvalUtil.CMP_OP_EQUALS, "on==", condition, condition, env);
if (processOn) {
env.visit(tel);
processedCaseOrOn = true;
break;
}
}
if (processedCaseOrOn) {
break;
}
} else { // Case
Expression condition = ((Case) tel).condition;
boolean processCase = false;

// Fall through if a previous case tested true.
if (processedCaseOrOn) {
processCase = true;
} else if (condition != null) {
// Otherwise, if this case isn't the default, test it.
processCase = EvalUtil.compare(
searched,
EvalUtil.CMP_OP_EQUALS, "case==", condition, condition, env);
}
if (processCase) {
env.visit(tel);
processedCaseOrOn = true;
}
}
}

// If we didn't process any nestedElements, and we have a default,
// process it.
if (!processedCase && defaultCase != null) {
if (!processedCaseOrOn && defaultCase != null) {
env.visit(defaultCase);
}
} catch (BreakOrContinueException br) {}
} catch (BreakOrContinueException br) {
// This catches both break and continue,
// hence continue is incorrectly treated as a break inside a case.
// Unless using On, do backwards compatible behavior.
if (usingOn) {
throw br; // On supports neither break nor continue.
}
}
return null;
}

Expand Down Expand Up @@ -142,10 +177,12 @@ TemplateElement postParseCleanup(boolean stripWhitespace) throws ParseException
// The first #case might have shifted in the child array, so we have to find it again:
int ln = getChildCount();
int i = 0;
while (i < ln && !(getChild(i) instanceof Case)) {
while (i < ln
&& !(getChild(i) instanceof Case)
&& !(getChild(i) instanceof On)) {
i++;
}
firstCaseIndex = i;
firstCaseOrOnIndex = i;

return result;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ private static void addName(Set<String> allNames, Set<String> lcNames, Set<Strin
addName(allNames, lcNames, ccNames, "noescape", "noEscape");
addName(allNames, lcNames, ccNames, "noparse", "noParse");
addName(allNames, lcNames, ccNames, "nt");
addName(allNames, lcNames, ccNames, "on");
addName(allNames, lcNames, ccNames, "outputformat", "outputFormat");
addName(allNames, lcNames, ccNames, "recover");
addName(allNames, lcNames, ccNames, "recurse");
Expand Down
87 changes: 70 additions & 17 deletions freemarker-core/src/main/javacc/freemarker/core/FTL.jj
Original file line number Diff line number Diff line change
Expand Up @@ -953,6 +953,8 @@ TOKEN:
|
<CASE : <START_TAG> "case" <BLANK>> { handleTagSyntaxAndSwitch(matchedToken, FM_EXPRESSION); }
|
<ON : <START_TAG> "on" <BLANK>> { handleTagSyntaxAndSwitch(matchedToken, FM_EXPRESSION); }
|
<ASSIGN : <START_TAG> "assign" <BLANK>> { handleTagSyntaxAndSwitch(matchedToken, FM_EXPRESSION); }
|
<GLOBALASSIGN : <START_TAG> "global" <BLANK>> { handleTagSyntaxAndSwitch(matchedToken, FM_EXPRESSION); }
Expand Down Expand Up @@ -3875,36 +3877,69 @@ SwitchBlock Switch() :
SwitchBlock switchBlock;
MixedContent ignoredSectionBeforeFirstCase = null;
Case caseIns;
On onIns;
Expression switchExp;
Token start, end;
boolean defaultFound = false;
}
{
(
start = <SWITCH>
switchExp = Expression()
<DIRECTIVE_END>
start = <SWITCH>
switchExp = Expression()
<DIRECTIVE_END>
[ ignoredSectionBeforeFirstCase = WhitespaceAndComments() ]
)
{
breakableDirectiveNesting++;
switchBlock = new SwitchBlock(switchExp, ignoredSectionBeforeFirstCase);
}
[
(
caseIns = Case()
{
if (caseIns.condition == null) {
if (defaultFound) {
throw new ParseException(
"You can only have one default case in a switch statement", template, start);
}
defaultFound = true;
}
switchBlock.addCase(caseIns);
}
)+
[<STATIC_TEXT_WS>]
(
(
caseIns = Case()
{
if (caseIns.condition == null) {
if (defaultFound) {
throw new ParseException(
"You can only have one default case in a switch statement", template, start);
}
defaultFound = true;
}
switchBlock.addCase(caseIns);
}
)+
|
(
{
// A Switch with Case supports break, but not one with On.
// Do it this way to ensure backwards compatibility.
breakableDirectiveNesting--;
}

(
onIns = On()
{
switchBlock.addOn(onIns);
}
)+
[
caseIns = Case()
{
// When using on, you can have a default, but not a normal case
if (caseIns.condition != null) {
throw new ParseException(
"You cannot mix \"case\" and \"on\" in a switch statement", template, start);
}
switchBlock.addCase(caseIns);
}
]

{
breakableDirectiveNesting++;
}
)
)
[<STATIC_TEXT_WS>]
]
end = <END_SWITCH>
{
Expand Down Expand Up @@ -3934,6 +3969,24 @@ Case Case() :
}
}

On On() :
{
ArrayList exps;
TemplateElements children;
Token start;
}
{
(
start = <ON> exps = PositionalArgs() <DIRECTIVE_END>
)
children = MixedContentElements()
{
On result = new On(exps, children);
result.setLocation(template, start, start, children);
return result;
}
}

EscapeBlock Escape() :
{
Token variable, start, end;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,16 +46,22 @@ public void testValidPlacements() throws IOException, TemplateException {
+ "<#list xs>[<#items as x>${x}</#items>]<#else><#break></#list>"
+ "</#list>.",
"[12][34].");
assertOutput("<#list 1..2 as x><#switch x><#on 1>one<#break></#switch>;</#list>", "one");
assertOutput("<#list 1..2 as x><#switch x><#on 1>one<#continue></#switch>;</#list>", "one;");
assertOutput("<#forEach x in 1..2>${x}<#break></#forEach>", "1");
assertOutput("<#forEach x in 1..2>${x}<#continue></#forEach>", "12");
assertOutput("<#switch 1><#case 1>1<#break></#switch>", "1");
assertOutput("<#switch 1><#default>1<#break></#switch>", "1");
}

@Test
public void testInvalidPlacements() throws IOException, TemplateException {
assertErrorContains("<#break>", BREAK_NESTING_ERROR_MESSAGE_PART);
assertErrorContains("<#continue>", CONTINUE_NESTING_ERROR_MESSAGE_PART);
assertErrorContains("<#switch 1><#case 1>1<#continue></#switch>", CONTINUE_NESTING_ERROR_MESSAGE_PART);
assertErrorContains("<#switch 1><#on 1>1<#continue></#switch>", CONTINUE_NESTING_ERROR_MESSAGE_PART);
assertErrorContains("<#switch 1><#on 1>1<#break></#switch>", BREAK_NESTING_ERROR_MESSAGE_PART);
assertErrorContains("<#switch 1><#on 1>1<#default><#break></#switch>", BREAK_NESTING_ERROR_MESSAGE_PART);
assertErrorContains("<#list 1..2 as x>${x}</#list><#break>", BREAK_NESTING_ERROR_MESSAGE_PART);
assertErrorContains("<#if false><#break></#if>", BREAK_NESTING_ERROR_MESSAGE_PART);
assertErrorContains("<#list xs><#break></#list>", BREAK_NESTING_ERROR_MESSAGE_PART);
Expand Down
Loading
Loading