Skip to content

Commit 47b593a

Browse files
committed
Cleanup file structure, use better emitter names
1 parent c274c21 commit 47b593a

File tree

18 files changed

+91
-241
lines changed

18 files changed

+91
-241
lines changed

tket2/src/ops.rs

Lines changed: 2 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use std::sync::{Arc, Weak};
22

33
use crate::extension::rotation::rotation_type;
4-
use crate::extension::sympy::{SympyOpDef, SYM_OP_ID};
4+
use crate::extension::sympy::SympyOpDef;
55
use crate::extension::{TKET2_EXTENSION, TKET2_EXTENSION_ID as EXTENSION_ID};
66
use hugr::ops::custom::ExtensionOp;
77
use hugr::ops::NamedOp;
@@ -14,7 +14,7 @@ use hugr::{
1414
},
1515
ops::OpType,
1616
type_row,
17-
types::{type_param::TypeArg, Signature},
17+
types::Signature,
1818
};
1919

2020
use derive_more::{Display, Error};
@@ -185,29 +185,6 @@ pub fn symbolic_constant_op(arg: String) -> OpType {
185185
SympyOpDef.with_expr(arg).into()
186186
}
187187

188-
/// match against a symbolic constant
189-
pub(crate) fn match_symb_const_op(op: &OpType) -> Option<String> {
190-
// Extract the symbol for a symbolic operation node.
191-
let symbol_from_typeargs = |args: &[TypeArg]| -> String {
192-
args.first()
193-
.and_then(|arg| match arg {
194-
TypeArg::String { arg } => Some(arg.clone()),
195-
_ => None,
196-
})
197-
.unwrap_or_else(|| panic!("Found an invalid type arg in a symbolic operation node."))
198-
};
199-
200-
if let OpType::ExtensionOp(e) = op {
201-
if e.def().name() == &SYM_OP_ID && e.def().extension_id() == &EXTENSION_ID {
202-
Some(symbol_from_typeargs(e.args()))
203-
} else {
204-
None
205-
}
206-
} else {
207-
None
208-
}
209-
}
210-
211188
#[cfg(test)]
212189
pub(crate) mod test {
213190

tket2/src/serialize/pytket.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,9 @@
33
mod decoder;
44
mod encoder;
55
pub mod extension;
6-
mod op;
7-
mod param;
86

97
pub use encoder::{default_encoder_config, Tk1EncoderConfig, Tk1EncoderContext};
10-
pub use extension::Tk1Encoder;
8+
pub use extension::PytketEmitter;
119

1210
use hugr::core::HugrNode;
1311
use hugr::types::Type;

tket2/src/serialize/pytket/decoder.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
//! Intermediate structure for decoding [`SerialCircuit`]s into [`Hugr`]s.
22
3+
mod op;
4+
mod param;
5+
36
use std::collections::{HashMap, HashSet};
47

58
use hugr::builder::{Container, Dataflow, DataflowHugr, FunctionBuilder};
@@ -19,8 +22,6 @@ use tket_json_rs::circuit_json;
1922
use tket_json_rs::circuit_json::SerialCircuit;
2023
use tket_json_rs::register;
2124

22-
use super::op::Tk1Op;
23-
use super::param::decode::{parse_pytket_param, PytketParam};
2425
use super::{
2526
OpConvertError, RegisterHash, Tk1ConvertError, METADATA_B_OUTPUT_REGISTERS,
2627
METADATA_B_REGISTERS, METADATA_OPGROUP, METADATA_PHASE, METADATA_Q_OUTPUT_REGISTERS,
@@ -30,6 +31,8 @@ use crate::extension::rotation::{rotation_type, RotationOp};
3031
use crate::extension::TKET1_EXTENSION_ID;
3132
use crate::serialize::pytket::METADATA_INPUT_PARAMETERS;
3233
use crate::symbolic_constant_op;
34+
use op::Tk1Op;
35+
use param::{parse_pytket_param, PytketParam};
3336

3437
/// The state of an in-progress [`FunctionBuilder`] being built from a [`SerialCircuit`].
3538
///

tket2/src/serialize/pytket/op.rs renamed to tket2/src/serialize/pytket/decoder/op.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use hugr::IncomingPort;
1111
use tk2op::NativeOp;
1212
use tket_json_rs::circuit_json;
1313

14-
use super::extension::OpaqueTk1Op;
14+
use super::super::extension::OpaqueTk1Op;
1515

1616
pub mod tk2op;
1717

tket2/src/serialize/pytket/param/decode.rs renamed to tket2/src/serialize/pytket/decoder/param.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ pub fn parse_pytket_param(param: &str) -> PytketParam<'_> {
5555
}
5656

5757
#[derive(Parser)]
58-
#[grammar = "serialize/pytket/param/param.pest"]
58+
#[grammar = "serialize/pytket/decoder/param.pest"]
5959
struct ParamParser;
6060

6161
lazy_static::lazy_static! {

tket2/src/serialize/pytket/encoder.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,12 +55,12 @@ pub struct Tk1EncoderContext<H: HugrView> {
5555
unsupported: UnsupportedTracker<H::Node>,
5656
/// Configuration for the encoding.
5757
///
58-
/// Contains custom operation/type encoders.
58+
/// Contains custom operation/type/const emitters.
5959
config: Arc<Tk1EncoderConfig<H>>,
6060
}
6161

6262
impl<H: HugrView> Tk1EncoderContext<H> {
63-
/// Create a new [`JsonEncoder`] from a [`Circuit`].
63+
/// Create a new [`Tk1EncoderContext`] from a [`Circuit`].
6464
pub(super) fn new(
6565
circ: &Circuit<H>,
6666
config: Tk1EncoderConfig<H>,
@@ -117,7 +117,7 @@ impl<H: HugrView> Tk1EncoderContext<H> {
117117
portgraph::algorithms::toposort(region, initials, portgraph::Direction::Outgoing);
118118
let io_nodes = circ.io_nodes();
119119
// TODO: Use weighted topological sort to try and explore unsupported
120-
// ops first (that is, ops with no available encoder in `self.config`),
120+
// ops first (that is, ops with no available emitter in `self.config`),
121121
// to ensure we group them as much as possible.
122122
for pg_node in topo {
123123
let node = hugr.get_node(pg_node);
@@ -771,7 +771,7 @@ impl<H: HugrView> Tk1EncoderContext<H> {
771771
}
772772

773773
/// Initialize a tket1 [Operation](circuit_json::Operation) to pass to
774-
/// [`Tk1Encoder::emit_command`].
774+
/// [`Tk1EncoderContext::emit_command`].
775775
///
776776
/// ## Arguments
777777
/// - `tk1_optype`: The operation type to use.

tket2/src/serialize/pytket/encoder/config.rs

Lines changed: 47 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! Configuration for converting [`Circuit`]s into [`SerialCircuit`]
22
//!
3-
//! A configuration struct contains a list of custom encoders that define translations
3+
//! A configuration struct contains a list of custom emitters that define translations
44
//! of HUGR operations and types into pytket primitives.
55
66
use std::collections::{BTreeSet, HashMap, VecDeque};
@@ -10,9 +10,9 @@ use hugr::ops::{ExtensionOp, Value};
1010
use hugr::types::{SumType, Type, TypeEnum};
1111

1212
use crate::serialize::pytket::extension::{
13-
FloatEncoder, PreludeEncoder, RotationEncoder, Tk1OpEncoder, Tk2OpEncoder,
13+
FloatEmitter, PreludeEmitter, RotationEmitter, Tk1Emitter, Tk2Emitter,
1414
};
15-
use crate::serialize::pytket::{Tk1ConvertError, Tk1Encoder};
15+
use crate::serialize::pytket::{PytketEmitter, Tk1ConvertError};
1616
use crate::Circuit;
1717

1818
use super::value_tracker::RegisterCount;
@@ -23,62 +23,61 @@ use itertools::Itertools;
2323

2424
/// Default encoder configuration for [`Circuit`]s.
2525
///
26-
/// Contains encoders for std and tket2 operations.
26+
/// Contains emitters for std and tket2 operations.
2727
pub fn default_encoder_config<H: HugrView>() -> Tk1EncoderConfig<H> {
28-
// TODO: Add std & tket2 encoders
2928
let mut config = Tk1EncoderConfig::new();
30-
config.add_encoder(PreludeEncoder);
31-
config.add_encoder(FloatEncoder);
32-
config.add_encoder(RotationEncoder);
33-
config.add_encoder(Tk1OpEncoder);
34-
config.add_encoder(Tk2OpEncoder);
29+
config.add_emitter(PreludeEmitter);
30+
config.add_emitter(FloatEmitter);
31+
config.add_emitter(RotationEmitter);
32+
config.add_emitter(Tk1Emitter);
33+
config.add_emitter(Tk2Emitter);
3534
config
3635
}
3736

3837
/// Configuration for converting [`Circuit`] into [`SerialCircuit`].
3938
///
40-
/// Contains custom encoders that define translations for HUGR operations and types
41-
/// into pytket primitives.
39+
/// Contains custom emitters that define translations for HUGR operations,
40+
/// types, and consts into pytket primitives.
4241
#[derive(derive_more::Debug)]
4342
#[debug(bounds(H: HugrView))]
4443
pub struct Tk1EncoderConfig<H: HugrView> {
45-
/// Operation encoders
44+
/// Operation emitters
4645
#[debug(skip)]
47-
pub(super) encoders: Vec<Box<dyn Tk1Encoder<H>>>,
48-
/// Pre-computed map from extension ids to corresponding encoders in
49-
/// `encoders`, identified by their index.
50-
#[debug("{:?}", extension_encoders.keys().collect_vec())]
51-
extension_encoders: HashMap<ExtensionId, Vec<usize>>,
52-
/// Extensions that request to be called for all operations.
53-
no_extension_encoders: Vec<usize>,
46+
pub(super) enmitters: Vec<Box<dyn PytketEmitter<H>>>,
47+
/// Pre-computed map from extension ids to corresponding emitters in
48+
/// `emitters`, identified by their index.
49+
#[debug("{:?}", extension_emitters.keys().collect_vec())]
50+
extension_emitters: HashMap<ExtensionId, Vec<usize>>,
51+
/// Emitters that request to be called for all operations.
52+
no_extension_emitters: Vec<usize>,
5453
}
5554

5655
impl<H: HugrView> Tk1EncoderConfig<H> {
5756
/// Create a new [`Tk1EncoderConfig`] with no encoders.
5857
pub fn new() -> Self {
5958
Self {
60-
encoders: vec![],
61-
extension_encoders: HashMap::new(),
62-
no_extension_encoders: vec![],
59+
enmitters: vec![],
60+
extension_emitters: HashMap::new(),
61+
no_extension_emitters: vec![],
6362
}
6463
}
6564

6665
/// Add an encoder to the configuration.
67-
pub fn add_encoder(&mut self, encoder: impl Tk1Encoder<H> + 'static) {
68-
let idx = self.encoders.len();
66+
pub fn add_emitter(&mut self, encoder: impl PytketEmitter<H> + 'static) {
67+
let idx = self.enmitters.len();
6968

7069
match encoder.extensions() {
7170
Some(extensions) => {
7271
for ext in extensions {
73-
self.extension_encoders.entry(ext).or_default().push(idx);
72+
self.extension_emitters.entry(ext).or_default().push(idx);
7473
}
7574
}
7675
// If the encoder does not specify an extension, it will be called
7776
// for all operations.
78-
None => self.no_extension_encoders.push(idx),
77+
None => self.no_extension_emitters.push(idx),
7978
}
8079

81-
self.encoders.push(Box::new(encoder));
80+
self.enmitters.push(Box::new(encoder));
8281
}
8382

8483
/// List the extensions supported by the encoders.
@@ -88,7 +87,7 @@ impl<H: HugrView> Tk1EncoderConfig<H> {
8887
///
8988
/// Use [`Tk1EncoderConfig::add_encoder`] to extend this list.
9089
pub fn supported_extensions(&self) -> impl Iterator<Item = &ExtensionId> {
91-
self.extension_encoders.keys()
90+
self.extension_emitters.keys()
9291
}
9392

9493
/// Encode a HUGR operation using the registered custom encoders.
@@ -103,7 +102,7 @@ impl<H: HugrView> Tk1EncoderConfig<H> {
103102
) -> Result<bool, Tk1ConvertError<H::Node>> {
104103
let mut result = false;
105104
let extension = op.def().extension_id();
106-
for enc in self.encoders_for_extension(extension) {
105+
for enc in self.emitters_for_extension(extension) {
107106
if enc.op_to_pytket(node, op, circ, encoder)? {
108107
result = true;
109108
break;
@@ -146,7 +145,7 @@ impl<H: HugrView> Tk1EncoderConfig<H> {
146145
}
147146
TypeEnum::Extension(custom) => {
148147
let type_ext = custom.extension();
149-
for encoder in self.encoders_for_extension(type_ext) {
148+
for encoder in self.emitters_for_extension(type_ext) {
150149
if let Some(count) = encoder.type_to_pytket(custom)? {
151150
return Ok(Some(count));
152151
}
@@ -185,7 +184,7 @@ impl<H: HugrView> Tk1EncoderConfig<H> {
185184
Value::Extension { e: opaque } => {
186185
let type_exts = opaque.extension_reqs();
187186
let mut encoded = false;
188-
for e in self.encoders_for_extensions(&type_exts) {
187+
for e in self.emitters_for_extensions(&type_exts) {
189188
if let Some(vs) = e.const_to_pytket(opaque, encoder)? {
190189
values.append(vs);
191190
encoded = true;
@@ -202,40 +201,40 @@ impl<H: HugrView> Tk1EncoderConfig<H> {
202201
Ok(Some(values))
203202
}
204203

205-
/// Lists the encoders that can handle a given extension.
206-
fn encoders_for_extension(
204+
/// Lists the emitters that can handle a given extension.
205+
fn emitters_for_extension(
207206
&self,
208207
ext: &ExtensionId,
209-
) -> impl Iterator<Item = &Box<dyn Tk1Encoder<H>>> {
210-
self.extension_encoders
208+
) -> impl Iterator<Item = &Box<dyn PytketEmitter<H>>> {
209+
self.extension_emitters
211210
.get(ext)
212211
.into_iter()
213212
.flatten()
214-
.chain(self.no_extension_encoders.iter())
215-
.map(move |idx| &self.encoders[*idx])
213+
.chain(self.no_extension_emitters.iter())
214+
.map(move |idx| &self.enmitters[*idx])
216215
}
217216

218-
/// Lists the encoders that can handle a given set extensions.
219-
fn encoders_for_extensions(
217+
/// Lists the emitters that can handle a given set extensions.
218+
fn emitters_for_extensions(
220219
&self,
221220
exts: &ExtensionSet,
222-
) -> impl Iterator<Item = &Box<dyn Tk1Encoder<H>>> {
223-
let encoder_ids: BTreeSet<usize> = exts
221+
) -> impl Iterator<Item = &Box<dyn PytketEmitter<H>>> {
222+
let emitter_ids: BTreeSet<usize> = exts
224223
.iter()
225-
.flat_map(|ext| self.extension_encoders.get(ext).into_iter().flatten())
226-
.chain(self.no_extension_encoders.iter())
224+
.flat_map(|ext| self.extension_emitters.get(ext).into_iter().flatten())
225+
.chain(self.no_extension_emitters.iter())
227226
.copied()
228227
.collect();
229-
encoder_ids.into_iter().map(move |idx| &self.encoders[idx])
228+
emitter_ids.into_iter().map(move |idx| &self.enmitters[idx])
230229
}
231230
}
232231

233232
impl<H: HugrView> Default for Tk1EncoderConfig<H> {
234233
fn default() -> Self {
235234
Self {
236-
encoders: Default::default(),
237-
extension_encoders: Default::default(),
238-
no_extension_encoders: Default::default(),
235+
enmitters: Default::default(),
236+
extension_emitters: Default::default(),
237+
no_extension_emitters: Default::default(),
239238
}
240239
}
241240
}

tket2/src/serialize/pytket/encoder/value_tracker.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ struct TrackedWire {
173173
/// The number of pytket qubits, bits, and sympy parameters corresponding to a
174174
/// HUGR type.
175175
///
176-
/// Used as return value for [`Tk1Encoder::type_to_pytket`](`super::Tk1Encoder::type_to_pytket`).
176+
/// Used as return value for [`PytketEmitter::type_to_pytket`](`super::PytketEmitter::type_to_pytket`).
177177
#[derive(
178178
Clone,
179179
Copy,

tket2/src/serialize/pytket/extension.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! Extension encoder/decoders for the tket2 <-> `pytket` conversion.
22
//!
3-
//! To add a new extension encoder, implement the [`Tk1Encoder`] trait and add
3+
//! To add a new extension encoder, implement the [`PytketEmitter`] trait and add
44
//! it to the [`Tk1EncoderConfig`](crate::serialize::pytket::Tk1EncoderConfig)
55
//! used for decoding.
66
//!
@@ -15,12 +15,12 @@ mod rotation;
1515
mod tk1;
1616
mod tk2;
1717

18-
pub use float::FloatEncoder;
18+
pub use float::FloatEmitter;
1919
use hugr::ops::constant::OpaqueValue;
20-
pub use prelude::PreludeEncoder;
21-
pub use rotation::RotationEncoder;
22-
pub use tk1::Tk1OpEncoder;
23-
pub use tk2::Tk2OpEncoder;
20+
pub use prelude::PreludeEmitter;
21+
pub use rotation::RotationEmitter;
22+
pub use tk1::Tk1Emitter;
23+
pub use tk2::Tk2Emitter;
2424

2525
pub(crate) use tk1::OpaqueTk1Op;
2626

@@ -41,10 +41,10 @@ use hugr::HugrView;
4141
/// constant in the HUGR being encoded, the configuration will call each of
4242
/// the encoders declaring support for the specific extension sequentially until
4343
/// one of them indicates a successful conversion.
44-
pub trait Tk1Encoder<H: HugrView> {
44+
pub trait PytketEmitter<H: HugrView> {
4545
/// The name of the extension this encoder/decoder is for.
4646
///
47-
/// [`Tk1Encoder::op_to_pytket`] and [`Tk1Encoder::type_to_pytket`] will
47+
/// [`PytketEmitter::op_to_pytket`] and [`PytketEmitter::type_to_pytket`] will
4848
/// only be called for operations/types of these extensions.
4949
///
5050
/// If the function returns `None`, the encoder will be called for all

0 commit comments

Comments
 (0)