Skip to content

Commit

Permalink
Set proper types for node[] in Java-generated code
Browse files Browse the repository at this point in the history
  • Loading branch information
eregon committed Feb 28, 2024
1 parent 8b8047b commit 322eaea
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 14 deletions.
38 changes: 25 additions & 13 deletions templates/java/org/prism/Loader.java.erb
Original file line number Diff line number Diff line change
Expand Up @@ -257,18 +257,6 @@ public class Loader {
return constants;
}

private Nodes.Node[] loadNodes() {
int length = loadVarUInt();
if (length == 0) {
return Nodes.Node.EMPTY_ARRAY;
}
Nodes.Node[] nodes = new Nodes.Node[length];
for (int i = 0; i < length; i++) {
nodes[i] = loadNode();
}
return nodes;
}

private Nodes.Location loadLocation() {
return new Nodes.Location(loadVarUInt(), loadVarUInt());
}
Expand Down Expand Up @@ -367,6 +355,7 @@ public class Loader {
int length = loadVarUInt();

switch (type) {
<%- array_types = [] -%>
<%- nodes.each_with_index do |node, index| -%>
case <%= index + 1 %>:
<%-
Expand All @@ -376,7 +365,10 @@ public class Loader {
when Prism::NodeField then "#{field.java_cast}loadNode()"
when Prism::OptionalNodeField then "#{field.java_cast}loadOptionalNode()"
when Prism::StringField then "loadString()"
when Prism::NodeListField then "loadNodes()"
when Prism::NodeListField then
element_type = field.java_type.sub('[]', '')
array_types << element_type
"load#{element_type}s()"
when Prism::ConstantField then "loadConstant()"
when Prism::OptionalConstantField then "loadOptionalConstant()"
when Prism::ConstantListField then "loadConstants()"
Expand All @@ -398,6 +390,26 @@ public class Loader {
throw new Error("Unknown node type: " + type);
}
}
<%- array_types.uniq.each do |type| -%>
private static final Nodes.<%= type %>[] EMPTY_<%= type %>_ARRAY = {};
private Nodes.<%= type %>[] load<%= type %>s() {
int length = loadVarUInt();
if (length == 0) {
return EMPTY_<%= type %>_ARRAY;
}
Nodes.<%= type %>[] nodes = new Nodes.<%= type %>[length];
for (int i = 0; i < length; i++) {
<%- if type == 'Node' -%>
nodes[i] = loadNode();
<%- else -%>
nodes[i] = (Nodes.<%= type %>) loadNode();
<%- end -%>
}
return nodes;
}
<%- end -%>
private void expect(byte value, String error) {
byte b = buffer.get();
Expand Down
6 changes: 5 additions & 1 deletion templates/template.rb
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,11 @@ def rbi_class
end

def java_type
"Node[]"
if specific_kind
"#{specific_kind}[]"
else
"Node[]"
end
end

# TODO: unduplicate with NodeKindField
Expand Down

0 comments on commit 322eaea

Please sign in to comment.