@@ -20,6 +20,7 @@ use std::str::FromStr;
2020use std:: { collections:: HashMap , fmt} ;
2121
2222use crate :: expression:: Expression ;
23+ use crate :: parser:: gate:: parse_gate;
2324use crate :: parser:: { common:: parse_memory_reference, lex, ParseError } ;
2425use crate :: program:: { disallow_leftover, frame:: FrameMatchCondition , SyntaxError } ;
2526
@@ -361,6 +362,35 @@ pub struct Gate {
361362 pub modifiers : Vec < GateModifier > ,
362363}
363364
365+ impl std:: fmt:: Display for Gate {
366+ fn fmt ( & self , f : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
367+ let parameter_str = get_expression_parameter_string ( & self . parameters ) ;
368+
369+ let qubit_str = format_qubits ( & self . qubits ) ;
370+ let modifier_str = self
371+ . modifiers
372+ . iter ( )
373+ . map ( |m| format ! ( "{} " , m) )
374+ . collect :: < Vec < String > > ( )
375+ . join ( "" ) ;
376+ write ! (
377+ f,
378+ "{}{}{} {}" ,
379+ modifier_str, self . name, parameter_str, qubit_str
380+ )
381+ }
382+ }
383+
384+ impl FromStr for Gate {
385+ type Err = SyntaxError < Self > ;
386+
387+ fn from_str ( s : & str ) -> Result < Self , Self :: Err > {
388+ let input = LocatedSpan :: new ( s) ;
389+ let tokens = lex ( input) ?;
390+ disallow_leftover ( parse_gate ( & tokens) . map_err ( ParseError :: from_nom_internal_err) )
391+ }
392+ }
393+
364394#[ derive( Clone , Debug , PartialEq ) ]
365395pub struct CircuitDefinition {
366396 pub name : String ,
@@ -837,21 +867,8 @@ impl fmt::Display for Instruction {
837867 . map( |( k, v) | format!( "\n \t {}: {}" , k, v) )
838868 . collect:: <String >( )
839869 ) ,
840- Instruction :: Gate ( Gate {
841- name,
842- parameters,
843- qubits,
844- modifiers,
845- } ) => {
846- let parameter_str = get_expression_parameter_string ( parameters) ;
847-
848- let qubit_str = format_qubits ( qubits) ;
849- let modifier_str = modifiers
850- . iter ( )
851- . map ( |m| format ! ( "{} " , m) )
852- . collect :: < Vec < String > > ( )
853- . join ( "" ) ;
854- write ! ( f, "{}{}{} {}" , modifier_str, name, parameter_str, qubit_str)
870+ Instruction :: Gate ( gate) => {
871+ write ! ( f, "{gate}" )
855872 }
856873 Instruction :: GateDefinition ( GateDefinition {
857874 name,
0 commit comments