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
mod error_code;
mod parser;
mod tokenizer;
mod util;

use std::panic;

use error_code::ErrorInfoWithPosition;
use parser::{parse, Ast};
use serde_json::json;
use tokenizer::tokenize;
use wasm_bindgen::{prelude::wasm_bindgen, JsValue};

use crate::error_code::ErrorCode;

/// @param {string} input - The chord progression string to parse.
/// @param {string} lang - The language to use for error messages.
/// @returns {Ast} - The parsed chord progression.
/// @throws {{code: string, additionalInfo: string} | string, position: {lineNumber: number, columnNumber: number}} - The error information.
#[wasm_bindgen(js_name = "parseChordProgressionString", skip_jsdoc)]
pub fn parse_chord_progression_string_js(input: &str) -> Result<JsValue, JsValue> {
    let result_of_result = panic::catch_unwind(|| parse_chord_progression_string(input));

    if result_of_result.is_err() {
        return Err(JsValue::from_str(
            &json!({
                "code": ErrorCode::Other1.to_string(),
                "additionalInfo": "",
                "position": {
                    "lineNumber": 0,
                    "columnNumber": 0,
                    "length": 0,
                },
            })
            .to_string(),
        ));
    }

    let result = result_of_result.unwrap();

    if result.is_err() {
        let error_info = result.err().unwrap();
        return Err(JsValue::from_str(
            &json!({
                "code": error_info.error.code.to_string(),
                "additionalInfo": error_info.error.additional_info,
                "position": {
                    "lineNumber": error_info.position.line_number,
                    "columnNumber": error_info.position.column_number,
                    "length": error_info.position.length,
                },
            })
            .to_string(),
        ));
    }

    serde_wasm_bindgen::to_value(&result.unwrap())
        .map_err(|err| JsValue::from_str(&format!("{}", err)))
}

/// parse a chord progression string and return the AST
///
/// @example
/// ```rust
/// use chord_progression_parser::parse_chord_progression_string;
///
/// let input: &str = "
/// @section=Intro
/// |[key=E]E|C#m(7)|Bm(7)|C#(7)|
/// |F#m(7)|Am(7)|F#(7)|B|
///
/// @section=Verse
/// |E|C#m(7)|Bm(7)|C#(7)|
/// |F#m(7)|Am(7)|F#(7)|B|
/// "
///
/// let result = parse_chord_progression_string(input);
/// ```
pub fn parse_chord_progression_string(input: &str) -> Result<Ast, ErrorInfoWithPosition> {
    let tokenized_result = tokenize(input);
    if tokenized_result.is_err() {
        return Err(tokenized_result.err().unwrap());
    }

    let parsed_result = parse(&tokenized_result.unwrap());
    if parsed_result.is_err() {
        return Err(parsed_result.err().unwrap());
    }

    Ok(parsed_result.unwrap())
}

#[cfg(test)]
mod tests {
    #[cfg(test)]
    mod success {
        use crate::parse_chord_progression_string;
        use serde_json::json;

        #[test]
        fn complex_input_can_be_parsed() {
            let input: &str = "
            @section=Intro
            |[key=E]E|C#m(7)|Bm(7)|C#(7)|
            |F#m(7)|Am(7)|F#(7)|B|
            
            @section=Verse
            |E|C#m(7)|Bm(7)|C#(7)|
            |F#m(7)|Am(7)|F#(7)|B|
            
            @section=Chorus
            |[key=C]C|C(7)|FM(7)|Fm(7)|
            |C|C(7)|FM(7)|Dm(7)|
            |Em(7)|E(7)|
        
            @section=Interlude
            |C|A,B|

            |[key=C]C(M9)|CM(9)|
            ";

            let result = parse_chord_progression_string(input);
            assert!(result.is_ok());
        }

        #[test]
        fn differ_major_9_vs_9_of_major() {
            let input: &str = "
            @section=Intro
            |[key=C]C(M9)|CM(9)|
            ";

            let result_json = json!(parse_chord_progression_string(input).unwrap());
            let expected = json!([
                {
                    "chordBlocks": [
                        [
                            {
                                "chordExpression": {
                                    "type": "chord",
                                    "value": {
                                        "detailed": {
                                            "accidental": null,
                                            "base":"C",
                                            "chordType":"M",
                                            "extensions": [
                                                "M9"
                                            ]
                                        },
                                        "plain":"C(M9)"
                                    }
                                },
                                "denominator":null,
                                "metaInfos": [
                                    {
                                        "type": "key",
                                        "value": "C_M",
                                    }
                                ]
                            },
                            {
                                "chordExpression": {
                                    "type": "chord",
                                    "value": {
                                        "detailed": {
                                            "accidental": null,
                                            "base":"C",
                                            "chordType":"M",
                                            "extensions": [
                                                "9"
                                            ]
                                        },
                                        "plain":"CM(9)"
                                    }
                                },
                                "denominator":null,
                                "metaInfos": []
                            }
                        ]
                    ],
                    "metaInfos": [
                        {
                            "type": "section",
                            "value": "Intro"
                        }
                    ]
                }
            ]);

            assert_eq!(result_json, expected);
        }
    }

    mod failure {
        use crate::{parse_chord_progression_string, util::position::Position};

        #[test]
        fn tension_position_when_error() {
            let input: &str = "|C(9,111)|";

            println!("111111 {:?}", parse_chord_progression_string(input));
            let result = parse_chord_progression_string(input);
            assert!(result.is_err());
            assert_eq!(
                result.unwrap_err().position,
                Position {
                    line_number: 1,
                    column_number: 6,
                    length: 3,
                },
            )
        }
    }
}