Skip to content

Commit

Permalink
Fix code generation for rules named 'keys' and 'values'
Browse files Browse the repository at this point in the history
Fixes #280
  • Loading branch information
sharwell committed Apr 29, 2018
1 parent a290fd4 commit ec9f0c7
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1108,5 +1108,11 @@ csIdentifier ::= [
"void" : "@void",
"volatile" : "@volatile",
"while" : "@while",

// These are not keywords, but including them explicitly prevents StringTemplate from treating them as keywords.
// https://github.com/tunnelvisionlabs/antlr4cs/issues/280
"keys": "keys",
"values": "values",

default : key
]
29 changes: 29 additions & 0 deletions tool/src/org/antlr/v4/codegen/target/CSharpTarget.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,21 @@
*/
package org.antlr.v4.codegen.target;

import java.util.Map;
import org.antlr.v4.codegen.CodeGenerator;
import org.antlr.v4.codegen.Target;
import org.antlr.v4.tool.ErrorType;
import org.antlr.v4.tool.ast.GrammarAST;
import org.stringtemplate.v4.Interpreter;
import org.stringtemplate.v4.NumberRenderer;
import org.stringtemplate.v4.ST;
import org.stringtemplate.v4.STErrorListener;
import org.stringtemplate.v4.STGroup;
import org.stringtemplate.v4.STGroupFile;
import org.stringtemplate.v4.StringRenderer;
import org.stringtemplate.v4.misc.MapModelAdaptor;
import org.stringtemplate.v4.misc.STMessage;
import org.stringtemplate.v4.misc.STNoSuchPropertyException;

public abstract class CSharpTarget extends Target {

Expand Down Expand Up @@ -138,6 +143,30 @@ protected boolean visibleGrammarSymbolCausesIssueInGeneratedCode(GrammarAST idNo
protected STGroup loadTemplates() {
// override the superclass behavior to put all C# templates in the same folder
STGroup result = new STGroupFile(CodeGenerator.TEMPLATE_ROOT+"/CSharp/"+getLanguage()+STGroup.GROUP_FILE_EXTENSION);
result.registerModelAdaptor(Map.class, new MapModelAdaptor() {
@Override
public Object getProperty(Interpreter interp, ST self, Object o, Object property, String propertyName) throws STNoSuchPropertyException {
// Override the default behavior to fix handling of 'keys' and 'values'.
// https://github.com/tunnelvisionlabs/antlr4cs/issues/280
Map<?, ?> map = (Map<?, ?>)o;
Object value;
if (map.containsKey(property)) {
value = map.get(property);
}
else if (map.containsKey(propertyName)) {
value = map.get(propertyName);
}
else {
return super.getProperty(interp, self, o, property, propertyName);
}

if (value == STGroup.DICT_KEY) {
value = property;
}

return value;
}
});
result.registerRenderer(Integer.class, new NumberRenderer());
result.registerRenderer(String.class, new StringRenderer());
result.setListener(new STErrorListener() {
Expand Down

0 comments on commit ec9f0c7

Please sign in to comment.