japanese_address_parser/
parser.rs

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
use std::sync::Arc;

use crate::domain::common::token::Token;
use crate::domain::geolonia::entity::Address;
use crate::domain::geolonia::error::{Error, ParseErrorKind};
use crate::interactor::geolonia::{GeoloniaInteractor, GeoloniaInteractorImpl};
use crate::tokenizer::{End, Tokenizer};
use serde::Serialize;

impl From<Tokenizer<End>> for Address {
    fn from(value: Tokenizer<End>) -> Self {
        let mut address = Address::new("", "", "", "");
        for token in value.tokens {
            match token {
                Token::Prefecture(prefecture_name) => address.prefecture = prefecture_name,
                Token::City(city_name) => address.city = city_name,
                Token::Town(town_name) => address.town = town_name,
                Token::Rest(rest) => address.rest = rest,
            }
        }
        address
    }
}

/// An asynchronous `Parser` to process addresses.
///
/// # Example
/// ```
/// use japanese_address_parser::parser::Parser;
///
/// async fn example() {
///     let parser : Parser = Default::default();
///     let result = parser.parse("東京都新宿区西新宿2-8-1").await;
///     println!("{:?}", result);
/// }
/// ```
pub struct Parser {
    interactor: Arc<GeoloniaInteractorImpl>,
}

impl Default for Parser {
    /// Constructs a new `Parser`.
    fn default() -> Self {
        Self {
            interactor: Arc::new(Default::default()),
        }
    }
}

impl Parser {
    /// Parses the given `address` asynchronously.
    pub async fn parse(&self, address: &str) -> ParseResult {
        let interactor = self.interactor.clone();
        let tokenizer = Tokenizer::new(address);
        // 都道府県を特定
        let (prefecture, tokenizer) = match tokenizer.read_prefecture() {
            Ok(found) => found,
            Err(tokenizer) => {
                return ParseResult {
                    address: Address::from(tokenizer),
                    error: Some(Error::new_parse_error(ParseErrorKind::Prefecture)),
                }
            }
        };
        // その都道府県の市町村名リストを取得
        let prefecture_master = match interactor.get_prefecture_master(prefecture.name_ja()).await {
            Err(error) => {
                return ParseResult {
                    address: Address::from(tokenizer.finish()),
                    error: Some(error),
                };
            }
            Ok(result) => result,
        };
        // 市町村名を特定
        let (city_name, tokenizer) = match tokenizer.read_city(&prefecture_master.cities) {
            Ok(found) => found,
            Err(not_found) => {
                // 市区町村が特定できない場合かつフィーチャフラグが有効な場合、郡名が抜けている可能性を検討
                match not_found.read_city_with_county_name_completion(&prefecture_master.cities) {
                    Ok(found) if cfg!(feature = "city-name-correction") => found,
                    _ => {
                        // それでも見つからない場合は終了
                        return ParseResult {
                            address: Address::from(tokenizer.finish()),
                            error: Some(Error::new_parse_error(ParseErrorKind::City)),
                        };
                    }
                }
            }
        };
        // その市町村の町名リストを取得
        let city = match interactor
            .get_city_master(prefecture.name_ja(), &city_name)
            .await
        {
            Err(error) => {
                return ParseResult {
                    address: Address::from(tokenizer.finish()),
                    error: Some(error),
                };
            }
            Ok(result) => result,
        };
        // 町名を特定
        let Ok((_, tokenizer)) =
            tokenizer.read_town(city.towns.iter().map(|x| x.name.clone()).collect())
        else {
            return ParseResult {
                address: Address::from(tokenizer.finish()),
                error: Some(Error::new_parse_error(ParseErrorKind::Town)),
            };
        };

        ParseResult {
            address: Address::from(tokenizer.finish()),
            error: None,
        }
    }

    /// Parses the given `address` synchronously.
    #[cfg(feature = "blocking")]
    pub fn parse_blocking(&self, address: &str) -> ParseResult {
        let interactor = self.interactor.clone();
        let tokenizer = Tokenizer::new(address);
        let (prefecture, tokenizer) = match tokenizer.read_prefecture() {
            Ok(found) => found,
            Err(tokenizer) => {
                return ParseResult {
                    address: Address::from(tokenizer),
                    error: Some(Error::new_parse_error(ParseErrorKind::Prefecture)),
                }
            }
        };
        let prefecture_master =
            match interactor.get_blocking_prefecture_master(prefecture.name_ja()) {
                Err(error) => {
                    return ParseResult {
                        address: Address::from(tokenizer.finish()),
                        error: Some(error),
                    };
                }
                Ok(result) => result,
            };
        let (city_name, tokenizer) = match tokenizer.read_city(&prefecture_master.cities) {
            Ok(found) => found,
            Err(not_found) => {
                match not_found.read_city_with_county_name_completion(&prefecture_master.cities) {
                    Ok(found) if cfg!(feature = "city-name-correction") => found,
                    _ => {
                        return ParseResult {
                            address: Address::from(tokenizer.finish()),
                            error: Some(Error::new_parse_error(ParseErrorKind::City)),
                        };
                    }
                }
            }
        };
        let city = match interactor.get_blocking_city_master(prefecture.name_ja(), &city_name) {
            Err(error) => {
                return ParseResult {
                    address: Address::from(tokenizer.finish()),
                    error: Some(error),
                };
            }
            Ok(result) => result,
        };
        let Ok((_, tokenizer)) =
            tokenizer.read_town(city.towns.iter().map(|x| x.name.clone()).collect())
        else {
            return ParseResult {
                address: Address::from(tokenizer.finish()),
                error: Some(Error::new_parse_error(ParseErrorKind::Town)),
            };
        };

        ParseResult {
            address: Address::from(tokenizer.finish()),
            error: None,
        }
    }
}

#[cfg(all(test, not(feature = "blocking")))]
mod tests {
    use crate::domain::geolonia::error::ParseErrorKind;
    use crate::parser::Parser;
    use wasm_bindgen_test::{wasm_bindgen_test, wasm_bindgen_test_configure};

    #[tokio::test]
    async fn 都道府県名が誤っている場合() {
        let parser = Parser::default();
        let result = parser.parse("青盛県青森市長島1丁目1−1").await;
        assert_eq!(result.address.prefecture, "");
        assert_eq!(result.address.city, "");
        assert_eq!(result.address.town, "");
        assert_eq!(result.address.rest, "青盛県青森市長島1丁目1−1");
        assert_eq!(result.error.is_some(), true);
        assert_eq!(
            result.error.unwrap().error_message,
            ParseErrorKind::Prefecture.to_string()
        );
    }

    #[tokio::test]
    async fn 市区町村名が誤っている場合() {
        let parser = Parser::default();
        let result = parser.parse("青森県青盛市長島1丁目1−1").await;
        assert_eq!(result.address.prefecture, "青森県");
        assert_eq!(result.address.city, "");
        assert_eq!(result.address.town, "");
        assert_eq!(result.address.rest, "青盛市長島1丁目1−1");
        assert_eq!(result.error.is_some(), true);
        assert_eq!(
            result.error.unwrap().error_message,
            ParseErrorKind::City.to_string()
        );
    }

    #[tokio::test]
    async fn 町名が誤っている場合() {
        let parser = Parser::default();
        let result = parser.parse("青森県青森市永嶋1丁目1−1").await;
        assert_eq!(result.address.prefecture, "青森県");
        assert_eq!(result.address.city, "青森市");
        assert_eq!(result.address.town, "");
        assert_eq!(result.address.rest, "永嶋1丁目1−1");
        assert_eq!(result.error.is_some(), true);
        assert_eq!(
            result.error.unwrap().error_message,
            ParseErrorKind::Town.to_string()
        );
    }

    wasm_bindgen_test_configure!(run_in_browser);

    #[wasm_bindgen_test]
    async fn parse_wasm_success() {
        let parser = Parser::default();
        let result = parser.parse("兵庫県淡路市生穂新島8番地").await;
        assert_eq!(result.address.prefecture, "兵庫県".to_string());
        assert_eq!(result.address.city, "淡路市".to_string());
        assert_eq!(result.address.town, "生穂".to_string());
        assert_eq!(result.address.rest, "新島8番地".to_string());
        assert_eq!(result.error, None);
    }
}

#[cfg(all(test, feature = "blocking"))]
mod blocking_tests {
    use crate::domain::geolonia::error::ParseErrorKind;
    use crate::parser::Parser;

    #[test]
    fn parse_blocking_success_埼玉県秩父市熊木町8番15号() {
        let parser = Parser::default();
        let result = parser.parse_blocking("埼玉県秩父市熊木町8番15号");
        assert_eq!(result.address.prefecture, "埼玉県");
        assert_eq!(result.address.city, "秩父市");
        assert_eq!(result.address.town, "熊木町");
        assert_eq!(result.address.rest, "8番15号");
        assert_eq!(result.error, None);
    }

    #[test]
    fn parse_blocking_fail_市町村名が間違っている場合() {
        let parser = Parser::default();
        let result = parser.parse_blocking("埼玉県秩父柿熊木町8番15号");
        assert_eq!(result.address.prefecture, "埼玉県");
        assert_eq!(result.address.city, "");
        assert_eq!(result.address.town, "");
        assert_eq!(result.address.rest, "秩父柿熊木町8番15号");
        assert_eq!(
            result.error.unwrap().error_message,
            ParseErrorKind::City.to_string()
        );
    }
}

#[derive(Serialize, PartialEq, Debug)]
pub struct ParseResult {
    pub address: Address,
    pub error: Option<Error>,
}