从结果行号中查找自由标记源行号



C++有一个预处理器。您可以添加Freemarker作为第二个预处理器。例如:

<#function oh>
<#return 'Oh!'>
</#function>
int main(){
std::cout << "I am in line: __LINE__. ${oh()}" << std::endl;
return 0;
}

代码为UTF8,换行为CRLF(窗口(。

输出为:

我在第2行。哦

(但其第5行(

我使用此代码将ftl转换为cpp:

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
// ...
@Override
public String load(final HttpServletRequest req) {
String code = iftl.load(req);
Configuration cfg = new Configuration();
cfg.setDefaultEncoding("UTF-8");
cfg.setLocale(Locale.US);
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
try {
Template template = new Template("x", new StringReader(code), cfg);
StringWriter sw = new StringWriter();
template.process(new LinkedHashMap<>(), sw);
sw.close();
return sw.toString();
} catch (IOException | TemplateException e) {
LOG.log(Level.SEVERE, "Could not parse freemaker-preprocessor.", e);
}
return code;
}

我的问题是:2号线不正确!第5行是正确的。

我需要这样的功能:

/** Takes a result-line-number and returns the source-line-number
*/
public int dest2src(int resultLineNumber, Template template) {
// what to write here?
}
// dest2src(2, template)) = 5

这个问题来自于空格剥离,其删除仅包含指令的行。你可以这样禁用它:

config.setWhitespaceStripping(false); 

然后,所有换行符都将被保留,因此处理前后的行号将保持不变。

最新更新