summaryrefslogtreecommitdiff
path: root/cpp/src/slice2freeze/Main.cpp
blob: b719c23e637d404cef0cabd285b080e0fd3d49a7 (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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
// **********************************************************************
//
// Copyright (c) 2003
// ZeroC, Inc.
// Billerica, MA, USA
//
// All Rights Reserved.
//
// Ice is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License version 2 as published by
// the Free Software Foundation.
//
// **********************************************************************

#include <Slice/Preprocessor.h>
#include <Slice/CPlusPlusUtil.h>
#include <IceUtil/OutputUtil.h>

using namespace std;
using namespace IceUtil;
using namespace Slice;

struct Dict
{
    string name;
    string key;
    string value;
};

void
usage(const char* n)
{
    cerr << "Usage: " << n << " [options] file-base [slice-files...]\n";
    cerr <<
	"Options:\n"
	"-h, --help            Show this message.\n"
	"-v, --version         Display the Ice version.\n"
	"-DNAME                Define NAME as 1.\n"
	"-DNAME=DEF            Define NAME as DEF.\n"
	"-UNAME                Remove any definition for NAME.\n"
	"-IDIR                 Put DIR in the include file search path.\n"
	"--include-dir DIR     Use DIR as the header include directory.\n"
	"--dll-export SYMBOL   Use SYMBOL for DLL exports.\n"
	"--dict NAME,KEY,VALUE Create a Freeze dictionary with the name NAME,\n"
	"                      using KEY as key, and VALUE as value. This\n"
	"                      option may be specified multiple times for\n"
	"                      different names. NAME may be a scoped name.\n"
	"--binary              Use the binary encoding.\n"
	"--output-dir DIR      Create files in the directory DIR.\n"
	"-d, --debug           Print debug messages.\n"
        "--ice                 Permit `Ice' prefix (for building Ice source code only)\n"
	;
    // Note: --case-sensitive is intentionally not shown here!
}

bool
checkIdentifier(string n, string t, string s)
{
    if(s.empty() || (!isalpha(s[0]) && s[0] != '_'))
    {
	cerr << n << ": `" << t << "' is not a valid type name" << endl;
	return false;
    }
    
    for(unsigned int i = 1; i < s.size(); ++i)
    {
	if(!isalnum(s[i]) && s[i] != '_')
	{
	    cerr << n << ": `" << t << "' is not a valid type name" << endl;
	    return false;
	}
    }

    return true;
}

void
printFreezeTypes(Output& out, const vector<Dict>& dicts)
{
    out << '\n';
    out << "\n// Freeze types in this file:";
    for(vector<Dict>::const_iterator p = dicts.begin(); p != dicts.end(); ++p)
    {
	out << "\n// name=\"" << p->name << "\", key=\"" << p->key << "\", value=\"" << p->value << "\"";
    }
    out << '\n';
}

void
writeCodecH(const TypePtr& type, const string& name, const string& freezeType, Output& H, const string& dllExport)
{
    H << sp << nl << dllExport << "class " << name;
    H << sb;
    H.dec();
    H << sp << nl << "public:";
    H << sp;
    H.inc();
    H << nl << "static void write(" << inputTypeToString(type)
      << ", Freeze::" << freezeType << "& bytes, const ::Ice::CommunicatorPtr& communicator);";
    H << nl << "static void read(" << typeToString(type) << "&, const Freeze::" << freezeType << "& bytes, "
      << "const ::Ice::CommunicatorPtr& communicator);";
    H << eb << ';';
}

void
writeCodecC(const TypePtr& type, const string& name, const string& freezeType, Output& C, bool binary)
{
    string quotedFreezeType = "\"" + freezeType + "\"";

    C << sp << nl << "void" << nl << name << "::write(" << inputTypeToString(type) << " v, "
      << "Freeze::" << freezeType << "& bytes, const ::Ice::CommunicatorPtr& communicator)";
    C << sb;
    if(binary)
    {
        C << nl << "IceInternal::InstancePtr instance = IceInternal::getInstance(communicator);";
        C << nl << "IceInternal::BasicStream stream(instance.get());";
        writeMarshalUnmarshalCode(C, type, "v", true, "stream", false);
        C << nl << "bytes = stream.b;";
    }
    else
    {
        C << nl << "std::ostringstream ostr;";
        C << nl << "Ice::StreamPtr stream = new IceXML::StreamI(communicator, ostr);";
        writeGenericMarshalUnmarshalCode(C, type, "v", true, quotedFreezeType, "stream", true);
        C << nl << "const std::string& str = ostr.str();";
        C << nl << "bytes.resize(str.size());";
        C << nl << "std::copy(str.begin(), str.end(), bytes.begin());";
    }
    C << eb;


    C << sp << nl << "void" << nl << name << "::read(" << typeToString(type) << "& v, "
      << "const Freeze::" << freezeType << "& bytes, const ::Ice::CommunicatorPtr& communicator)";
    C << sb;
    if(binary)
    {
        C << nl << "IceInternal::InstancePtr instance = IceInternal::getInstance(communicator);";
        C << nl << "IceInternal::BasicStream stream(instance.get());";
        C << nl << "stream.b = bytes;";
        C << nl << "stream.i = stream.b.begin();";
        writeMarshalUnmarshalCode(C, type, "v", false, "stream", false);
    }
    else
    {
        //
        // COMPILERFIX: string data(bytes.begin(), bytes.end());
        //
        // This won't link with STLport 4.5.3 stldebug version.
        //
        C << nl << "std::string str;";
        C << nl << "str.append(\"<data>\");";
        C << nl << "str.append(&bytes[0], bytes.size());";
        C << nl << "str.append(\"</data>\");";
        C << nl << "std::istringstream istr(str);";
        C << nl << "Ice::StreamPtr stream = new IceXML::StreamI(communicator, istr, false);";
        writeGenericMarshalUnmarshalCode(C, type, "v", false, quotedFreezeType, "stream", true);
    }
    C << eb;
}

bool
writeCodecs(const string& n, UnitPtr& unit, const Dict& dict, Output& H, Output& C, const string& dllExport,
            bool binary)
{
    string absolute = dict.name;
    if(absolute.find("::") == 0)
    {
	absolute.erase(0, 2);
    }
    string name = absolute;
    vector<string> scope;
    string::size_type pos;
    while((pos = name.find("::")) != string::npos)
    {
	string s = name.substr(0, pos);
	name.erase(0, pos + 2);
	
	if(!checkIdentifier(n, absolute, s))
	{
	    return false;
	}
	
	scope.push_back(s);
    }
    
    if(!checkIdentifier(n, absolute, name))
    {
	return false;
    }

    TypeList keyTypes = unit->lookupType(dict.key, false);
    if(keyTypes.empty())
    {
	cerr << n << ": `" << dict.key << "' is not a valid type" << endl;
	return false;
    }
    TypePtr keyType = keyTypes.front();
    
    TypeList valueTypes = unit->lookupType(dict.value, false);
    if(valueTypes.empty())
    {
	cerr << n << ": `" << dict.value << "' is not a valid type" << endl;
	return false;
    }
    TypePtr valueType = valueTypes.front();
    
    vector<string>::const_iterator q;
    
    for(q = scope.begin(); q != scope.end(); ++q)
    {
	H << sp;
	H << nl << "namespace " << *q << nl << '{';
    }

    writeCodecH(keyType, name + "KeyCodec", "Key", H, dllExport);
    writeCodecH(valueType, name + "ValueCodec", "Value", H, dllExport);

    H << sp << nl << "typedef Freeze::DBMap< " << typeToString(keyType) << ", " << typeToString(valueType) << ", "
      << name << "KeyCodec, " << name << "ValueCodec> " << name << ";";

    for(q = scope.begin(); q != scope.end(); ++q)
    {
	H << sp;
	H << nl << '}';
    }

    writeCodecC(keyType, absolute + "KeyCodec", "Key", C, binary);
    writeCodecC(valueType, absolute + "ValueCodec", "Value", C, binary);

    return true;
}

int
main(int argc, char* argv[])
{
    string cppArgs;
    vector<string> includePaths;
    string include;
    string dllExport;
    bool binary = false;
    string output;
    bool debug = false;
    bool ice = false;
    bool caseSensitive = false;
    vector<Dict> dicts;

    int idx = 1;
    while(idx < argc)
    {
	if(strncmp(argv[idx], "-I", 2) == 0)
	{
	    cppArgs += ' ';
	    cppArgs += argv[idx];

	    string path = argv[idx] + 2;
	    if(path.length())
	    {
		includePaths.push_back(path);
	    }

	    for(int i = idx ; i + 1 < argc ; ++i)
	    {
		argv[i] = argv[i + 1];
	    }
	    --argc;
	}
	else if(strncmp(argv[idx], "-D", 2) == 0 || strncmp(argv[idx], "-U", 2) == 0)
	{
	    cppArgs += ' ';
	    cppArgs += argv[idx];

	    for(int i = idx ; i + 1 < argc ; ++i)
	    {
		argv[i] = argv[i + 1];
	    }
	    --argc;
	}
	else if(strcmp(argv[idx], "--dict") == 0)
	{
	    if(idx + 1 >= argc || argv[idx + 1][0] == '-')
            {
		cerr << argv[0] << ": argument expected for`" << argv[idx] << "'" << endl;
		usage(argv[0]);
		return EXIT_FAILURE;
            }

	    string s = argv[idx + 1];
	    s.erase(remove_if(s.begin(), s.end(), ::isspace), s.end());
	    
	    Dict dict;

	    string::size_type pos;
	    pos = s.find(',');
	    if(pos != string::npos)
	    {
		dict.name = s.substr(0, pos);
		s.erase(0, pos + 1);
	    }
	    pos = s.find(',');
	    if(pos != string::npos)
	    {
		dict.key = s.substr(0, pos);
		s.erase(0, pos + 1);
	    }
	    dict.value = s;

	    if(dict.name.empty())
	    {
		cerr << argv[0] << ": " << argv[idx] << ": no name specified" << endl;
		usage(argv[0]);
		return EXIT_FAILURE;
	    }

	    if(dict.key.empty())
	    {
		cerr << argv[0] << ": " << argv[idx] << ": no key specified" << endl;
		usage(argv[0]);
		return EXIT_FAILURE;
	    }

	    if(dict.value.empty())
	    {
		cerr << argv[0] << ": " << argv[idx] << ": no value specified" << endl;
		usage(argv[0]);
		return EXIT_FAILURE;
	    }

	    dicts.push_back(dict);

	    for(int i = idx ; i + 2 < argc ; ++i)
	    {
		argv[i] = argv[i + 2];
	    }
	    argc -= 2;
	}
	else if(strcmp(argv[idx], "-h") == 0 || strcmp(argv[idx], "--help") == 0)
	{
	    usage(argv[0]);
	    return EXIT_SUCCESS;
	}
	else if(strcmp(argv[idx], "-v") == 0 || strcmp(argv[idx], "--version") == 0)
	{
	    cout << ICE_STRING_VERSION << endl;
	    return EXIT_SUCCESS;
	}
	else if(strcmp(argv[idx], "-d") == 0 || strcmp(argv[idx], "--debug") == 0)
	{
	    debug = true;
	    for(int i = idx ; i + 1 < argc ; ++i)
	    {
		argv[i] = argv[i + 1];
	    }
	    --argc;
	}
	else if(strcmp(argv[idx], "--ice") == 0)
	{
	    ice = true;
	    for(int i = idx ; i + 1 < argc ; ++i)
	    {
		argv[i] = argv[i + 1];
	    }
	    --argc;
	}
	else if(strcmp(argv[idx], "--case-sensitive") == 0)
	{
	    caseSensitive = true;
	    for(int i = idx ; i + 1 < argc ; ++i)
	    {
		argv[i] = argv[i + 1];
	    }
	    --argc;
	}
	else if(strcmp(argv[idx], "--include-dir") == 0)
	{
	    if(idx + 1 >= argc)
            {
		cerr << argv[0] << ": argument expected for`" << argv[idx] << "'" << endl;
		usage(argv[0]);
		return EXIT_FAILURE;
            }
	    
	    include = argv[idx + 1];
	    for(int i = idx ; i + 2 < argc ; ++i)
	    {
		argv[i] = argv[i + 2];
	    }
	    argc -= 2;
	}
	else if(strcmp(argv[idx], "--dll-export") == 0)
	{
	    if(idx + 1 >= argc)
            {
		cerr << argv[0] << ": argument expected for`" << argv[idx] << "'" << endl;
		usage(argv[0]);
		return EXIT_FAILURE;
            }
	    
	    dllExport = argv[idx + 1];
	    for(int i = idx ; i + 2 < argc ; ++i)
	    {
		argv[i] = argv[i + 2];
	    }
	    argc -= 2;
	}
	else if(strcmp(argv[idx], "--binary") == 0)
	{
	    binary = true;
	    for(int i = idx ; i + 1 < argc ; ++i)
	    {
		argv[i] = argv[i + 1];
	    }
	    --argc;
	}
	else if(strcmp(argv[idx], "--output-dir") == 0)
	{
	    if(idx + 1 >= argc)
	    {
		cerr << argv[0] << ": argument expected for`" << argv[idx] << "'" << endl;
		usage(argv[0]);
		return EXIT_FAILURE;
	    }
	    
	    output = argv[idx + 1];
	    for(int i = idx ; i + 2 < argc ; ++i)
	    {
		argv[i] = argv[i + 2];
	    }
	    argc -= 2;
	}
	else if(argv[idx][0] == '-')
	{
	    cerr << argv[0] << ": unknown option `" << argv[idx] << "'" << endl;
	    usage(argv[0]);
	    return EXIT_FAILURE;
	}
	else
	{
	    ++idx;
	}
    }

    if(dicts.empty())
    {
	cerr << argv[0] << ": no Freeze types specified" << endl;
	usage(argv[0]);
	return EXIT_FAILURE;
    }

    if(argc < 2)
    {
	cerr << argv[0] << ": no file name base specified" << endl;
	usage(argv[0]);
	return EXIT_FAILURE;
    }

    string fileH = argv[1];
    fileH += ".h";
    string fileC = argv[1];
    fileC += ".cpp";
    if(!output.empty())
    {
	fileH = output + '/' + fileH;
	fileC = output + '/' + fileC;
    }

    UnitPtr unit = Unit::createUnit(true, false, ice, caseSensitive);

    StringList includes;

    int status = EXIT_SUCCESS;

    for(idx = 2 ; idx < argc ; ++idx)
    {
	Preprocessor icecpp(argv[0], argv[idx], cppArgs);

	includes.push_back(icecpp.getBaseName() + ".h");

	FILE* cppHandle = icecpp.preprocess(false);

	if(cppHandle == 0)
	{
	    unit->destroy();
	    return EXIT_FAILURE;
	}
	
	status = unit->parse(cppHandle, debug);

	if(!icecpp.close())
	{
	    unit->destroy();
	    return EXIT_FAILURE;	    
	}
    }

    if(status == EXIT_SUCCESS)
    {
	unit->mergeModules();
	unit->sort();

	{
	    for(vector<string>::iterator p = includePaths.begin(); p != includePaths.end(); ++p)
	    {
		if(p->length() && (*p)[p->length() - 1] != '/')
		{
		    *p += '/';
		}
	    }
	}

	Output H;
	H.open(fileH.c_str());
	if(!H)
	{
	    cerr << argv[0] << ": can't open `" << fileH << "' for writing: " << strerror(errno) << endl;
	    unit->destroy();
	    return EXIT_FAILURE;
	}
	printHeader(H);
	printFreezeTypes(H, dicts);

	Output C;
	C.open(fileC.c_str());
	if(!C)
	{
	    cerr << argv[0] << ": can't open `" << fileC << "' for writing: " << strerror(errno) << endl;
	    unit->destroy();
	    return EXIT_FAILURE;
	}
	printHeader(C);
	printFreezeTypes(C, dicts);
	
	string s = fileH;
	transform(s.begin(), s.end(), s.begin(), ToIfdef());
	H << "\n#ifndef __" << s << "__";
	H << "\n#define __" << s << "__";
	H << '\n';
	H << "\n#include <Freeze/Map.h>";
	
	{
	    for(StringList::const_iterator p = includes.begin(); p != includes.end(); ++p)
	    {
		H << "\n#include <" << changeInclude(*p, includePaths) << ".h>";
	    }
	}

        if(binary)
        {
            C << "\n#include <Ice/BasicStream.h>";
        }
        else
        {
            C << "\n#include <IceXML/StreamI.h>";
            C << "\n#include <algorithm>";
        }
	C << "\n#include <";
	if(include.size())
	{
	    C << include << '/';
	}
	C << fileH << '>';

	printVersionCheck(H);
	printVersionCheck(C);

	printDllExportStuff(H, dllExport);
	if(dllExport.size())
	{
	    dllExport += " ";
	}

	{
	    for(vector<Dict>::const_iterator p = dicts.begin(); p != dicts.end(); ++p)
	    {
		try
		{
		    if(!writeCodecs(argv[0], unit, *p, H, C, dllExport, binary))
		    {
			unit->destroy();
			return EXIT_FAILURE;
		    }
		}
		catch(...)
		{
		    cerr << argv[0] << ": unknown exception" << endl;
		    unit->destroy();
		    return EXIT_FAILURE;
		}
	    }
	}

	H << "\n\n#endif\n";
	C << '\n';
    }
    
    unit->destroy();

    return status;
}