@@ -178,6 +178,50 @@ impl KdlEntry {
178178 name. autoformat ( ) ;
179179 }
180180 }
181+
182+ /// Parses a string into a entry.
183+ ///
184+ /// If the `v1-fallback` feature is enabled, this method will first try to
185+ /// parse the string as a KDL v2 entry, and, if that fails, it will try
186+ /// to parse again as a KDL v1 entry. If both fail, only the v2 parse
187+ /// errors will be returned.
188+ pub fn parse ( s : & str ) -> Result < Self , KdlParseFailure > {
189+ #[ cfg( not( feature = "v1-fallback" ) ) ]
190+ {
191+ v2_parser:: try_parse ( v2_parser:: padded_node_entry, s)
192+ }
193+ #[ cfg( feature = "v1-fallback" ) ]
194+ {
195+ v2_parser:: try_parse ( v2_parser:: padded_node_entry, s)
196+ . or_else ( |e| KdlEntry :: parse_v1 ( s) . map_err ( |_| e) )
197+ }
198+ }
199+
200+ /// Parses a KDL v1 string into an entry.
201+ #[ cfg( feature = "v1" ) ]
202+ pub fn parse_v1 ( s : & str ) -> Result < Self , KdlParseFailure > {
203+ let ret: Result < kdlv1:: KdlEntry , kdlv1:: KdlError > = s. parse ( ) ;
204+ ret. map ( |x| x. into ( ) ) . map_err ( |e| e. into ( ) )
205+ }
206+ }
207+
208+ #[ cfg( feature = "v1" ) ]
209+ impl From < kdlv1:: KdlEntry > for KdlEntry {
210+ fn from ( value : kdlv1:: KdlEntry ) -> Self {
211+ KdlEntry {
212+ ty : value. ty ( ) . map ( |x| x. clone ( ) . into ( ) ) ,
213+ value : value. value ( ) . clone ( ) . into ( ) ,
214+ name : value. name ( ) . map ( |x| x. clone ( ) . into ( ) ) ,
215+ format : Some ( KdlEntryFormat {
216+ value_repr : value. value_repr ( ) . unwrap_or ( "" ) . into ( ) ,
217+ leading : value. leading ( ) . unwrap_or ( "" ) . into ( ) ,
218+ trailing : value. trailing ( ) . unwrap_or ( "" ) . into ( ) ,
219+ ..Default :: default ( )
220+ } ) ,
221+ #[ cfg( feature = "span" ) ]
222+ span : SourceSpan :: new ( value. span ( ) . offset ( ) . into ( ) , value. span ( ) . len ( ) ) ,
223+ }
224+ }
181225}
182226
183227impl Display for KdlEntry {
@@ -249,7 +293,7 @@ impl FromStr for KdlEntry {
249293 type Err = KdlParseFailure ;
250294
251295 fn from_str ( s : & str ) -> Result < Self , Self :: Err > {
252- v2_parser :: try_parse ( v2_parser :: padded_node_entry , s)
296+ KdlEntry :: parse ( s)
253297 }
254298}
255299
0 commit comments