Debian Codegraph @

one-ini-wasm/src/lib.rs

raw symbols SCIP
1 //! # EditorConfig
2 //!
3 //! A collection of utilities that handle the parsing of
4 //! [EditorConfig-INI](https://editorconfig-specification.readthedocs.io/en/latest/#file-format)
5 //! file contents into [AST](https://en.wikipedia.org/wiki/Abstract_syntax_tree),
6 //! which can then be modified and/or serialized.
7
8 // Enable WeeAlloc as global memory allocator for the WASM target
9 #[cfg(target_arch = "wasm32")]
10 extern crate wee_alloc;
11 #[cfg(target_arch = "wasm32")]
12 #[global_allocator]
13 static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
14
15 extern crate pest;
16 #[macro_use]
17 extern crate pest_derive;
18
19 use pest::error::Error;
20 use pest::Parser;
21 use serde::{Deserialize, Serialize};
22 use std::{env, fmt, str};
23 use wasm_bindgen::prelude::*;
24
25 #[derive(Parser)]
26 #[grammar = "ini.pest"]
27 struct INIParser;
28
29 #[wasm_bindgen]
30 pub fn parse_to_json(contents: &str) -> JsValue {
31 let ast = parse(&contents).unwrap();
32 return serde_wasm_bindgen::to_value(&ast).unwrap();
33 //return JsValue::from_serde(&ast).unwrap();
34 }
35
36 #[wasm_bindgen]
37 pub fn version() -> String {
38 String::from(env!("CARGO_PKG_VERSION"))
39 }
40
41 #[wasm_bindgen]
42 #[derive(Copy, Clone)]
43 #[repr(u32)]
44 pub enum TokenTypes {
45 Key,
46 Value,
47 Section,
48 CommentIndicator,
49 CommentValue,
50 }
51
52 #[wasm_bindgen]
53 pub fn parse_to_uint32array(contents: &[u8]) -> Result<Vec<u32>, JsError> {
54 let input = str::from_utf8(contents)?;
55 match parse_to_vec(input) {
56 Ok(res) => Ok(res),
57 Err(er) => Err(JsError::from(er)),
58 }
59 }
60
61 /// Parses
62 /// [EditorConfig-INI](https://editorconfig-specification.readthedocs.io/en/latest/#file-format)
63 /// contents into an array of unsigned ints. Each token consists of three
64 /// ints, a type from the TokenTypes enum, a starting byte offset, and an
65 /// ending byte offset. It is up to the caller to reconstruct an AST, and
66 /// pull UTF8-encoding strings out of the input buffer.
67 ///
68 /// # Example
69 ///
70 /// ```
71 /// let contents = String::from("root=true\n");
72 /// let results = one_ini::parse_to_vec(&contents).unwrap();
73 /// assert_eq!(results, vec![0, 0, 4, 1, 5, 9]);
74 /// ```
75 pub fn parse_to_vec(contents: &str) -> Result<Vec<u32>, Error<Rule>> {
76 let mut parsed = INIParser::parse(Rule::ini, contents)?;
77 // 300 is slightly larger than the max size found in the test suite, and
78 // should be larger than most normal .editorconfig files, to avoid a few
79 // allocations.
80 let mut results = Vec::with_capacity(300);
81
82 fill_vec(parsed.next().unwrap(), &mut results);
83 Ok(results)
84 }
85
86 fn push_token(typ: TokenTypes, pair: pest::iterators::Pair<'_, Rule>, results: &mut Vec<u32>) {
87 let span = pair.as_span();
88 results.push(typ as u32);
89 results.push(span.start() as u32);
90 results.push(span.end() as u32);
91 }
92
93 fn fill_vec(pair: pest::iterators::Pair<'_, Rule>, results: &mut Vec<u32>) {
94 let children = pair.into_inner().filter(|p| match p.as_rule() {
95 Rule::EOI => false,
96 _ => true,
97 });
98 for child in children {
99 match child.as_rule() {
100 Rule::section => {
101 let mut inner_rules = child.into_inner();
102 let mut header = inner_rules.next().unwrap().into_inner();
103 push_token(TokenTypes::Section, header.next().unwrap(), results);
104 // Body always exists, even if empty
105 fill_vec(inner_rules.next().unwrap(), results);
106 }
107 Rule::pair => {
108 let mut inner_rules = child.into_inner();
109 push_token(TokenTypes::Key, inner_rules.next().unwrap(), results);
110 push_token(TokenTypes::Value, inner_rules.next().unwrap(), results);
111 }
112 Rule::comment => {
113 let mut inner_rules = child.into_inner();
114 push_token(
115 TokenTypes::CommentIndicator,
116 inner_rules.next().unwrap(),
117 results,
118 );
119 push_token(
120 TokenTypes::CommentValue,
121 inner_rules.next().unwrap(),
122 results,
123 );
124 }
125 _ => unreachable!(),
126 }
127 }
128 }
129
130 /// Parses [EditorConfig-INI](https://editorconfig-specification.readthedocs.io/en/latest/#file-format)
131 /// contents into [AST](https://en.wikipedia.org/wiki/Abstract_syntax_tree).
132 ///
133 /// # Example
134 ///
135 /// ```
136 /// let contents = String::from("root=true\n");
137 /// let ast = one_ini::parse(&contents).unwrap();
138 ///
139 /// assert_eq!(ast.to_string(), contents);
140 /// ```
141 pub fn parse(contents: &str) -> Result<OneINIAST, Error<Rule>> {
142 return match INIParser::parse(Rule::ini, contents) {
143 Ok(mut pairs) => Ok(OneINIAST::new(create_body(pairs.next().unwrap()))),
144 Err(e) => Err(e),
145 };
146 }
147
148 fn create_body(pair: pest::iterators::Pair<'_, Rule>) -> Vec<Item> {
149 return pair
150 .into_inner()
151 .filter(|p| match p.as_rule() {
152 Rule::EOI => false,
153 _ => true,
154 })
155 .map(|p| match p.as_rule() {
156 Rule::section => {
157 let mut inner_rules = p.into_inner();
158 let header = inner_rules.next().unwrap().into_inner().next().unwrap();
159 return Item::Section(Section {
160 name: String::from(header.as_str()),
161 body: match inner_rules.next() {
162 Some(pair) => create_body(pair),
163 _ => vec![],
164 },
165 });
166 }
167 Rule::pair => {
168 let mut inner_rules = p.into_inner();
169 return Item::Pair(Pair {
170 key: String::from(inner_rules.next().unwrap().as_str()),
171 value: String::from(inner_rules.next().unwrap().as_str()),
172 });
173 }
174 Rule::comment => {
175 let mut inner_rules = p.into_inner();
176 return Item::Comment(Comment {
177 indicator: inner_rules.next().unwrap().as_str().chars().nth(0).unwrap(),
178 value: String::from(inner_rules.next().unwrap().as_str()),
179 });
180 }
181 _ => unreachable!(),
182 })
183 .collect();
184 }
185
186 /// The root [AST](https://en.wikipedia.org/wiki/Abstract_syntax_tree) node of
187 /// a [parsed](fn.parse.html) INI file that conforms to the
188 /// [EditorConfig INI file format](https://editorconfig-specification.readthedocs.io/en/latest/#file-format).
189 ///
190 /// # Example
191 ///
192 /// ```
193 /// use one_ini::*;
194 ///
195 /// let ast = OneINIAST::new(vec![
196 /// Item::Pair(Pair {
197 /// key: String::from("root"),
198 /// value: String::from("true"),
199 /// }),
200 /// Item::Section(Section {
201 /// name: String::from("one"),
202 /// body: vec![
203 /// Item::Comment(Comment {
204 /// indicator: '#',
205 /// value: String::from(" body1"),
206 /// }),
207 /// ],
208 /// }),
209 /// Item::Section(Section {
210 /// name: String::from("two"),
211 /// body: vec![
212 /// Item::Comment(Comment {
213 /// indicator: ';',
214 /// value: String::from(" body2"),
215 /// }),
216 /// ],
217 /// }),
218 /// ]);
219 ///
220 /// assert_eq!(ast.to_string(), "root=true\n\n[one]\n# body1\n\n[two]\n; body2\n");
221 ///
222 /// let ver = env!("CARGO_PKG_VERSION");
223 /// let serialized = serde_json::to_string(&ast).unwrap();
224 /// let expected = "{\"version\":\"".to_owned() + ver + "\",\"body\":[{\"type\":\"Pair\",\"key\":\"root\",\"value\":\"true\"},{\"type\":\"Section\",\"name\":\"one\",\"body\":[{\"type\":\"Comment\",\"indicator\":\"#\",\"value\":\" body1\"}]},{\"type\":\"Section\",\"name\":\"two\",\"body\":[{\"type\":\"Comment\",\"indicator\":\";\",\"value\":\" body2\"}]}]}";
225 /// assert_eq!(serialized, expected);
226 ///
227 /// let deserialized: OneINIAST = serde_json::from_str(&serialized).unwrap();
228 /// assert_eq!(serde_json::to_string(&deserialized).unwrap(), expected);
229 /// ```
230 #[derive(Serialize, Deserialize, Debug)]
231 pub struct OneINIAST {
232 /// The version of the EditorConfig-INI parser.
233 pub version: String,
234 /// Contains the _prelude_, followed by any number of sections.
235 #[serde(skip_serializing_if = "Vec::is_empty")]
236 pub body: Vec<Item>,
237 }
238
239 impl OneINIAST {
240 pub fn new<B: Into<Vec<Item>>>(body: B) -> Self {
241 OneINIAST {
242 version: String::from(env!("CARGO_PKG_VERSION")),
243 body: body.into(),
244 }
245 }
246 }
247
248 impl fmt::Display for OneINIAST {
249 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
250 let mut wrote = false;
251 for item in &self.body {
252 match item {
253 Item::Section(_section) => {
254 if wrote {
255 writeln!(formatter)?;
256 }
257 }
258 _ => (),
259 }
260 item.fmt(formatter)?;
261 wrote = true;
262 }
263 Ok(())
264 }
265 }
266
267 /// Any number of items may be used within a prelude or
268 /// [section](struct.section.html) body.
269 ///
270 /// # Serializing & Deserializing
271 ///
272 /// ```
273 /// use one_ini::{Comment,Item};
274 ///
275 /// let item = Item::Comment(Comment {
276 /// indicator: '#',
277 /// value: String::from("octothorpe"),
278 /// });
279 /// let serialized = serde_json::to_string(&item).unwrap();
280 /// assert_eq!(
281 /// serialized,
282 /// "{\"type\":\"Comment\",\"indicator\":\"#\",\"value\":\"octothorpe\"}",
283 /// );
284 ///
285 /// let deserialized: Comment = serde_json::from_str(&serialized).unwrap();
286 /// assert_eq!(deserialized.indicator, '#');
287 /// assert_eq!(deserialized.value, "octothorpe");
288 /// ```
289 #[derive(Serialize, Deserialize, Debug)]
290 #[serde(tag = "type")]
291 pub enum Item {
292 Comment(Comment),
293 Pair(Pair),
294 Section(Section),
295 }
296
297 impl fmt::Display for Item {
298 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
299 match self {
300 Item::Comment(comment) => comment.fmt(formatter),
301 Item::Pair(pair) => pair.fmt(formatter),
302 Item::Section(section) => section.fmt(formatter),
303 }?;
304 Ok(())
305 }
306 }
307
308 /// Starts with either a `#` or `;` comment indicator on a new or blank line,
309 /// followed by any characters until it reaches a newline or the end of input.
310 ///
311 /// # Examples
312 ///
313 /// ```
314 /// let comment = one_ini::Comment {
315 /// indicator: '#',
316 /// value: String::from("octothorpe"),
317 /// };
318 ///
319 /// assert_eq!(comment.to_string(), "#octothorpe\n");
320 /// ```
321 ///
322 /// ```
323 /// let comment = one_ini::Comment {
324 /// indicator: ';',
325 /// value: String::from("semi-colon"),
326 /// };
327 ///
328 /// assert_eq!(comment.to_string(), ";semi-colon\n");
329 /// ```
330 ///
331 /// # Serializing & Deserializing
332 ///
333 /// ```
334 /// let comment = one_ini::Comment {
335 /// indicator: '#',
336 /// value: String::from("octothorpe"),
337 /// };
338 /// let serialized = serde_json::to_string(&comment).unwrap();
339 /// let deserialized: one_ini::Comment = serde_json::from_str(&serialized).unwrap();
340 ///
341 /// assert_eq!(
342 /// serialized,
343 /// "{\"indicator\":\"#\",\"value\":\"octothorpe\"}",
344 /// );
345 /// assert_eq!(deserialized.indicator, '#');
346 /// assert_eq!(deserialized.value, "octothorpe");
347 /// ```
348 #[derive(Serialize, Deserialize, Debug)]
349 pub struct Comment {
350 /// The character that begins a comment. This may only be
351 /// an octothorpe (`#`) or a semi-colon (`;`).
352 pub indicator: char,
353 /// The value that follows the comment indicator.
354 pub value: String,
355 }
356
357 /// Serializes a comment as a JSON string.
358 ///
359 /// # Example
360 ///
361 /// ```
362 /// let comment = one_ini::Comment {
363 /// indicator: '#',
364 /// value: String::from("octothorpe"),
365 /// };
366 /// let serialized = serde_json::to_string(&comment).unwrap();
367 /// let deserialized: one_ini::Comment = serde_json::from_str(&serialized).unwrap();
368 ///
369 /// assert_eq!(
370 /// serialized,
371 /// "{\"indicator\":\"#\",\"value\":\"octothorpe\"}",
372 /// );
373 /// assert_eq!(deserialized.indicator, '#');
374 /// assert_eq!(deserialized.value, "octothorpe");
375 /// ```
376 // impl Serialize for Comment {
377 // fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
378 // where
379 // S: Serializer,
380 // {
381 // let mut state = serializer.serialize_struct("Comment", 3)?;
382 // // state.serialize_field("type", "comment")?;
383 // state.serialize_field("indicator", &self.indicator)?;
384 // state.serialize_field("value", &self.value)?;
385 // return state.end();
386 // }
387 // }
388
389 impl fmt::Display for Comment {
390 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
391 writeln!(formatter, "{}{}", self.indicator, self.value)?;
392 Ok(())
393 }
394 }
395
396 /// A key-value pair.
397 ///
398 /// # Example
399 ///
400 /// ```
401 /// let pair = one_ini::Pair {
402 /// key: String::from("left"),
403 /// value: String::from("right"),
404 /// };
405 ///
406 /// assert_eq!(pair.to_string(), "left=right\n");
407 /// ```
408 #[derive(Serialize, Deserialize, Debug)]
409 pub struct Pair {
410 /// Appears on the _left_ side of the assignment (`=`).
411 pub key: String,
412 /// Appears on the _right_ side of the assignment (`=`).
413 pub value: String,
414 }
415
416 impl fmt::Display for Pair {
417 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
418 writeln!(formatter, "{}={}", self.key, self.value)?;
419 Ok(())
420 }
421 }
422
423 /// Starts with a header and ends just before another section begins.
424 ///
425 /// # Example
426 ///
427 /// ```
428 /// use one_ini::*;
429 ///
430 /// let section = Section {
431 /// name: String::from("header"),
432 /// body: vec![
433 /// Item::Comment(Comment {
434 /// indicator: '#',
435 /// value: String::from(" body"),
436 /// }),
437 /// Item::Pair(Pair {
438 /// key: String::from("left"),
439 /// value: String::from("right"),
440 /// }),
441 /// Item::Pair(Pair {
442 /// key: String::from("empty"),
443 /// value: String::from(""),
444 /// }),
445 /// ],
446 /// };
447 ///
448 /// assert_eq!(section.to_string(), "[header]\n# body\nleft=right\nempty=\n");
449 /// ```
450 #[derive(Serialize, Deserialize, Debug)]
451 pub struct Section {
452 /// The section header's name (i.e., the part between `[` and `]`).,
453 pub name: String,
454 /// Contains any number of items, which may only consist of
455 /// comments and pairs.
456 #[serde(skip_serializing_if = "Vec::is_empty")]
457 pub body: Vec<Item>,
458 }
459
460 impl fmt::Display for Section {
461 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
462 writeln!(formatter, "[{}]", self.name)?;
463 for item in &self.body {
464 item.fmt(formatter)?;
465 }
466 Ok(())
467 }
468 }
469
470 #[cfg(test)]
471 mod tests {
472 use super::*;
473 use std::fs;
474
475 #[test]
476 fn it_works() {
477 let contents = fs::read_to_string("tests/fixtures/config.ini").unwrap();
478 let ast = parse(&contents).unwrap();
479 assert_eq!(ast.to_string(), contents);
480 }
481 }