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

[Addition] Added IniRenderer and IniRenderer test cases #137 #149

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
247 changes: 247 additions & 0 deletions pkl-core/src/main/java/org/pkl/core/IniRenderer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,247 @@
/**
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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 org.pkl.core;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.pkl.core.util.Nullable;
import org.pkl.core.util.ini.IniUtils;

// To instantiate this class, use ValueRenderers.properties().
final class IniRenderer implements ValueRenderer {

private final Writer writer;
private final boolean omitNullProperties;
private final boolean restrictCharset;

public IniRenderer(Writer writer, boolean omitNullProperties, boolean restrictCharset) {
this.writer = writer;
this.omitNullProperties = omitNullProperties;
this.restrictCharset = restrictCharset;
}

@Override
public void renderDocument(Object value) {
new Visitor().renderDocument(value);
}

@Override
public void renderValue(Object value) {
new Visitor().renderValue(value);
}

public class Visitor implements ValueConverter<String> {

public void renderValue(Object value) {
write(convert(value), false, restrictCharset);
}

public void renderDocument(Object value) {
if (value instanceof Composite) {
doVisitMap(null, ((Composite) value).getProperties());
} else if (value instanceof Map) {
doVisitMap(null, (Map<?, ?>) value);
} else if (value instanceof Pair) {
Pair<?, ?> pair = (Pair<?, ?>) value;
doVisitKeyAndValue(null, pair.getFirst(), pair.getSecond());
} else {
Madmegsox1 marked this conversation as resolved.
Show resolved Hide resolved
throw new RendererException(
String.format(
"The top-level value of a Java properties file must have type `Composite`, `Map`, or `Pair`, but got type `%s`.",
value.getClass().getTypeName()));
}
}

private void doVisitMap(@Nullable String keyPrefix, Map<?, ?> map) {
for (Map.Entry<?, ?> entry : map.entrySet()) {
doVisitKeyAndValue(keyPrefix, entry.getKey(), entry.getValue());
}
}

private void doVisitKeyAndValue(@Nullable String keyPrefix, Object key, Object value) {
if (omitNullProperties && value instanceof PNull) {
return;
}
var baseKey = convert(key);
// gets existing key and appends the existing keypreifx if it's not null
var keyString = keyPrefix == null ? baseKey : keyPrefix + "." + baseKey;
// discovered a new section and writes key then writes the child values
// e.g. [example.dog]
if (value instanceof Composite) {
writeIniKey(keyString);
doVisitMap(keyString, ((Composite) value).getProperties());
} else if (value instanceof Map) {
writeIniKey(keyString);
doVisitMap(keyString, (Map<?, ?>) value);
} else {
writeIniValue(baseKey, convert(value));
}
}

@Override
public String convertNull() {
return "";
}

@Override
public String convertString(String value) {
return value;
}

@Override
public String convertBoolean(Boolean value) {
return value.toString();
}

@Override
public String convertInt(Long value) {
return value.toString();
}

@Override
public String convertFloat(Double value) {
return value.toString();
}

@Override
public String convertDuration(Duration value) {
throw new RendererException(
String.format(
"Values of type `Duration` cannot be rendered as Properties. Value: %s", value));
}

@Override
public String convertDataSize(DataSize value) {
throw new RendererException(
String.format(
"Values of type `DateSize` cannot be rendered as Properties. Value: %s", value));
}

@Override
public String convertPair(Pair<?, ?> value) {
throw new RendererException(
String.format(
"Values of type `Pair` cannot be rendered as Properties. Value: %s", value));
}

@Override
public String convertList(List<?> value) {
throw new RendererException(
String.format(
"Values of type `List` cannot be rendered as Properties. Value: %s", value));
}

@Override
public String convertSet(Set<?> value) {
throw new RendererException(
String.format("Values of type `Set` cannot be rendered as Properties. Value: %s", value));
}

@Override
public String convertMap(Map<?, ?> value) {
throw new RendererException(
String.format("Values of type `Map` cannot be rendered as Properties. Value: %s", value));
}

@Override
public String convertObject(PObject value) {
throw new RendererException(
String.format(
"Values of type `Object` cannot be rendered as Properties. Value: %s", value));
}

@Override
public String convertModule(PModule value) {
throw new RendererException(
String.format(
"Values of type `Module` cannot be rendered as Properties. Value: %s", value));
}

@Override
public String convertClass(PClass value) {
throw new RendererException(
String.format(
"Values of type `Class` cannot be rendered as Properties. Value: %s",
value.getSimpleName()));
}

@Override
public String convertTypeAlias(TypeAlias value) {
throw new RendererException(
String.format(
"Values of type `TypeAlias` cannot be rendered as Properties. Value: %s",
value.getSimpleName()));
}

@Override
public String convertRegex(Pattern value) {
throw new RendererException(
String.format(
"Values of type `Regex` cannot be rendered as Properties. Value: %s", value));
}

private void write(String value, boolean escapeSpace, boolean restrictCharset) {
try {
writer.write(IniUtils.renderPropertiesKeyOrValue(value, escapeSpace, restrictCharset));
} catch (IOException e) {
throw new RuntimeException(e);
}
}

private void writeIniValue(String key, String value) {
write(key, true, restrictCharset);
writeSeparator();
write(value, false, restrictCharset);
writeLineBreak();
}

private void writeIniKey(String keyValue) {
try {
// inserts a line break to make sure ini file is correct format
writeLineBreak();
writer.write('[');
write(keyValue, true, restrictCharset);
writer.write(']');
writeLineBreak();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}

private void writeSeparator() {
try {
writer.write(' ');
writer.write('=');
writer.write(' ');
} catch (IOException e) {
throw new RuntimeException(e);
}
}

private void writeLineBreak() {
try {
writer.write('\n');
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
}
11 changes: 11 additions & 0 deletions pkl-core/src/main/java/org/pkl/core/ValueRenderers.java
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,15 @@ public static ValueRenderer properties(
Writer writer, boolean omitNullProperties, boolean restrictCharset) {
return new PropertiesRenderer(writer, omitNullProperties, restrictCharset);
}

/**
* Creates a renderer for INI file format. If {@code omitNullProperties} is {@code true}, object
* properties and map entries whose value is {@code null} will not be rendered. If {@code
* restrictCharset} is {@code true} characters outside the printable US-ASCII charset range will
* be rendered as Unicode escapes
*/
public static ValueRenderer ini(
Writer writer, boolean omitNullProperties, boolean restrictCharset) {
return new IniRenderer(writer, omitNullProperties, restrictCharset);
}
}
65 changes: 65 additions & 0 deletions pkl-core/src/main/java/org/pkl/core/util/ini/IniUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/**
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed 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
*
* https://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 org.pkl.core.util.ini;

public class IniUtils {
// bitmap 32 bit need to escape ' ', ';'
private static final int[] bitmapEscapeSpace = new int[] {9728, 738197900, 268435456, 0};

private static final int[] bitmapNoEscapeSpace = new int[] {9728, 738197644, 268435456, 0};

private static final char[] hexDigitTable =
new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

private static final char[] hashTable =
new char[] {
' ', 0, '"', '#', 0, 0, 0, '\'', 0, 't', 'n', 0, 0, 'r', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
':', ';', '\\', '=', 0, 0
};

public static String renderPropertiesKeyOrValue(
String value, boolean escapeSpace, boolean restrictCharset) {
if (value.isEmpty()) {
return "";
}
var builder = new StringBuilder();

if (!escapeSpace && value.charAt(0) == ' ') {
builder.append('\\');
}

for (var i = 0; i < value.length(); i++) {
var c = value.charAt(i);
var bitmap = escapeSpace ? bitmapEscapeSpace : bitmapNoEscapeSpace;
var isEscapeChar = c < 128 && (bitmap[c >> 5] & (1 << c)) != 0;

if (isEscapeChar) {
builder.append('\\').append(hashTable[c % 32]);
} else if (restrictCharset && (c < 32 || c > 126)) {
builder
.append('\\')
.append('u')
.append(hexDigitTable[c >> 12 & 0xF])
.append(hexDigitTable[c >> 8 & 0xF])
.append(hexDigitTable[c >> 4 & 0xF])
.append(hexDigitTable[c & 0xF]);
} else {
builder.append(c);
}
}
return builder.toString();
}
}
54 changes: 54 additions & 0 deletions pkl-core/src/test/kotlin/org/pkl/core/IniRendererTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package org.pkl.core

import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.pkl.core.util.IoUtils
import java.io.StringWriter

class IniRendererTest {
@Test
fun `render document`() {
val evaluator = Evaluator.preconfigured()
val module = evaluator.evaluate(ModuleSource.modulePath("org/pkl/core/iniRendererTest.pkl"))
val writer = StringWriter()
val renderer = ValueRenderers.ini(writer, true, false)

renderer.renderDocument(module)
val output = writer.toString()
val expected = IoUtils.readClassPathResourceAsString(javaClass, "iniRendererTest.ini")


assertThat(output).isEqualTo(expected)
}

@Test
fun `render unsupported document values`() {
val unsupportedValues = listOf(
"List()", "new Listing {}", "Map()", "new Mapping {}", "Set()",
"new PropertiesRenderer {}", "new Dynamic {}"
)

unsupportedValues.forEach {
val evaluator = Evaluator.preconfigured()
val renderer = ValueRenderers.ini(StringWriter(), true, false)

val module = evaluator.evaluate(ModuleSource.text("value = $it"))
assertThrows<RendererException> { renderer.renderValue(module) }
}
}

@Test
fun `rendered document ends in newline`() {
val module = Evaluator.preconfigured()
.evaluate(ModuleSource.text("foo { bar = 0 }"))

for (omitNullProperties in listOf(false, true)) {
for (restrictCharSet in listOf(false, true)) {
val writer = StringWriter()
ValueRenderers.ini(writer, omitNullProperties, restrictCharSet).renderDocument(module)
assertThat(writer.toString()).endsWith("\n")
}
}
}
}
Loading