1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
//! Version 0.
//!
//! This module defines representations of the hugr IR as plain data, designed
//! to be as independent of implementation details of the compiler as feasible.
//! It can be used by the core compiler, alternative implementations or tooling
//! that does not need the power/complexity of the full compiler. We provide the
//! following in-memory representations:
//!
//! - [Table]: Efficient intermediate data structure to facilitate conversions.
//! - [AST]: Abstract syntax tree that uses direct references rather than table indices.
//!
//! The table and AST format are interconvertible and can be serialised to
//! a binary and text format, respectively:
//!
//! - [Binary]: Binary serialisation format optimised for performance and size.
//! - [Text]: Human readable s-expression based text format.
//!
//! # Logical Format
//!
//! The hugr IR is a hierarchical graph data structure. __Nodes__ represent both
//! __instructions__ that manipulate runtime values and __symbols__ which
//! represent named language objects. Instructions have __input__ and __output__ ports
//! and runtime values flow between ports when they are connected by a __link__.
//!
//! Nodes are organised into __regions__ and do not have any explicit ordering
//! between them; any schedule that respects the data dependencies between nodes
//! is valid. Previous designs included order-edges that could be added between nodes
//! to further constrain the ordering; as long as this system is still used, order hint
//! metadata can be used to encode the additional ordering constraints.
//!
//! Regions come in three different kinds. __Module regions__ form the
//! top level of a module and can only contain symbols. __Dataflow regions__
//! describe how data flows from the region's __source__ ports to the region's
//! __target__ ports and are restricted to contain instructions. __Controlflow regions__
//! are control flow graphs containing dataflow __blocks__, with control flow originating
//! from the region's source ports and ending in the region's target ports.
//!
//! __Terms__ form a meta language that is used to describe types, parameters and metadata that
//! are known statically. To allow types to be parameterized by statically known values, types
//! and static values are treated uniformly as terms, enabling a restricted form of dependent typing.
//! Terms are extensible declaratively via __constructors__. __Constraints__ can be used to express
//! more complex validation rules.
//!
//! # Remaining Mismatch with `hugr-core`
//!
//! This data model was designed to encode as much of `hugr-core` as possible while also
//! filling in conceptual gaps and providing a forward-compatible foundation for future
//! development. However, there are still some mismatches with `hugr-core` that are not
//! addressed by conversions in import/export:
//!
//! - Some terms can not yet be represented in `hugr-core` although they should be.
//! Importing such terms will result in an error that declares these terms as currently
//! unsupported.
//! - In particular `hugr-core` (as of `v0.22.3`) only allows to define custom runtime types but
//! can not represent custom term constructors for static types. Implementing support for
//! static `Term`s in `hugr-core` will allow to use the term system for extensible metadata
//! and constants. Once that is implemented, the hugr IR will have a unified extension mechanism.
//! - `hugr-core` uses a JSON encoding for metadata which is supported by `hugr-model` via the
//! `compat.meta_json` metadata constructor. `hugr-model` further allows to declare custom
//! metadata constructors so that metadata can be composed of terms. These are currently not
//! supported in `hugr-core` beyond a few exceptions which are hard-coded into the import/export
//! process.
//! - `hugr-core` uses JSON encoded constants. Similarly to metadata, `hugr-model` provides a
//! compatibility mechanism via the `compat.const_json` constant constructor but also allows
//! to declare custom constant constructors. Import/export has hard-coded support for a small
//! fixed set of these for now.
//! - In `hugr-core` a constant is a `Value`, included in the hugr graph via a `Const` node.
//! A `LoadConst` node connects to the `Const` node via a static edge. `Value`s are separate
//! from `Term`s in `hugr-core` and can not refer to local variables or to function nodes.
//! In `hugr-model` the `Const` node is not needed: The `core.load_const` operation takes
//! the constant's description as a term argument. This enables `hugr-model` constants to
//! depend on local variables and to refer to functions in the module (removing the need
//! for a separate `LoadFunc` operation).
//! - `Value`s in `hugr-core` have a single representation for every constant. The encoding
//! of constants as terms in `hugr-model` can use different constructors for the same type
//! of constant value. This can be useful for large constants by enabling efficient encodings.
//! For example, a constant array of integers could have a constructor taking a byte string
//! that consists of the integer values, which is significantly more economical than a generic
//! representation of arrays that has a term for every element.
//! - The model does not have types with a copy bound as `hugr-core` does, and instead uses
//! a more general form of type constraints ([#1556]). Similarly, the model does not have
//! bounded naturals. We perform a conversion for compatibility where possible, but this does
//! not fully cover all potential cases of bounds.
//! - `hugr-model` has support for passing closed regions as static parameters to operations,
//! which allows for higher-order operations that require their function arguments to be
//! statically known. We currently do not yet support converting this to `hugr-core`.
//! - In a model module, ports are connected when they share the same link. This differs from
//! the type of port connectivity in the graph data structure used by `hugr-core`. However,
//! `hugr-core` restricts connectivity so that in any group of connected ports there is at
//! most one output port (for dataflow) or at most one input port (for control flow). In
//! these cases, there is no mismatch.
//! - `hugr-core` only allows to define type aliases, but not aliases for other terms. The
//! alias system is under-developed in both `hugr-core` and `hugr-model` and will need some
//! considerable design and implementation work (or to be removed if deemed unnecessary).
//! See [#2558].
//!
//! [#1556]: https://github.com/CQCL/hugr/discussions/1556
//! [#2558]: https://github.com/CQCL/hugr/issues/2558
//! [Text]: crate::v0::ast
//! [Binary]: crate::v0::binary
//! [Table]: crate::v0::table
//! [AST]: crate::v0::ast
use OrderedFloat;
use PyTypeInfo as _;
use PyAnyMethods as _;
use SmolStr;
use Arc;
use LinkIndex;
/// Describes how a function or symbol should be acted upon by a linker
/// Core function types.
///
/// - **Parameter:** `?inputs : (core.list core.type)`
/// - **Parameter:** `?outputs : (core.list core.type)`
/// - **Result:** `core.type`
pub const CORE_FN: &str = "core.fn";
/// The type of runtime types.
///
/// Runtime types are the types of values that can flow between nodes at runtime.
///
/// - **Result:** `?type : core.static`
pub const CORE_TYPE: &str = "core.type";
/// The type of static types.
///
/// Static types are the types of statically known parameters.
///
/// This is the only term that is its own type.
///
/// - **Result:** `?type : core.static`
pub const CORE_STATIC: &str = "core.static";
/// The type of constraints.
///
/// - **Result:** `?type : core.static`
pub const CORE_CONSTRAINT: &str = "core.constraint";
/// The constraint for non-linear runtime data.
///
/// Runtime values are copied implicitly by connecting an output port to more
/// than one input port. Similarly runtime values can be deleted implicitly when
/// an output port is not connected to any input port. In either of these cases
/// the type of the runtime value must satisfy this constraint.
///
/// - **Parameter:** `?type : core.type`
/// - **Result:** `core.constraint`
pub const CORE_NON_LINEAR: &str = "core.nonlinear";
/// The type of metadata.
///
/// - **Result:** `?type : core.static`
pub const CORE_META: &str = "core.meta";
/// Runtime algebraic data types.
///
/// Algebraic data types are sums of products of other runtime types.
///
/// - **Parameter:** `?variants : (core.list (core.list core.type))`
/// - **Result:** `core.type`
pub const CORE_ADT: &str = "core.adt";
/// Type of string literals.
///
/// - **Result:** `core.static`
pub const CORE_STR_TYPE: &str = "core.str";
/// Type of natural number literals.
///
/// - **Result:** `core.static`
pub const CORE_NAT_TYPE: &str = "core.nat";
/// Type of bytes literals.
///
/// - **Result:** `core.static`
pub const CORE_BYTES_TYPE: &str = "core.bytes";
/// Type of float literals.
///
/// - **Result:** `core.static`
pub const CORE_FLOAT_TYPE: &str = "core.float";
/// Type of control flow regions.
///
/// - **Parameter:** `?inputs : (core.list (core.list core.type))`
/// - **Parameter:** `?outputs : (core.list (core.list core.type))`
/// - **Result:** `core.type`
pub const CORE_CTRL: &str = "core.ctrl";
/// The type for runtime constants.
///
/// - **Parameter:** `?type : core.type`
/// - **Result:** `core.static`
pub const CORE_CONST: &str = "core.const";
/// Constants for runtime algebraic data types.
///
/// - **Parameter:** `?variants : (core.list core.type)`
/// - **Parameter:** `?types : (core.list core.static)`
/// - **Parameter:** `?tag : core.nat`
/// - **Parameter:** `?values : (core.tuple ?types)`
/// - **Result:** `(core.const (core.adt ?variants))`
pub const CORE_CONST_ADT: &str = "core.const.adt";
/// The type for lists of static data.
///
/// Lists are finite sequences such that all elements have the same type.
/// For heterogeneous sequences, see [`CORE_TUPLE_TYPE`].
///
/// - **Parameter:** `?type : core.static`
/// - **Result:** `core.static`
pub const CORE_LIST_TYPE: &str = "core.list";
/// The type for tuples of static data.
///
/// Tuples are finite sequences that allow elements to have different types.
/// For homogeneous sequences, see [`CORE_LIST_TYPE`].
///
/// - **Parameter:** `?types : (core.list core.static)`
/// - **Result:** `core.static`
pub const CORE_TUPLE_TYPE: &str = "core.tuple";
/// Operation to call a statically known function.
///
/// - **Parameter:** `?inputs : (core.list core.type)`
/// - **Parameter:** `?outputs : (core.list core.type)`
/// - **Parameter:** `?func : (core.const (core.fn ?inputs ?outputs))`
/// - **Result:** `(core.fn ?inputs ?outputs ?ext)`
pub const CORE_CALL: &str = "core.call";
/// Operation to call a function known at runtime.
///
/// - **Parameter:** `?inputs : (core.list core.type)`
/// - **Parameter:** `?outputs : (core.list core.type)`
/// - **Result:** `(core.fn [(core.fn ?inputs ?outputs) ?inputs ...] ?outputs)`
pub const CORE_CALL_INDIRECT: &str = "core.call_indirect";
/// Operation to load a constant value.
///
/// - **Parameter:** `?type : core.type`
/// - **Parameter:** `?value : (core.const ?type)`
/// - **Result:** `(core.fn [] [?type])`
pub const CORE_LOAD_CONST: &str = "core.load_const";
/// Operation to create a value of an algebraic data type.
///
/// - **Parameter:** `?variants : (core.list (core.list core.type))`
/// - **Parameter:** `?types : (core.list core.type)`
/// - **Parameter:** `?tag : core.nat`
/// - **Result:** `(core.fn ?types [(core.adt ?variants)])`
pub const CORE_MAKE_ADT: &str = "core.make_adt";
/// Constructor for documentation metadata.
///
/// - **Parameter:** `?description : core.str`
/// - **Result:** `core.meta`
pub const CORE_META_DESCRIPTION: &str = "core.meta.description";
/// Metadata to tag a node or region as the entrypoint of a module.
///
/// - **Result:** `core.meta`
pub const CORE_ENTRYPOINT: &str = "core.entrypoint";
/// Constructor for JSON encoded metadata.
///
/// This is included in the model to allow for compatibility with `hugr-core`.
/// The intention is to deprecate this in the future in favor of metadata
/// expressed with custom constructors.
///
/// - **Parameter:** `?name : core.str`
/// - **Parameter:** `?json : core.str`
/// - **Result:** `core.meta`
pub const COMPAT_META_JSON: &str = "compat.meta_json";
/// Constructor for JSON encoded constants.
///
/// This is included in the model to allow for compatibility with `hugr-core`.
/// The intention is to deprecate this in the future in favor of constants
/// expressed with custom constructors.
///
/// - **Parameter:** `?type : core.type`
/// - **Parameter:** `?json : core.str`
/// - **Result:** `(core.const ?type)`
pub const COMPAT_CONST_JSON: &str = "compat.const_json";
/// Metadata constructor for order hint keys.
///
/// Nodes in a dataflow region can be annotated with a key. Each node may have
/// at most one key and the key must be unique among all nodes in the same
/// dataflow region. The parent dataflow graph can then use the
/// `order_hint.order` metadata to imply a desired ordering relation, referring
/// to the nodes by their key.
///
/// - **Parameter:** `?key : core.nat`
/// - **Result:** `core.meta`
pub const ORDER_HINT_KEY: &str = "core.order_hint.key";
/// Metadata constructor for order hint keys on input nodes.
///
/// When the sources of a dataflow region are represented by an input operation
/// within the region, this metadata can be attached the region to give the
/// input node an order hint key.
///
/// - **Parameter:** `?key : core.nat`
/// - **Result:** `core.meta`
pub const ORDER_HINT_INPUT_KEY: &str = "core.order_hint.input_key";
/// Metadata constructor for order hint keys on output nodes.
///
/// When the targets of a dataflow region are represented by an output operation
/// within the region, this metadata can be attached the region to give the
/// output node an order hint key.
///
/// - **Parameter:** `?key : core.nat`
/// - **Result:** `core.meta`
pub const ORDER_HINT_OUTPUT_KEY: &str = "core.order_hint.output_key";
/// Metadata constructor for order hints.
///
/// When this metadata is attached to a dataflow region, it can indicate a
/// preferred ordering relation between child nodes. Code generation must take
/// this into account when deciding on an execution order. The child nodes are
/// identified by a key, using the `order_hint.key` metadata.
///
/// The graph consisting of both value dependencies between nodes and order
/// hints must be directed acyclic.
///
/// - **Parameter:** `?before : core.nat`
/// - **Parameter:** `?after : core.nat`
/// - **Result:** `core.meta`
pub const ORDER_HINT_ORDER: &str = "core.order_hint.order";
/// Metadata constructor for symbol titles.
///
/// The names of functions in `hugr-core` are currently not used for symbol
/// resolution, but rather serve as a short description of the function.
/// As such, there is no requirement for uniqueness or formatting.
/// This metadata can be used to preserve that name when serializing through
/// `hugr-model`.
///
/// - **Parameter:** `?title: core.str`
/// - **Result:** `core.meta`
pub const CORE_TITLE: &str = "core.title";
pub use bumpalo;
/// Type to indicate whether scopes are open or closed.
/// The kind of a region.
/// The name of a variable.
;
/// The name of a symbol.
;
/// The name of a link.
;
/// A static literal value.
///
/// Literal values may be large since they can include strings and byte
/// sequences of arbitrary length. To enable cheap cloning and sharing,
/// strings and byte sequences use reference counting.