forked from xmppo/node-expat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimple-node-expat.cc
368 lines (302 loc) · 9.74 KB
/
simple-node-expat.cc
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
//#include <iostream>
#include <list>
//#include <pcrecpp.h>
#include <cctype>
#include <algorithm>
#include <nan.h>
extern "C" {
#include <expat.h>
}
// String utility functions, probably better to be in a separated file
bool BothAreSpaces(char lhs, char rhs) {
return std::isspace(rhs) && std::isspace(lhs);
}
void RemoveDuplicatedSpaces(std::string &str) {
std::string::iterator new_end = std::unique(str.begin(), str.end(), BothAreSpaces);
str.erase(new_end, str.end());
}
bool IsNotSpace(char chr) {
return ! std::isspace(chr);
}
bool IsEmpty(std::string str) {
std::string::iterator result = std::find_if(str.begin(), str.end(), IsNotSpace);
return result == str.end();
}
void Trim(std::string &str) {
std::string spaces = " \n\t\v";
std::size_t first = str.find_first_not_of(spaces);
str.replace(0, first, "");
std::size_t last = str.find_last_not_of(spaces);
str.replace(last + 1, str.length(), "");
}
using namespace v8;
using namespace node;
class Parser : public ObjectWrap {
public:
static void Initialize(Handle<Object> target)
{
NanScope();
Local<FunctionTemplate> t = NanNew<FunctionTemplate>(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(t, "parse", Parse);
NODE_SET_PROTOTYPE_METHOD(t, "getResult", GetResult);
NODE_SET_PROTOTYPE_METHOD(t, "getError", GetError);
target->Set(NanNew("Parser"), t->GetFunction());
}
protected:
/*** Constructor ***/
static NAN_METHOD(New)
{
NanScope();
XML_Char *encoding = NULL;
if (args.Length() == 1 && args[0]->IsString())
{
encoding = *NanAsciiString(args[0]);
}
Parser *parser = new Parser(encoding);
if (encoding)
delete[] encoding;
parser->Wrap(args.This());
NanReturnValue(args.This());
}
Parser(const XML_Char *encoding)
: ObjectWrap()
{
stack = new std::list<Local<Value> >;
parser = XML_ParserCreate(encoding);
assert(parser != NULL);
attachHandlers();
}
~Parser()
{
// TODO: The persistent handles need to be cleanup up as well?
XML_ParserFree(parser);
delete stack;
}
void attachHandlers()
{
XML_SetUserData(parser, this);
XML_SetElementHandler(parser, StartElement, EndElement);
XML_SetCharacterDataHandler(parser, Text);
}
static NAN_METHOD(Parse)
{
Parser *parser = ObjectWrap::Unwrap<Parser>(args.This());
NanScope();
Local<String> str;
int isFinal = 0;
/* Argument 2: isFinal :: Bool */
if (args.Length() >= 2)
{
isFinal = args[1]->IsTrue();
}
/* Argument 1: buf :: String or Buffer */
if (args.Length() >= 1 && args[0]->IsString())
{
str = args[0]->ToString();
NanReturnValue(parser->parseString(**str, isFinal) ? NanTrue() : NanFalse());
}
else if (args.Length() >= 1 && args[0]->IsObject())
{
Local<Object> obj = args[0]->ToObject();
if (Buffer::HasInstance(obj))
{
NanReturnValue(parser->parseBuffer(obj, isFinal) ? NanTrue() : NanFalse());
}
else
{
NanThrowTypeError("Parse buffer must be String or Buffer");
NanReturnUndefined();
}
}
else {
NanThrowTypeError("Parse buffer must be String or Buffer");
NanReturnUndefined();
}
}
/** Parse a v8 String by first writing it to the expat parser's
buffer */
bool parseString(String &str, int isFinal)
{
int len = str.Utf8Length();
if (len == 0)
return true;
void *buf = XML_GetBuffer(parser, len);
assert(buf != NULL);
assert(str.WriteUtf8(static_cast<char *>(buf), len) == len);
// TODO: Emit "end" event before returning status
return XML_ParseBuffer(parser, len, isFinal) != XML_STATUS_ERROR;
}
/** Parse a node.js Buffer directly */
bool parseBuffer(Local<Object> buffer, int isFinal)
{
return XML_Parse(parser, Buffer::Data(buffer), Buffer::Length(buffer), isFinal) != XML_STATUS_ERROR;
}
/*** getError() ***/
static NAN_METHOD(GetError)
{
NanScope();
Parser *parser = ObjectWrap::Unwrap<Parser>(args.This());
const XML_LChar *error = parser->getError();
if (error)
NanReturnValue(NanNew(error));
else
NanReturnValue(NanNull());
}
const XML_LChar *getError()
{
enum XML_Error code;
code = XML_GetErrorCode(parser);
return XML_ErrorString(code);
}
/*** getResult() ***/
static NAN_METHOD(GetResult)
{
NanScope();
Parser *parser = ObjectWrap::Unwrap<Parser>(args.This());
const XML_LChar *error = parser->getError();
if (error)
NanReturnValue(NanNull());
else
NanReturnValue(NanNew(parser->result));
// NanReturnValue(NanNew("fruta"));
}
private:
/* expat instance */
XML_Parser parser;
/* no default ctor */
Parser();
/* Stack for parsed elements */
std::list<Local<Value> > * stack;
/* The final parsing result */
Local<Value> result;
/*** SAX callbacks ***/
/* Should a local HandleScope be used in those callbacks? */
static void StartElement(void *userData,
const XML_Char *name, const XML_Char **atts)
{
// NanScope();
Parser *parser = reinterpret_cast<Parser *>(userData);
/* Collect atts into JS object */
Local<Object> attr = NanNew<Object>();
for(const XML_Char **atts1 = atts; *atts1; atts1 += 2)
attr->Set(NanNew(atts1[0]), NanNew(atts1[1]));
Local<Object> currentNode = NanNew<Object>();
// Create the "@" only if needed
if (attr->GetPropertyNames()->Length() > 0) {
currentNode->Set(NanNew("@"), attr);
}
currentNode->Set(NanNew("#"), NanNew(""));
currentNode->Set(NanNew("#name"), NanNew(name));
// Add parsed element to array
parser->stack->push_back(currentNode);
// parser->stack->push_back(NanNew(currentNode));
}
static void EndElement(void *userData,
const XML_Char *name)
{
// NanScope();
Parser *parser = reinterpret_cast<Parser *>(userData);
// Get current node from top of stack
Local<Value> currentValue = parser->stack->back();
Local<Object> currentNode = Local<Object>::Cast(currentValue);
parser->stack->pop_back();
// std::string nodeName = std::string(*NanAsciiString(currentNode->Get(NanNew("#name"))));
Local<String> nodeName = Local<String>::Cast(currentNode->Get(NanNew("#name")));
currentNode->Delete(NanNew("#name"));
// std::cout << "Current node " << nodeName << "\n";
std::string text = std::string(*NanAsciiString(currentNode->Get(NanNew("#"))));
// Handling of "#" attribute
if (IsEmpty(text)) {
currentNode->Delete(NanNew("#"));
} else {
// Remove unnecessary spaces
RemoveDuplicatedSpaces(text);
// trim
Trim(text);
Local<String> newText = NanNew(text);
if (currentNode->GetPropertyNames()->Length() == 1 && currentNode->Has(NanNew("#"))) {
// Overwrite node with current string
currentValue = newText;
} else {
currentNode->Set(NanNew("#"), newText);
}
}
if (! parser->stack->empty()) {
// std::cout << "Stack not empty\n";
// Get parent from current node
Local<Object> parent = Local<Object>::Cast(parser->stack->back());
// std::string parentName = std::string(*NanAsciiString(parent->Get(NanNew("#name"))));
// std::cout << "Parent node " << parentName << "\n";
// Check if parent has an attribute to the current node
if (! parent->Has(nodeName)) {
// std::cout << "Parent does not have attribute\n";
// Add current node as a single object attribute
parent->Set(nodeName, currentValue);
} else {
// Get attribute from parent and check it's type
Local<Value> parentAttribute = parent->Get(nodeName);
if (parentAttribute->IsArray()) {
// std::cout << "Attribute on parent is array\n";
// Add current node to attribute
Local<Array> attributes = Local<Array>::Cast(parentAttribute);
// Get the native push function
Local<Function> push = Local<Function>::Cast(
attributes->Get(NanNew<String>("push"))
);
Local<Value> argv[1] = { currentValue };
// Do the push!
push->Call(attributes, 1, argv);
} else {
// Convert attribute to array
// std::cout << "Attribute on parent is single object\n";
Local<Array> attributes = NanNew<Array>(2);
attributes->Set(0, parentAttribute);
attributes->Set(1, currentValue);
parent->Set(nodeName, attributes);
}
}
} else {
// std::cout << "Stack empty\n";
parser->result = NanNew(currentValue);
}
}
static void Text(void *userData,
const XML_Char *s, int len)
{
// NanScope();
Parser *parser = reinterpret_cast<Parser *>(userData);
// Get current node from top of stack
Local<Object> currentNode = Local<Object>::Cast(parser->stack->back());
Local<String> text = Local<String>::Cast(currentNode->Get(NanNew("#")));
Local<String> newText = String::Concat(text, NanNew(s, len));
currentNode->Set(NanNew("#"), newText);
}
/*
void Emit(int argc, Handle<Value> argv[])
{
NanScope();
Handle<Object> handle = NanObjectWrapHandle(this);
Local<Function> emit = handle->Get(NanNew("emit")).As<Function>();
emit->Call(handle, argc, argv);
}
*/
/*
void push(Local<Value> currentNode)
{
NanScope();
Local<Value> argv[1];
argv[0] = NanNew(currentNode);
std::cout << "push\n";
pushFunction->Call(NanNew(stack), 1, argv);
}
*/
};
extern "C" {
static void init (Handle<Object> target)
{
Parser::Initialize(target);
}
//Changed the name cause I couldn't load the module with - in their names
NODE_MODULE(simple_node_expat, init);
};