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
//! A JSON writer for BinAST file structure.
//! The written file is supposed to be filtered with some command to generate
//! an invalid content, and then fed to binjs_convert_from_json command to
//! generate BinAST file with the invalid content.
//! See mod.rs for the detail of the filter.

use io::{Path, TokenWriter};
use TokenWriterError;

use binjs_shared::{FieldName, IdentifierName, InterfaceName, Node, PropertyKey, SharedString};

use escaped_wtf8;

use serde_json::Value as JSON;

/// Context for either list or tagged tuple.
enum Context {
    List {
        /// The list of items.
        items: Vec<JSON>,
    },
    TaggedTuple {
        /// The interface name.
        interface: InterfaceName,

        /// The list of field values.
        field_values: Vec<JSON>,
    },
}
impl Context {
    /// Create a new list context.
    fn new_list() -> Self {
        Context::List { items: Vec::new() }
    }

    /// Create a new tagged tuple context.
    fn new_tagged_tuple(tag: InterfaceName) -> Self {
        Context::TaggedTuple {
            interface: tag,
            field_values: Vec::new(),
        }
    }
}

pub struct TreeTokenWriter {
    /// The context stack.
    contexts: Vec<Context>,
}

impl TreeTokenWriter {
    pub fn new() -> Self {
        Self {
            contexts: vec![Context::new_list()],
        }
    }

    /// Add the given item/field to the current list/tagged tuple.
    fn push(&mut self, v: JSON) {
        match self.contexts.last_mut() {
            Some(Context::TaggedTuple { field_values, .. }) => {
                field_values.push(v);
            }
            Some(Context::List { items }) => {
                items.push(v);
            }
            _ => {
                panic!("context mismatch");
            }
        }
    }
}

impl TokenWriter for TreeTokenWriter {
    type Data = Box<[u8]>;

    fn done(mut self) -> Result<Self::Data, TokenWriterError> {
        match self.contexts.pop() {
            Some(Context::List { mut items }) => {
                let top_level_item = items
                    .pop()
                    .expect("There should be only one item at the top level");
                let source = format!("{:#}", top_level_item);
                let result = escaped_wtf8::to_unicode_escape(source).into_bytes().into();
                Ok(result)
            }
            _ => {
                panic!("context mismatch");
            }
        }
    }

    fn enter_tagged_tuple_at(
        &mut self,
        _node: &dyn Node,
        tag: &InterfaceName,
        _children: &[&FieldName],
        _path: &Path,
    ) -> Result<(), TokenWriterError> {
        self.contexts.push(Context::new_tagged_tuple(tag.clone()));
        Ok(())
    }
    fn exit_tagged_tuple_at(
        &mut self,
        _node: &dyn Node,
        _tag: &InterfaceName,
        children: &[&FieldName],
        _path: &Path,
    ) -> Result<(), TokenWriterError> {
        match self.contexts.pop() {
            Some(Context::TaggedTuple {
                interface: tag,
                field_values,
            }) => {
                let mut obj = serde_json::Map::with_capacity(2);
                obj.insert(
                    "@TYPE".to_string(),
                    JSON::String("tagged tuple".to_string()),
                );
                obj.insert(
                    "@INTERFACE".to_string(),
                    JSON::String(tag.as_str().to_string()),
                );

                let mut fields: Vec<JSON> = Vec::new();
                assert!(children.len() == field_values.len());
                let mut i = 0;
                for field_value in field_values {
                    let mut field = serde_json::Map::with_capacity(2);
                    field.insert(
                        "@FIELD_NAME".to_string(),
                        JSON::String(children[i].as_str().to_string()),
                    );
                    field.insert("@FIELD_VALUE".to_string(), field_value);
                    fields.push(JSON::Object(field));
                    i += 1;
                }
                obj.insert("@FIELDS".to_string(), JSON::Array(fields));

                self.push(JSON::Object(obj));
            }
            _ => {
                panic!("context mismatch");
            }
        };
        Ok(())
    }

    fn enter_list_at(&mut self, _len: usize, _path: &Path) -> Result<(), TokenWriterError> {
        self.contexts.push(Context::new_list());
        Ok(())
    }
    fn exit_list_at(&mut self, _path: &Path) -> Result<(), TokenWriterError> {
        match self.contexts.pop() {
            Some(Context::List { items }) => {
                let mut obj = serde_json::Map::with_capacity(2);
                obj.insert("@TYPE".to_string(), JSON::String("list".to_string()));
                obj.insert("@VALUE".to_string(), JSON::Array(items));
                self.push(JSON::Object(obj));
            }
            _ => {
                panic!("context mismatch");
            }
        };

        Ok(())
    }

    fn string_at(
        &mut self,
        value: Option<&SharedString>,
        _path: &Path,
    ) -> Result<(), TokenWriterError> {
        let mut obj = serde_json::Map::with_capacity(2);
        obj.insert("@TYPE".to_string(), JSON::String("string".to_string()));
        match value {
            Some(v) => {
                obj.insert("@VALUE".to_string(), JSON::String(v.to_string()));
            }
            None => {
                obj.insert("@VALUE".to_string(), JSON::Null);
            }
        };
        self.push(JSON::Object(obj));
        Ok(())
    }

    fn string_enum_at(
        &mut self,
        value: &SharedString,
        _path: &Path,
    ) -> Result<(), TokenWriterError> {
        let mut obj = serde_json::Map::with_capacity(2);
        obj.insert("@TYPE".to_string(), JSON::String("enum".to_string()));
        obj.insert("@VALUE".to_string(), JSON::String(value.to_string()));
        self.push(JSON::Object(obj));
        Ok(())
    }

    fn float_at(&mut self, value: Option<f64>, _path: &Path) -> Result<(), TokenWriterError> {
        let mut obj = serde_json::Map::with_capacity(2);
        obj.insert("@TYPE".to_string(), JSON::String("float".to_string()));
        obj.insert(
            "@VALUE".to_string(),
            value
                .and_then(serde_json::Number::from_f64)
                .map(JSON::Number)
                .unwrap_or(JSON::Null),
        );
        self.push(JSON::Object(obj));
        Ok(())
    }

    fn unsigned_long_at(&mut self, value: u32, _path: &Path) -> Result<(), TokenWriterError> {
        let mut obj = serde_json::Map::with_capacity(2);
        obj.insert(
            "@TYPE".to_string(),
            JSON::String("unsigned long".to_string()),
        );
        obj.insert("@VALUE".to_string(), JSON::Number(value.into()));
        self.push(JSON::Object(obj));
        Ok(())
    }

    fn bool_at(&mut self, value: Option<bool>, _path: &Path) -> Result<(), TokenWriterError> {
        let mut obj = serde_json::Map::with_capacity(2);
        obj.insert("@TYPE".to_string(), JSON::String("bool".to_string()));
        match value {
            Some(v) => {
                obj.insert("@VALUE".to_string(), JSON::Bool(v));
            }
            None => {
                obj.insert("@VALUE".to_string(), JSON::Null);
            }
        };
        self.push(JSON::Object(obj));
        Ok(())
    }

    fn offset_at(&mut self, _path: &Path) -> Result<(), TokenWriterError> {
        unimplemented!()
    }

    fn property_key_at(
        &mut self,
        value: Option<&PropertyKey>,
        _path: &Path,
    ) -> Result<(), TokenWriterError> {
        let mut obj = serde_json::Map::with_capacity(2);
        obj.insert(
            "@TYPE".to_string(),
            JSON::String("property key".to_string()),
        );
        match value {
            Some(v) => {
                obj.insert("@VALUE".to_string(), JSON::String(v.as_str().to_string()));
            }
            None => {
                obj.insert("@VALUE".to_string(), JSON::Null);
            }
        };
        self.push(JSON::Object(obj));
        Ok(())
    }

    fn identifier_name_at(
        &mut self,
        value: Option<&IdentifierName>,
        _path: &Path,
    ) -> Result<(), TokenWriterError> {
        let mut obj = serde_json::Map::with_capacity(2);
        obj.insert(
            "@TYPE".to_string(),
            JSON::String("identifier name".to_string()),
        );
        match value {
            Some(v) => {
                obj.insert("@VALUE".to_string(), JSON::String(v.as_str().to_string()));
            }
            None => {
                obj.insert("@VALUE".to_string(), JSON::Null);
            }
        };
        self.push(JSON::Object(obj));
        Ok(())
    }
}