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

Create a frozen dictionary type. #22166

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import net.starlark.java.eval.Debug;
import net.starlark.java.eval.Dict;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.FrozenDict;
import net.starlark.java.eval.NoneType;
import net.starlark.java.eval.Printer;
import net.starlark.java.eval.Sequence;
Expand Down Expand Up @@ -132,7 +133,7 @@ private static void checkElement(Object x, boolean strict) throws EvalException
}

// Even the looser regime forbids the top-level class to be list or dict.
if (x instanceof StarlarkList || x instanceof Dict) {
if (x instanceof StarlarkList || (x instanceof Dict && !(x instanceof FrozenDict))) {
throw Starlark.errorf("depsets cannot contain items of type '%s'", Starlark.type(x));
}
}
Expand Down
1 change: 1 addition & 0 deletions src/main/java/net/starlark/java/eval/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ java_library(
"EvalUtils.java",
"FlagGuardedValue.java",
"FormatParser.java",
"FrozenDict.java",
"GuardedValue.java",
"HasBinary.java",
"ImmutableSingletonStarlarkList.java",
Expand Down
7 changes: 5 additions & 2 deletions src/main/java/net/starlark/java/eval/Dict.java
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public class Dict<K, V>
/** Final except for {@link #unsafeShallowFreeze}; must not be modified any other way. */
private Mutability mutability;

private Dict(Mutability mutability, LinkedHashMap<K, V> contents) {
protected Dict(Mutability mutability, LinkedHashMap<K, V> contents) {
Preconditions.checkNotNull(mutability);
Preconditions.checkState(mutability != Mutability.IMMUTABLE);
this.mutability = mutability;
Expand Down Expand Up @@ -181,7 +181,10 @@ public boolean updateIteratorCount(int delta) {
@Override
public void checkHashable() throws EvalException {
// Even a frozen dict is unhashable.
throw Starlark.errorf("unhashable type: 'dict'");
// This is because you can create a self-referential dict. For example:
// a = {}
// a["a"] = a
throw Starlark.errorf("unhashable type: 'dict' (consider using frozendict)");
}

@Override
Expand Down
71 changes: 71 additions & 0 deletions src/main/java/net/starlark/java/eval/FrozenDict.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// Copyright 2016 The Bazel 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
//
// 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 net.starlark.java.eval;

import com.google.common.collect.Maps;
import java.util.LinkedHashMap;
import net.starlark.java.annot.StarlarkBuiltin;

/**
* A FrozenDict is a Dict that is frozen upon initialization.
*/
@StarlarkBuiltin(
name = "frozendict",
category = "core",
doc =
"frozendict is a <code>dict</code> that is frozen upon initializatiion."
+ " Because it is frozen upon initialization, it cannot be self-referential, and is"
+ " thus suitable for hashing and use in a depset.")
public class FrozenDict extends Dict<Object, Object> {
private FrozenDict(Mutability mutability, LinkedHashMap<Object, Object> contents) {
super(mutability, contents);
}

@Override
public void checkHashable() throws EvalException {
// A dict that has been frozen from the very start cannot be self-referential, and thus can be
// hashable (assuming the elements are).

// Up for debate: Maybe this should be in the FrozenDict.of method.
// Does it ever make sense to allow frozendict(a={"b": "c"}), for example.
// Also up for debate: should we cache the result of this.
for (Object value : this.values()) {
Starlark.checkHashable(value);
}
}

// Although this is a departure from how Dict works, there is a TODO stating that the only thing
// isImmutable is used for is checking whether it's a valid depset element, and that they want to
// replace the isImmutable check with checkHashable in the future.
@Override
public boolean isImmutable() {
try {
checkHashable();
return true;
} catch (EvalException e) {
return false;
}
}

public static FrozenDict of(Object pairs, Dict<String, Object> kwargs) throws EvalException {
FrozenDict dict = new FrozenDict(
Mutability.createAllowingShallowFreeze(),
Maps.newLinkedHashMapWithExpectedSize(1)
);
Dict.update("dict", dict, pairs, kwargs);
dict.unsafeShallowFreeze();
return dict;
}
}
19 changes: 19 additions & 0 deletions src/main/java/net/starlark/java/eval/MethodLibrary.java
Original file line number Diff line number Diff line change
Expand Up @@ -642,6 +642,25 @@ public StarlarkInt intForStarlark(Object x, Object baseO) throws EvalException {
return dict;
}

@StarlarkMethod(
name = "frozendict",
doc =
"Creates a <a href=\"../core/dict.html\">dictionary</a> from an optional positional "
+ "argument and an optional set of keyword arguments. In the case where the same key "
+ "is given multiple times, the last value will be used. Entries supplied via "
+ "keyword arguments are considered to come after entries supplied via the "
+ "positional argument.",
parameters = {
@Param(
name = "pairs",
defaultValue = "[]",
doc = "A dict, or an iterable whose elements are each of length 2 (key, value)."),
},
extraKeywords = @Param(name = "kwargs", doc = "Dictionary of additional entries."))
public FrozenDict frozendict(Object pairs, Dict<String, Object> kwargs)
throws EvalException {
return FrozenDict.of(pairs, kwargs);
}
@StarlarkMethod(
name = "enumerate",
doc =
Expand Down