aboutsummaryrefslogtreecommitdiff
path: root/examples/cxx/tree/embedded/xsdbin.cxx
blob: dc42fd66007ffe18a276a2a8e67fc72b1797b028 (plain)
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
// file      : examples/cxx/tree/embedded/xsdbin.cxx
// author    : Boris Kolpackov <boris@codesynthesis.com>
// copyright : not copyrighted - public domain

// This program loads the XML Schema file(s) and converts them to
// the Xerces-C++ binary schema format which can then be embedded
// into C++ programs and used to validate XML documents. The output
// is written as a C++ source file containing the array with the
// binary data.
//

#include <string>
#include <memory>   // std::auto_ptr
#include <cstddef>  // std::size_t
#include <fstream>
#include <iostream>

#include <xercesc/util/XMLUni.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XercesVersion.hpp>

#include <xercesc/internal/BinMemOutputStream.hpp>
#include <xercesc/validators/common/Grammar.hpp>

#include <xercesc/sax/ErrorHandler.hpp>
#include <xercesc/sax/SAXParseException.hpp>
#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/sax2/XMLReaderFactory.hpp>

#include <xercesc/framework/XMLGrammarPoolImpl.hpp>

using namespace std;
using namespace xercesc;

class error_handler: public ErrorHandler
{
public:
  error_handler ()
      : failed_ (false)
  {
  }

  bool
  failed () const
  {
    return failed_;
  }

  enum severity {s_warning, s_error, s_fatal};

  virtual void
  warning (const SAXParseException&);

  virtual void
  error (const SAXParseException&);

  virtual void
  fatalError (const SAXParseException&);

  virtual void
  resetErrors ()
  {
    failed_ = false;
  }

  void
  handle (const SAXParseException&, severity);

private:
  bool failed_;
};

void
cxx_escape (string&);

int
main (int argc, char* argv[])
{
  const char* hxx_suffix = "-schema.hxx";
  const char* cxx_suffix = "-schema.cxx";

  string name;
  string base;
  string outdir;

  struct usage
  {
    usage (bool e = true): error (e) {}
    bool error;
  };

  int argi (1);
  bool multi_import (true);
  bool verbose (false);

  try
  {
    for (; argi < argc; ++argi)
    {
      string a (argv[argi]);

      if (a == "--help")
        throw usage (false);
      else if (a == "--verbose")
      {
        verbose = true;
      }
      else if (a == "--hxx-suffix")
      {
        if (++argi >= argc)
          throw usage ();

        hxx_suffix = argv[argi];
      }
      else if (a == "--cxx-suffix")
      {
        if (++argi >= argc)
          throw usage ();

        cxx_suffix = argv[argi];
      }
      else if (a == "--output-dir")
      {
        if (++argi >= argc)
          throw usage ();

        outdir = argv[argi];
      }
      else if (a == "--array-name")
      {
        if (++argi >= argc)
          throw usage ();

        name = argv[argi];
      }
      else if (a == "--disable-multi-import")
      {
        multi_import = false;
      }
      else
        break;
    }

    if (argi >= argc)
    {
      cerr << "no input file specified" << endl;
      throw usage ();
    }

    base = argv[argi];
  }
  catch (usage const& e)
  {
    ostream& o (e.error ? cerr : cout);

    o << "Usage: " << argv[0] << " [options] <files>" << endl
      << "Options:" << endl
      << "  --help                 Print usage information and exit." << endl
      << "  --verbose              Print progress information." << endl
      << "  --output-dir <dir>     Write generated files to <dir>." << endl
      << "  --hxx-suffix <sfx>     Header file suffix instead of '-schema.hxx'." << endl
      << "  --cxx-suffix <sfx>     Source file suffix instead of '-schema.cxx'." << endl
      << "  --array-name <name>    Binary data array name." << endl
      << "  --disable-multi-import Disable multiple import support." << endl
      << endl;

    return e.error ? 0 : 1;
  }

  XMLPlatformUtils::Initialize ();

  {
    MemoryManager* mm (XMLPlatformUtils::fgMemoryManager);

    auto_ptr<XMLGrammarPool> gp (new XMLGrammarPoolImpl (mm));

    // Load the schemas into grammar pool.
    //
    {
      auto_ptr<SAX2XMLReader> parser (
        XMLReaderFactory::createXMLReader (mm, gp.get ()));

      parser->setFeature (XMLUni::fgSAX2CoreNameSpaces, true);
      parser->setFeature (XMLUni::fgSAX2CoreNameSpacePrefixes, true);
      parser->setFeature (XMLUni::fgSAX2CoreValidation, true);
      parser->setFeature (XMLUni::fgXercesSchema, true);
      parser->setFeature (XMLUni::fgXercesSchemaFullChecking, true);
      parser->setFeature (XMLUni::fgXercesValidationErrorAsFatal, true);

      // Xerces-C++ 3.1.0 is the first version with working multi import
      // support.
      //
#if _XERCES_VERSION >= 30100
      parser->setFeature (XMLUni::fgXercesHandleMultipleImports, multi_import);
#endif

      error_handler eh;
      parser->setErrorHandler (&eh);

      for (; argi < argc; ++argi)
      {
        if (verbose)
          cerr << "loading " << argv[argi] << endl;

        if (!parser->loadGrammar (argv[argi], Grammar::SchemaGrammarType, true))
        {
          cerr << argv[argi] << ": error: unable to load" << endl;
          return 1;
        }

        if (eh.failed ())
          return 1;
      }
    }

    // Get the binary representation.
    //
    BinMemOutputStream data;

    try
    {
      gp->serializeGrammars (&data);
    }
    catch (const XSerializationException& e)
    {
      char* msg (XMLString::transcode (e.getMessage ()));
      cerr << "error: " << msg << endl;
      XMLString::release (&msg);
      return 1;
    }

    size_t n (static_cast<size_t> (data.curPos ()));
    const unsigned char* buf (
      static_cast<const unsigned char*> (data.getRawBuffer ()));

    if (verbose)
      cerr << "uncomressed data size " << n << " bytes" << endl;

    // Compress zeros.
    //
    size_t cn (0);
    unsigned char* cbuf = new unsigned char[n];

    size_t cseq (0);  // Number of bytes left in a compression sequence.
    bool alt (false); // Alternating or sequential sequence.

    for (size_t i (0); i < n;)
    {
      unsigned char v (buf[i++]);

      // See if we are in a compression sequence.
      //
      if (cseq != 0)
      {
        // See if this byte needs to be copied.
        //
        if (alt && cseq % 2 == 0)
          cbuf[cn++] = v;

        cseq--;
        continue;
      }

      // If we are not in a compression sequence and this byte is
      // not zero then simply copy it.
      //
      if (v != 0)
      {
        cbuf[cn++] = v;
        continue;
      }

      // We have a zero.
      //
      cbuf[cn++] = 0;

      // See if we can start a new compression sequence.
      //
      if (i < n)
      {
        if (buf[i] == 0)
        {
          // Sequential sequence. See how far it runs.
          //
          alt = false;

          for (cseq = 1; cseq < 127 && cseq + i < n; cseq++)
            if (buf[cseq + i] != 0)
              break;
        }
        else if (i + 1 < n && buf[i + 1] == 0)
        {
          // Alternating sequence. See how far it runs.
          //
          alt = true;

          for (cseq = 1; cseq < 127 && cseq * 2 + i + 1 < n; cseq++)
          {
            if (buf[cseq * 2 + i + 1] != 0)
              break;

            // For longer sequences prefer sequential to alternating.
            //
            if (cseq > 2 &&
                buf[cseq * 2 + i] == 0 &&
                buf[(cseq - 1) * 2 + i] == 0 &&
                buf[(cseq - 2) * 2 + i] == 0)
            {
              cseq -= 2;
              break;
            }
          }

          cseq *= 2;
        }
      }

      if (cseq != 0)
      {
        cbuf[cn++] = static_cast<unsigned char> (
          alt ? (128  | cseq / 2) : cseq);
      }
      else
        cbuf[cn++] = 0;
    }

    if (verbose)
      cerr << "comressed data size " << cn << " bytes" << endl;

    buf = cbuf;
    n = cn;

    // Figure out the file names.
    //
    string::size_type p (base.rfind ('/')), p1 (base.rfind ('\\'));

    if (p1 != string::npos && p1 > p)
      p = p1;

    if (p != string::npos)
      base = string (base, p + 1);

    p = base.rfind ('.');

    if (p != string::npos)
      base.resize (p);

    string hxx (base + hxx_suffix);
    string cxx (base + cxx_suffix);

    if (!outdir.empty ())
    {
#if defined (WIN32) || defined (__WIN32__)
      hxx = outdir + '\\' + hxx;
      cxx = outdir + '\\' + cxx;
#else
      hxx = outdir + '/' + hxx;
      cxx = outdir + '/' + cxx;
#endif
    }

    if (name.empty ())
    {
      name = base + "_schema";
      cxx_escape (name);
    }

    // Write header.
    //
    {
      ofstream os (hxx.c_str ());

      if (!os.is_open ())
      {
        cerr << hxx << ": error: unable to open" << endl;
        return 1;
      }

      os << "// Automatically generated. Do not edit." << endl
         << "//" << endl
         << endl
         << "#include <xercesc/util/XercesDefs.hpp>" << endl
         << endl
         << "extern const XMLByte " << name << "[" << n << "UL];" << endl;
    }

    {
      ofstream os (cxx.c_str ());

      if (!os.is_open ())
      {
        cerr << cxx << ": error: unable to open" << endl;
        return 1;
      }

      os << "// Automatically generated. Do not edit." << endl
         << "//" << endl
         << endl
         << "#include <xercesc/util/XercesDefs.hpp>" << endl
         << "#include <xercesc/util/XercesVersion.hpp>" << endl
         << endl
         << "#if XERCES_GRAMMAR_SERIALIZATION_LEVEL != " <<
        XERCES_GRAMMAR_SERIALIZATION_LEVEL << endl
         << "#  error incompatible Xerces-C++ version detected" << endl
         << "#endif" << endl
         << endl
         << "extern const XMLByte " << name << "[" << n << "UL] =" << endl
         << "{";

      for (size_t i (0); i < n; ++i)
      {
        if (i != 0)
          os << ',';

        os << (i % 12 == 0 ? "\n  " : " ") << "0x";
        os.width (2);
        os.fill ('0');
        os << hex << static_cast<unsigned short> (buf[i]);
      }

      os << endl
         << "};" << endl
         << endl;
    }

    delete[] cbuf;
  }

  XMLPlatformUtils::Terminate ();
}

void
cxx_escape (string& s)
{
  for (string::size_type i (0); i < s.size (); ++i)
  {
    char& c (s[i]);

    if (i == 0)
    {
      if (!((c >= 'a' && c <= 'z') ||
            (c >= 'A' && c <= 'Z') ||
            c == '_'))
        c = '_';
    }
    else
    {
      if (!((c >= 'a' && c <= 'z') ||
            (c >= 'A' && c <= 'Z') ||
            (c >= '0' && c <= '9') ||
            c == '_'))
        c = '_';
    }
  }
}

void error_handler::
warning (const SAXParseException& e)
{
  handle (e, s_warning);
}

void error_handler::
error (const SAXParseException& e)
{
  failed_ = true;
  handle (e, s_error);
}

void error_handler::
fatalError (const SAXParseException& e)
{
  failed_ = true;
  handle (e, s_fatal);
}

void error_handler::
handle (const SAXParseException& e, severity s)
{
  const XMLCh* xid (e.getPublicId ());

  if (xid == 0)
    xid = e.getSystemId ();

  char* id (XMLString::transcode (xid));
  char* msg (XMLString::transcode (e.getMessage ()));

  cerr << id << ":"
       << e.getLineNumber () << ":" << e.getColumnNumber () << " "
       << (s == s_warning ? "warning: " : "error: ") << msg << endl;

  XMLString::release (&id);
  XMLString::release (&msg);
}