proj-wkt 0.5.0

WKT and PROJ string parser for proj-core CRS definitions
Documentation
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
#![forbid(unsafe_code)]

//! Parser for WKT and PROJ format CRS strings.
//!
//! Converts CRS definition strings into [`proj_core::CrsDef`] values that can
//! be used with [`proj_core::Transform::from_crs_defs()`].
//!
//! # Supported formats
//!
//! - **Authority codes**: `"EPSG:4326"` — delegates to proj-core's registry
//! - **PROJ strings**: `"+proj=utm +zone=18 +datum=WGS84"` — parsed into CrsDef
//! - **WKT1**: `GEOGCS[...]` / `PROJCS[...]` — extracts AUTHORITY tag when present,
//!   otherwise parses projection parameters
//! - **WKT2/PROJJSON compound CRS**: parses explicit vertical CRS components for
//!   equality-checked z preservation and same-reference vertical unit conversion
//!
//! Custom CRS definitions are only accepted when their semantics fit the
//! `proj_core::CrsDef` model: longitude/latitude geographic coordinates in
//! degrees with a Greenwich prime meridian, projected coordinates with
//! easting/northing axis order, and compound vertical components that can be
//! preserved or unit-converted only when source and target vertical CRS
//! definitions use the same vertical reference frame.
//! Unsupported axis-order, prime-meridian, geographic angular-unit, and vertical
//! transformation semantics are rejected.
//!
//! # Example
//!
//! ```
//! use proj_wkt::parse_crs;
//! use proj_core::Transform;
//!
//! let from = parse_crs("+proj=longlat +datum=WGS84").unwrap();
//! let to = parse_crs("EPSG:3857").unwrap();
//! let t = Transform::from_crs_defs(&from, &to).unwrap();
//! let (x, y) = t.convert((-74.006, 40.7128)).unwrap();
//! ```

mod proj_string;
mod projjson;
mod semantics;
mod wkt;

use proj_core::{
    Bounds, Coord, Coord3D, CrsDef, SelectionOptions, Transform, Transformable, Transformable3D,
};

/// Parse error.
#[derive(Debug, thiserror::Error)]
pub enum ParseError {
    #[error("failed to parse CRS string: {0}")]
    Parse(String),
    #[error("unsupported CRS semantics: {0}")]
    UnsupportedSemantics(String),
    #[error(transparent)]
    Core(#[from] proj_core::Error),
}

pub type Result<T> = std::result::Result<T, ParseError>;

/// Parse a CRS definition string in any supported format.
///
/// Automatically detects and handles:
/// - **Authority codes**: `"EPSG:4326"`
/// - **Bare EPSG codes**: `"4326"` (numeric-only strings)
/// - **URN format**: `"urn:ogc:def:crs:EPSG::4326"`
/// - **OGC CRS84**: `"CRS:84"`, `"OGC:CRS84"`
/// - **PROJ strings**: `"+proj=utm +zone=18 +datum=WGS84"`
/// - **PROJJSON**: `{"type": "ProjectedCRS", ...}`
/// - **WKT1**: `GEOGCS[...]` / `PROJCS[...]`
/// - **WKT2**: `GEODCRS[...]` / `PROJCRS[...]` / `COMPOUNDCRS[...]`
pub fn parse_crs(s: &str) -> Result<CrsDef> {
    let s = s.trim();

    // Normalize common aliases
    let upper = s.to_uppercase();
    if upper == "CRS:84" || upper == "OGC:CRS84" {
        return proj_core::lookup_epsg(4326)
            .ok_or_else(|| ParseError::Parse("CRS:84 not found in registry".into()));
    }

    // URN format: urn:ogc:def:crs:EPSG::4326
    if upper.starts_with("URN:OGC:DEF:CRS:") {
        // Format: urn:ogc:def:crs:AUTHORITY::CODE or urn:ogc:def:crs:AUTHORITY:VERSION:CODE
        if let Some((_, code_str)) = s.rsplit_once(':') {
            if let Ok(code) = code_str.parse::<u32>() {
                return proj_core::lookup_epsg(code)
                    .ok_or_else(|| ParseError::Parse(format!("unknown EPSG code in URN: {code}")));
            }
        }
        return Err(ParseError::Parse(format!("invalid URN format: {s}")));
    }

    // Try authority code (EPSG:XXXX)
    if s.contains(':')
        && !s.starts_with('+')
        && !upper.starts_with("GEOG")
        && !upper.starts_with("PROJ")
    {
        if let Ok(crs) = proj_core::lookup_authority_code(s) {
            return Ok(crs);
        }
    }

    // Bare numeric EPSG code (e.g., "4326")
    if let Ok(code) = s.parse::<u32>() {
        if let Some(crs) = proj_core::lookup_epsg(code) {
            return Ok(crs);
        }
    }

    // PROJ string
    if s.starts_with('+') {
        return proj_string::parse_proj_string(s);
    }

    // PROJJSON
    if s.starts_with('{') {
        return projjson::parse_projjson(s);
    }

    // WKT
    if upper.starts_with("GEOGCS")
        || upper.starts_with("PROJCS")
        || upper.starts_with("GEODCRS")
        || upper.starts_with("GEOGCRS")
        || upper.starts_with("PROJCRS")
        || upper.starts_with("COMPD_CS")
        || upper.starts_with("COMPOUNDCRS")
        || upper.starts_with("VERT_CS")
        || upper.starts_with("VERTCRS")
        || upper.starts_with("VERTICALCRS")
    {
        return wkt::parse_wkt(s);
    }

    Err(ParseError::Parse(format!(
        "unrecognized CRS format: {:.80}",
        s
    )))
}

/// Create a [`Transform`] from two CRS strings in any format.
///
/// Convenience function for downstream projects that need to handle free-form CRS strings.
pub fn transform_from_crs_strings(
    from: &str,
    to: &str,
) -> std::result::Result<proj_core::Transform, ParseError> {
    let from_crs = parse_crs(from)?;
    let to_crs = parse_crs(to)?;
    Ok(proj_core::Transform::from_crs_defs(&from_crs, &to_crs)?)
}

/// Create a [`Transform`] from two CRS strings using explicit selection options.
///
/// This is the path for parsed PROJ strings that reference external resources
/// such as `+nadgrids`, because callers can provide a [`proj_core::GridProvider`]
/// through [`SelectionOptions::grid_provider`].
pub fn transform_from_crs_strings_with_selection_options(
    from: &str,
    to: &str,
    options: SelectionOptions,
) -> std::result::Result<proj_core::Transform, ParseError> {
    let from_crs = parse_crs(from)?;
    let to_crs = parse_crs(to)?;
    Ok(proj_core::Transform::from_crs_defs_with_selection_options(
        &from_crs, &to_crs, options,
    )?)
}

/// Create a horizontal-only [`Transform`] from two CRS strings in any format.
///
/// Compound CRS definitions are reduced to their horizontal component before
/// operation selection. This is intended for AOI, footprint, and preview
/// workflows where vertical coordinates are not part of the operation.
pub fn transform_from_crs_strings_horizontal(
    from: &str,
    to: &str,
) -> std::result::Result<proj_core::Transform, ParseError> {
    transform_from_crs_strings_horizontal_with_selection_options(
        from,
        to,
        SelectionOptions::default(),
    )
}

/// Create a horizontal-only [`Transform`] from two CRS strings using explicit
/// selection options.
pub fn transform_from_crs_strings_horizontal_with_selection_options(
    from: &str,
    to: &str,
    options: SelectionOptions,
) -> std::result::Result<proj_core::Transform, ParseError> {
    let from_crs = parse_crs(from)?;
    let to_crs = parse_crs(to)?;
    Ok(
        proj_core::Transform::from_horizontal_components_with_selection_options(
            &from_crs, &to_crs, options,
        )?,
    )
}

/// Lightweight compatibility facade for downstream code that currently expects
/// a `proj::Proj`-like flow:
/// 1. parse a CRS definition with [`Proj::new`]
/// 2. build a CRS-to-CRS transform with [`Proj::create_crs_to_crs_from_pj`]
/// 3. convert coordinates with [`Proj::convert`]
pub struct Proj {
    inner: ProjInner,
}

enum ProjInner {
    Definition(CrsDef),
    Transform(Box<Transform>),
}

impl Proj {
    /// Parse a single CRS definition in any supported format.
    pub fn new(definition: &str) -> Result<Self> {
        Ok(Self {
            inner: ProjInner::Definition(parse_crs(definition)?),
        })
    }

    /// Build a transform directly from two CRS strings.
    pub fn new_known_crs(from: &str, to: &str, _area: Option<&str>) -> Result<Self> {
        Ok(Self {
            inner: ProjInner::Transform(Box::new(transform_from_crs_strings(from, to)?)),
        })
    }

    /// Build a horizontal-only transform directly from two CRS strings.
    pub fn new_known_crs_horizontal(from: &str, to: &str, _area: Option<&str>) -> Result<Self> {
        Ok(Self {
            inner: ProjInner::Transform(Box::new(transform_from_crs_strings_horizontal(from, to)?)),
        })
    }

    /// Build a transform from two parsed CRS definitions.
    pub fn create_crs_to_crs_from_pj(
        &self,
        target: &Self,
        _area: Option<&str>,
        _options: Option<&str>,
    ) -> Result<Self> {
        let source = self.definition()?;
        let target = target.definition()?;
        Ok(Self {
            inner: ProjInner::Transform(Box::new(Transform::from_crs_defs(source, target)?)),
        })
    }

    /// Build a horizontal-only transform from two parsed CRS definitions.
    pub fn create_horizontal_crs_to_crs_from_pj(
        &self,
        target: &Self,
        _area: Option<&str>,
        _options: Option<&str>,
    ) -> Result<Self> {
        let source = self.definition()?;
        let target = target.definition()?;
        Ok(Self {
            inner: ProjInner::Transform(Box::new(Transform::from_horizontal_components(
                source, target,
            )?)),
        })
    }

    /// Transform a coordinate using a CRS-to-CRS transform.
    pub fn convert<T: Transformable>(&self, coord: T) -> proj_core::Result<T> {
        match &self.inner {
            ProjInner::Transform(transform) => transform.convert(coord),
            ProjInner::Definition(_) => Err(proj_core::Error::InvalidDefinition(
                "coordinate conversion requires a CRS-to-CRS transform, not a standalone CRS definition".into(),
            )),
        }
    }

    /// Transform a 3D coordinate using a CRS-to-CRS transform.
    pub fn convert_3d<T: Transformable3D>(&self, coord: T) -> proj_core::Result<T> {
        match &self.inner {
            ProjInner::Transform(transform) => transform.convert_3d(coord),
            ProjInner::Definition(_) => Err(proj_core::Error::InvalidDefinition(
                "coordinate conversion requires a CRS-to-CRS transform, not a standalone CRS definition".into(),
            )),
        }
    }

    /// Transform a coordinate using the native [`Coord`] type.
    pub fn convert_coord(&self, coord: Coord) -> proj_core::Result<Coord> {
        self.convert(coord)
    }

    /// Transform a 3D coordinate using the native [`Coord3D`] type.
    pub fn convert_coord_3d(&self, coord: Coord3D) -> proj_core::Result<Coord3D> {
        self.convert_3d(coord)
    }

    /// Return the inverse of a CRS-to-CRS transform.
    pub fn inverse(&self) -> Result<Self> {
        match &self.inner {
            ProjInner::Transform(transform) => Ok(Self {
                inner: ProjInner::Transform(Box::new(transform.inverse()?)),
            }),
            ProjInner::Definition(_) => Err(ParseError::Parse(
                "inverse requires a CRS-to-CRS transform, not a standalone CRS definition".into(),
            )),
        }
    }

    /// Reproject an axis-aligned bounding box by sampling its perimeter.
    pub fn transform_bounds(
        &self,
        bounds: Bounds,
        densify_points: usize,
    ) -> proj_core::Result<Bounds> {
        match &self.inner {
            ProjInner::Transform(transform) => transform.transform_bounds(bounds, densify_points),
            ProjInner::Definition(_) => Err(proj_core::Error::InvalidDefinition(
                "bounds reprojection requires a CRS-to-CRS transform, not a standalone CRS definition".into(),
            )),
        }
    }

    fn definition(&self) -> Result<&CrsDef> {
        match &self.inner {
            ProjInner::Definition(crs) => Ok(crs),
            ProjInner::Transform(_) => Err(ParseError::Parse(
                "expected a CRS definition, found a transform".into(),
            )),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn bare_epsg_code() {
        let crs = parse_crs("4326").unwrap();
        assert!(crs.is_geographic());
        assert_eq!(crs.epsg(), 4326);
    }

    #[test]
    fn bare_epsg_projected() {
        let crs = parse_crs("32618").unwrap();
        assert!(crs.is_projected());
    }

    #[test]
    fn urn_format() {
        let crs = parse_crs("urn:ogc:def:crs:EPSG::4326").unwrap();
        assert!(crs.is_geographic());
        assert_eq!(crs.epsg(), 4326);
    }

    #[test]
    fn urn_with_version() {
        let crs = parse_crs("urn:ogc:def:crs:EPSG:9.8.15:3857").unwrap();
        assert!(crs.is_projected());
    }

    #[test]
    fn crs84() {
        let crs = parse_crs("CRS:84").unwrap();
        assert!(crs.is_geographic());
    }

    #[test]
    fn ogc_crs84() {
        let crs = parse_crs("OGC:CRS84").unwrap();
        assert!(crs.is_geographic());
    }

    #[test]
    fn epsg_authority_code() {
        let crs = parse_crs("EPSG:3857").unwrap();
        assert!(crs.is_projected());
    }

    #[test]
    fn epsg_authority_code_3d_geographic() {
        let crs = parse_crs("EPSG:4979").unwrap();
        assert!(crs.is_compound());
        assert!(crs.is_geographic());
        assert!(crs.vertical_crs().is_some());
    }

    #[test]
    fn unsupported_format_error() {
        assert!(parse_crs("not a crs").is_err());
    }

    #[test]
    fn transform_from_strings() {
        let t = transform_from_crs_strings("EPSG:4326", "EPSG:3857").unwrap();
        let (x, _y) = t.convert((-74.006, 40.7128)).unwrap();
        assert!((x - (-8238310.0)).abs() < 100.0);
    }

    #[test]
    fn transform_from_strings_with_selection_options() {
        let t = transform_from_crs_strings_with_selection_options(
            "EPSG:4326",
            "EPSG:3857",
            SelectionOptions::default(),
        )
        .unwrap();
        let (x, _y) = t.convert((-74.006, 40.7128)).unwrap();
        assert!((x - (-8238310.0)).abs() < 100.0);
    }

    #[test]
    fn horizontal_transform_from_compound_strings() {
        let err = match transform_from_crs_strings("EPSG:4979", "EPSG:3857") {
            Ok(_) => panic!("expected compound-to-horizontal transform to fail"),
            Err(err) => err,
        };
        assert!(err.to_string().contains("explicit vertical CRS"));

        let t = transform_from_crs_strings_horizontal("EPSG:4979", "EPSG:3857").unwrap();
        let (x, _y, z) = t.convert_3d((-74.006, 40.7128, 25.0)).unwrap();
        assert!((x - (-8238310.0)).abs() < 100.0);
        assert!((z - 25.0).abs() < 1e-12);
    }

    #[test]
    fn transform_bare_to_authority() {
        let t = transform_from_crs_strings("4326", "EPSG:3857").unwrap();
        let (x, _y) = t.convert((-74.006, 40.7128)).unwrap();
        assert!((x - (-8238310.0)).abs() < 100.0);
    }

    #[test]
    fn proj_facade_from_known_crs() {
        let proj = Proj::new_known_crs("EPSG:4326", "EPSG:3857", None).unwrap();
        let (x, _y) = proj.convert((-74.006, 40.7128)).unwrap();
        assert!((x - (-8238310.0)).abs() < 100.0);
    }

    #[test]
    fn proj_facade_from_known_crs_3d() {
        let proj = Proj::new_known_crs("EPSG:4326", "EPSG:3857", None).unwrap();
        let (x, _y, z) = proj.convert_3d((-74.006, 40.7128, 25.0)).unwrap();
        assert!((x - (-8238310.0)).abs() < 100.0);
        assert!((z - 25.0).abs() < 1e-12);
    }

    #[test]
    fn proj_facade_from_known_crs_horizontal() {
        let proj = Proj::new_known_crs_horizontal("EPSG:4979", "EPSG:3857", None).unwrap();
        let (x, _y, z) = proj.convert_3d((-74.006, 40.7128, 25.0)).unwrap();
        assert!((x - (-8238310.0)).abs() < 100.0);
        assert!((z - 25.0).abs() < 1e-12);
    }

    #[test]
    fn proj_facade_create_from_definitions() {
        let from = Proj::new("+proj=longlat +datum=WGS84").unwrap();
        let to = Proj::new("EPSG:3857").unwrap();
        let proj = from.create_crs_to_crs_from_pj(&to, None, None).unwrap();
        let (x, _y) = proj.convert((-74.006, 40.7128)).unwrap();
        assert!((x - (-8238310.0)).abs() < 100.0);
    }

    #[test]
    fn proj_facade_create_horizontal_from_compound_definition() {
        let from = Proj::new("EPSG:4979").unwrap();
        let to = Proj::new("EPSG:3857").unwrap();
        let proj = from
            .create_horizontal_crs_to_crs_from_pj(&to, None, None)
            .unwrap();
        let (x, _y) = proj.convert((-74.006, 40.7128)).unwrap();
        assert!((x - (-8238310.0)).abs() < 100.0);
    }

    #[test]
    fn proj_facade_inverse() {
        let proj = Proj::new_known_crs("EPSG:4326", "EPSG:3857", None).unwrap();
        let inv = proj.inverse().unwrap();
        let (lon, lat) = inv.convert((-8_238_310.0, 4_970_072.0)).unwrap();
        assert!(lon < -70.0);
        assert!(lat > 40.0);
    }

    #[test]
    fn proj_facade_transform_bounds() {
        let proj = Proj::new_known_crs("EPSG:4326", "EPSG:3857", None).unwrap();
        let result = proj
            .transform_bounds(Bounds::new(-74.3, 40.45, -73.65, 40.95), 4)
            .unwrap();
        assert!(result.max_x > result.min_x);
        assert!(result.max_y > result.min_y);
    }
}