| 1 |
/* |
| 2 |
Copyright 2015 Google Inc. All rights reserved. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
#ifndef JSONNET_STATE_H |
| 18 |
#define JSONNET_STATE_H |
| 19 |
|
| 20 |
#include "ast.h" |
| 21 |
namespace jsonnet::internal { |
| 22 |
namespace { |
| 23 |
|
| 24 |
/** Mark & sweep: advanced by 1 each GC cycle. |
| 25 |
*/ |
| 26 |
typedef unsigned char GarbageCollectionMark; |
| 27 |
|
| 28 |
/** Supertype of everything that is allocated on the heap. |
| 29 |
*/ |
| 30 |
struct HeapEntity { |
| 31 |
enum Type : unsigned char { |
| 32 |
THUNK, |
| 33 |
ARRAY, |
| 34 |
CLOSURE, |
| 35 |
STRING, |
| 36 |
SIMPLE_OBJECT, |
| 37 |
COMPREHENSION_OBJECT, |
| 38 |
EXTENDED_OBJECT, |
| 39 |
RESTRICTED_OBJECT, |
| 40 |
}; |
| 41 |
GarbageCollectionMark mark; |
| 42 |
Type type; |
| 43 |
HeapEntity(Type type_) : type(type_) {} |
| 44 |
virtual ~HeapEntity() {} |
| 45 |
}; |
| 46 |
|
| 47 |
/** Tagged union of all values. |
| 48 |
* |
| 49 |
* Primitives (<= 8 bytes) are copied by value. Otherwise a pointer to a HeapEntity is used. |
| 50 |
*/ |
| 51 |
struct Value { |
| 52 |
enum Type { |
| 53 |
NULL_TYPE = 0x0, // Unfortunately NULL is a macro in C. |
| 54 |
BOOLEAN = 0x1, |
| 55 |
NUMBER = 0x2, |
| 56 |
|
| 57 |
ARRAY = 0x10, |
| 58 |
FUNCTION = 0x11, |
| 59 |
OBJECT = 0x12, |
| 60 |
STRING = 0x13 |
| 61 |
}; |
| 62 |
Type t; |
| 63 |
union { |
| 64 |
HeapEntity *h; |
| 65 |
double d; |
| 66 |
bool b; |
| 67 |
} v; |
| 68 |
bool isHeap(void) const |
| 69 |
{ |
| 70 |
return t & 0x10; |
| 71 |
} |
| 72 |
}; |
| 73 |
|
| 74 |
/** Convert the type into a string, for error messages. */ |
| 75 |
std::string type_str(Value::Type t) |
| 76 |
{ |
| 77 |
switch (t) { |
| 78 |
case Value::NULL_TYPE: return "null"; |
| 79 |
case Value::BOOLEAN: return "boolean"; |
| 80 |
case Value::NUMBER: return "number"; |
| 81 |
case Value::ARRAY: return "array"; |
| 82 |
case Value::FUNCTION: return "function"; |
| 83 |
case Value::OBJECT: return "object"; |
| 84 |
case Value::STRING: return "string"; |
| 85 |
default: |
| 86 |
std::cerr << "INTERNAL ERROR: Unknown type: " << t << std::endl; |
| 87 |
std::abort(); |
| 88 |
return ""; // Quiet, compiler. |
| 89 |
} |
| 90 |
} |
| 91 |
|
| 92 |
/** Convert the value's type into a string, for error messages. */ |
| 93 |
std::string type_str(const Value &v) |
| 94 |
{ |
| 95 |
return type_str(v.t); |
| 96 |
} |
| 97 |
|
| 98 |
struct HeapThunk; |
| 99 |
|
| 100 |
/** Stores the values bound to variables. |
| 101 |
* |
| 102 |
* Each nested local statement, function call, and field access has its own binding frame to |
| 103 |
* give the values for the local variable, function parameters, or upValues. |
| 104 |
*/ |
| 105 |
typedef std::map<const Identifier *, HeapThunk *> BindingFrame; |
| 106 |
|
| 107 |
/** Supertype of all objects. Types of Value::OBJECT will point at these. */ |
| 108 |
struct HeapObject : public HeapEntity { |
| 109 |
HeapObject(Type type) : HeapEntity(type) {} |
| 110 |
}; |
| 111 |
|
| 112 |
/** Hold an unevaluated expression. This implements lazy semantics. |
| 113 |
*/ |
| 114 |
struct HeapThunk : public HeapEntity { |
| 115 |
/** Whether or not the thunk was forced. */ |
| 116 |
bool filled; |
| 117 |
|
| 118 |
/** The result when the thunk was forced, if filled == true. */ |
| 119 |
Value content; |
| 120 |
|
| 121 |
/** Used in error tracebacks. */ |
| 122 |
const Identifier *name; |
| 123 |
|
| 124 |
/** The captured environment. |
| 125 |
* |
| 126 |
* Note, this is non-const because we have to add cyclic references to it. |
| 127 |
*/ |
| 128 |
BindingFrame upValues; |
| 129 |
|
| 130 |
/** The captured self variable, or nullptr if there was none. \see CallFrame. */ |
| 131 |
HeapObject *self; |
| 132 |
|
| 133 |
/** The offset from the captured self variable. \see CallFrame. */ |
| 134 |
unsigned offset; |
| 135 |
|
| 136 |
/** Evaluated to force the thunk. */ |
| 137 |
const AST *body; |
| 138 |
|
| 139 |
HeapThunk(const Identifier *name, HeapObject *self, unsigned offset, const AST *body) |
| 140 |
: HeapEntity(THUNK), filled(false), name(name), self(self), offset(offset), body(body) |
| 141 |
{ |
| 142 |
} |
| 143 |
|
| 144 |
void fill(const Value &v) |
| 145 |
{ |
| 146 |
content = v; |
| 147 |
filled = true; |
| 148 |
self = nullptr; |
| 149 |
upValues.clear(); |
| 150 |
} |
| 151 |
}; |
| 152 |
|
| 153 |
struct HeapArray : public HeapEntity { |
| 154 |
// It is convenient for this to not be const, so that we can add elements to it one at a |
| 155 |
// time after creation. Thus, elements are not GCed as the array is being |
| 156 |
// created. |
| 157 |
std::vector<HeapThunk *> elements; |
| 158 |
HeapArray(const std::vector<HeapThunk *> &elements) |
| 159 |
: HeapEntity(ARRAY), elements(elements) |
| 160 |
{ |
| 161 |
} |
| 162 |
}; |
| 163 |
|
| 164 |
/** Supertype of all objects that are not super objects or extended objects. */ |
| 165 |
struct HeapLeafObject : public HeapObject { |
| 166 |
HeapLeafObject(Type type) : HeapObject(type) {} |
| 167 |
}; |
| 168 |
|
| 169 |
/** Objects created via the simple object constructor construct. */ |
| 170 |
struct HeapSimpleObject : public HeapLeafObject { |
| 171 |
/** The captured environment. */ |
| 172 |
const BindingFrame upValues; |
| 173 |
|
| 174 |
struct Field { |
| 175 |
/** Will the field appear in output? */ |
| 176 |
ObjectField::Hide hide; |
| 177 |
/** Expression that is evaluated when indexing this field. */ |
| 178 |
AST *body; |
| 179 |
}; |
| 180 |
|
| 181 |
/** The fields. |
| 182 |
* |
| 183 |
* These are evaluated in the captured environment and with self and super bound |
| 184 |
* dynamically. |
| 185 |
*/ |
| 186 |
const std::map<const Identifier *, Field> fields; |
| 187 |
|
| 188 |
/** The object's invariants. |
| 189 |
* |
| 190 |
* These are evaluated in the captured environment with self and super bound. |
| 191 |
*/ |
| 192 |
ASTs asserts; |
| 193 |
|
| 194 |
HeapSimpleObject(const BindingFrame &up_values, |
| 195 |
const std::map<const Identifier *, Field> fields, ASTs asserts) |
| 196 |
: HeapLeafObject(SIMPLE_OBJECT), upValues(up_values), fields(fields), asserts(asserts) |
| 197 |
{ |
| 198 |
} |
| 199 |
}; |
| 200 |
|
| 201 |
/** Objects created by the + construct. */ |
| 202 |
struct HeapExtendedObject : public HeapObject { |
| 203 |
/** The left hand side of the construct. */ |
| 204 |
HeapObject *left; |
| 205 |
|
| 206 |
/** The right hand side of the construct. */ |
| 207 |
HeapObject *right; |
| 208 |
|
| 209 |
HeapExtendedObject(HeapObject *left, HeapObject *right) |
| 210 |
: HeapObject(EXTENDED_OBJECT), left(left), right(right) |
| 211 |
{ |
| 212 |
} |
| 213 |
}; |
| 214 |
|
| 215 |
/** Objects created by std.objectRemoveKey(s). */ |
| 216 |
struct HeapRestrictedObject : public HeapLeafObject { |
| 217 |
/** The 'parent' object from which we inherit. */ |
| 218 |
HeapObject *obj; |
| 219 |
|
| 220 |
/** A 'filter list' of keys retained in the object. */ |
| 221 |
std::map<const Identifier *, ObjectField::Hide> retainedKeys; |
| 222 |
|
| 223 |
HeapRestrictedObject(HeapObject *obj, const std::map<const Identifier *, ObjectField::Hide> &retained_keys) |
| 224 |
: HeapLeafObject(RESTRICTED_OBJECT), obj(obj), retainedKeys(retained_keys) |
| 225 |
{ |
| 226 |
} |
| 227 |
}; |
| 228 |
|
| 229 |
/** Objects created by the ObjectComprehensionSimple construct. */ |
| 230 |
struct HeapComprehensionObject : public HeapLeafObject { |
| 231 |
/** The captured environment. */ |
| 232 |
const BindingFrame upValues; |
| 233 |
|
| 234 |
/** The expression used to compute the field values. */ |
| 235 |
const AST *value; |
| 236 |
|
| 237 |
/** The identifier of bound variable in that construct. */ |
| 238 |
const Identifier *const id; |
| 239 |
|
| 240 |
/** Binding for id. |
| 241 |
* |
| 242 |
* For each field, holds the value that should be bound to id. This is the corresponding |
| 243 |
* array element from the original array used to define this object. This should not really |
| 244 |
* be a thunk, but it makes the implementation easier. |
| 245 |
* |
| 246 |
* It is convenient to make this non-const to allow building up the values one by one, so that |
| 247 |
* the garbage collector can see them at each intermediate point. |
| 248 |
*/ |
| 249 |
std::map<const Identifier *, HeapThunk *> compValues; |
| 250 |
|
| 251 |
HeapComprehensionObject(const BindingFrame &up_values, const AST *value, const Identifier *id, |
| 252 |
const std::map<const Identifier *, HeapThunk *> &comp_values) |
| 253 |
: HeapLeafObject(COMPREHENSION_OBJECT), upValues(up_values), value(value), id(id), compValues(comp_values) |
| 254 |
{ |
| 255 |
} |
| 256 |
}; |
| 257 |
|
| 258 |
/** Stores the function itself and also the captured environment. |
| 259 |
* |
| 260 |
* Either body is non-null and builtinName is "", or body is null and builtin refers to a built-in |
| 261 |
* function. In the former case, the closure represents a user function, otherwise calling it |
| 262 |
* will trigger the builtin function to execute. Params is empty when the function is a |
| 263 |
* builtin. |
| 264 |
*/ |
| 265 |
struct HeapClosure : public HeapEntity { |
| 266 |
/** The captured environment. */ |
| 267 |
const BindingFrame upValues; |
| 268 |
/** The captured self variable, or nullptr if there was none. \see Frame. */ |
| 269 |
HeapObject *self; |
| 270 |
/** The offset from the captured self variable. \see Frame.*/ |
| 271 |
unsigned offset; |
| 272 |
struct Param { |
| 273 |
const Identifier *id; |
| 274 |
const AST *def; |
| 275 |
Param(const Identifier *id, const AST *def) : id(id), def(def) {} |
| 276 |
}; |
| 277 |
typedef std::vector<Param> Params; |
| 278 |
const Params params; |
| 279 |
const AST *body; |
| 280 |
std::string builtinName; |
| 281 |
HeapClosure(const BindingFrame &up_values, HeapObject *self, unsigned offset, |
| 282 |
const Params ¶ms, const AST *body, const std::string &builtin_name) |
| 283 |
: HeapEntity(CLOSURE), |
| 284 |
upValues(up_values), |
| 285 |
self(self), |
| 286 |
offset(offset), |
| 287 |
params(params), |
| 288 |
body(body), |
| 289 |
builtinName(builtin_name) |
| 290 |
{ |
| 291 |
} |
| 292 |
|
| 293 |
bool isBuiltin() const { return !this->body || this->body->type == AST_BUILTIN_FUNCTION_BODY; } |
| 294 |
}; |
| 295 |
|
| 296 |
/** Stores a simple string on the heap. */ |
| 297 |
struct HeapString : public HeapEntity { |
| 298 |
const UString value; |
| 299 |
HeapString(const UString &value) : HeapEntity(STRING), value(value) {} |
| 300 |
}; |
| 301 |
|
| 302 |
/** The heap does memory management, i.e. garbage collection. */ |
| 303 |
class Heap { |
| 304 |
/** How many objects must exist in the heap before we bother doing garbage collection? |
| 305 |
*/ |
| 306 |
unsigned gcTuneMinObjects; |
| 307 |
|
| 308 |
/** How much must the heap have grown since the last cycle to trigger a collection? |
| 309 |
*/ |
| 310 |
double gcTuneGrowthTrigger; |
| 311 |
|
| 312 |
/** Value used to mark entities at the last garbage collection cycle. */ |
| 313 |
GarbageCollectionMark lastMark; |
| 314 |
|
| 315 |
/** The heap entities (strings, arrays, objects, functions, etc). |
| 316 |
* |
| 317 |
* Not all may be reachable, all should have o->mark == this->lastMark. Entities are |
| 318 |
* removed from the heap via O(1) swap with last element, so the ordering of entities is |
| 319 |
* arbitrary and changes every garbage collection cycle. |
| 320 |
*/ |
| 321 |
std::vector<HeapEntity *> entities; |
| 322 |
|
| 323 |
/** The number of heap entities at the last garbage collection cycle. */ |
| 324 |
unsigned long lastNumEntities; |
| 325 |
|
| 326 |
/** The number of heap entities now. */ |
| 327 |
unsigned long numEntities; |
| 328 |
|
| 329 |
/** Add the HeapEntity inside v to vec, if the value exists on the heap. |
| 330 |
*/ |
| 331 |
void addIfHeapEntity(Value v, std::vector<HeapEntity *> &vec) |
| 332 |
{ |
| 333 |
if (v.isHeap()) |
| 334 |
vec.push_back(v.v.h); |
| 335 |
} |
| 336 |
|
| 337 |
/** Add the HeapEntity inside v to vec, if the value exists on the heap. |
| 338 |
*/ |
| 339 |
void addIfHeapEntity(HeapEntity *v, std::vector<HeapEntity *> &vec) |
| 340 |
{ |
| 341 |
vec.push_back(v); |
| 342 |
} |
| 343 |
|
| 344 |
public: |
| 345 |
Heap(unsigned gc_tune_min_objects, double gc_tune_growth_trigger) |
| 346 |
: gcTuneMinObjects(gc_tune_min_objects), |
| 347 |
gcTuneGrowthTrigger(gc_tune_growth_trigger), |
| 348 |
lastMark(0), |
| 349 |
lastNumEntities(0), |
| 350 |
numEntities(0) |
| 351 |
{ |
| 352 |
} |
| 353 |
|
| 354 |
~Heap(void) |
| 355 |
{ |
| 356 |
// Nothing is marked, everything will be collected. |
| 357 |
sweep(); |
| 358 |
} |
| 359 |
|
| 360 |
/** Garbage collection: Mark v, and entities reachable from v. */ |
| 361 |
void markFrom(Value v) |
| 362 |
{ |
| 363 |
if (v.isHeap()) |
| 364 |
markFrom(v.v.h); |
| 365 |
} |
| 366 |
|
| 367 |
/** Garbage collection: Mark heap entities reachable from the given heap entity. */ |
| 368 |
void markFrom(HeapEntity *from) |
| 369 |
{ |
| 370 |
assert(from != nullptr); |
| 371 |
const GarbageCollectionMark thisMark = lastMark + 1; |
| 372 |
struct State { |
| 373 |
HeapEntity *ent; |
| 374 |
std::vector<HeapEntity *> children; |
| 375 |
State(HeapEntity *ent) : ent(ent) {} |
| 376 |
}; |
| 377 |
|
| 378 |
std::vector<State> stack; |
| 379 |
stack.emplace_back(from); |
| 380 |
|
| 381 |
while (stack.size() > 0) { |
| 382 |
size_t curr_index = stack.size() - 1; |
| 383 |
State &s = stack[curr_index]; |
| 384 |
HeapEntity *curr = s.ent; |
| 385 |
if (curr->mark != thisMark) { |
| 386 |
curr->mark = thisMark; |
| 387 |
|
| 388 |
switch(curr->type) { |
| 389 |
case HeapEntity::SIMPLE_OBJECT: { |
| 390 |
assert(dynamic_cast<HeapSimpleObject *>(curr)); |
| 391 |
auto *obj = static_cast<HeapSimpleObject *>(curr); |
| 392 |
for (auto upv : obj->upValues) |
| 393 |
addIfHeapEntity(upv.second, s.children); |
| 394 |
break; |
| 395 |
} |
| 396 |
case HeapEntity::EXTENDED_OBJECT: { |
| 397 |
assert(dynamic_cast<HeapExtendedObject *>(curr)); |
| 398 |
auto *obj = static_cast<HeapExtendedObject *>(curr); |
| 399 |
addIfHeapEntity(obj->left, s.children); |
| 400 |
addIfHeapEntity(obj->right, s.children); |
| 401 |
break; |
| 402 |
} |
| 403 |
case HeapEntity::RESTRICTED_OBJECT: { |
| 404 |
assert(dynamic_cast<HeapRestrictedObject *>(curr)); |
| 405 |
auto *obj = static_cast<HeapRestrictedObject *>(curr); |
| 406 |
addIfHeapEntity(obj->obj, s.children); |
| 407 |
break; |
| 408 |
} |
| 409 |
case HeapEntity::COMPREHENSION_OBJECT: { |
| 410 |
assert(dynamic_cast<HeapComprehensionObject *>(curr)); |
| 411 |
auto *obj = static_cast<HeapComprehensionObject *>(curr); |
| 412 |
for (auto upv : obj->upValues) |
| 413 |
addIfHeapEntity(upv.second, s.children); |
| 414 |
for (auto upv : obj->compValues) |
| 415 |
addIfHeapEntity(upv.second, s.children); |
| 416 |
break; |
| 417 |
} |
| 418 |
case HeapEntity::ARRAY: { |
| 419 |
assert(dynamic_cast<HeapArray *>(curr)); |
| 420 |
auto *arr = static_cast<HeapArray *>(curr); |
| 421 |
for (auto el : arr->elements) |
| 422 |
addIfHeapEntity(el, s.children); |
| 423 |
break; |
| 424 |
} |
| 425 |
case HeapEntity::CLOSURE: { |
| 426 |
assert(dynamic_cast<HeapClosure *>(curr)); |
| 427 |
auto *func = static_cast<HeapClosure *>(curr); |
| 428 |
for (auto upv : func->upValues) |
| 429 |
addIfHeapEntity(upv.second, s.children); |
| 430 |
if (func->self) |
| 431 |
addIfHeapEntity(func->self, s.children); |
| 432 |
break; |
| 433 |
} |
| 434 |
case HeapEntity::THUNK: { |
| 435 |
assert(dynamic_cast<HeapThunk *>(curr)); |
| 436 |
auto *thunk = static_cast<HeapThunk *>(curr); |
| 437 |
if (thunk->filled) { |
| 438 |
if (thunk->content.isHeap()) |
| 439 |
addIfHeapEntity(thunk->content.v.h, s.children); |
| 440 |
} else { |
| 441 |
for (auto upv : thunk->upValues) |
| 442 |
addIfHeapEntity(upv.second, s.children); |
| 443 |
if (thunk->self) |
| 444 |
addIfHeapEntity(thunk->self, s.children); |
| 445 |
} |
| 446 |
break; |
| 447 |
} |
| 448 |
case HeapEntity::STRING: |
| 449 |
assert(dynamic_cast<HeapString *>(curr)); |
| 450 |
break; |
| 451 |
default: |
| 452 |
assert(false); |
| 453 |
break; |
| 454 |
} |
| 455 |
} |
| 456 |
|
| 457 |
if (s.children.size() > 0) { |
| 458 |
HeapEntity *next = s.children[s.children.size() - 1]; |
| 459 |
s.children.pop_back(); |
| 460 |
stack.emplace_back(next); // CAUTION: s invalidated here |
| 461 |
} else { |
| 462 |
stack.pop_back(); // CAUTION: s invalidated here |
| 463 |
} |
| 464 |
} |
| 465 |
} |
| 466 |
|
| 467 |
/** Delete everything that was not marked since the last collection. */ |
| 468 |
void sweep(void) |
| 469 |
{ |
| 470 |
lastMark++; |
| 471 |
// Heap shrinks during this loop. Do not cache entities.size(). |
| 472 |
for (unsigned long i = 0; i < entities.size(); ++i) { |
| 473 |
HeapEntity *x = entities[i]; |
| 474 |
if (x->mark != lastMark) { |
| 475 |
delete x; |
| 476 |
if (i != entities.size() - 1) { |
| 477 |
// Swap it with the back. |
| 478 |
entities[i] = entities[entities.size() - 1]; |
| 479 |
} |
| 480 |
entities.pop_back(); |
| 481 |
--i; |
| 482 |
} |
| 483 |
} |
| 484 |
lastNumEntities = numEntities = entities.size(); |
| 485 |
} |
| 486 |
|
| 487 |
/** Is it time to initiate a GC cycle? */ |
| 488 |
bool checkHeap(void) |
| 489 |
{ |
| 490 |
return numEntities > gcTuneMinObjects && |
| 491 |
numEntities > gcTuneGrowthTrigger * lastNumEntities; |
| 492 |
} |
| 493 |
|
| 494 |
/** Allocate a heap entity. |
| 495 |
* |
| 496 |
* If the heap is large enough (\see gcTuneMinObjects) and has grown by enough since the |
| 497 |
* last collection cycle (\see gcTuneGrowthTrigger), a collection cycle should be performed. |
| 498 |
*/ |
| 499 |
template <class T, class... Args> |
| 500 |
T *makeEntity(Args &&... args) |
| 501 |
{ |
| 502 |
T *r = new T(std::forward<Args>(args)...); |
| 503 |
entities.push_back(r); |
| 504 |
r->mark = lastMark; |
| 505 |
numEntities = entities.size(); |
| 506 |
return r; |
| 507 |
} |
| 508 |
}; |
| 509 |
|
| 510 |
} // namespace |
| 511 |
} // namespace jsonnet::internal |
| 512 |
|
| 513 |
#endif // JSONNET_STATE_H |