1 /*
2 Copyright (c) 2005, Steve Dekorte
3 All rights reserved. See _License.txt.
4 */
5 
6 #include <stdio.h>
7 #include <stdlib.h>
8 
showUsage(void)9 void showUsage(void)
10 {
11 	printf("usage: io2c ObjectName ParseFunctionName ioFile1 ioFile2 ...\n");
12 	printf("output is sent to standard output\n");
13         printf("ParseFunctionName is either IoState_on_doCString_withLabel_ or IoState_on_doPackedCString_withLabel_\n\n");
14 }
15 
quoteStream(FILE * in,FILE * out)16 void quoteStream(FILE *in, FILE *out)
17 {
18 	fputc('"', out);
19 
20 	for (;;)
21 	{
22 		char c = fgetc(in);
23 
24 		if (feof(in)) break;
25 
26 		if (c == '\\' || c == '"')
27 		{
28 			fputc('\\', out);
29 		}
30 
31 		if (c == '\n')
32 		{
33 			fputs("\\n\"\n  ", out);
34 			fputc('\t', out);
35 			fputc('"', out);
36 		}
37 		else if (c == '\r')
38 		{
39 			fputs("\\r\"\r  ", out);
40 			fputc('\t', out);
41 			fputc('"', out);
42 		}
43 		else
44 		{
45 			fputc(c, out);
46 		}
47 	}
48 
49 	fputs("\";\n\n", out);
50 }
51 
processFile(const char * objectName,const char * fileName,const char * parseFunctionName)52 void processFile(const char *objectName, const char *fileName, const char *parseFunctionName)
53 {
54 	FILE *in  = fopen(fileName, "r");
55 	FILE *out = stdout;
56 
57 	if (!in)
58 	{
59 		printf("unable to open input file %s\n", fileName);
60 		exit(-1);
61 	}
62 
63 	fputs("\ts = ", out);
64 	quoteStream(in, out);
65 	//fprintf(out, "\t%s(self, context, s, \"%s\");\n\n", parseFunctionName, fileName);
66 	//fprintf(out, "\tIoState_rawOn_doCString_withLabel_(self, context, \"writeln(\\\"%s\\\")\", \"%s\");\n\n", fileName, fileName);
67 	fprintf(out, "\tIoState_rawOn_doCString_withLabel_(self, context, s, \"%s\");\n\n", fileName);
68 
69 	fclose(in);
70 }
71 
main(int argc,const char * argv[])72 int main(int argc, const char *argv[])
73 {
74     if (argc < 4)
75     {
76 	    showUsage();
77     }
78     else
79     {
80 	    int i;
81 	    const char *objectName = argv[1];
82 	    FILE *out = stdout;
83 		const char *parseFunctionName = argv[2];
84 
85 	    fputs("#include \"IoState.h\"\n", out);
86 	    fputs("#include \"IoObject.h\"\n\n", out);
87 	    fputs("void Io", out);
88 	    fputs(objectName, out);
89 	    fputs("Init(IoObject *context)\n{\n", out);
90 	    fputs("\tIoState *self = IoObject_state((IoObject *)context);\n", out);
91 	    fputs("\tchar *s;\n\n", out);
92 
93 	    for (i = 3; i < argc; i ++)
94 	    {
95 		    const char *fileName = argv[i];
96 		    processFile(objectName, fileName, parseFunctionName);
97 	    }
98 
99 	    fputs("}\n\n", out);
100     }
101 
102     return 0;
103 }
104