liquid5-c 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE.txt +22 -0
  3. data/README.md +164 -0
  4. data/ext/liquid_c/block.c +970 -0
  5. data/ext/liquid_c/block.h +37 -0
  6. data/ext/liquid_c/c_buffer.c +48 -0
  7. data/ext/liquid_c/c_buffer.h +82 -0
  8. data/ext/liquid_c/context.c +262 -0
  9. data/ext/liquid_c/context.h +72 -0
  10. data/ext/liquid_c/document_body.c +181 -0
  11. data/ext/liquid_c/document_body.h +84 -0
  12. data/ext/liquid_c/expression.c +130 -0
  13. data/ext/liquid_c/expression.h +24 -0
  14. data/ext/liquid_c/extconf.rb +60 -0
  15. data/ext/liquid_c/intutil.h +36 -0
  16. data/ext/liquid_c/lexer.c +172 -0
  17. data/ext/liquid_c/lexer.h +61 -0
  18. data/ext/liquid_c/liquid.c +182 -0
  19. data/ext/liquid_c/liquid.h +112 -0
  20. data/ext/liquid_c/liquid_vm.c +907 -0
  21. data/ext/liquid_c/liquid_vm.h +35 -0
  22. data/ext/liquid_c/mri_compat.h +35 -0
  23. data/ext/liquid_c/native_parser.c +2360 -0
  24. data/ext/liquid_c/native_value.c +49 -0
  25. data/ext/liquid_c/parse_context.c +84 -0
  26. data/ext/liquid_c/parse_context.h +13 -0
  27. data/ext/liquid_c/parser.c +285 -0
  28. data/ext/liquid_c/parser.h +25 -0
  29. data/ext/liquid_c/raw.c +136 -0
  30. data/ext/liquid_c/raw.h +6 -0
  31. data/ext/liquid_c/resource_limits.c +459 -0
  32. data/ext/liquid_c/resource_limits.h +28 -0
  33. data/ext/liquid_c/stringutil.h +37 -0
  34. data/ext/liquid_c/tokenizer.c +326 -0
  35. data/ext/liquid_c/tokenizer.h +46 -0
  36. data/ext/liquid_c/usage.c +18 -0
  37. data/ext/liquid_c/usage.h +9 -0
  38. data/ext/liquid_c/variable.c +198 -0
  39. data/ext/liquid_c/variable.h +61 -0
  40. data/ext/liquid_c/variable_lookup.c +73 -0
  41. data/ext/liquid_c/variable_lookup.h +8 -0
  42. data/ext/liquid_c/vm_assembler.c +631 -0
  43. data/ext/liquid_c/vm_assembler.h +294 -0
  44. data/ext/liquid_c/vm_assembler_pool.c +117 -0
  45. data/ext/liquid_c/vm_assembler_pool.h +27 -0
  46. data/lib/liquid/c/compile_ext.rb +47 -0
  47. data/lib/liquid/c/native_compiler.rb +262 -0
  48. data/lib/liquid/c/native_parser.rb +261 -0
  49. data/lib/liquid/c/native_tags.rb +103 -0
  50. data/lib/liquid/c/native_values.rb +9 -0
  51. data/lib/liquid/c/version.rb +7 -0
  52. data/lib/liquid/c.rb +379 -0
  53. metadata +140 -0
@@ -0,0 +1,2360 @@
1
+ #include "liquid.h"
2
+ #include "mri_compat.h"
3
+ #include "parser.h"
4
+ #include "document_body.h"
5
+ #include "variable.h"
6
+ #include <stdlib.h>
7
+
8
+ // This frontend is deliberately non-diagnostic. Unsupported syntax is returned
9
+ // to Liquid's parser, which owns mode-specific errors and warnings. All offsets
10
+ // refer to an owned, pinned string; no pointer survives an allocation.
11
+ typedef struct {
12
+ VALUE source, cache, pending;
13
+ // Conditions and fused outputs use disjoint parsing operations.
14
+ union { VALUE condition_literals; VALUE pending_value; };
15
+ VALUE variable_name, variable_filters;
16
+ bool literals_checked, guarded, compact_pending;
17
+ size_t initial_gc_count;
18
+ size_t position, length, start, end;
19
+ int token, operation;
20
+ vm_assembler_t *code;
21
+ } native_parser_t;
22
+
23
+ enum { N_END = 256, N_ID, N_NUMBER, N_STRING, N_DOTDOT, N_COMPARE, N_UNSUPPORTED };
24
+
25
+ static ID id_name, id_lookups, id_commands, id_start, id_end;
26
+ static ID id_string_scanner, id_new_native, id_allocate_native;
27
+ static ID id_disabled_native, id_mode_native, id_cache_native;
28
+ static ID id_options_native, id_stats_native, id_enabled_native, id_parse_context_native, id_for_fields[6];
29
+ static VALUE native_context_class, native_case_class, native_if_class, native_unless_class, native_for_class;
30
+ static VALUE native_original_if, native_original_for;
31
+ static bool native_variable_ready;
32
+ static VALUE native_expression_class, native_parser_class, native_condition_class, native_literals, native_unbound_class;
33
+ static VALUE native_hash_readers[3];
34
+ enum { HASH_IDENTITY_READER, HASH_DEFAULT_PROC_READER, HASH_DEFAULT_READER };
35
+
36
+ #ifndef HAVE_RB_AUTOLOAD_P
37
+ static VALUE native_autoload_reader = Qnil;
38
+ #endif
39
+
40
+ static VALUE native_autoload_p(VALUE owner, ID name)
41
+ {
42
+ #ifdef HAVE_RB_AUTOLOAD_P
43
+ return rb_autoload_p(owner, name);
44
+ #else
45
+ if (NIL_P(native_autoload_reader)) return Qtrue;
46
+ VALUE args[] = { owner, ID2SYM(name), Qfalse };
47
+ return liquid_method_call(3, args, native_autoload_reader);
48
+ #endif
49
+ }
50
+
51
+ // Stored builtin bodies read Hash metadata without invoking application
52
+ // overrides. Public Method APIs avoid depending on MRI's Hash layout.
53
+ static VALUE native_hash_property(VALUE hash, size_t reader)
54
+ {
55
+ if (CLASS_OF(hash) != rb_cHash) return Qundef;
56
+ #ifdef HAVE_RB_HASH_COMPARE_BY_ID_P
57
+ if (reader == HASH_IDENTITY_READER) return rb_hash_compare_by_id_p(hash);
58
+ #endif
59
+ if (NIL_P(native_hash_readers[reader])) return Qundef;
60
+ return liquid_method_call(1, &hash, native_hash_readers[reader]);
61
+ }
62
+
63
+ static bool native_normal_hash(VALUE hash)
64
+ {
65
+ size_t before = liquid_gc_count();
66
+ VALUE identity = native_hash_property(hash, HASH_IDENTITY_READER);
67
+ return identity == Qfalse && liquid_gc_count() == before;
68
+ }
69
+
70
+ static VALUE native_capture_constant(VALUE owner, const char *name)
71
+ {
72
+ ID id = rb_intern(name);
73
+ if (!RB_TYPE_P(owner, T_CLASS) && !RB_TYPE_P(owner, T_MODULE)) return Qnil;
74
+ if (!rb_const_defined_at(owner, id) || RTEST(native_autoload_p(owner, id))) return Qnil;
75
+ return rb_const_get_at(owner, id);
76
+ }
77
+
78
+ typedef struct { VALUE owner; ID method; bool public_call; } primitive_guard_t;
79
+ static primitive_guard_t primitive_guards[96];
80
+ static size_t primitive_guard_count;
81
+
82
+ static void native_guard_primitive(VALUE owner, const char *method)
83
+ {
84
+ if (primitive_guard_count >= sizeof(primitive_guards) / sizeof(primitive_guards[0]))
85
+ rb_raise(rb_eRuntimeError, "too many native primitive guards");
86
+ primitive_guard_t *guard = &primitive_guards[primitive_guard_count++];
87
+ guard->owner = owner;
88
+ guard->method = rb_intern(method);
89
+ guard->public_call = strcmp(method, "initialize_copy") && strcmp(method, "initialize_dup");
90
+ }
91
+
92
+ static bool native_primitives_standard(bool check_visibility)
93
+ {
94
+ for (size_t i = 0; i < primitive_guard_count; i++) {
95
+ const primitive_guard_t *guard = &primitive_guards[i];
96
+ if (!liquid_method_basic_definition_p(guard->owner, guard->method)) return false;
97
+ if (check_visibility && guard->public_call && rb_method_boundp(guard->owner, guard->method, 3) != 1) return false;
98
+ }
99
+ return true;
100
+ }
101
+
102
+ static VALUE native_public_method(VALUE self, VALUE receiver, VALUE name)
103
+ {
104
+ return rb_method_boundp(CLASS_OF(receiver), SYM2ID(name), 3) == 1 ? Qtrue : Qfalse;
105
+ }
106
+
107
+ static bool native_snapshot_matches(VALUE value, VALUE snapshot)
108
+ {
109
+ if (NIL_P(snapshot)) return true;
110
+ if (!RB_TYPE_P(value, T_ARRAY) || !RB_TYPE_P(snapshot, T_ARRAY) || RARRAY_LEN(value) != RARRAY_LEN(snapshot)) return false;
111
+ for (long i = 0; i < RARRAY_LEN(snapshot); i++)
112
+ if (RARRAY_AREF(value, i) != RARRAY_AREF(snapshot, i)) return false;
113
+ return true;
114
+ }
115
+
116
+ static VALUE native_constant_matches(VALUE self, VALUE owner, VALUE name, VALUE expected, VALUE snapshot)
117
+ {
118
+ if (!RB_TYPE_P(owner, T_CLASS) && !RB_TYPE_P(owner, T_MODULE)) return Qfalse;
119
+ Check_Type(name, T_SYMBOL);
120
+ ID id = SYM2ID(name);
121
+ if (!rb_const_defined_at(owner, id) || RTEST(native_autoload_p(owner, id)) || rb_const_get_at(owner, id) != expected) return Qfalse;
122
+ return native_snapshot_matches(expected, snapshot) ? Qtrue : Qfalse;
123
+ }
124
+
125
+ // Public reflection is portable but expensive. Amortize it only over complex
126
+ // expressions on Rubies which do not export the optional opaque method API.
127
+ static VALUE native_frontend_candidate(VALUE self, VALUE markup)
128
+ {
129
+ if (!RB_TYPE_P(markup, T_STRING) || RSTRING_LEN(markup) < 1024) return Qfalse;
130
+ const unsigned char *bytes = (const unsigned char *)RSTRING_PTR(markup);
131
+ size_t count = 0;
132
+ unsigned char quote = 0;
133
+ for (long i = 0; i < RSTRING_LEN(markup); i++) {
134
+ unsigned char c = bytes[i];
135
+ if (quote) { if (c == quote) quote = 0; continue; }
136
+ if (c == '\'' || c == '"') { quote = c; continue; }
137
+ if (c == '.' || c == '[' || c == '|' || c == ',') {
138
+ if (++count >= 128) return Qtrue;
139
+ }
140
+ }
141
+ return Qfalse;
142
+ }
143
+
144
+ #ifdef HAVE_RB_CALLABLE_METHOD_ENTRY
145
+ typedef struct { VALUE owner, entry, snapshot; ID method; int receiver; bool constant, public_call, builtin; } native_method_guard_t;
146
+ static native_method_guard_t *method_guards;
147
+ static long method_guard_count;
148
+ static VALUE integer_to_i_entry;
149
+ static VALUE constant_watchers = Qnil, constant_vm = Qnil, constant_epoch = Qundef;
150
+ static ID id_stat, id_constant_invalidations;
151
+ static bool guard_roots_registered;
152
+
153
+ static VALUE native_watchers_supported(VALUE self, VALUE vm)
154
+ {
155
+ return liquid_method_basic_definition_p(CLASS_OF(vm), rb_intern("stat")) &&
156
+ liquid_method_basic_definition_p(rb_cModule, rb_intern("module_eval")) &&
157
+ liquid_method_basic_definition_p(rb_cModule, rb_intern("instance_method")) &&
158
+ (RB_TYPE_P(native_unbound_class, T_CLASS) && liquid_method_basic_definition_p(native_unbound_class, rb_intern("bind_call"))) &&
159
+ liquid_method_basic_definition_p(rb_cProc, rb_intern("call")) ? Qtrue : Qfalse;
160
+ }
161
+
162
+ static VALUE native_constant_epoch(void)
163
+ {
164
+ if (NIL_P(constant_vm) || !liquid_method_basic_definition_p(CLASS_OF(constant_vm), id_stat)) return Qundef;
165
+ return rb_funcall(constant_vm, id_stat, 1, ID2SYM(id_constant_invalidations));
166
+ }
167
+
168
+ static VALUE native_register_guards(VALUE self, VALUE specifications, VALUE watchers, VALUE vm)
169
+ {
170
+ Check_Type(specifications, T_ARRAY);
171
+ long count = RARRAY_LEN(specifications);
172
+ if (count < 0 || (size_t)count > SIZE_MAX / sizeof(*method_guards))
173
+ rb_raise(rb_eArgError, "too many method guards");
174
+ bool first = method_guards == NULL;
175
+ if (!first && count != method_guard_count) rb_raise(rb_eArgError, "guard count changed");
176
+ for (long i = 0; i < count; i++) {
177
+ VALUE spec = RARRAY_AREF(specifications, i);
178
+ Check_Type(spec, T_ARRAY);
179
+ if (RARRAY_LEN(spec) != 7) rb_raise(rb_eArgError, "invalid method guard");
180
+ VALUE owner = RARRAY_AREF(spec, 0);
181
+ if (!RB_TYPE_P(owner, T_CLASS) && !RB_TYPE_P(owner, T_MODULE)) rb_raise(rb_eTypeError, "guard owner must be a module");
182
+ Check_Type(RARRAY_AREF(spec, 1), T_SYMBOL);
183
+ int receiver = NUM2INT(RARRAY_AREF(spec, 2));
184
+ if (receiver < 0 || receiver > 3) rb_raise(rb_eArgError, "invalid method guard receiver");
185
+ if (!NIL_P(RARRAY_AREF(spec, 4))) Check_Type(RARRAY_AREF(spec, 4), T_ARRAY);
186
+ }
187
+ if (!NIL_P(watchers)) Check_Type(watchers, T_ARRAY);
188
+ if (first) method_guards = ruby_xcalloc((size_t)count, sizeof(*method_guards));
189
+ if (!guard_roots_registered) {
190
+ rb_gc_register_address(&constant_watchers);
191
+ rb_gc_register_address(&constant_vm);
192
+ rb_gc_register_address(&constant_epoch);
193
+ guard_roots_registered = true;
194
+ }
195
+ constant_watchers = watchers;
196
+ constant_vm = NIL_P(watchers) ? Qnil : vm;
197
+ constant_epoch = Qundef;
198
+ id_stat = rb_intern("stat");
199
+ id_constant_invalidations = rb_intern("constant_cache_invalidations");
200
+ if (first) {
201
+ for (long i = 0; i < count; i++) {
202
+ rb_gc_register_address(&method_guards[i].owner);
203
+ rb_gc_register_address(&method_guards[i].entry);
204
+ rb_gc_register_address(&method_guards[i].snapshot);
205
+ }
206
+ }
207
+ for (long i = 0; i < count; i++) {
208
+ VALUE spec = RARRAY_AREF(specifications, i);
209
+ native_method_guard_t *guard = &method_guards[i];
210
+ guard->owner = RARRAY_AREF(spec, 0);
211
+ guard->method = SYM2ID(RARRAY_AREF(spec, 1));
212
+ guard->receiver = NUM2INT(RARRAY_AREF(spec, 2));
213
+ guard->constant = RTEST(RARRAY_AREF(spec, 3));
214
+ guard->public_call = RTEST(RARRAY_AREF(spec, 6));
215
+ guard->builtin = !guard->constant && liquid_method_basic_definition_p(guard->owner, guard->method);
216
+ guard->snapshot = RARRAY_AREF(spec, 4);
217
+ guard->entry = guard->constant ? RARRAY_AREF(spec, 5) :
218
+ liquid_method_entry(guard->owner, guard->method);
219
+ if (!guard->constant && guard->owner == rb_cInteger && guard->method == rb_intern("to_i"))
220
+ integer_to_i_entry = guard->entry;
221
+ }
222
+ method_guard_count = count;
223
+ return Qtrue;
224
+ }
225
+
226
+ static bool native_method_guard_current(native_method_guard_t *guard)
227
+ {
228
+ VALUE current = liquid_method_entry(guard->owner, guard->method);
229
+ if (!guard->entry) return false;
230
+ if (guard->entry != current) {
231
+ // MRI can recreate inherited entries for an unchanged core constructor.
232
+ if (!guard->builtin || !liquid_method_basic_definition_p(guard->owner, guard->method)) return false;
233
+ guard->entry = current;
234
+ if (guard->owner == rb_cInteger && guard->method == rb_intern("to_i")) integer_to_i_entry = current;
235
+ }
236
+ return true;
237
+ }
238
+
239
+ static bool native_guards_match(VALUE context, VALUE variable, bool cached_constants)
240
+ {
241
+ VALUE scanner = rb_ivar_get(context, id_string_scanner);
242
+ VALUE receiver_classes[] = { Qnil, CLASS_OF(context), CLASS_OF(scanner), NIL_P(variable) ? Qnil : CLASS_OF(variable) };
243
+ for (long i = 0; i < method_guard_count; i++) {
244
+ native_method_guard_t *guard = &method_guards[i];
245
+ if (guard->constant) {
246
+ if (cached_constants) {
247
+ // Reader ISeqs are rooted in constant_watchers. MRI invalidates
248
+ // their registered IC sites even before they are read again.
249
+ // Mutable table slots must still be checked on every operation.
250
+ if (!native_snapshot_matches(guard->entry, guard->snapshot)) return false;
251
+ } else if (!RTEST(native_constant_matches(Qnil, guard->owner, ID2SYM(guard->method), guard->entry, guard->snapshot))) return false;
252
+ continue;
253
+ }
254
+ if (!native_method_guard_current(guard)) return false;
255
+ if (guard->public_call && rb_method_boundp(guard->owner, guard->method, 3) != 1) return false;
256
+ if (guard->receiver) {
257
+ if (guard->receiver == 3 && NIL_P(variable)) continue;
258
+ VALUE target_class = receiver_classes[guard->receiver];
259
+ if (guard->receiver == 2 && RB_OBJ_FROZEN(scanner)) return false;
260
+ // Standard receivers have the same class already checked above.
261
+ // Singleton classes still require their own current method lookup.
262
+ if (target_class != guard->owner &&
263
+ guard->entry != liquid_method_entry(target_class, guard->method)) return false;
264
+ }
265
+ }
266
+ return true;
267
+ }
268
+
269
+ static VALUE native_methods_compatible(VALUE self, VALUE context, VALUE variable)
270
+ {
271
+ VALUE epoch = native_constant_epoch();
272
+ if (!native_guards_match(context, variable, epoch != Qundef && epoch == constant_epoch)) return Qfalse;
273
+ if (epoch != Qundef && epoch != native_constant_epoch()) return Qfalse;
274
+ constant_epoch = epoch;
275
+ return Qtrue;
276
+ }
277
+ #endif
278
+
279
+ static bool native_conversion_is_standard(VALUE value)
280
+ {
281
+ VALUE klass = CLASS_OF(value);
282
+ if (!liquid_method_basic_definition_p(klass, rb_intern("respond_to?")) ||
283
+ !liquid_method_basic_definition_p(klass, rb_intern("respond_to_missing?")) ||
284
+ rb_method_boundp(klass, id_evaluate, 0)) return false;
285
+ if (liquid_method_basic_definition_p(klass, rb_intern("to_i"))) return true;
286
+ #ifdef HAVE_RB_CALLABLE_METHOD_ENTRY
287
+ return RB_INTEGER_TYPE_P(value) && integer_to_i_entry && integer_to_i_entry ==
288
+ liquid_method_entry(CLASS_OF(value), rb_intern("to_i"));
289
+ #else
290
+ return false;
291
+ #endif
292
+ }
293
+
294
+ static bool native_space(unsigned char c)
295
+ {
296
+ return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v';
297
+ }
298
+
299
+ static bool native_alpha(unsigned char c)
300
+ {
301
+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_';
302
+ }
303
+
304
+ static bool native_digit(unsigned char c) { return c >= '0' && c <= '9'; }
305
+
306
+ static void native_next(native_parser_t *p)
307
+ {
308
+ const unsigned char *s = (const unsigned char *)RSTRING_PTR(p->source);
309
+ size_t i = p->position, n = p->length;
310
+ while (i < n && native_space(s[i])) i++;
311
+ p->start = i;
312
+ if (i == n) { p->token = N_END; p->end = i; return; }
313
+ unsigned char c = s[i++];
314
+ p->token = c;
315
+ if (native_alpha(c)) {
316
+ while (i < n && (native_alpha(s[i]) || native_digit(s[i]) || s[i] == '-')) i++;
317
+ if (i < n && s[i] == '?') i++;
318
+ p->token = N_ID;
319
+ } else if (native_digit(c) || (c == '-' && i < n && native_digit(s[i]))) {
320
+ while (i < n && native_digit(s[i])) i++;
321
+ if (i + 1 < n && s[i] == '.' && native_digit(s[i + 1])) {
322
+ i++;
323
+ while (i < n && native_digit(s[i])) i++;
324
+ }
325
+ p->token = N_NUMBER;
326
+ } else if (c == '\'' || c == '"') {
327
+ while (i < n && s[i] != c) i++;
328
+ if (i == n) p->token = N_UNSUPPORTED;
329
+ else { i++; p->token = N_STRING; }
330
+ } else if (c == '.' && i < n && s[i] == '.') {
331
+ i++;
332
+ p->token = N_DOTDOT;
333
+ } else if (c == '<' || c == '>' || c == '=' || c == '!') {
334
+ if (i < n && (s[i] == '=' || (c == '<' && s[i] == '>'))) {
335
+ i++;
336
+ p->token = N_COMPARE;
337
+ } else p->token = c == '<' || c == '>' ? N_COMPARE : N_UNSUPPORTED;
338
+ } else if (c != '.' && c != '[' && c != ']' && c != '(' && c != ')' &&
339
+ c != '|' && c != ':' && c != ',') p->token = N_UNSUPPORTED;
340
+ p->end = p->position = i;
341
+ }
342
+
343
+ static VALUE native_slice(native_parser_t *p, size_t start, size_t end)
344
+ {
345
+ return rb_enc_str_new(RSTRING_PTR(p->source) + start, (long)(end - start), utf8_encoding);
346
+ }
347
+
348
+ static bool native_word_bytes(native_parser_t *p, const char *word, size_t length)
349
+ {
350
+ return p->end - p->start == length && !memcmp(RSTRING_PTR(p->source) + p->start, word, length);
351
+ }
352
+
353
+ // Every keyword at these call sites is a string literal. Keep its length at
354
+ // the call site even when the compiler chooses not to inline the comparison.
355
+ #define native_word(parser, literal) native_word_bytes((parser), (literal), sizeof(literal) - 1)
356
+
357
+ static VALUE native_key(native_parser_t *p, size_t start, size_t end)
358
+ {
359
+ VALUE key = rb_str_new(NULL, (long)(end - start));
360
+ // Reserve once, then copy without allocating while a pointer is in use.
361
+ char *out = RSTRING_PTR(key);
362
+ const char *source = RSTRING_PTR(p->source);
363
+ size_t written = 0;
364
+ char quote = 0;
365
+ for (size_t i = start; i < end; i++) {
366
+ char c = source[i];
367
+ if (quote || !native_space((unsigned char)c)) out[written++] = c;
368
+ if (quote == c) quote = 0;
369
+ else if (!quote && (c == '\'' || c == '"')) quote = c;
370
+ }
371
+ rb_str_set_len(key, (long)written);
372
+ rb_enc_associate(key, utf8_encoding);
373
+ return key;
374
+ }
375
+
376
+ // A finalizer can redefine a guarded method during allocation. Drop the pending
377
+ // parse before publishing cache entries or bytecode based on the old definition.
378
+ static bool native_gc_changed(const native_parser_t *p)
379
+ {
380
+ return p->guarded && p->initial_gc_count != liquid_gc_count();
381
+ }
382
+
383
+ static VALUE native_pending_lookup(const native_parser_t *p, VALUE key)
384
+ {
385
+ if (NIL_P(p->pending)) return Qundef;
386
+ if (p->compact_pending && RB_TYPE_P(p->pending, T_STRING)) {
387
+ if (RSTRING_LEN(key) == RSTRING_LEN(p->pending) &&
388
+ !memcmp(RSTRING_PTR(key), RSTRING_PTR(p->pending), (size_t)RSTRING_LEN(key))) return p->pending_value;
389
+ return Qundef;
390
+ }
391
+ return rb_hash_lookup2(p->pending, key, Qundef);
392
+ }
393
+
394
+ static VALUE native_cached(native_parser_t *p, size_t start, size_t end, VALUE value, VALUE cache_key)
395
+ {
396
+ if (native_gc_changed(p)) return Qundef;
397
+ rb_obj_freeze(value);
398
+ if (NIL_P(p->cache)) return value;
399
+ VALUE key = NIL_P(cache_key) ? native_key(p, start, end) : cache_key;
400
+ if (native_gc_changed(p)) return Qundef;
401
+ VALUE previous = rb_hash_lookup2(p->cache, key, Qundef);
402
+ if (previous != Qundef) return previous;
403
+ previous = native_pending_lookup(p, key);
404
+ if (previous != Qundef) return previous;
405
+ rb_obj_freeze(key);
406
+ // Most fused outputs introduce one cache entry. Keep its key and value
407
+ // on the parser stack; promote to a Hash for multiple distinct entries.
408
+ if (p->compact_pending && NIL_P(p->pending)) {
409
+ p->pending = key;
410
+ p->pending_value = value;
411
+ return value;
412
+ }
413
+ if (NIL_P(p->pending) || (p->compact_pending && RB_TYPE_P(p->pending, T_STRING))) {
414
+ VALUE previous_key = p->pending;
415
+ p->pending = rb_hash_new();
416
+ if (!NIL_P(previous_key)) {
417
+ if (native_gc_changed(p)) return Qundef;
418
+ rb_hash_aset(p->pending, previous_key, p->pending_value);
419
+ }
420
+ RB_GC_GUARD(previous_key);
421
+ }
422
+ if (native_gc_changed(p)) return Qundef;
423
+ rb_hash_aset(p->pending, key, value);
424
+ return value;
425
+ }
426
+
427
+ static VALUE native_object_alloc(VALUE klass)
428
+ {
429
+ if (rb_get_alloc_func(klass) != rb_get_alloc_func(rb_cObject)) return Qundef;
430
+ return rb_obj_alloc(klass);
431
+ }
432
+
433
+ // Cached expressions retain their identity and may have been edited by a tag.
434
+ // Only the ordinary, currently guarded expression classes can be inlined.
435
+ static bool native_compile_cached(vm_assembler_t *code, VALUE value, size_t gc)
436
+ {
437
+ if (gc != liquid_gc_count()) return false;
438
+ if (liquid_stack_check()) rb_raise(rb_eSysStackError, "stack level too deep");
439
+ if (CLASS_OF(value) == cLiquidVariableLookup) {
440
+ VALUE name = rb_ivar_get(value, id_name);
441
+ VALUE lookups = rb_ivar_get(value, id_lookups);
442
+ VALUE commands = rb_ivar_get(value, id_commands);
443
+ if (CLASS_OF(lookups) != rb_cArray || !RB_FIXNUM_P(commands) || RARRAY_LEN(lookups) > 60 || RARRAY_LEN(lookups) > (long)(sizeof(unsigned long) * CHAR_BIT)) return false;
444
+ if (CLASS_OF(name) == rb_cString) vm_assembler_add_find_static_variable(code, name);
445
+ else {
446
+ if (!native_compile_cached(code, name, gc)) return false;
447
+ vm_assembler_add_find_variable(code);
448
+ }
449
+ size_t guards[60];
450
+ long count = RARRAY_LEN(lookups);
451
+ for (long i = 0; i < count; i++) {
452
+ if (gc != liquid_gc_count()) return false;
453
+ VALUE key = RARRAY_AREF(lookups, i);
454
+ if (((unsigned long)FIX2LONG(commands) >> i) & 1) {
455
+ if (CLASS_OF(key) != rb_cString) return false;
456
+ vm_assembler_add_lookup_command(code, key);
457
+ } else if (CLASS_OF(key) == rb_cString) vm_assembler_add_lookup_const_key(code, key);
458
+ else {
459
+ if (!native_compile_cached(code, key, gc)) return false;
460
+ vm_assembler_add_lookup_key(code);
461
+ }
462
+ if (i + 1 < count) guards[i] = vm_assembler_add_lookup_guard(code);
463
+ }
464
+ for (long i = 0; i + 1 < count; i++) vm_assembler_patch_lookup_guard(code, guards[i]);
465
+ return true;
466
+ }
467
+ if (CLASS_OF(value) == cLiquidRangeLookup) {
468
+ if (!native_compile_cached(code, rb_ivar_get(value, id_start), gc) ||
469
+ !native_compile_cached(code, rb_ivar_get(value, id_end), gc)) return false;
470
+ vm_assembler_add_new_int_range(code);
471
+ return true;
472
+ }
473
+ if (NIL_P(value) || value == Qtrue || value == Qfalse || RB_INTEGER_TYPE_P(value) ||
474
+ CLASS_OF(value) == rb_cString || CLASS_OF(value) == rb_cFloat || CLASS_OF(value) == rb_cRange) {
475
+ // A cached literal with an evaluate/compile hook is observable too.
476
+ if (rb_method_boundp(CLASS_OF(value), id_compile_evaluate, 0) ||
477
+ rb_method_boundp(CLASS_OF(value), id_evaluate, 0)) return false;
478
+ vm_assembler_add_push_literal(code, value);
479
+ return true;
480
+ }
481
+ return false;
482
+ }
483
+
484
+ static VALUE native_expression(native_parser_t *p);
485
+
486
+ static bool native_validate_expression(native_parser_t *p)
487
+ {
488
+ if (liquid_stack_check()) {
489
+ if (p->code) return false;
490
+ rb_raise(rb_eSysStackError, "stack level too deep");
491
+ }
492
+ if (p->token == N_NUMBER || p->token == N_STRING) { native_next(p); return true; }
493
+ if (p->token == '(') {
494
+ native_next(p);
495
+ if (!native_validate_expression(p) || p->token != N_DOTDOT) return false;
496
+ native_next(p);
497
+ if (!native_validate_expression(p) || p->token != ')') return false;
498
+ native_next(p);
499
+ return true;
500
+ }
501
+ if (p->token == N_ID) {
502
+ if (native_word(p, "contains")) return false;
503
+ native_next(p);
504
+ } else if (p->token == '[') {
505
+ native_next(p);
506
+ if (!native_validate_expression(p) || p->token != ']') return false;
507
+ native_next(p);
508
+ } else return false;
509
+ size_t lookups = 0;
510
+ while (p->token == '.' || p->token == '[') {
511
+ if (p->code && ++lookups > 60) return false;
512
+ bool dot = p->token == '.';
513
+ native_next(p);
514
+ if (dot) {
515
+ if (p->token != N_ID) return false;
516
+ } else if (!native_validate_expression(p) || p->token != ']') return false;
517
+ native_next(p);
518
+ }
519
+ return true;
520
+ }
521
+
522
+ static bool native_validate_variable(native_parser_t *p, native_parser_t *name)
523
+ {
524
+ native_next(p);
525
+ if (p->token != N_END && !native_validate_expression(p)) return false;
526
+ if (name) *name = *p;
527
+ while (p->token == '|') {
528
+ native_next(p);
529
+ if (p->token != N_ID || native_word(p, "contains")) return false;
530
+ native_next(p);
531
+ if (p->token == ':') {
532
+ native_next(p);
533
+ while (true) {
534
+ if (p->token == N_ID) {
535
+ native_parser_t saved = *p;
536
+ native_next(p);
537
+ if (p->token == ':') native_next(p);
538
+ else *p = saved;
539
+ }
540
+ if (!native_validate_expression(p)) return false;
541
+ if (p->token != ',') break;
542
+ native_next(p);
543
+ }
544
+ }
545
+ }
546
+ return p->token == N_END;
547
+ }
548
+
549
+ static VALUE native_expression_probed(native_parser_t *p, const native_parser_t *validated, VALUE cache_key);
550
+
551
+ static VALUE native_expression(native_parser_t *p)
552
+ {
553
+ return native_expression_probed(p, NULL, Qnil);
554
+ }
555
+
556
+ static VALUE native_expression_probed(native_parser_t *p, const native_parser_t *validated, VALUE cache_key)
557
+ {
558
+ if (liquid_stack_check()) rb_raise(rb_eSysStackError, "stack level too deep");
559
+ size_t start = p->start;
560
+ if (!NIL_P(p->cache) && (p->token == N_ID || p->token == N_NUMBER || p->token == '(' || p->token == '[')) {
561
+ bool literal = p->token == N_ID && (native_word(p, "nil") || native_word(p, "null") ||
562
+ native_word(p, "true") || native_word(p, "false") || native_word(p, "blank") || native_word(p, "empty"));
563
+ if (!literal) {
564
+ native_parser_t probe = validated ? *validated : *p;
565
+ if (validated || native_validate_expression(&probe)) {
566
+ VALUE key = NIL_P(cache_key) ? native_key(p, start, probe.start) : cache_key;
567
+ cache_key = key;
568
+ if (native_gc_changed(p)) return Qundef;
569
+ VALUE found = rb_hash_lookup2(p->cache, key, Qundef);
570
+ if (found == Qundef) found = native_pending_lookup(p, key);
571
+ if (found != Qundef) {
572
+ if (p->code && !native_compile_cached(p->code, found, p->initial_gc_count)) return Qundef;
573
+ *p = probe;
574
+ return found;
575
+ }
576
+ }
577
+ }
578
+ }
579
+ if (p->token == N_STRING) {
580
+ VALUE value = native_slice(p, start + 1, p->end - 1);
581
+ native_next(p);
582
+ if (p->code) vm_assembler_add_push_literal(p->code, value);
583
+ return value;
584
+ }
585
+ if (p->token == N_NUMBER) {
586
+ VALUE text = native_slice(p, start, p->end);
587
+ bool floating = memchr(RSTRING_PTR(text), '.', RSTRING_LEN(text)) != NULL;
588
+ if (floating && RSTRING_LEN(text) > 64) return Qundef;
589
+ if (!floating && !liquid_method_basic_definition_p(
590
+ CLASS_OF(native_expression_class), rb_intern("Integer"))) return Qundef;
591
+ VALUE value = floating ?
592
+ DBL2NUM(liquid_str_to_dbl(text, 1)) : rb_str_to_inum(text, 10, 1);
593
+ size_t end = p->end;
594
+ native_next(p);
595
+ value = native_cached(p, start, end, value, cache_key);
596
+ if (value == Qundef) return Qundef;
597
+ if (p->code && !native_compile_cached(p->code, value, p->initial_gc_count)) return Qundef;
598
+ return value;
599
+ }
600
+ if (p->token == '(') {
601
+ vm_assembler_t *code = p->code;
602
+ p->code = NULL;
603
+ native_next(p);
604
+ VALUE first = native_expression(p);
605
+ if (first == Qundef || p->token != N_DOTDOT) return Qundef;
606
+ native_next(p);
607
+ VALUE last = native_expression(p);
608
+ if (last == Qundef || p->token != ')') return Qundef;
609
+ size_t end = p->end;
610
+ native_next(p);
611
+ VALUE range;
612
+ if (rb_obj_is_kind_of(first, cLiquidVariableLookup) || rb_obj_is_kind_of(first, cLiquidRangeLookup) ||
613
+ rb_obj_is_kind_of(last, cLiquidVariableLookup) || rb_obj_is_kind_of(last, cLiquidRangeLookup)) {
614
+ if (!liquid_method_basic_definition_p(CLASS_OF(first), rb_intern("respond_to?")) ||
615
+ !liquid_method_basic_definition_p(CLASS_OF(last), rb_intern("respond_to?"))) return Qundef;
616
+ bool first_evaluates = rb_method_boundp(CLASS_OF(first), id_evaluate, 1);
617
+ bool last_evaluates = rb_method_boundp(CLASS_OF(last), id_evaluate, 1);
618
+ if (!first_evaluates && !last_evaluates) return Qundef;
619
+ if (!first_evaluates && !liquid_method_basic_definition_p(CLASS_OF(first), rb_intern("respond_to_missing?"))) return Qundef;
620
+ range = rb_obj_alloc(cLiquidRangeLookup);
621
+ rb_ivar_set(range, id_start, first);
622
+ rb_ivar_set(range, id_end, last);
623
+ } else if ((RB_INTEGER_TYPE_P(first) || RB_TYPE_P(first, T_FLOAT) || RB_TYPE_P(first, T_STRING)) &&
624
+ (RB_INTEGER_TYPE_P(last) || RB_TYPE_P(last, T_FLOAT) || RB_TYPE_P(last, T_STRING))) {
625
+ if (!native_conversion_is_standard(first) || !native_conversion_is_standard(last)) return Qundef;
626
+ VALUE begin = RB_INTEGER_TYPE_P(first) ? first : (RB_TYPE_P(first, T_STRING) ?
627
+ rb_str_to_inum(first, 10, 0) : rb_dbl2big(RFLOAT_VALUE(first)));
628
+ VALUE end_value = RB_INTEGER_TYPE_P(last) ? last : (RB_TYPE_P(last, T_STRING) ?
629
+ rb_str_to_inum(last, 10, 0) : rb_dbl2big(RFLOAT_VALUE(last)));
630
+ range = rb_range_new(begin, end_value, false);
631
+ } else return Qundef;
632
+ range = native_cached(p, start, end, range, cache_key);
633
+ p->code = code;
634
+ if (range == Qundef) return Qundef;
635
+ if (code && !native_compile_cached(code, range, p->initial_gc_count)) return Qundef;
636
+ return range;
637
+ }
638
+ VALUE name;
639
+ bool literal = false;
640
+ VALUE literal_value = Qnil;
641
+ if (p->token == N_ID) {
642
+ if (native_word(p, "contains")) return Qundef;
643
+ if (native_word(p, "nil") || native_word(p, "null")) literal = true;
644
+ else if (native_word(p, "true")) { literal = true; literal_value = Qtrue; }
645
+ else if (native_word(p, "false")) { literal = true; literal_value = Qfalse; }
646
+ else if (native_word(p, "blank") || native_word(p, "empty")) {
647
+ literal = true;
648
+ VALUE literals = native_literals;
649
+ if (!RB_TYPE_P(literals, T_HASH)) return Qundef;
650
+ literal_value = rb_hash_lookup2(literals, native_slice(p, start, p->end), Qundef);
651
+ if (literal_value == Qundef) return Qundef;
652
+ }
653
+ name = native_slice(p, start, p->end);
654
+ native_next(p);
655
+ if (literal && p->token != '.' && p->token != '[') {
656
+ if (p->code && !native_compile_cached(p->code, literal_value, p->initial_gc_count)) return Qundef;
657
+ return literal_value;
658
+ }
659
+ if (p->code) vm_assembler_add_find_static_variable(p->code, name);
660
+ } else if (p->token == '[') {
661
+ native_next(p);
662
+ name = native_expression(p);
663
+ if (name == Qundef || p->token != ']') return Qundef;
664
+ native_next(p);
665
+ if (p->code) vm_assembler_add_find_variable(p->code);
666
+ } else return Qundef;
667
+
668
+ VALUE lookups = rb_ary_new();
669
+ VALUE commands = INT2FIX(0);
670
+ size_t guards[60], guard_count = 0;
671
+ while (p->token == '.' || p->token == '[') {
672
+ bool command = p->token == '.';
673
+ bool command_key = false;
674
+ native_next(p);
675
+ VALUE key;
676
+ if (command) {
677
+ if (p->token != N_ID) return Qundef;
678
+ if (native_word(p, "size") || native_word(p, "first") || native_word(p, "last")) {
679
+ command_key = true;
680
+ size_t index = (size_t)RARRAY_LEN(lookups);
681
+ VALUE bit = index < sizeof(unsigned long) * CHAR_BIT - 2 ? ULONG2NUM(1UL << index) :
682
+ liquid_big_lshift(rb_uint2big(1), SIZET2NUM(index));
683
+ if (RB_FIXNUM_P(commands) && RB_FIXNUM_P(bit)) commands = LONG2FIX(FIX2LONG(commands) | FIX2LONG(bit));
684
+ else commands = liquid_big_or(RB_FIXNUM_P(commands) ? rb_int2big(FIX2LONG(commands)) : commands, bit);
685
+ }
686
+ key = native_slice(p, p->start, p->end);
687
+ native_next(p);
688
+ if (p->code) {
689
+ if (command_key) vm_assembler_add_lookup_command(p->code, key);
690
+ else vm_assembler_add_lookup_const_key(p->code, key);
691
+ }
692
+ } else {
693
+ key = native_expression(p);
694
+ if (key == Qundef || p->token != ']') return Qundef;
695
+ native_next(p);
696
+ if (p->code) vm_assembler_add_lookup_key(p->code);
697
+ }
698
+ rb_ary_push(lookups, key);
699
+ if (p->code && (p->token == '.' || p->token == '[')) {
700
+ if (guard_count == 60) return Qundef;
701
+ guards[guard_count++] = vm_assembler_add_lookup_guard(p->code);
702
+ }
703
+ }
704
+ if (p->code)
705
+ for (size_t i = 0; i < guard_count; i++) vm_assembler_patch_lookup_guard(p->code, guards[i]);
706
+ VALUE value = rb_obj_alloc(cLiquidVariableLookup);
707
+ rb_ivar_set(value, id_name, name);
708
+ rb_ivar_set(value, id_lookups, lookups);
709
+ rb_ivar_set(value, id_commands, commands);
710
+ return native_cached(p, start, p->start, value, cache_key);
711
+ }
712
+
713
+ static bool native_comparison(native_parser_t *p)
714
+ {
715
+ return p->token == N_COMPARE || (p->token == N_ID && native_word(p, "contains"));
716
+ }
717
+
718
+ static bool native_validate_comparison(native_parser_t *p)
719
+ {
720
+ if (!native_validate_expression(p)) return false;
721
+ if (native_comparison(p)) {
722
+ native_next(p);
723
+ if (!native_validate_expression(p)) return false;
724
+ }
725
+ return true;
726
+ }
727
+
728
+ static int native_cache_key(VALUE key, VALUE value, VALUE opaque)
729
+ {
730
+ if (!RB_TYPE_P(key, T_STRING) || CLASS_OF(key) != rb_cString) {
731
+ *(bool *)opaque = false;
732
+ return ST_STOP;
733
+ }
734
+ return ST_CONTINUE;
735
+ }
736
+
737
+ static bool native_string_cache(VALUE cache)
738
+ {
739
+ if (!native_normal_hash(cache)) return false;
740
+ bool safe = true;
741
+ rb_hash_foreach(cache, native_cache_key, (VALUE)&safe);
742
+ return safe;
743
+ }
744
+
745
+ static VALUE native_condition_expression(native_parser_t *p)
746
+ {
747
+ native_parser_t probe = *p;
748
+ if (!native_validate_expression(&probe)) return Qundef;
749
+ VALUE literals = p->condition_literals;
750
+ if (!p->literals_checked) {
751
+ VALUE condition = native_condition_class;
752
+ if (!rb_cvar_defined(condition, rb_intern("@@method_literals"))) return Qundef;
753
+ literals = rb_cvar_get(condition, rb_intern("@@method_literals"));
754
+ if (!native_string_cache(literals) || !liquid_method_basic_definition_p(rb_cHash, rb_intern("[]"))) return Qundef;
755
+ VALUE default_proc = native_hash_property(literals, HASH_DEFAULT_PROC_READER);
756
+ VALUE default_value = native_hash_property(literals, HASH_DEFAULT_READER);
757
+ if (!NIL_P(default_proc) || !NIL_P(default_value)) return Qundef;
758
+ p->condition_literals = literals;
759
+ p->literals_checked = true;
760
+ }
761
+ probe.condition_literals = p->condition_literals;
762
+ probe.literals_checked = p->literals_checked;
763
+ VALUE key = native_key(p, p->start, probe.start);
764
+ if (liquid_gc_count() != p->initial_gc_count) return Qundef;
765
+ VALUE literal = rb_hash_lookup2(literals, key, Qnil);
766
+ if (RTEST(literal)) { *p = probe; return literal; }
767
+ return native_expression_probed(p, &probe, key);
768
+ }
769
+
770
+ static VALUE native_condition_node(native_parser_t *p)
771
+ {
772
+ VALUE left = native_condition_expression(p), right = Qnil, op = Qnil;
773
+ if (left == Qundef) return Qundef;
774
+ if (native_comparison(p)) {
775
+ op = rb_str_to_interned_str(native_slice(p, p->start, p->end));
776
+ native_next(p);
777
+ right = native_condition_expression(p);
778
+ if (right == Qundef) return Qundef;
779
+ }
780
+ VALUE node = native_object_alloc(native_condition_class);
781
+ if (node == Qundef) return Qundef;
782
+ rb_ivar_set(node, rb_intern("@left"), left);
783
+ rb_ivar_set(node, rb_intern("@operator"), op);
784
+ rb_ivar_set(node, rb_intern("@right"), right);
785
+ rb_ivar_set(node, rb_intern("@child_relation"), Qnil);
786
+ rb_ivar_set(node, rb_intern("@child_condition"), Qnil);
787
+ return node;
788
+ }
789
+
790
+ static VALUE native_condition_body(native_parser_t *p)
791
+ {
792
+ native_parser_t probe = *p;
793
+ native_next(&probe);
794
+ if (!native_validate_comparison(&probe)) return Qnil;
795
+ while (probe.token == N_ID && (native_word(&probe, "and") || native_word(&probe, "or"))) {
796
+ native_next(&probe);
797
+ if (!native_validate_comparison(&probe)) return Qnil;
798
+ }
799
+ if (probe.token != N_END) return Qnil;
800
+ if (!p->guarded) p->pending = rb_hash_new();
801
+ native_next(p);
802
+ VALUE root = native_condition_node(p), current = root;
803
+ if (root == Qundef) return Qnil;
804
+ while (p->token == N_ID && (native_word(p, "and") || native_word(p, "or"))) {
805
+ VALUE relation = ID2SYM(rb_intern(native_word(p, "and") ? "and" : "or"));
806
+ native_next(p);
807
+ VALUE child = native_condition_node(p);
808
+ if (child == Qundef) return Qnil;
809
+ rb_ivar_set(current, rb_intern("@child_relation"), relation);
810
+ rb_ivar_set(current, rb_intern("@child_condition"), child);
811
+ current = child;
812
+ }
813
+ return rb_ary_new_from_args(2, root, p->pending);
814
+ }
815
+
816
+ static bool native_validate_for(native_parser_t *p)
817
+ {
818
+ native_next(p);
819
+ if (p->token != N_ID || native_word(p, "contains")) return false;
820
+ native_next(p);
821
+ if (p->token != N_ID || !native_word(p, "in")) return false;
822
+ native_next(p);
823
+ if (!native_validate_expression(p)) return false;
824
+ if (p->token == N_ID && native_word(p, "reversed")) native_next(p);
825
+ while (p->token == ',' || p->token == N_ID) {
826
+ if (p->token == ',') native_next(p);
827
+ if (p->token != N_ID || (!native_word(p, "offset") && !native_word(p, "limit"))) return false;
828
+ native_next(p);
829
+ if (p->token != ':') return false;
830
+ native_next(p);
831
+ if (!native_validate_expression(p)) return false;
832
+ }
833
+ return p->token == N_END;
834
+ }
835
+
836
+ static VALUE native_for_body(native_parser_t *p)
837
+ {
838
+ native_parser_t probe = *p;
839
+ if (!native_validate_for(&probe)) return Qnil;
840
+ if (!p->guarded) p->pending = rb_hash_new();
841
+ native_next(p);
842
+ VALUE variable = native_slice(p, p->start, p->end);
843
+ native_next(p); // in
844
+ native_next(p);
845
+ size_t start = p->start;
846
+ VALUE collection = native_expression(p);
847
+ if (collection == Qundef) return Qnil;
848
+ VALUE markup = native_key(p, start, p->start);
849
+ VALUE name = rb_str_dup(variable);
850
+ rb_str_cat_cstr(name, "-");
851
+ rb_str_append(name, markup);
852
+ VALUE reversed = Qfalse, from = Qnil, limit = Qnil;
853
+ if (p->token == N_ID && native_word(p, "reversed")) {
854
+ reversed = native_slice(p, p->start, p->end);
855
+ native_next(p);
856
+ }
857
+ while (p->token != N_END) {
858
+ if (p->token == ',') native_next(p);
859
+ bool offset = native_word(p, "offset");
860
+ native_next(p); // colon
861
+ native_next(p);
862
+ VALUE value;
863
+ probe = *p;
864
+ bool continuation = offset && p->token == N_ID && native_word(p, "continue");
865
+ native_next(&probe);
866
+ if (continuation && probe.token != '.' && probe.token != '[') {
867
+ value = ID2SYM(rb_intern("continue"));
868
+ *p = probe;
869
+ } else value = native_expression(p);
870
+ if (value == Qundef) return Qnil;
871
+ if (offset) from = value;
872
+ else limit = value;
873
+ }
874
+ VALUE fields = rb_ary_new_from_args(6, variable, collection, name, reversed, from, limit);
875
+ return rb_ary_new_from_args(2, fields, p->pending);
876
+ }
877
+
878
+ static VALUE native_single_expression_body(native_parser_t *p)
879
+ {
880
+ native_parser_t probe = *p;
881
+ native_next(&probe);
882
+ if (!native_validate_expression(&probe) || probe.token != N_END) return Qnil;
883
+ if (!p->guarded) p->pending = rb_hash_new();
884
+ native_next(p);
885
+ VALUE expression = native_expression(p);
886
+ if (expression == Qundef) return Qnil;
887
+ return rb_ary_new_from_args(2, expression, p->pending);
888
+ }
889
+
890
+ static bool native_validate_include(native_parser_t *p)
891
+ {
892
+ native_next(p);
893
+ if (!native_validate_expression(p)) return false;
894
+ if (p->token == N_ID && (native_word(p, "with") || native_word(p, "for"))) {
895
+ native_next(p);
896
+ if (!native_validate_expression(p)) return false;
897
+ }
898
+ if (p->token == N_ID && native_word(p, "as")) {
899
+ native_next(p);
900
+ if (p->token != N_ID || native_word(p, "contains")) return false;
901
+ native_next(p);
902
+ }
903
+ if (p->token == ',') native_next(p);
904
+ while (p->token == N_ID && !native_word(p, "contains")) {
905
+ native_next(p);
906
+ if (p->token != ':') return false;
907
+ native_next(p);
908
+ if (!native_validate_expression(p)) return false;
909
+ if (p->token == ',') native_next(p);
910
+ }
911
+ return p->token == N_END;
912
+ }
913
+
914
+ static VALUE native_include_body(native_parser_t *p)
915
+ {
916
+ native_parser_t probe = *p;
917
+ if (!native_validate_include(&probe)) return Qnil;
918
+ native_next(p);
919
+ VALUE template = native_expression(p);
920
+ if (template == Qundef) return Qnil;
921
+ VALUE variable = Qnil, alias = Qnil, is_for = Qfalse;
922
+ bool has_variable = false;
923
+ if (p->token == N_ID && (native_word(p, "with") || native_word(p, "for"))) {
924
+ is_for = native_word(p, "for") ? Qtrue : Qfalse;
925
+ has_variable = true;
926
+ native_next(p);
927
+ variable = native_expression(p);
928
+ if (variable == Qundef) return Qnil;
929
+ }
930
+ if (p->token == N_ID && native_word(p, "as")) {
931
+ native_next(p);
932
+ alias = native_slice(p, p->start, p->end);
933
+ native_next(p);
934
+ }
935
+ if (p->token == ',') native_next(p);
936
+ VALUE attributes = rb_hash_new();
937
+ while (p->token != N_END) {
938
+ VALUE key = native_slice(p, p->start, p->end);
939
+ native_next(p); // colon
940
+ native_next(p);
941
+ VALUE value = native_expression(p);
942
+ if (value == Qundef || native_gc_changed(p)) return Qnil;
943
+ rb_hash_aset(attributes, key, value);
944
+ if (p->token == ',') native_next(p);
945
+ }
946
+ VALUE fields = rb_ary_new_from_args(6, template, variable, alias, is_for, attributes, has_variable ? Qtrue : Qfalse);
947
+ return rb_ary_new_from_args(2, fields, p->pending);
948
+ }
949
+
950
+ #ifdef LIQUID_C_TEST_ALLOC_FAILURES
951
+ static VALUE native_parser_test_callback = Qnil;
952
+ static VALUE native_set_parser_test_callback(VALUE self, VALUE callback)
953
+ {
954
+ if (!NIL_P(callback) && !rb_obj_is_proc(callback)) rb_raise(rb_eTypeError, "expected Proc or nil");
955
+ native_parser_test_callback = callback;
956
+ return callback;
957
+ }
958
+ #endif
959
+
960
+ typedef struct { vm_assembler_t *code; bool valid; size_t gc; } native_keyword_compile_t;
961
+
962
+ static int native_compile_keyword(VALUE key, VALUE value, VALUE opaque)
963
+ {
964
+ native_keyword_compile_t *compile = (void *)opaque;
965
+ compile->valid = native_compile_cached(compile->code, key, compile->gc) && native_compile_cached(compile->code, value, compile->gc);
966
+ return compile->valid ? ST_CONTINUE : ST_STOP;
967
+ }
968
+
969
+ static VALUE native_variable_body_probed(VALUE opaque, const native_parser_t *validated_name)
970
+ {
971
+ #ifdef LIQUID_C_TEST_ALLOC_FAILURES
972
+ if (!NIL_P(native_parser_test_callback)) {
973
+ VALUE callback = native_parser_test_callback;
974
+ native_parser_test_callback = Qnil;
975
+ rb_proc_call(callback, rb_ary_new());
976
+ RB_GC_GUARD(callback);
977
+ }
978
+ #endif
979
+ native_parser_t *p = (void *)opaque;
980
+ if (p->operation == 1) return native_condition_body(p);
981
+ if (p->operation == 2) return native_for_body(p);
982
+ if (p->operation == 3) return native_single_expression_body(p);
983
+ if (p->operation == 4) return native_include_body(p);
984
+ native_parser_t probe = *p;
985
+ if (!p->code && !native_validate_variable(&probe, NULL)) return Qnil;
986
+ if (!p->code) p->pending = rb_hash_new();
987
+ native_next(p);
988
+ bool empty = p->token == N_END;
989
+ VALUE name = empty ? Qnil : native_expression_probed(p, validated_name, Qnil);
990
+ if (name == Qundef) return Qnil;
991
+ if (p->code && empty) vm_assembler_add_push_nil(p->code);
992
+ VALUE filters = p->code ? Qnil : rb_ary_new();
993
+ while (p->token == '|') {
994
+ native_next(p);
995
+ if (p->token != N_ID || native_word(p, "contains")) return Qnil;
996
+ VALUE filter_name;
997
+ if (p->code) {
998
+ // Preserve collectable symbols for names absent from the method table.
999
+ filter_name = rb_check_symbol_cstr(RSTRING_PTR(p->source) + p->start,
1000
+ (long)(p->end - p->start), utf8_encoding);
1001
+ if (NIL_P(filter_name)) filter_name = rb_str_intern(native_slice(p, p->start, p->end));
1002
+ } else filter_name = native_slice(p, p->start, p->end);
1003
+ native_next(p);
1004
+ VALUE args = p->code ? Qnil : rb_ary_new(), kwargs = Qnil;
1005
+ long count = 0, filter_offset = 0;
1006
+ if (p->code) {
1007
+ if (NIL_P(filters)) filters = rb_ary_new();
1008
+ filter_offset = RARRAY_LEN(filters);
1009
+ rb_ary_push(filters, filter_name);
1010
+ rb_ary_push(filters, Qnil);
1011
+ rb_ary_push(filters, Qnil);
1012
+ }
1013
+ if (p->token == ':') {
1014
+ native_next(p);
1015
+ while (true) {
1016
+ VALUE keyword = Qnil;
1017
+ if (p->token == N_ID) {
1018
+ native_parser_t saved = *p;
1019
+ native_next(p);
1020
+ if (p->token == ':') {
1021
+ keyword = native_slice(p, saved.start, saved.end);
1022
+ native_next(p);
1023
+ }
1024
+ else { *p = saved; keyword = Qnil; }
1025
+ }
1026
+ vm_assembler_t *code = p->code;
1027
+ if (!NIL_P(keyword)) p->code = NULL;
1028
+ VALUE arg = native_expression(p);
1029
+ p->code = code;
1030
+ if (arg == Qundef) return Qnil;
1031
+ if (NIL_P(keyword)) {
1032
+ rb_ary_push(p->code ? filters : args, arg);
1033
+ count++;
1034
+ }
1035
+ else {
1036
+ if (NIL_P(kwargs)) kwargs = rb_hash_new();
1037
+ if (native_gc_changed(p)) return Qnil;
1038
+ rb_hash_aset(kwargs, keyword, arg);
1039
+ }
1040
+ if (p->token != ',') break;
1041
+ native_next(p);
1042
+ }
1043
+ }
1044
+ if (p->code) {
1045
+ long argc = count;
1046
+ if (argc + (NIL_P(kwargs) ? 0 : 1) > 254 || (!NIL_P(kwargs) && RHASH_SIZE(kwargs) > 255)) return Qnil;
1047
+ if (!NIL_P(kwargs)) {
1048
+ native_keyword_compile_t compile = { p->code, true, p->initial_gc_count };
1049
+ rb_hash_foreach(kwargs, native_compile_keyword, (VALUE)&compile);
1050
+ if (!compile.valid) return Qnil;
1051
+ vm_assembler_add_hash_new(p->code, RHASH_SIZE(kwargs));
1052
+ argc++;
1053
+ }
1054
+ vm_assembler_add_filter(p->code, filter_name, (size_t)argc);
1055
+ }
1056
+ if (p->code) {
1057
+ rb_ary_store(filters, filter_offset + 1, LONG2NUM(count));
1058
+ rb_ary_store(filters, filter_offset + 2, kwargs);
1059
+ } else {
1060
+ VALUE filter = rb_ary_new_from_args(2, filter_name, args);
1061
+ if (!NIL_P(kwargs)) rb_ary_push(filter, kwargs);
1062
+ rb_ary_push(filters, filter);
1063
+ }
1064
+ }
1065
+ if (p->token != N_END) return Qnil;
1066
+ if (p->code) {
1067
+ p->variable_name = name;
1068
+ p->variable_filters = filters;
1069
+ return Qtrue;
1070
+ }
1071
+ return rb_ary_new_from_args(3, name, filters, p->pending);
1072
+ }
1073
+
1074
+ static VALUE native_variable_body(VALUE opaque)
1075
+ {
1076
+ return native_variable_body_probed(opaque, NULL);
1077
+ }
1078
+
1079
+ static VALUE native_variable_unpin(VALUE opaque)
1080
+ {
1081
+ native_parser_t *p = (void *)opaque;
1082
+ rb_gc_unregister_address(&p->source);
1083
+ return Qnil;
1084
+ }
1085
+
1086
+ static bool native_payload_methods_standard(int operation)
1087
+ {
1088
+ if (!native_primitives_standard(true)) return false;
1089
+ VALUE constructors[] = { cLiquidVariableLookup, cLiquidRangeLookup, native_parser_class };
1090
+ for (size_t i = 0; i < sizeof(constructors) / sizeof(constructors[0]); i++) {
1091
+ VALUE owner = CLASS_OF(constructors[i]);
1092
+ if (!RB_TYPE_P(constructors[i], T_CLASS) ||
1093
+ rb_get_alloc_func(constructors[i]) != rb_get_alloc_func(rb_cObject) ||
1094
+ !liquid_method_basic_definition_p(owner, id_new_native) ||
1095
+ !liquid_method_basic_definition_p(owner, id_allocate_native)) return false;
1096
+ }
1097
+ if (operation == 1) {
1098
+ if (!RB_TYPE_P(native_condition_class, T_CLASS) ||
1099
+ rb_get_alloc_func(native_condition_class) != rb_get_alloc_func(rb_cObject)) return false;
1100
+ VALUE owner = CLASS_OF(native_condition_class);
1101
+ if (!liquid_method_basic_definition_p(owner, id_new_native) ||
1102
+ !liquid_method_basic_definition_p(owner, id_allocate_native)) return false;
1103
+ }
1104
+ return true;
1105
+ }
1106
+
1107
+ static VALUE native_parse_payload(VALUE markup, VALUE cache, int operation, bool checked_cache, bool checked_methods, variable_compile_guard_t *guard)
1108
+ {
1109
+ if (!RB_TYPE_P(markup, T_STRING) || CLASS_OF(markup) != rb_cString ||
1110
+ rb_enc_get_index(markup) != utf8_encoding_index) return Qnil;
1111
+ size_t before_gc = liquid_gc_count();
1112
+ if (!checked_methods && !native_payload_methods_standard(operation)) return Qnil;
1113
+ if (rb_enc_str_coderange(markup) == ENC_CODERANGE_BROKEN) return Qnil;
1114
+ if (!checked_methods && !NIL_P(cache) && (!RB_TYPE_P(cache, T_HASH) ||
1115
+ !liquid_method_basic_definition_p(CLASS_OF(cache), rb_intern("[]")) ||
1116
+ !liquid_method_basic_definition_p(CLASS_OF(cache), rb_intern("[]=")) ||
1117
+ !liquid_method_basic_definition_p(CLASS_OF(cache), rb_intern("key?")))) return Qnil;
1118
+ if (!NIL_P(cache) && !checked_cache && !native_string_cache(cache)) return Qnil;
1119
+ native_parser_t parser = { .cache = cache, .pending = Qnil, .operation = operation,
1120
+ .initial_gc_count = before_gc, .guarded = checked_methods };
1121
+ if (guard && guard->literals_checked) {
1122
+ parser.condition_literals = guard->condition_literals;
1123
+ parser.literals_checked = true;
1124
+ }
1125
+ parser.source = rb_str_dup_frozen(markup);
1126
+ if (rb_enc_get_index(parser.source) != utf8_encoding_index ||
1127
+ rb_enc_str_coderange(parser.source) == ENC_CODERANGE_BROKEN) return Qnil;
1128
+ parser.length = (size_t)RSTRING_LEN(parser.source);
1129
+ rb_gc_register_address(&parser.source);
1130
+ VALUE result = rb_ensure(native_variable_body, (VALUE)&parser, native_variable_unpin, (VALUE)&parser);
1131
+ if (!NIL_P(result) && !NIL_P(cache) && !native_normal_hash(cache)) result = Qnil;
1132
+ if ((!checked_cache || liquid_gc_count() != before_gc) && !native_payload_methods_standard(operation)) result = Qnil;
1133
+ RB_GC_GUARD(parser.source);
1134
+ if (guard && parser.literals_checked && liquid_gc_count() == before_gc) {
1135
+ guard->condition_literals = parser.condition_literals;
1136
+ guard->literals_checked = true;
1137
+ }
1138
+ RB_GC_GUARD(parser.pending);
1139
+ RB_GC_GUARD(cache);
1140
+ RB_GC_GUARD(result);
1141
+ return result;
1142
+ }
1143
+
1144
+ static VALUE native_parse_variable(VALUE self, VALUE markup, VALUE cache) { return native_parse_payload(markup, cache, 0, false, false, NULL); }
1145
+ static VALUE native_parse_condition(VALUE self, VALUE markup, VALUE cache) { return native_parse_payload(markup, cache, 1, false, false, NULL); }
1146
+ static VALUE native_parse_for(VALUE self, VALUE markup, VALUE cache) { return native_parse_payload(markup, cache, 2, false, false, NULL); }
1147
+ static VALUE native_parse_expression(VALUE self, VALUE markup, VALUE cache) { return native_parse_payload(markup, cache, 3, false, false, NULL); }
1148
+
1149
+ static int native_publish_entry(VALUE key, VALUE value, VALUE cache)
1150
+ {
1151
+ if (liquid_method_basic_definition_p(CLASS_OF(cache), rb_intern("[]="))) rb_hash_aset(cache, key, value);
1152
+ else rb_funcall(cache, rb_intern("[]="), 2, key, value);
1153
+ return ST_CONTINUE;
1154
+ }
1155
+
1156
+ static VALUE native_publish_cache(VALUE self, VALUE cache, VALUE pending)
1157
+ {
1158
+ if (!RTEST(cache)) return Qnil;
1159
+ Check_Type(cache, T_HASH);
1160
+ if (NIL_P(pending)) return Qnil;
1161
+ Check_Type(pending, T_HASH);
1162
+ rb_hash_foreach(pending, native_publish_entry, cache);
1163
+ return Qnil;
1164
+ }
1165
+
1166
+ static VALUE native_record_stats(VALUE self, VALUE context, VALUE reason)
1167
+ {
1168
+ VALUE options = rb_ivar_get(context, id_options_native);
1169
+ if (!RB_TYPE_P(options, T_HASH)) return Qnil;
1170
+ VALUE stats = rb_hash_lookup2(options, ID2SYM(id_stats_native), Qnil);
1171
+ if (NIL_P(stats)) return Qnil;
1172
+ Check_Type(stats, T_HASH);
1173
+ VALUE count = rb_funcall(stats, rb_intern("fetch"), 2, reason, INT2FIX(0));
1174
+ count = rb_funcall(count, rb_intern("+"), 1, INT2FIX(1));
1175
+ rb_funcall(stats, rb_intern("[]="), 2, reason, count);
1176
+ return Qnil;
1177
+ }
1178
+
1179
+ static VALUE native_parser_tracing(VALUE self)
1180
+ {
1181
+ #ifdef HAVE_RUBY_VM_EVENT_FLAGS
1182
+ return liquid_vm_tracing() ? Qtrue : Qfalse;
1183
+ #else
1184
+ // Portable frontend checks methods before and after construction; the
1185
+ // single-operation optimization above requires the optional tracing flag.
1186
+ return Qfalse;
1187
+ #endif
1188
+ }
1189
+
1190
+ #ifdef LIQUID_HAVE_GUARDED_COMPILER
1191
+
1192
+ static bool native_opted_out(const char *option)
1193
+ {
1194
+ const char *value = getenv(option);
1195
+ return value && !strcmp(value, "false");
1196
+ }
1197
+
1198
+ static bool native_parse_interrupted(size_t gc_before)
1199
+ {
1200
+ return gc_before != liquid_gc_count() || liquid_vm_tracing();
1201
+ }
1202
+
1203
+ static bool native_bare_identifier(VALUE markup)
1204
+ {
1205
+ if (!RB_TYPE_P(markup, T_STRING)) return false;
1206
+ const unsigned char *bytes = (const unsigned char *)RSTRING_PTR(markup);
1207
+ size_t i = 0, size = (size_t)RSTRING_LEN(markup);
1208
+ while (i < size && native_space(bytes[i])) i++;
1209
+ if (i == size || !native_alpha(bytes[i++])) return false;
1210
+ while (i < size && (native_alpha(bytes[i]) || native_digit(bytes[i]) || bytes[i] == '-')) i++;
1211
+ if (i < size && bytes[i] == '?') i++;
1212
+ while (i < size && native_space(bytes[i])) i++;
1213
+ return i == size;
1214
+ }
1215
+
1216
+ static bool native_plain_lookup(VALUE markup)
1217
+ {
1218
+ if (!RB_TYPE_P(markup, T_STRING) || RSTRING_LEN(markup) >= 128) return false;
1219
+ const unsigned char *bytes = (const unsigned char *)RSTRING_PTR(markup);
1220
+ size_t i = 0, size = (size_t)RSTRING_LEN(markup);
1221
+ for (;;) {
1222
+ while (i < size && native_space(bytes[i])) i++;
1223
+ if (i == size || !native_alpha(bytes[i++])) return false;
1224
+ while (i < size && (native_alpha(bytes[i]) || native_digit(bytes[i]) || bytes[i] == '-')) i++;
1225
+ if (i < size && bytes[i] == '?') i++;
1226
+ while (i < size && native_space(bytes[i])) i++;
1227
+ if (i == size) return true;
1228
+ if (bytes[i++] != '.') return false;
1229
+ }
1230
+ }
1231
+
1232
+ static VALUE native_try_variable_impl(VALUE self, VALUE markup, VALUE context, VALUE variable, bool retry);
1233
+
1234
+ static VALUE native_variable_guard_failure(VALUE self, VALUE markup, VALUE context, VALUE variable, bool retry)
1235
+ {
1236
+ if (retry) {
1237
+ VALUE helper = rb_const_get(mLiquidC, rb_intern("NativeParser"));
1238
+ if (RTEST(rb_funcall(helper, rb_intern("compatible?"), 2, context, variable)))
1239
+ return native_try_variable_impl(self, markup, context, variable, false);
1240
+ }
1241
+ native_record_stats(self, context, ID2SYM(rb_intern("hooks")));
1242
+ return Qnil;
1243
+ }
1244
+
1245
+ static VALUE native_try_variable_impl(VALUE self, VALUE markup, VALUE context, VALUE variable, bool retry)
1246
+ {
1247
+ if (!method_guard_count) return Qnil;
1248
+ if (liquid_vm_tracing()) return Qnil;
1249
+ if (rb_obj_class(context) != native_context_class || rb_obj_class(variable) != cLiquidVariable) return Qnil;
1250
+ VALUE early_cache = rb_ivar_get(context, id_cache_native);
1251
+ // Reject costly short unique forms before environment/method checks.
1252
+ if (RB_TYPE_P(early_cache, T_HASH) && RHASH_SIZE(early_cache) > 32 &&
1253
+ RB_TYPE_P(markup, T_STRING) && RSTRING_LEN(markup) < 128) {
1254
+ native_record_stats(self, context, ID2SYM(rb_intern("guard_cost")));
1255
+ return Qnil;
1256
+ }
1257
+ if (native_bare_identifier(markup) && (!RB_TYPE_P(early_cache, T_HASH) || RHASH_SIZE(early_cache) != 1)) {
1258
+ native_record_stats(self, context, ID2SYM(rb_intern("guard_cost")));
1259
+ return Qnil;
1260
+ }
1261
+ if (RB_TYPE_P(early_cache, T_HASH) && native_plain_lookup(markup)) {
1262
+ VALUE document = rb_ivar_get(context, rb_intern("document_body"));
1263
+ if (!NIL_P(document) && !document_body_cache_stable(document, RHASH_SIZE(early_cache))) {
1264
+ native_record_stats(self, context, ID2SYM(rb_intern("guard_cost")));
1265
+ return Qnil;
1266
+ }
1267
+ }
1268
+ // Tokenizer setup initializes this flag. Standalone Variable.new retains
1269
+ // the original Ruby path rather than calling extra context callbacks.
1270
+ if (!rb_ivar_defined(context, id_disabled_native)) {
1271
+ native_record_stats(self, context, ID2SYM(rb_intern("context")));
1272
+ return Qnil;
1273
+ }
1274
+ if (!RTEST(rb_ivar_get(mLiquidC, id_enabled_native)) || native_opted_out("LIQUID_C_NATIVE_PARSER")) {
1275
+ native_record_stats(self, context, ID2SYM(rb_intern("disabled")));
1276
+ return Qnil;
1277
+ }
1278
+ size_t guard_gc = liquid_gc_count();
1279
+ if (!RTEST(native_methods_compatible(self, context, variable)))
1280
+ return native_variable_guard_failure(self, markup, context, variable, retry);
1281
+ if (liquid_gc_count() != guard_gc) {
1282
+ guard_gc = liquid_gc_count();
1283
+ if (!RTEST(native_methods_compatible(self, context, variable)) || liquid_gc_count() != guard_gc)
1284
+ return native_variable_guard_failure(self, markup, context, variable, retry);
1285
+ }
1286
+ if (liquid_vm_tracing()) return Qnil;
1287
+ if (RTEST(rb_ivar_get(context, id_disabled_native))) {
1288
+ native_record_stats(self, context, ID2SYM(rb_intern("disabled")));
1289
+ return Qnil;
1290
+ }
1291
+ VALUE mode = rb_ivar_get(context, id_mode_native);
1292
+ if (mode != ID2SYM(rb_intern("lax")) && mode != ID2SYM(rb_intern("warn")) && mode != ID2SYM(rb_intern("strict"))) {
1293
+ native_record_stats(self, context, ID2SYM(rb_intern("mode")));
1294
+ return Qnil;
1295
+ }
1296
+ VALUE cache = rb_ivar_get(context, id_cache_native);
1297
+ if (RTEST(cache)) {
1298
+ if (CLASS_OF(cache) != rb_cHash) return Qnil;
1299
+ if (!native_string_cache(cache)) {
1300
+ native_record_stats(self, context, ID2SYM(rb_intern("cache")));
1301
+ return Qnil;
1302
+ }
1303
+ } else cache = Qnil;
1304
+ if (rb_get_alloc_func(cLiquidVariableLookup) != rb_get_alloc_func(rb_cObject) ||
1305
+ rb_get_alloc_func(cLiquidRangeLookup) != rb_get_alloc_func(rb_cObject)) return Qnil;
1306
+ size_t gc_count = liquid_gc_count();
1307
+ VALUE result = native_parse_payload(markup, cache, 0, true, false, NULL);
1308
+ if (NIL_P(result)) {
1309
+ native_record_stats(self, context, ID2SYM(rb_intern("syntax")));
1310
+ return Qnil;
1311
+ }
1312
+ if (liquid_vm_tracing()) return Qnil;
1313
+ if (liquid_gc_count() != gc_count && !RTEST(native_methods_compatible(self, context, variable))) return Qnil;
1314
+ native_publish_cache(self, cache, RARRAY_AREF(result, 2));
1315
+ native_record_stats(self, context, ID2SYM(rb_intern("accepted")));
1316
+ return result;
1317
+ }
1318
+ static VALUE native_try_variable(VALUE self, VALUE markup, VALUE context, VALUE variable)
1319
+ {
1320
+ return native_try_variable_impl(self, markup, context, variable, true);
1321
+ }
1322
+
1323
+ #endif
1324
+
1325
+ static VALUE native_variable_candidate(VALUE self, VALUE markup, VALUE context)
1326
+ {
1327
+ VALUE candidate = native_frontend_candidate(self, markup);
1328
+ if (!RTEST(candidate)) native_record_stats(self, context, ID2SYM(rb_intern("guard_cost")));
1329
+ return candidate;
1330
+ }
1331
+
1332
+ static VALUE native_case_candidate(VALUE self, VALUE markup, VALUE cache)
1333
+ {
1334
+ if (!RB_TYPE_P(markup, T_STRING) || CLASS_OF(markup) != rb_cString ||
1335
+ rb_enc_get_index(markup) != utf8_encoding_index) return Qfalse;
1336
+ long length = RSTRING_LEN(markup);
1337
+ if (length < 64) return Qfalse;
1338
+ const unsigned char *source = (const unsigned char *)RSTRING_PTR(markup);
1339
+ if (!native_alpha(source[0])) return Qfalse;
1340
+ int selectors = 0;
1341
+ unsigned char quote = 0;
1342
+ for (long i = 0; i < length; i++) {
1343
+ unsigned char c = source[i];
1344
+ if (quote == c) quote = 0;
1345
+ else if (!quote && (c == '\'' || c == '"')) quote = c;
1346
+ else if (!quote && (c == '.' || c == '[')) selectors++;
1347
+ }
1348
+ if (selectors < 16) return Qfalse;
1349
+ if (RTEST(cache)) {
1350
+ if (CLASS_OF(cache) != rb_cHash || !liquid_method_basic_definition_p(rb_cHash, rb_intern("key?")) ||
1351
+ !liquid_method_basic_definition_p(rb_cHash, rb_intern("[]"))) return Qfalse;
1352
+ if (rb_hash_lookup2(cache, markup, Qundef) != Qundef) return Qfalse;
1353
+ }
1354
+ return Qtrue;
1355
+ }
1356
+
1357
+ static VALUE native_case_expression(int argc, VALUE *argv, VALUE self)
1358
+ {
1359
+ if (argc == 1 && !rb_keyword_given_p() && rb_obj_class(self) == native_case_class) {
1360
+ VALUE context = rb_ivar_get(self, rb_intern("@parse_context"));
1361
+ VALUE cache = rb_ivar_get(context, id_cache_native);
1362
+ if (RTEST(native_case_candidate(Qnil, argv[0], cache))) {
1363
+ VALUE helpers = rb_const_get(mLiquidC, rb_intern("NativeTags"));
1364
+ VALUE result = rb_funcall(helpers, rb_intern("try_case_expression"), 2, self, argv[0]);
1365
+ if (!NIL_P(result)) return RARRAY_AREF(result, 0);
1366
+ }
1367
+ }
1368
+ return rb_call_super_kw(argc, argv, RB_PASS_CALLED_KEYWORDS);
1369
+ }
1370
+
1371
+ #ifdef HAVE_RB_CALLABLE_METHOD_ENTRY
1372
+ static VALUE native_if_parse_entry, native_for_parse_entry;
1373
+ static VALUE native_context_entries[3];
1374
+ static VALUE native_switching_module;
1375
+ static ID id_strict_context_native, id_strict_parse_native;
1376
+
1377
+ static VALUE native_fast_header(VALUE self, VALUE markup);
1378
+
1379
+ typedef struct { VALUE self, markup; bool second; } native_strict_args_t;
1380
+
1381
+ static VALUE native_strict_body(VALUE opaque)
1382
+ {
1383
+ native_strict_args_t *args = (void *)opaque;
1384
+ VALUE fast = native_fast_header(args->self, args->markup);
1385
+ if (fast != Qundef) return fast;
1386
+ if (args->second) return rb_funcall(args->self, rb_intern("strict2_parse"), 1, args->markup);
1387
+ VALUE klass = rb_obj_class(args->self);
1388
+ int index = klass == native_if_class ? 0 : (klass == native_unless_class ? 1 : (klass == native_for_class ? 2 : -1));
1389
+ if (index >= 0 && !(index == 2 && RB_OBJ_FROZEN(args->self)) &&
1390
+ native_context_entries[index] == liquid_method_entry(CLASS_OF(args->self), id_strict_context_native) &&
1391
+ (index == 2 ? native_for_parse_entry : native_if_parse_entry) ==
1392
+ liquid_method_entry(CLASS_OF(args->self), id_strict_parse_native) &&
1393
+ RTEST(native_case_candidate(Qnil, args->markup, Qnil))) {
1394
+ VALUE helper = rb_const_get(mLiquidC, rb_intern("NativeTags"));
1395
+ VALUE kind = ID2SYM(rb_intern(index == 2 ? "for" : "condition"));
1396
+ VALUE result = rb_funcall(helper, rb_intern("try_tag_header"), 3, args->self, args->markup, kind);
1397
+ if (!NIL_P(result)) {
1398
+ VALUE payload = RARRAY_AREF(result, 0);
1399
+ if (index != 2) return payload;
1400
+ Check_Type(payload, T_ARRAY);
1401
+ if (RARRAY_LEN(payload) != 6) rb_raise(rb_eRuntimeError, "invalid native for header");
1402
+ for (size_t i = 0; i < 6; i++) rb_ivar_set(args->self, id_for_fields[i], RARRAY_AREF(payload, i));
1403
+ return Qnil;
1404
+ }
1405
+ }
1406
+ return rb_funcall(args->self, id_strict_parse_native, 1, args->markup);
1407
+ }
1408
+
1409
+ static VALUE native_strict_rescue(VALUE opaque, VALUE exception)
1410
+ {
1411
+ VALUE syntax_error = rb_const_get(mLiquid, rb_intern("SyntaxError"));
1412
+ if (!rb_obj_is_kind_of(exception, syntax_error)) rb_exc_raise(exception);
1413
+ native_strict_args_t *args = (void *)opaque;
1414
+ VALUE line = rb_funcall(args->self, rb_intern("line_number"), 0);
1415
+ rb_funcallv_public(exception, rb_intern("line_number="), 1, &line);
1416
+ VALUE markup = rb_funcall(args->self, rb_intern("markup_context"), 1, args->markup);
1417
+ rb_funcallv_public(exception, rb_intern("markup_context="), 1, &markup);
1418
+ rb_exc_raise(exception);
1419
+ }
1420
+
1421
+ static VALUE native_strict_context(VALUE self, VALUE markup)
1422
+ {
1423
+ native_strict_args_t args = { self, markup };
1424
+ return rb_rescue2(native_strict_body, (VALUE)&args, native_strict_rescue, (VALUE)&args, rb_eException, (VALUE)0);
1425
+ }
1426
+ static VALUE native_strict2_context(VALUE self, VALUE markup)
1427
+ {
1428
+ native_strict_args_t args = { self, markup, true };
1429
+ return rb_rescue2(native_strict_body, (VALUE)&args, native_strict_rescue, (VALUE)&args, rb_eException, (VALUE)0);
1430
+ }
1431
+
1432
+ static VALUE native_install_compiler_context(VALUE self)
1433
+ {
1434
+ VALUE owner = rb_const_get(mLiquid, rb_intern("ParserSwitching"));
1435
+ rb_define_private_method(owner, "strict2_parse_with_error_context", native_strict2_context, 1);
1436
+ return Qnil;
1437
+ }
1438
+
1439
+ #endif
1440
+
1441
+ static VALUE native_install_header_parser(VALUE self, VALUE original, VALUE for_tag)
1442
+ {
1443
+ #ifdef HAVE_RB_CALLABLE_METHOD_ENTRY
1444
+ if (RTEST(for_tag)) {
1445
+ native_original_for = original;
1446
+ native_for_parse_entry = liquid_method_entry(native_for_class, rb_intern("strict_parse"));
1447
+ } else {
1448
+ native_original_if = original;
1449
+ native_if_parse_entry = liquid_method_entry(native_if_class, rb_intern("strict_parse"));
1450
+ }
1451
+ #endif
1452
+ return Qnil;
1453
+ }
1454
+
1455
+ static VALUE native_install_strict_context(VALUE self)
1456
+ {
1457
+ #ifdef HAVE_RB_CALLABLE_METHOD_ENTRY
1458
+ id_strict_context_native = rb_intern("strict_parse_with_error_context");
1459
+ id_strict_parse_native = rb_intern("strict_parse");
1460
+ native_switching_module = rb_const_get(mLiquid, rb_intern("ParserSwitching"));
1461
+ rb_define_private_method(native_switching_module, "strict_parse_with_error_context", native_strict_context, 1);
1462
+ VALUE classes[] = { native_if_class, native_unless_class, native_for_class };
1463
+ for (size_t i = 0; i < 3; i++)
1464
+ native_context_entries[i] = liquid_method_entry(classes[i], id_strict_context_native);
1465
+ #endif
1466
+ return Qnil;
1467
+ }
1468
+
1469
+ static VALUE native_install_case_parser(VALUE self)
1470
+ {
1471
+ rb_define_private_method(native_case_class, "parse_expression", native_case_expression, -1);
1472
+ return Qnil;
1473
+ }
1474
+
1475
+ static VALUE native_variable_frontend(VALUE self, VALUE markup, VALUE context, VALUE variable)
1476
+ {
1477
+ if (!native_variable_ready) return Qnil;
1478
+ #ifdef LIQUID_HAVE_GUARDED_COMPILER
1479
+ return native_try_variable(self, markup, context, variable);
1480
+ #else
1481
+ if (!RTEST(native_variable_candidate(self, markup, context))) return Qnil;
1482
+ VALUE helper = rb_const_get(mLiquidC, rb_intern("NativeParser"));
1483
+ return rb_funcall(helper, rb_intern("parse"), 3, markup, context, variable);
1484
+ #endif
1485
+ }
1486
+
1487
+ static VALUE native_variable_frontend_method(VALUE self, VALUE markup)
1488
+ {
1489
+ VALUE context = rb_ivar_get(self, id_parse_context_native);
1490
+ return native_variable_frontend(mLiquidC, markup, context, self);
1491
+ }
1492
+
1493
+ static VALUE native_enable_variable_frontend(VALUE self)
1494
+ {
1495
+ native_variable_ready = true;
1496
+ return Qnil;
1497
+ }
1498
+
1499
+ #ifdef LIQUID_HAVE_GUARDED_COMPILER
1500
+ static struct { VALUE owner, entry; ID method; bool public_call, control, builtin; } compiler_methods[256];
1501
+ static size_t compiler_method_count;
1502
+ static VALUE renderer_guard_entries = Qnil;
1503
+ static VALUE compiler_body_class = Qnil;
1504
+ static rb_alloc_func_t compiler_body_allocator;
1505
+ static VALUE compiler_constants = Qnil;
1506
+ static VALUE compiler_constant_watchers = Qnil;
1507
+ static VALUE compiler_ancestor_prefixes = Qnil;
1508
+ static VALUE control_helpers[2], control_else_class, control_environment_class, native_assign_class, native_capture_class, native_include_class;
1509
+ static VALUE control_tag_new_entry;
1510
+ static bool native_control_binding(VALUE lexical_owner, ID name, VALUE expected);
1511
+
1512
+ static VALUE native_register_control(VALUE self, VALUE helpers, VALUE constants, VALUE prefixes, VALUE watchers)
1513
+ {
1514
+ Check_Type(helpers, T_ARRAY);
1515
+ Check_Type(constants, T_ARRAY);
1516
+ Check_Type(prefixes, T_ARRAY);
1517
+ if (!NIL_P(watchers)) Check_Type(watchers, T_ARRAY);
1518
+ if (!NIL_P(compiler_constants)) rb_raise(rb_eRuntimeError, "control guards already registered");
1519
+ VALUE unbound = rb_const_get(rb_cObject, rb_intern("UnboundMethod"));
1520
+ for (long i = 0; i < RARRAY_LEN(helpers); i++)
1521
+ if (!rb_obj_is_kind_of(RARRAY_AREF(helpers, i), unbound)) rb_raise(rb_eTypeError, "expected UnboundMethod");
1522
+ for (long i = 0; i < RARRAY_LEN(prefixes); i++) {
1523
+ VALUE pair = RARRAY_AREF(prefixes, i);
1524
+ Check_Type(pair, T_ARRAY);
1525
+ if (RARRAY_LEN(pair) != 2 || !RB_TYPE_P(RARRAY_AREF(pair, 0), T_CLASS))
1526
+ rb_raise(rb_eTypeError, "expected class and ancestor prefix");
1527
+ Check_Type(RARRAY_AREF(pair, 1), T_ARRAY);
1528
+ }
1529
+ if (RARRAY_LEN(helpers) != 2) rb_raise(rb_eArgError, "invalid control helpers");
1530
+ for (long i = 0; i < RARRAY_LEN(constants); i++) {
1531
+ VALUE spec = RARRAY_AREF(constants, i);
1532
+ Check_Type(spec, T_ARRAY);
1533
+ if (RARRAY_LEN(spec) != 3) rb_raise(rb_eArgError, "invalid control constant");
1534
+ VALUE owner = RARRAY_AREF(spec, 0);
1535
+ if (!RB_TYPE_P(owner, T_CLASS) && !RB_TYPE_P(owner, T_MODULE)) rb_raise(rb_eTypeError, "expected module");
1536
+ Check_Type(RARRAY_AREF(spec, 1), T_SYMBOL);
1537
+ }
1538
+ compiler_constants = constants;
1539
+ compiler_constant_watchers = watchers;
1540
+ compiler_ancestor_prefixes = prefixes;
1541
+ control_else_class = rb_const_get(mLiquid, rb_intern("ElseCondition"));
1542
+ control_environment_class = rb_const_get(mLiquid, rb_intern("Environment"));
1543
+ native_assign_class = rb_const_get(mLiquid, rb_intern("Assign"));
1544
+ native_capture_class = rb_const_get(mLiquid, rb_intern("Capture"));
1545
+ native_include_class = rb_const_get(mLiquid, rb_intern("Include"));
1546
+ control_tag_new_entry = liquid_method_entry(CLASS_OF(native_if_class), rb_intern("new"));
1547
+ for (size_t i = 0; i < 2; i++) {
1548
+ VALUE helper = RARRAY_AREF(helpers, i);
1549
+ if (!rb_obj_is_kind_of(helper, rb_const_get(rb_cObject, rb_intern("UnboundMethod"))))
1550
+ rb_raise(rb_eTypeError, "expected UnboundMethod");
1551
+ control_helpers[i] = liquid_method_handle(rb_obj_method(helper, ID2SYM(rb_intern("bind_call"))));
1552
+ }
1553
+ return Qnil;
1554
+ }
1555
+ static VALUE compiler_stat = Qnil, compiler_epoch = Qundef;
1556
+ static bool compiler_ready;
1557
+ static bool compiler_registered;
1558
+ static ID renderer_ids[3];
1559
+
1560
+ static VALUE native_register_compiler(VALUE self, VALUE specifications, VALUE enabled)
1561
+ {
1562
+ Check_Type(specifications, T_ARRAY);
1563
+ if (compiler_registered) rb_raise(rb_eRuntimeError, "compiler guards already registered");
1564
+ if (RARRAY_LEN(specifications) > 256) rb_raise(rb_eArgError, "too many compiler guards");
1565
+ for (long i = 0; i < RARRAY_LEN(specifications); i++) {
1566
+ VALUE spec = RARRAY_AREF(specifications, i);
1567
+ Check_Type(spec, T_ARRAY);
1568
+ if (RARRAY_LEN(spec) != 3) rb_raise(rb_eArgError, "invalid compiler guard");
1569
+ VALUE owner = RARRAY_AREF(spec, 0);
1570
+ if (!RB_TYPE_P(owner, T_CLASS) && !RB_TYPE_P(owner, T_MODULE)) rb_raise(rb_eTypeError, "guard owner must be a module");
1571
+ Check_Type(RARRAY_AREF(spec, 1), T_SYMBOL);
1572
+ }
1573
+ compiler_registered = true;
1574
+ compiler_body_class = rb_const_get(mLiquidC, rb_intern("BlockBody"));
1575
+ compiler_body_allocator = rb_get_alloc_func(compiler_body_class);
1576
+ compiler_method_count = (size_t)RARRAY_LEN(specifications);
1577
+ for (long i = 0; i < RARRAY_LEN(specifications); i++) {
1578
+ VALUE spec = RARRAY_AREF(specifications, i);
1579
+ VALUE owner = RARRAY_AREF(spec, 0);
1580
+ ID method = SYM2ID(RARRAY_AREF(spec, 1));
1581
+ VALUE entry = liquid_method_entry(owner, method);
1582
+ compiler_methods[i].control = RTEST(RARRAY_AREF(spec, 2));
1583
+ compiler_methods[i].builtin = liquid_method_basic_definition_p(owner, method);
1584
+ compiler_methods[i].owner = owner;
1585
+ compiler_methods[i].entry = entry;
1586
+ compiler_methods[i].method = method;
1587
+ compiler_methods[i].public_call =
1588
+ (owner == compiler_body_class && method != rb_intern("initialize")) || owner == native_context_class ||
1589
+ owner == CLASS_OF(compiler_body_class) || owner == CLASS_OF(control_else_class) ||
1590
+ owner == CLASS_OF(native_condition_class) || owner == control_environment_class ||
1591
+ owner == cLiquidVariableLookup || owner == cLiquidRangeLookup ||
1592
+ ((owner == native_condition_class || owner == control_else_class) && method != rb_intern("initialize"));
1593
+ rb_gc_register_address(&compiler_methods[i].owner);
1594
+ rb_gc_register_address(&compiler_methods[i].entry);
1595
+ }
1596
+ bool renderers_standard = liquid_vm_render_methods_standard();
1597
+ renderer_guard_entries = rb_ary_new_capa(3);
1598
+ const char *names[] = { "render", "render_to_output_buffer", "render_obj_to_output" };
1599
+ for (size_t i = 0; i < 3; i++) {
1600
+ renderer_ids[i] = rb_intern(names[i]);
1601
+ VALUE entry = renderers_standard ? liquid_method_entry(cLiquidVariable, renderer_ids[i]) : 0;
1602
+ rb_ary_push(renderer_guard_entries, entry);
1603
+ }
1604
+ compiler_ready = RTEST(enabled);
1605
+ if (!liquid_method_basic_definition_p(native_unbound_class, rb_intern("==")) ||
1606
+ !liquid_method_basic_definition_p(native_unbound_class, rb_intern("super_method")) ||
1607
+ !liquid_method_basic_definition_p(native_unbound_class, rb_intern("bind_call"))) compiler_ready = false;
1608
+ if (!native_primitives_standard(false)) compiler_ready = false;
1609
+ if (!NIL_P(constant_vm) && liquid_method_basic_definition_p(CLASS_OF(constant_vm), id_stat))
1610
+ compiler_stat = liquid_method_handle(rb_obj_method(constant_vm, ID2SYM(id_stat)));
1611
+ return compiler_ready ? Qtrue : Qfalse;
1612
+ }
1613
+
1614
+ bool variable_render_methods_standard(void)
1615
+ {
1616
+ if (!compiler_registered) return false;
1617
+ for (size_t i = 0; i < 3; i++) {
1618
+ VALUE current = liquid_method_entry(cLiquidVariable, renderer_ids[i]);
1619
+ if (RARRAY_AREF(renderer_guard_entries, i) == current) continue;
1620
+ // Re-aliasing a builtin creates a new method entry with the same body.
1621
+ size_t gc = liquid_gc_count();
1622
+ bool standard = liquid_vm_render_methods_standard();
1623
+ if (gc != liquid_gc_count()) return false;
1624
+ if (!standard) return false;
1625
+ for (size_t j = 0; j < 3; j++)
1626
+ rb_ary_store(renderer_guard_entries, (long)j, liquid_method_entry(cLiquidVariable, renderer_ids[j]));
1627
+ break;
1628
+ }
1629
+ return true;
1630
+ }
1631
+
1632
+ bool variable_render_traced(void)
1633
+ {
1634
+ return liquid_vm_tracing();
1635
+ }
1636
+
1637
+ bool variable_output_method_standard(void)
1638
+ {
1639
+ return compiler_ready && !liquid_vm_tracing() && RARRAY_AREF(renderer_guard_entries, 2) ==
1640
+ liquid_method_entry(cLiquidVariable, renderer_ids[2]);
1641
+ }
1642
+
1643
+ static bool native_compiler_method_entries_match(bool control)
1644
+ {
1645
+ for (size_t i = 0; i < compiler_method_count; i++) {
1646
+ if (compiler_methods[i].control != control) continue;
1647
+ VALUE owner = compiler_methods[i].owner;
1648
+ ID method = compiler_methods[i].method;
1649
+ VALUE current_entry = liquid_method_entry(owner, method);
1650
+ if (compiler_methods[i].entry != current_entry) {
1651
+ if (!compiler_methods[i].builtin || !liquid_method_basic_definition_p(owner, method)) return false;
1652
+ compiler_methods[i].entry = current_entry;
1653
+ }
1654
+ if (compiler_methods[i].public_call && rb_method_boundp(owner, method, 3) != 1) return false;
1655
+ }
1656
+ return true;
1657
+ }
1658
+
1659
+ static bool native_compiler_methods_standard(variable_parse_args_t *args)
1660
+ {
1661
+ VALUE context = args->parse_context;
1662
+ if (rb_get_alloc_func(compiler_body_class) != compiler_body_allocator) return false;
1663
+ if (CLASS_OF(context) != native_context_class || (!NIL_P(args->code_obj) && CLASS_OF(args->code_obj) != compiler_body_class)) return false;
1664
+ size_t validation_gc = liquid_gc_count();
1665
+ VALUE epoch = Qundef;
1666
+ if (!NIL_P(compiler_stat)) {
1667
+ VALUE key = ID2SYM(id_constant_invalidations);
1668
+ epoch = liquid_method_call(1, &key, compiler_stat);
1669
+ }
1670
+ bool unchanged_constants = epoch != Qundef && epoch == compiler_epoch;
1671
+ if (!native_guards_match(context, Qnil, unchanged_constants)) return false;
1672
+ if (!native_compiler_method_entries_match(false)) return false;
1673
+ if (NIL_P(compiler_constants)) return false;
1674
+ if (!unchanged_constants || NIL_P(compiler_constant_watchers)) {
1675
+ for (long i = 0; i < RARRAY_LEN(compiler_constants); i++) {
1676
+ VALUE spec = RARRAY_AREF(compiler_constants, i);
1677
+ VALUE expected = RARRAY_AREF(spec, 2);
1678
+ if (expected != compiler_body_class && expected != control_environment_class) continue;
1679
+ if (!RTEST(native_constant_matches(Qnil, RARRAY_AREF(spec, 0), RARRAY_AREF(spec, 1), expected, Qnil))) return false;
1680
+ }
1681
+ }
1682
+ VALUE klass = CLASS_OF(cLiquidVariable);
1683
+ if (!liquid_method_basic_definition_p(klass, id_new_native) ||
1684
+ !liquid_method_basic_definition_p(klass, id_allocate_native) ||
1685
+ rb_get_alloc_func(cLiquidVariable) != rb_get_alloc_func(rb_cObject)) return false;
1686
+ if (!native_primitives_standard(true)) return false;
1687
+ if (rb_get_alloc_func(cLiquidVariableLookup) != rb_get_alloc_func(rb_cObject) ||
1688
+ rb_get_alloc_func(cLiquidRangeLookup) != rb_get_alloc_func(rb_cObject) ||
1689
+ rb_get_alloc_func(native_parser_class) != rb_get_alloc_func(rb_cObject)) return false;
1690
+ if (validation_gc != liquid_gc_count()) return false;
1691
+ compiler_epoch = epoch;
1692
+ VALUE options = rb_ivar_get(context, id_options_native);
1693
+ if (CLASS_OF(options) != rb_cHash ||
1694
+ RTEST(rb_hash_lookup2(options, ID2SYM(id_stats_native), Qnil)) ||
1695
+ RTEST(rb_hash_lookup2(options, ID2SYM(rb_intern("stats_callbacks")), Qnil))) return false;
1696
+ if (!RTEST(rb_ivar_get(mLiquidC, id_enabled_native)) || RTEST(rb_ivar_get(context, id_disabled_native))) return false;
1697
+ VALUE mode = rb_ivar_get(context, id_mode_native);
1698
+ if (mode != ID2SYM(rb_intern("lax")) && mode != ID2SYM(rb_intern("warn")) && mode != ID2SYM(rb_intern("strict"))) return false;
1699
+ VALUE cache = rb_ivar_get(context, id_cache_native);
1700
+ if (RTEST(cache) && (CLASS_OF(cache) != rb_cHash || RB_OBJ_FROZEN(cache) || !native_string_cache(cache))) return false;
1701
+ return true;
1702
+ }
1703
+
1704
+ // Structural hooks are needed only when entering the native control parser.
1705
+ // A variable-only interval need not validate unrelated tag implementations.
1706
+ static bool native_control_methods_standard(void)
1707
+ {
1708
+ if (!native_compiler_method_entries_match(true)) return false;
1709
+ if (NIL_P(compiler_constants)) return false;
1710
+ for (long i = 0; i < RARRAY_LEN(compiler_constants); i++) {
1711
+ VALUE spec = RARRAY_AREF(compiler_constants, i);
1712
+ if (!RTEST(native_constant_matches(Qnil, RARRAY_AREF(spec, 0), RARRAY_AREF(spec, 1), RARRAY_AREF(spec, 2), Qnil))) return false;
1713
+ }
1714
+ for (long i = 0; i < RARRAY_LEN(compiler_ancestor_prefixes); i++) {
1715
+ VALUE pair = RARRAY_AREF(compiler_ancestor_prefixes, i);
1716
+ VALUE prefix = RARRAY_AREF(pair, 1);
1717
+ VALUE ancestors = rb_mod_ancestors(RARRAY_AREF(pair, 0));
1718
+ if (RARRAY_LEN(ancestors) < RARRAY_LEN(prefix)) return false;
1719
+ for (long j = 0; j < RARRAY_LEN(prefix); j++)
1720
+ if (RARRAY_AREF(ancestors, j) != RARRAY_AREF(prefix, j)) return false;
1721
+ }
1722
+ return native_control_binding(native_if_class, rb_intern("Condition"), native_condition_class) &&
1723
+ native_control_binding(native_if_class, rb_intern("ElseCondition"), control_else_class);
1724
+ }
1725
+
1726
+ static VALUE native_fast_header(VALUE self, VALUE markup)
1727
+ {
1728
+ if (!compiler_ready || liquid_vm_tracing()) return Qundef;
1729
+ VALUE klass = CLASS_OF(self);
1730
+ bool condition = klass == native_if_class || klass == native_unless_class;
1731
+ if (!condition && klass != native_for_class) return Qundef;
1732
+ if (native_opted_out("LIQUID_C_NATIVE_TAGS") || native_opted_out("LIQUID_C_NATIVE_PARSER")) return Qundef;
1733
+ VALUE context = rb_ivar_get(self, id_parse_context_native);
1734
+ VALUE mode = rb_ivar_get(context, id_mode_native);
1735
+ if (mode != ID2SYM(rb_intern("warn")) && mode != ID2SYM(rb_intern("strict"))) return Qundef;
1736
+ variable_parse_args_t args = { .parse_context = context, .code_obj = Qnil };
1737
+ size_t gc = liquid_gc_count();
1738
+ if (!native_compiler_methods_standard(&args) || !native_control_methods_standard() || gc != liquid_gc_count()) return Qundef;
1739
+ if (condition && (rb_get_alloc_func(native_condition_class) != rb_get_alloc_func(rb_cObject) ||
1740
+ !liquid_method_basic_definition_p(CLASS_OF(native_condition_class), id_new_native) ||
1741
+ !liquid_method_basic_definition_p(CLASS_OF(native_condition_class), id_allocate_native))) return Qundef;
1742
+ VALUE cache = rb_ivar_get(context, id_cache_native);
1743
+ VALUE result = native_parse_payload(markup, RTEST(cache) ? cache : Qnil, condition ? 1 : 2, true, true, NULL);
1744
+ if (NIL_P(result) || native_parse_interrupted(gc)) return Qundef;
1745
+ VALUE payload = RARRAY_AREF(result, 0);
1746
+ native_publish_cache(Qnil, cache, RARRAY_AREF(result, 1));
1747
+ if (!condition) {
1748
+ for (size_t i = 0; i < 6; i++) rb_ivar_set(self, id_for_fields[i], RARRAY_AREF(payload, i));
1749
+ payload = Qnil;
1750
+ }
1751
+ RB_GC_GUARD(result);
1752
+ return payload;
1753
+ }
1754
+
1755
+ static void native_restore_assembler(vm_assembler_t *code, const vm_assembler_t *saved,
1756
+ size_t instruction_size, size_t constant_size)
1757
+ {
1758
+ for (size_t i = constant_size / sizeof(VALUE); i < c_buffer_size(&code->constants) / sizeof(VALUE); i++) {
1759
+ st_data_t key = ((VALUE *)code->constants.data)[i];
1760
+ st_delete(code->constants_table, &key, NULL);
1761
+ }
1762
+ code->instructions.data_end = code->instructions.data + instruction_size;
1763
+ code->constants.data_end = code->constants.data + constant_size;
1764
+ code->stack_size = saved->stack_size;
1765
+ code->max_stack_size = saved->max_stack_size;
1766
+ code->protected_stack_size = saved->protected_stack_size;
1767
+ }
1768
+
1769
+ bool native_compiler_guard(variable_parse_args_t *args)
1770
+ {
1771
+ variable_compile_guard_t *guard = args->guard;
1772
+ if (!compiler_ready || !guard || liquid_vm_tracing() || !method_guard_count) return false;
1773
+ #ifdef LIQUID_C_TEST_ALLOC_FAILURES
1774
+ if (!NIL_P(native_parser_test_callback)) return false;
1775
+ #endif
1776
+ size_t gc = liquid_gc_count();
1777
+ if (!guard->valid || gc != guard->gc_count) {
1778
+ guard->valid = false;
1779
+ guard->control_validated = false;
1780
+ VALUE mode = rb_ivar_get(args->parse_context, id_mode_native);
1781
+ if (mode != ID2SYM(rb_intern("lax")) && mode != ID2SYM(rb_intern("warn")) &&
1782
+ mode != ID2SYM(rb_intern("strict"))) return false;
1783
+
1784
+ if (native_opted_out("LIQUID_C_NATIVE_COMPILER") || native_opted_out("LIQUID_C_NATIVE_PARSER")) return false;
1785
+
1786
+ if (!native_compiler_methods_standard(args) || native_parse_interrupted(gc)) return false;
1787
+ guard->valid = true;
1788
+ guard->gc_count = gc;
1789
+ guard->cache = rb_ivar_get(args->parse_context, id_cache_native);
1790
+ guard->environment = Qnil;
1791
+ guard->tags = Qnil;
1792
+ guard->literals_checked = false;
1793
+ guard->control_checked = false;
1794
+ }
1795
+ return true;
1796
+ }
1797
+
1798
+ bool native_control_guard(variable_parse_args_t *args)
1799
+ {
1800
+ if (!native_compiler_guard(args)) return false;
1801
+ if (!args->guard->control_validated) {
1802
+ size_t gc = liquid_gc_count();
1803
+ bool standard = native_control_methods_standard();
1804
+ if (native_parse_interrupted(gc)) {
1805
+ args->guard->valid = false;
1806
+ return false;
1807
+ }
1808
+ if (!standard) return false;
1809
+ args->guard->tags_enabled = !native_opted_out("LIQUID_C_NATIVE_TAGS");
1810
+ args->guard->control_validated = true;
1811
+ }
1812
+ return true;
1813
+ }
1814
+
1815
+ bool native_assignment_class_p(VALUE klass)
1816
+ {
1817
+ return klass == native_assign_class;
1818
+ }
1819
+
1820
+ static bool native_control_binding(VALUE lexical_owner, ID name, VALUE expected)
1821
+ {
1822
+ VALUE lexical[] = { lexical_owner, mLiquid };
1823
+ for (size_t i = 0; i < sizeof(lexical) / sizeof(lexical[0]); i++) {
1824
+ VALUE owner = lexical[i];
1825
+ if (rb_const_defined_at(owner, name))
1826
+ return !RTEST(native_autoload_p(owner, name)) && rb_const_get_at(owner, name) == expected;
1827
+ }
1828
+ // The full ancestor prefix is verified by the control guard. Looking only
1829
+ // at defined constants cannot trigger autoload or const_missing callbacks.
1830
+ VALUE prefix = Qnil;
1831
+ for (long i = 0; i < RARRAY_LEN(compiler_ancestor_prefixes); i++) {
1832
+ VALUE pair = RARRAY_AREF(compiler_ancestor_prefixes, i);
1833
+ if (RARRAY_AREF(pair, 0) == lexical_owner) {
1834
+ prefix = RARRAY_AREF(pair, 1);
1835
+ break;
1836
+ }
1837
+ }
1838
+ if (NIL_P(prefix)) return false;
1839
+ for (long i = 1; i < RARRAY_LEN(prefix); i++) {
1840
+ VALUE owner = RARRAY_AREF(prefix, i);
1841
+ if (rb_const_defined_at(owner, name))
1842
+ return !RTEST(native_autoload_p(owner, name)) && rb_const_get_at(owner, name) == expected;
1843
+ }
1844
+ return false;
1845
+ }
1846
+
1847
+ // A result is publishable only while the checks made by native_compiler_guard
1848
+ // still hold. Use its GC count across all allocations for the tag or variable.
1849
+ static bool native_compiler_accepts_result(variable_compile_guard_t *guard, VALUE result)
1850
+ {
1851
+ if (NIL_P(result) || native_parse_interrupted(guard->gc_count)) guard->valid = false;
1852
+ return guard->valid;
1853
+ }
1854
+
1855
+ static bool native_tag_constructor_standard(VALUE klass)
1856
+ {
1857
+ return rb_get_alloc_func(klass) == rb_get_alloc_func(rb_cObject) &&
1858
+ liquid_method_entry(CLASS_OF(klass), id_new_native) == control_tag_new_entry &&
1859
+ liquid_method_basic_definition_p(CLASS_OF(klass), id_allocate_native);
1860
+ }
1861
+
1862
+ static VALUE native_tag_alloc(VALUE klass, VALUE name, VALUE markup, VALUE context, VALUE line)
1863
+ {
1864
+ VALUE tag = rb_obj_alloc(klass);
1865
+ rb_ivar_set(tag, rb_intern("@tag_name"), name);
1866
+ rb_ivar_set(tag, rb_intern("@markup"), markup);
1867
+ rb_ivar_set(tag, id_parse_context_native, context);
1868
+ rb_ivar_set(tag, id_ivar_line_number, line);
1869
+ return tag;
1870
+ }
1871
+
1872
+ // Assign retains its ordinary Variable and Ruby renderer. Only supported,
1873
+ // non-diagnostic construction stays inside the current native parse interval.
1874
+ VALUE native_parse_assignment(variable_parse_args_t *args, VALUE klass, VALUE name, VALUE markup)
1875
+ {
1876
+ if (!native_assignment_class_p(klass) || !native_control_guard(args)) return Qundef;
1877
+ ID last_match = rb_intern("last_match");
1878
+ if (!native_control_binding(native_assign_class, rb_intern("Variable"), cLiquidVariable) ||
1879
+ !native_control_binding(native_assign_class, rb_intern("Regexp"), rb_cRegexp) ||
1880
+ !liquid_method_basic_definition_p(CLASS_OF(rb_cRegexp), last_match) ||
1881
+ rb_method_boundp(CLASS_OF(rb_cRegexp), last_match, 3) != 1) return Qundef;
1882
+ if (!args->guard->tags_enabled || !native_tag_constructor_standard(klass)) return Qundef;
1883
+ native_parser_t lhs = { .source = markup, .length = (size_t)RSTRING_LEN(markup) };
1884
+ native_next(&lhs);
1885
+ if (lhs.token != N_ID || native_word(&lhs, "contains") ||
1886
+ RSTRING_PTR(markup)[lhs.end - 1] == '?') return Qundef;
1887
+ size_t position = lhs.end;
1888
+ while (position < lhs.length && native_space((unsigned char)RSTRING_PTR(markup)[position])) position++;
1889
+ if (position == lhs.length || RSTRING_PTR(markup)[position++] != '=') return Qundef;
1890
+ while (position < lhs.length && native_space((unsigned char)RSTRING_PTR(markup)[position])) position++;
1891
+ VALUE target = native_slice(&lhs, lhs.start, lhs.end);
1892
+ VALUE rhs = native_slice(&lhs, position, lhs.length);
1893
+ if (!native_compiler_accepts_result(args->guard, rhs)) return Qundef;
1894
+ VALUE cache = args->guard->cache;
1895
+ VALUE parsed = native_parse_payload(rhs, RTEST(cache) ? cache : Qnil, 0, true, true, NULL);
1896
+ if (!native_compiler_accepts_result(args->guard, parsed)) return Qundef;
1897
+ VALUE line = rb_ivar_get(args->parse_context, id_ivar_line_number);
1898
+ VALUE variable = variable_from_parse(rhs, args->parse_context, line, RARRAY_AREF(parsed, 0), RARRAY_AREF(parsed, 1));
1899
+ if (!native_compiler_accepts_result(args->guard, variable)) return Qundef;
1900
+ VALUE tag = native_tag_alloc(klass, name, markup, args->parse_context, line);
1901
+ rb_ivar_set(tag, rb_intern("@to"), target);
1902
+ rb_ivar_set(tag, rb_intern("@from"), variable);
1903
+ if (!native_compiler_accepts_result(args->guard, tag)) return Qundef;
1904
+ native_publish_cache(Qnil, cache, RARRAY_AREF(parsed, 2));
1905
+ if (args->guard->gc_count != liquid_gc_count()) args->guard->valid = false;
1906
+ RB_GC_GUARD(parsed);
1907
+ RB_GC_GUARD(variable);
1908
+ RB_GC_GUARD(rhs);
1909
+ RB_GC_GUARD(target);
1910
+ RB_GC_GUARD(markup);
1911
+ RB_GC_GUARD(tag);
1912
+ return tag;
1913
+ }
1914
+
1915
+ bool native_include_class_p(VALUE klass)
1916
+ {
1917
+ return klass == native_include_class;
1918
+ }
1919
+
1920
+ VALUE native_parse_include(variable_parse_args_t *args, VALUE klass, VALUE name, VALUE markup)
1921
+ {
1922
+ if (!native_include_class_p(klass) ||
1923
+ rb_ivar_get(args->parse_context, id_mode_native) != ID2SYM(rb_intern("warn")) ||
1924
+ !native_control_guard(args)) return Qundef;
1925
+ if (!args->guard->tags_enabled || !native_tag_constructor_standard(klass)) return Qundef;
1926
+ VALUE cache = args->guard->cache;
1927
+ VALUE parsed = native_parse_payload(markup, RTEST(cache) ? cache : Qnil, 4, true, true, args->guard);
1928
+ if (!native_compiler_accepts_result(args->guard, parsed)) return Qundef;
1929
+ VALUE fields = RARRAY_AREF(parsed, 0);
1930
+ if (!RTEST(RARRAY_AREF(fields, 5)) &&
1931
+ (!liquid_method_basic_definition_p(rb_cFalseClass, rb_intern("==")) ||
1932
+ rb_method_boundp(rb_cFalseClass, rb_intern("=="), 3) != 1)) return Qundef;
1933
+ VALUE tag = native_tag_alloc(klass, name, markup, args->parse_context, rb_ivar_get(args->parse_context, id_ivar_line_number));
1934
+ const char *names[] = { "@template_name_expr", "@variable_name_expr", "@alias_name", "@is_for_loop", "@attributes" };
1935
+ for (size_t i = 0; i < 5; i++) {
1936
+ if ((i == 1 && !RTEST(RARRAY_AREF(fields, 5))) || (i == 2 && NIL_P(RARRAY_AREF(fields, i)))) continue;
1937
+ rb_ivar_set(tag, rb_intern(names[i]), RARRAY_AREF(fields, i));
1938
+ }
1939
+ if (!native_compiler_accepts_result(args->guard, tag)) return Qundef;
1940
+ native_publish_cache(Qnil, cache, RARRAY_AREF(parsed, 1));
1941
+ if (args->guard->gc_count != liquid_gc_count()) args->guard->valid = false;
1942
+ RB_GC_GUARD(parsed);
1943
+ return tag;
1944
+ }
1945
+
1946
+ VALUE native_parse_capture(variable_parse_args_t *args, VALUE klass, VALUE name, VALUE markup)
1947
+ {
1948
+ if (klass != native_capture_class ||
1949
+ rb_ivar_get(args->parse_context, id_mode_native) != ID2SYM(rb_intern("warn")) ||
1950
+ !native_control_guard(args)) return Qundef;
1951
+ if (!args->guard->tags_enabled || !native_tag_constructor_standard(klass) ||
1952
+ rb_get_alloc_func(compiler_body_class) != compiler_body_allocator ||
1953
+ !liquid_method_basic_definition_p(CLASS_OF(compiler_body_class), id_new_native) ||
1954
+ !liquid_method_basic_definition_p(CLASS_OF(compiler_body_class), id_allocate_native)) return Qundef;
1955
+ native_parser_t parser = { .source = markup, .length = (size_t)RSTRING_LEN(markup) };
1956
+ native_next(&parser);
1957
+ if (parser.token != N_ID || native_word(&parser, "contains")) return Qundef;
1958
+ size_t start = parser.start, end = parser.end;
1959
+ native_next(&parser);
1960
+ if (parser.token != N_END) return Qundef;
1961
+ VALUE target = native_slice(&parser, start, end);
1962
+ VALUE tag = native_tag_alloc(klass, name, markup, args->parse_context, rb_ivar_get(args->parse_context, id_ivar_line_number));
1963
+ rb_ivar_set(tag, rb_intern("@blank"), Qtrue);
1964
+ rb_ivar_set(tag, rb_intern("@to"), target);
1965
+ if (!native_compiler_accepts_result(args->guard, tag)) return Qundef;
1966
+ RB_GC_GUARD(target);
1967
+ return tag;
1968
+ }
1969
+
1970
+ int native_control_kind(VALUE klass)
1971
+ {
1972
+ return klass == native_if_class || klass == native_unless_class ? 1 :
1973
+ (klass == native_for_class ? 2 : (klass == native_capture_class ? 3 : 0));
1974
+ }
1975
+
1976
+ VALUE native_registered_tag(variable_parse_args_t *args, VALUE environment, VALUE name)
1977
+ {
1978
+ if (!args->guard->valid || args->guard->gc_count != liquid_gc_count()) return Qundef;
1979
+ if (!native_compiler_guard(args) || CLASS_OF(environment) != control_environment_class) return Qundef;
1980
+ variable_compile_guard_t *guard = args->guard;
1981
+ VALUE tags = guard->tags;
1982
+ if (guard->environment != environment) {
1983
+ tags = rb_ivar_get(environment, rb_intern("@tags"));
1984
+ size_t gc = liquid_gc_count();
1985
+ if (CLASS_OF(tags) != rb_cHash || !native_string_cache(tags) ||
1986
+ !liquid_method_basic_definition_p(rb_cHash, rb_intern("default")) ||
1987
+ !NIL_P(native_hash_property(tags, HASH_DEFAULT_PROC_READER)) ||
1988
+ !NIL_P(native_hash_property(tags, HASH_DEFAULT_READER)) || gc != liquid_gc_count()) return Qundef;
1989
+ guard->environment = environment;
1990
+ guard->tags = tags;
1991
+ }
1992
+ return rb_hash_lookup2(tags, name, Qnil);
1993
+ }
1994
+
1995
+ VALUE native_control_header(variable_parse_args_t *args, VALUE markup, int kind, bool commit)
1996
+ {
1997
+ if (!native_control_guard(args)) return Qnil;
1998
+ if (!args->guard->control_checked) {
1999
+ args->guard->control_checked = true;
2000
+ args->guard->control_enabled = false;
2001
+ VALUE mode = rb_ivar_get(args->parse_context, id_mode_native);
2002
+ if (mode != ID2SYM(rb_intern("warn")) && mode != ID2SYM(rb_intern("strict"))) return Qnil;
2003
+
2004
+ if (!args->guard->tags_enabled) return Qnil;
2005
+ VALUE classes[] = { native_condition_class, control_else_class, native_if_class, native_unless_class, native_for_class };
2006
+ for (size_t i = 0; i < sizeof(classes) / sizeof(classes[0]); i++) {
2007
+ VALUE klass = classes[i];
2008
+ bool original_new = i < 2 ? liquid_method_basic_definition_p(CLASS_OF(klass), id_new_native) :
2009
+ liquid_method_entry(CLASS_OF(klass), id_new_native) == control_tag_new_entry;
2010
+ if (rb_get_alloc_func(klass) != rb_get_alloc_func(rb_cObject) || !original_new ||
2011
+ !liquid_method_basic_definition_p(CLASS_OF(klass), id_allocate_native)) return Qnil;
2012
+ }
2013
+ if (rb_get_alloc_func(compiler_body_class) != compiler_body_allocator ||
2014
+ !liquid_method_basic_definition_p(CLASS_OF(compiler_body_class), id_new_native) ||
2015
+ !liquid_method_basic_definition_p(CLASS_OF(compiler_body_class), id_allocate_native)) return Qnil;
2016
+ args->guard->control_enabled = true;
2017
+ }
2018
+ if (!args->guard->control_enabled) return Qnil;
2019
+ size_t gc = liquid_gc_count();
2020
+ VALUE cache = args->guard->cache;
2021
+ VALUE result = native_parse_payload(markup, RTEST(cache) ? cache : Qnil, kind == 1 ? 1 : 2, true, true, args->guard);
2022
+ if (NIL_P(result) || native_parse_interrupted(gc)) return Qnil;
2023
+ if (commit) native_publish_cache(Qnil, cache, RARRAY_AREF(result, 1));
2024
+ RB_GC_GUARD(result);
2025
+ return result;
2026
+ }
2027
+
2028
+ void native_control_for_fields(VALUE tag, VALUE payload)
2029
+ {
2030
+ for (size_t i = 0; i < 6; i++) rb_ivar_set(tag, id_for_fields[i], RARRAY_AREF(payload, i));
2031
+ }
2032
+
2033
+ void native_control_commit(variable_parse_args_t *args, VALUE header)
2034
+ {
2035
+ native_publish_cache(Qnil, args->guard->cache, RARRAY_AREF(header, 1));
2036
+ }
2037
+
2038
+ void native_control_attach(variable_parse_args_t *args, VALUE condition, VALUE body)
2039
+ {
2040
+ if (native_control_guard(args) && native_control_condition(condition))
2041
+ rb_ivar_set(condition, rb_intern("@attachment"), body);
2042
+ else {
2043
+ args->guard->valid = false;
2044
+ rb_funcallv_public(condition, rb_intern("attach"), 1, &body);
2045
+ }
2046
+ }
2047
+
2048
+ VALUE native_control_else(variable_parse_args_t *args)
2049
+ {
2050
+ if (!native_control_guard(args) || rb_get_alloc_func(control_else_class) != rb_get_alloc_func(rb_cObject)) {
2051
+ args->guard->valid = false;
2052
+ return rb_funcall(control_else_class, id_new_native, 0);
2053
+ }
2054
+ size_t gc = liquid_gc_count();
2055
+ VALUE node = rb_obj_alloc(control_else_class);
2056
+ if (gc != liquid_gc_count()) {
2057
+ args->guard->valid = false;
2058
+ rb_funcall(node, rb_intern("initialize"), 0);
2059
+ } else {
2060
+ rb_ivar_set(node, rb_intern("@left"), Qnil);
2061
+ rb_ivar_set(node, rb_intern("@operator"), Qnil);
2062
+ rb_ivar_set(node, rb_intern("@right"), Qnil);
2063
+ rb_ivar_set(node, rb_intern("@child_relation"), Qnil);
2064
+ rb_ivar_set(node, rb_intern("@child_condition"), Qnil);
2065
+ }
2066
+ RB_GC_GUARD(node);
2067
+ return node;
2068
+ }
2069
+
2070
+ bool native_control_condition(VALUE node)
2071
+ {
2072
+ return CLASS_OF(node) == native_condition_class || CLASS_OF(node) == control_else_class;
2073
+ }
2074
+
2075
+ typedef struct { variable_parse_args_t *args; VALUE tag; } native_finish_t;
2076
+
2077
+ static void native_finish_body(variable_parse_args_t *args, VALUE body, const char *method)
2078
+ {
2079
+ if (!native_control_guard(args) || CLASS_OF(body) != compiler_body_class) args->guard->valid = false;
2080
+ rb_funcallv_public(body, rb_intern(method), 0, NULL);
2081
+ }
2082
+
2083
+ static VALUE native_finish_attachment(native_finish_t *finish, VALUE condition)
2084
+ {
2085
+ if (native_control_guard(finish->args) && native_control_condition(condition))
2086
+ return rb_ivar_get(condition, rb_intern("@attachment"));
2087
+ finish->args->guard->valid = false;
2088
+ return rb_funcallv_public(condition, rb_intern("attachment"), 0, NULL);
2089
+ }
2090
+
2091
+ static VALUE native_finish_condition(RB_BLOCK_CALL_FUNC_ARGLIST(condition, opaque))
2092
+ {
2093
+ native_finish_t *finish = (void *)opaque;
2094
+ VALUE blank;
2095
+ if (native_control_guard(finish->args) && native_control_kind(CLASS_OF(finish->tag)))
2096
+ blank = rb_ivar_get(finish->tag, rb_intern("@blank"));
2097
+ else {
2098
+ finish->args->guard->valid = false;
2099
+ blank = rb_funcall(finish->tag, rb_intern("blank?"), 0);
2100
+ }
2101
+ if (RTEST(blank)) native_finish_body(finish->args, native_finish_attachment(finish, condition), "remove_blank_strings");
2102
+ native_finish_body(finish->args, native_finish_attachment(finish, condition), "freeze");
2103
+ return Qnil;
2104
+ }
2105
+
2106
+ void native_control_finish(variable_parse_args_t *args, VALUE tag, int kind)
2107
+ {
2108
+ if (kind == 3) {
2109
+ native_finish_body(args, rb_ivar_get(tag, rb_intern("@body")), "freeze");
2110
+ return;
2111
+ }
2112
+ if (!args->guard->valid || !args->guard->control_validated || !native_control_guard(args)) {
2113
+ args->guard->valid = false;
2114
+ liquid_method_call(1, &tag, control_helpers[kind - 1]);
2115
+ return;
2116
+ }
2117
+ if (kind == 1) {
2118
+ native_finish_t finish = { args, tag };
2119
+ rb_block_call(rb_ivar_get(tag, rb_intern("@blocks")), rb_intern("reverse_each"), 0, NULL,
2120
+ native_finish_condition, (VALUE)&finish);
2121
+ } else {
2122
+ if (RTEST(rb_ivar_get(tag, rb_intern("@blank")))) {
2123
+ VALUE otherwise = rb_ivar_get(tag, rb_intern("@else_block"));
2124
+ if (!NIL_P(otherwise)) native_finish_body(args, otherwise, "remove_blank_strings");
2125
+ native_finish_body(args, rb_ivar_get(tag, rb_intern("@for_block")), "remove_blank_strings");
2126
+ }
2127
+ VALUE otherwise = rb_ivar_get(tag, rb_intern("@else_block"));
2128
+ if (!NIL_P(otherwise)) native_finish_body(args, otherwise, "freeze");
2129
+ native_finish_body(args, rb_ivar_get(tag, rb_intern("@for_block")), "freeze");
2130
+ }
2131
+ }
2132
+
2133
+ bool native_compile_variable(variable_parse_args_t *args, VALUE line_number)
2134
+ {
2135
+ if (!compiler_ready || !args->guard || liquid_vm_tracing()) return false;
2136
+ // The tokenizer owns and pins the frozen source during parsing.
2137
+ VALUE source = args->source;
2138
+ size_t offset = (size_t)(args->markup - RSTRING_PTR(source));
2139
+ size_t length = (size_t)(args->markup_end - args->markup);
2140
+ int coderange = ENC_CODERANGE_UNKNOWN;
2141
+ rb_str_coderange_scan_restartable(args->markup, args->markup_end, utf8_encoding, &coderange);
2142
+ if (coderange == ENC_CODERANGE_BROKEN || coderange == ENC_CODERANGE_UNKNOWN) return false;
2143
+ native_parser_t parser = { .source = source, .cache = Qnil,
2144
+ .pending = Qnil, .position = offset, .length = offset + length, .code = args->code, .guarded = true, .compact_pending = true };
2145
+ native_parser_t probe = parser, validated_name;
2146
+ if (!native_validate_variable(&probe, &validated_name)) return false;
2147
+ if (!native_compiler_guard(args)) return false;
2148
+ variable_compile_guard_t *guard = args->guard;
2149
+ parser.cache = RTEST(guard->cache) ? guard->cache : Qnil;
2150
+ parser.initial_gc_count = guard->gc_count;
2151
+ // The descriptor owns its markup bytes independently of the tokenizer.
2152
+ // Temporary parsing uses offsets into the tokenizer's pinned source.
2153
+ VALUE node = variable_placeholder_new(source, offset, length, args->parse_context, line_number);
2154
+ if (!native_compiler_accepts_result(guard, node)) return false;
2155
+ vm_assembler_t saved = *args->code;
2156
+ size_t instruction_size = c_buffer_size(&saved.instructions);
2157
+ size_t constant_size = c_buffer_size(&saved.constants);
2158
+ vm_assembler_add_unique_variable(args->code, line_number, node);
2159
+ args->code->protected_stack_size = args->code->stack_size;
2160
+ // Reuse the lexical preflight without copying its earlier cache/GC state.
2161
+ native_parser_t name_probe = parser;
2162
+ name_probe.position = validated_name.position;
2163
+ name_probe.start = validated_name.start;
2164
+ name_probe.end = validated_name.end;
2165
+ name_probe.token = validated_name.token;
2166
+ VALUE result = native_variable_body_probed((VALUE)&parser, &name_probe);
2167
+ if (!native_compiler_accepts_result(guard, result)) {
2168
+ native_restore_assembler(args->code, &saved, instruction_size, constant_size);
2169
+ return false;
2170
+ }
2171
+ variable_placeholder_set(node, parser.variable_name, parser.variable_filters);
2172
+ vm_assembler_add_pop_write(args->code);
2173
+ // Only builtin Hash operations on verified plain String keys execute here.
2174
+ if (RB_TYPE_P(parser.pending, T_STRING)) native_publish_entry(parser.pending, parser.pending_value, parser.cache);
2175
+ else native_publish_cache(Qnil, parser.cache, parser.pending);
2176
+ if (guard->gc_count != liquid_gc_count()) guard->valid = false;
2177
+ RB_GC_GUARD(result);
2178
+ RB_GC_GUARD(node);
2179
+ RB_GC_GUARD(source);
2180
+ RB_GC_GUARD(parser.pending);
2181
+ RB_GC_GUARD(parser.pending_value);
2182
+ return true;
2183
+ }
2184
+ #else
2185
+ #ifdef HAVE_RB_CALLABLE_METHOD_ENTRY
2186
+ static VALUE native_fast_header(VALUE self, VALUE markup) { return Qundef; }
2187
+ #endif
2188
+ bool native_compiler_guard(variable_parse_args_t *args) { return false; }
2189
+ bool native_include_class_p(VALUE klass) { return false; }
2190
+ VALUE native_parse_include(variable_parse_args_t *args, VALUE klass, VALUE name, VALUE markup) { return Qundef; }
2191
+ VALUE native_parse_capture(variable_parse_args_t *args, VALUE klass, VALUE name, VALUE markup) { return Qundef; }
2192
+ bool native_assignment_class_p(VALUE klass) { return false; }
2193
+ VALUE native_parse_assignment(variable_parse_args_t *args, VALUE klass, VALUE name, VALUE markup) { return Qundef; }
2194
+ bool native_control_guard(variable_parse_args_t *args) { return false; }
2195
+ VALUE native_registered_tag(variable_parse_args_t *args, VALUE environment, VALUE name) { return Qundef; }
2196
+ VALUE native_control_header(variable_parse_args_t *args, VALUE markup, int kind, bool commit) { return Qnil; }
2197
+ void native_control_commit(variable_parse_args_t *args, VALUE header) {}
2198
+ void native_control_for_fields(VALUE tag, VALUE payload) {}
2199
+ void native_control_attach(variable_parse_args_t *args, VALUE condition, VALUE body) {}
2200
+ int native_control_kind(VALUE klass) { return 0; }
2201
+ VALUE native_control_else(variable_parse_args_t *args) { return Qnil; }
2202
+ void native_control_finish(variable_parse_args_t *args, VALUE tag, int kind) {}
2203
+ bool native_control_condition(VALUE node) { return false; }
2204
+ bool native_compile_variable(variable_parse_args_t *args, VALUE line_number) { return false; }
2205
+ bool variable_render_methods_standard(void) { return liquid_vm_render_methods_standard(); }
2206
+ bool variable_render_traced(void) { return true; }
2207
+ bool variable_output_method_standard(void) { return false; }
2208
+ #endif
2209
+
2210
+ void liquid_define_native_parser(void)
2211
+ {
2212
+ #ifdef LIQUID_HAVE_GUARDED_COMPILER
2213
+ rb_global_variable(&renderer_guard_entries);
2214
+ rb_global_variable(&compiler_body_class);
2215
+ rb_global_variable(&compiler_constants);
2216
+ rb_global_variable(&native_assign_class);
2217
+ rb_global_variable(&native_capture_class);
2218
+ rb_global_variable(&native_include_class);
2219
+ rb_global_variable(&compiler_constant_watchers);
2220
+ rb_global_variable(&compiler_ancestor_prefixes);
2221
+ rb_global_variable(&control_else_class);
2222
+ rb_global_variable(&control_environment_class);
2223
+ rb_global_variable(&control_tag_new_entry);
2224
+ for (size_t i = 0; i < 2; i++) rb_global_variable(&control_helpers[i]);
2225
+ rb_define_singleton_method(mLiquidC, "native_register_control", native_register_control, 4);
2226
+ rb_global_variable(&compiler_stat);
2227
+ rb_global_variable(&compiler_epoch);
2228
+ rb_define_singleton_method(mLiquidC, "native_register_compiler", native_register_compiler, 2);
2229
+ rb_define_singleton_method(mLiquidC, "native_install_compiler_context", native_install_compiler_context, 0);
2230
+ #endif
2231
+ #ifdef LIQUID_C_TEST_ALLOC_FAILURES
2232
+ rb_global_variable(&native_parser_test_callback);
2233
+ rb_define_singleton_method(mLiquidC, "native_parser_test_callback=", native_set_parser_test_callback, 1);
2234
+ #endif
2235
+ VALUE *roots[] = { &native_expression_class, &native_parser_class, &native_condition_class, &native_literals, &native_unbound_class };
2236
+ for (size_t i = 0; i < sizeof(roots) / sizeof(roots[0]); i++) rb_global_variable(roots[i]);
2237
+ native_unbound_class = Qnil;
2238
+ #ifndef HAVE_RB_AUTOLOAD_P
2239
+ rb_global_variable(&native_autoload_reader);
2240
+ ID autoload_query = rb_intern("autoload?"), module_instance_method = rb_intern("instance_method");
2241
+ if (liquid_method_basic_definition_p(CLASS_OF(rb_cModule), module_instance_method) &&
2242
+ liquid_method_basic_definition_p(rb_cModule, autoload_query)) {
2243
+ VALUE unbound = rb_funcall(rb_cModule, module_instance_method, 1, ID2SYM(autoload_query));
2244
+ ID reader_bind_call = rb_intern("bind_call");
2245
+ if (liquid_method_basic_definition_p(CLASS_OF(unbound), reader_bind_call))
2246
+ native_autoload_reader = liquid_method_handle(rb_obj_method(unbound, ID2SYM(reader_bind_call)));
2247
+ RB_GC_GUARD(unbound);
2248
+ }
2249
+ #endif
2250
+ native_expression_class = native_capture_constant(mLiquid, "Expression");
2251
+ native_parser_class = native_capture_constant(mLiquid, "Parser");
2252
+ native_condition_class = native_capture_constant(mLiquid, "Condition");
2253
+ native_literals = native_capture_constant(native_expression_class, "LITERALS");
2254
+ const char *properties[] = { "compare_by_identity?", "default_proc", "default" };
2255
+ ID instance_method = rb_intern("instance_method"), bind_call = rb_intern("bind_call");
2256
+ for (size_t i = 0; i < sizeof(properties) / sizeof(properties[0]); i++) {
2257
+ rb_global_variable(&native_hash_readers[i]);
2258
+ native_hash_readers[i] = Qnil;
2259
+ ID property = rb_intern(properties[i]);
2260
+ if (!liquid_method_basic_definition_p(CLASS_OF(rb_cHash), instance_method) ||
2261
+ !liquid_method_basic_definition_p(rb_cHash, property)) continue;
2262
+ VALUE unbound = rb_funcall(rb_cHash, instance_method, 1, ID2SYM(property));
2263
+ native_unbound_class = CLASS_OF(unbound);
2264
+ if (!liquid_method_basic_definition_p(native_unbound_class, bind_call)) continue;
2265
+ VALUE reader = liquid_method_handle(rb_obj_method(unbound, ID2SYM(bind_call)));
2266
+ if (liquid_method_basic_definition_p(CLASS_OF(unbound), bind_call) &&
2267
+ liquid_method_basic_definition_p(rb_cHash, property)) native_hash_readers[i] = reader;
2268
+ RB_GC_GUARD(unbound);
2269
+ }
2270
+ const char *strings[] = { "strip", "start_with?", "end_with?", "scan", "match", "to_f", "[]", "freeze", "=~", "<<", "==", "byteslice", "length", "dup", "initialize_copy", "initialize_dup", "hash", "eql?" };
2271
+ for (size_t i = 0; i < sizeof(strings) / sizeof(strings[0]); i++) native_guard_primitive(rb_cString, strings[i]);
2272
+ const char *arrays[] = { "all?", "each_with_index", "push", "reverse_each", "shift", "each_index", "[]", "[]=", "<<", "include?", "each", "size", "==" };
2273
+ for (size_t i = 0; i < sizeof(arrays) / sizeof(arrays[0]); i++) native_guard_primitive(rb_cArray, arrays[i]);
2274
+ native_guard_primitive(cLiquidVariableLookup, "freeze");
2275
+ native_guard_primitive(cLiquidRangeLookup, "freeze");
2276
+ native_guard_primitive(rb_cRange, "freeze");
2277
+ native_guard_primitive(rb_cHash, "[]");
2278
+ native_guard_primitive(rb_cHash, "[]=");
2279
+ native_guard_primitive(rb_cHash, "key?");
2280
+ native_guard_primitive(rb_cHash, "each");
2281
+ native_guard_primitive(rb_cHash, "size");
2282
+ native_guard_primitive(rb_cInteger, "<<");
2283
+ native_guard_primitive(rb_cInteger, "|");
2284
+ native_guard_primitive(rb_cInteger, "&");
2285
+ native_guard_primitive(rb_cInteger, "<=>");
2286
+ native_guard_primitive(rb_cInteger, "freeze");
2287
+ native_guard_primitive(rb_cFloat, "freeze");
2288
+ native_guard_primitive(rb_cNilClass, "==");
2289
+ native_guard_primitive(rb_cRegexp, "===");
2290
+ native_guard_primitive(rb_cRegexp, "match?");
2291
+ native_guard_primitive(native_condition_class, "send");
2292
+ native_guard_primitive(rb_cMatch, "[]");
2293
+ native_guard_primitive(rb_cObject, "is_a?");
2294
+ native_guard_primitive(rb_cObject, "freeze");
2295
+ const char *integers[] = { "+", "-", "==", "!=", "<", ">", ">=" };
2296
+ for (size_t i = 0; i < sizeof(integers) / sizeof(integers[0]); i++) native_guard_primitive(rb_cInteger, integers[i]);
2297
+ const char *symbols[] = { "==", "!=", "===" };
2298
+ for (size_t i = 0; i < sizeof(symbols) / sizeof(symbols[0]); i++) native_guard_primitive(rb_cSymbol, symbols[i]);
2299
+ id_string_scanner = rb_intern("@string_scanner");
2300
+ id_new_native = rb_intern("new");
2301
+ id_allocate_native = rb_intern("allocate");
2302
+ id_disabled_native = rb_intern("@liquid_c_nodes_disabled");
2303
+ id_mode_native = rb_intern("@error_mode");
2304
+ id_cache_native = rb_intern("@expression_cache");
2305
+ id_options_native = rb_intern("@options");
2306
+ id_parse_context_native = rb_intern("@parse_context");
2307
+ id_stats_native = rb_intern("native_parser_stats");
2308
+ id_enabled_native = rb_intern("@enabled");
2309
+ const char *for_fields[] = { "@variable_name", "@collection_name", "@name", "@reversed", "@from", "@limit" };
2310
+ for (size_t i = 0; i < 6; i++) id_for_fields[i] = rb_intern(for_fields[i]);
2311
+ rb_global_variable(&native_if_class);
2312
+ rb_global_variable(&native_unless_class);
2313
+ rb_global_variable(&native_for_class);
2314
+ rb_global_variable(&native_original_if);
2315
+ rb_global_variable(&native_original_for);
2316
+ #ifdef HAVE_RB_CALLABLE_METHOD_ENTRY
2317
+ rb_global_variable(&native_if_parse_entry);
2318
+ rb_global_variable(&native_for_parse_entry);
2319
+ rb_global_variable(&native_switching_module);
2320
+ for (size_t i = 0; i < 3; i++) rb_global_variable(&native_context_entries[i]);
2321
+ #endif
2322
+ rb_global_variable(&native_context_class);
2323
+ rb_global_variable(&native_case_class);
2324
+ native_context_class = rb_const_get(mLiquid, rb_intern("ParseContext"));
2325
+ native_case_class = rb_const_get(mLiquid, rb_intern("Case"));
2326
+ native_if_class = rb_const_get(mLiquid, rb_intern("If"));
2327
+ native_unless_class = rb_const_get(mLiquid, rb_intern("Unless"));
2328
+ native_for_class = rb_const_get(mLiquid, rb_intern("For"));
2329
+ #ifdef LIQUID_HAVE_GUARDED_COMPILER
2330
+ rb_define_singleton_method(mLiquidC, "native_try_parse_variable", native_try_variable, 3);
2331
+ #endif
2332
+ rb_define_singleton_method(mLiquidC, "native_install_case_parser", native_install_case_parser, 0);
2333
+ rb_define_singleton_method(mLiquidC, "native_install_header_parser", native_install_header_parser, 2);
2334
+ rb_define_singleton_method(mLiquidC, "native_install_strict_context", native_install_strict_context, 0);
2335
+ rb_define_singleton_method(mLiquidC, "native_parser_tracing?", native_parser_tracing, 0);
2336
+ rb_define_singleton_method(mLiquidC, "native_variable_frontend", native_variable_frontend, 3);
2337
+ rb_define_private_method(rb_const_get(mLiquid, rb_intern("Variable")), "liquid_c_native_parse", native_variable_frontend_method, 1);
2338
+ rb_define_singleton_method(mLiquidC, "native_enable_variable_frontend", native_enable_variable_frontend, 0);
2339
+ #ifdef HAVE_RB_CALLABLE_METHOD_ENTRY
2340
+ rb_define_singleton_method(mLiquidC, "native_constant_watchers_supported?", native_watchers_supported, 1);
2341
+ rb_define_singleton_method(mLiquidC, "native_parser_register_guards", native_register_guards, 3);
2342
+ rb_define_singleton_method(mLiquidC, "native_parser_methods_compatible?", native_methods_compatible, 2);
2343
+ #endif
2344
+ rb_define_singleton_method(mLiquidC, "native_constant_matches?", native_constant_matches, 4);
2345
+ rb_define_singleton_method(mLiquidC, "native_public_method?", native_public_method, 2);
2346
+ rb_define_singleton_method(mLiquidC, "native_frontend_candidate?", native_frontend_candidate, 1);
2347
+ rb_define_singleton_method(mLiquidC, "native_variable_candidate?", native_variable_candidate, 2);
2348
+ id_name = rb_intern("@name");
2349
+ id_lookups = rb_intern("@lookups");
2350
+ id_commands = rb_intern("@command_flags");
2351
+ id_start = rb_intern("@start_obj");
2352
+ id_end = rb_intern("@end_obj");
2353
+ rb_define_singleton_method(mLiquidC, "native_parse_variable", native_parse_variable, 2);
2354
+ rb_define_singleton_method(mLiquidC, "native_parse_condition", native_parse_condition, 2);
2355
+ rb_define_singleton_method(mLiquidC, "native_parse_for", native_parse_for, 2);
2356
+ rb_define_singleton_method(mLiquidC, "native_parse_expression", native_parse_expression, 2);
2357
+ rb_define_singleton_method(mLiquidC, "native_case_candidate?", native_case_candidate, 2);
2358
+ rb_define_singleton_method(mLiquidC, "native_publish_cache", native_publish_cache, 2);
2359
+ rb_define_singleton_method(mLiquidC, "native_record_stats", native_record_stats, 2);
2360
+ }