summaryrefslogtreecommitdiffstats
path: root/tags/cpp-1.0-incubating-M2-RC2/sca/tools/scagen/src/org/apache/tuscany/sca/cpp/tools/common/InputCppSourceCode.java
blob: 235d0a13d8d850d590ab55351c9977b21ceba03e (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
/**
 *
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 */

/* @version $Rev$ $Date$ */

/*
 * Branched from the original class that was also contributed to the
 * org.apache.axis.tools.common package.
 */
package org.apache.tuscany.sca.cpp.tools.common;

import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;

public class InputCppSourceCode {

    private ArrayList parts = new ArrayList();

    private String name;

    public InputCppSourceCode(BufferedReader br, String name) throws Exception {
        this.name = name;

        String s = null;
        StringBuffer buff = new StringBuffer();
        for (int i = 1;; i++) {
            try {
                s = br.readLine();
            } catch (Exception e) {
                System.err.println("Ignoring exception thrown parsing file "
                        + name + " line number " + i);
                e.printStackTrace();
                break;
            }
            if (s == null)
                break;
            buff.append(s + "\n");
        }
        String str = buff.toString();

        // TODO: When checking for rest.startsWith("struct") should
        // check the next letter after struct is not alphanumeric otherwise
        // we'll get false matches on a function called structify() for
        // instance. Also applies to enum, union, public, typedef, etc

        String rest, text = "";
        int scopedepth = 0;
        String scope = "public";
        String currentClass = null;
        String currentNamespace = null;
        for (int idx = 0; idx < str.length(); /* No idx++ */
        ) {
            rest = str.substring(idx);
            if (Character.isWhitespace(rest.charAt(0))) {
                int ridx = 0;
                while (ridx < rest.length()
                        && Character.isWhitespace(rest.charAt(ridx)))
                    ridx++;
                text = rest.substring(0, ridx);
                FilePart fp = new FilePart(text, FilePart.WHITESPACE);
                parts.add(fp);
                idx += ridx;

            } else if (rest.startsWith("/*")) {
                int ridx = rest.indexOf("*/"); // Don't use Utils here
                text = str.substring(idx, idx + ridx + 2);
                FilePart fp = new FilePart(text, FilePart.COMMENT);
                parts.add(fp);
                idx += text.length();

            } else if (rest.startsWith("//")) {
                text = str.substring(idx, idx + rest.indexOf("\n"));
                FilePart fp = new FilePart(text, FilePart.COMMENT);
                parts.add(fp);
                idx += text.length();

            } else if (rest.startsWith("#")) {
                int ridx = rest.indexOf("\n");
                char c = rest.charAt(ridx - 1);
                while (-1 != ridx && '\\' == c) {
                    String rest2 = rest.substring(ridx + 1);
                    ridx += rest2.indexOf("\n") + 1;
                    c = rest.charAt(ridx - 1);
                }
                text = str.substring(idx, idx + ridx);
                FilePart fp = new FilePart(text, FilePart.DIRECTIVE);
                parts.add(fp);
                idx += text.length();

            } else if (rest.startsWith("}")) {
                if (scopedepth <= 0) //Tuscany need to increase scopedepth for
                    // namespaces?
                    Utils.rude("Braces do not match", name, lineNo(str, idx),
                            rest.substring(0, rest.indexOf("\n")));
                else
                    scopedepth--;
                // TODO: better checking that this brace really ends the class
                if (0 == scopedepth)
                    currentClass = null;
                scope = "public";
                parts.add(new FilePart("}", FilePart.ENDSCOPE));
                idx++;

            } else if (rest.startsWith(";")) {
                parts.add(new FilePart(";", FilePart.FIELD));
                idx++;

            } else if (!Character.isLetter(rest.charAt(0))
                    && '~' != rest.charAt(0) && '_' != rest.charAt(0)) {
                Utils.rude("Lines must start with a letter ", name, lineNo(str,
                        idx), rest.substring(0, rest.indexOf("\n")));

            } else if (MacroPart.isAMacro(rest)) {
                MacroPart mp = MacroPart.create(rest);
                parts.add(mp);
                idx += mp.length();

            } else if (beginsScope(rest)) {

                //Tuscany a namespace comes in here
                scopedepth++;
                text = rest.substring(0, Utils.indexOf(rest, "{") + 1);
                FilePart fp = new FilePart(text, FilePart.BEGINSCOPE);
                parts.add(fp);
                idx += text.length();
                if (Utils.startsWith(text, "class")) {
                    // TODO: cope with comments here
                    // TODO: split out classes into a ClassPart
                    StringTokenizer st = new StringTokenizer(text,
                            Utils.whitespace + ":");
                    st.nextToken(); // step over "class"
                    while (st.hasMoreTokens()) {
                        String word = st.nextToken();
                        if (Configuration.isAttribute(word))
                            continue;
                        currentClass = word;
                        break;
                    }
                }

                //Tuscany
                if (Utils.startsWith(text, "namespace")) {
                    // TODO: cope with comments here
                    StringTokenizer st = new StringTokenizer(text,
                            Utils.whitespace + "{");
                    st.nextToken(); // step over "namespace"
                    String word = "";
                    while (st.hasMoreTokens()) {
                        word = st.nextToken();
                        if (word.equals("{")) {
                            break;
                        }

                    }
                    
                    if(currentNamespace == null)
                    {
                        currentNamespace = word;
                    }
                    else
                    {
                        currentNamespace += "::" + word;
                    }
                    //We have not got to the class yet
                    //so will need ot deal with the namespace
                    //when we do
                }
                // Tuscany end

            } else if (isEnumOrUnion(rest)) {
                int ridx = Utils.findMatching(rest, '{', '}') + 1;
                String rest2 = rest.substring(ridx);
                ridx = idx + ridx + Utils.indexOf(rest2, ';') + 1;
                text = str.substring(idx, ridx);
                FilePart fp = new FilePart(text, FilePart.ENUM);
                parts.add(fp);
                idx += text.length();

            } else if (scopedepth > 0
                    && (rest.startsWith("public")
                            || rest.startsWith("protected") || rest
                            .startsWith("private"))) {
                int colon = rest.indexOf(":");
                if (-1 == colon)
                    Utils.rude("No colon found after public or private ", name,
                            lineNo(str, idx), rest.substring(0, rest
                                    .indexOf("\n")));
                scope = str.substring(idx, idx + colon);
                text = str.substring(idx, idx + colon + 1);
                FilePart fp = new FilePart(text, FilePart.CLASSATTRIBUTE);
                parts.add(fp);
                idx += text.length();

            } else if (Utils.startsWith(rest, "typedef")) {
                int semicolon = Utils.indexOf(rest, ';');
                int brace = Utils.indexOf(rest, '{');

                if (-1 == semicolon)
                    Utils.rude("No semicolon found after typedef", name,
                            lineNo(str, idx), rest.substring(0, rest
                                    .indexOf("\n")));

                if (-1 == brace || semicolon < brace) {
                    // Simple typedef
                    text = str.substring(idx, idx + semicolon + 1);
                } else {
                    // Typedef of a struct, etc
                    int endbrace = Utils.findMatching(rest, '{', '}');
                    String rest2 = rest.substring(endbrace);
                    semicolon = Utils.indexOf(rest2, ';');
                    text = str.substring(idx, idx + endbrace + semicolon + 1);
                }
                FilePart fp = new FilePart(text, FilePart.TYPEDEF);
                parts.add(fp);
                idx += text.length();

            } else {
                if (isMethod(rest)) {

                    int brace = Utils.indexOf(rest, '{');
                    Signature signature = new Signature(str.substring(idx, idx
                            + brace));
                    if (signature.failed())
                        Utils.rude("Signature parsing failed", name, lineNo(
                                str, idx), signature.getOriginal());
                    if (null != currentClass
                            && null == signature.getClassName())
                        signature.setClassName(currentClass);
                    signature.setScope(scope);
                    signature.setNamespace(currentNamespace);

                    String body = rest.substring(brace);
                    int endBrace = Utils.findMatching(body, '{', '}');
                    body = body.substring(0, endBrace + 1);
                    int endIdx = idx + signature.originalLength()
                            + body.length();
                    text = str.substring(idx, endIdx);
                    MethodPart mp = new MethodPart(text, signature, body);
                    parts.add(mp);
                    idx += text.length();

                } else if (isField(rest)) {
                    int semicolon = Utils.indexOf(rest, ';');
                    text = str.substring(idx, idx + semicolon + 1);
                    FilePart fp = new FilePart(text, FilePart.FIELD);
                    parts.add(fp);
                    idx += text.length();

                } else if (isPrototype(rest)) {
                    int semicolon = Utils.indexOf(rest, ';');
                    text = str.substring(idx, idx + semicolon + 1);
                    PrototypePart pp = new PrototypePart(text, currentClass, currentNamespace);
                    pp.setScope(scope);
                    parts.add(pp);
                    idx += text.length();

                } else {
                    //TODO other file parts here - not sure if there are any
                    // others?
                    Utils.rude("Unrecognised file part", name,
                            lineNo(str, idx), rest.substring(0, rest
                                    .indexOf("\n")));
                } // end if
            } // end if
        } // end for
    }

    public Iterator getPartIterator() {
        return parts.iterator();
    }

    private int lineNo(String s, int idx) {
        int n = 0;
        for (int i = 0; i < idx && i < s.length(); i++)
            if ('\n' == s.charAt(i))
                n++;
        return n;
    }

    /**
     * Find out whether we are defining a class, struct or extern "C" which may
     * contain function implementations. These will have braces which begin a
     * new scope. Ignore function prototypes that return a struct. struct mystr {
     * int f1; }; struct mystr func(); struct mystr func() { struct mystr a;
     * return a; }
     */
    private static boolean beginsScope(String s) throws ParsingException {
        if (isMethod(s))
            return false;

        int brace = Utils.indexOf(s, '{');
        int semicolon = Utils.indexOf(s, ';');

        // Return false for class prototypes, but true for class definitions.
        if (Utils.startsWith(s, "class")) {
            if (-1 == brace)
                return false;
            if (-1 == semicolon)
                return true;
            return brace < semicolon;
        }

        if (Utils.startsWith(s, "struct")) {
            if (-1 == brace || -1 == semicolon)
                return false;
            return brace < semicolon;
        }

        //Tuscany handle namespace for prototypes
        //in a similar way to "class"
        if (Utils.startsWith(s, "namespace")) {
            if (-1 == brace || -1 == semicolon)
                return false;
            return brace < semicolon;
        }

        return startsWithExternScope(s);
    }

    /**
     * There are 4 types of extern ... extern int field; extern int func();
     * extern "C" int func() { return 2; } extern "C" { int func() { return 2; } }
     * This method should return true only for the last of these three examples
     * since only the last one creates a new scope using braces.
     */
    private static boolean startsWithExternScope(String s)
            throws ParsingException {
        if (!s.startsWith("extern"))
            return false;

        int brace = Utils.indexOf(s, '{');
        int semicolon = Utils.indexOf(s, ';');
        int bracket = Utils.indexOf(s, '(');

        if (-1 == brace)
            return false;
        return (-1 == semicolon || brace < semicolon)
                && (-1 == bracket || brace < bracket);
    }

    /**
     * Find out whether we are defining an enum or union which will contain
     * braces. Ignore function prototypes that return an enum or union. enum
     * colour { red, blue }; enum colour func(); enum colour func() { return
     * colour.red; }
     */
    private static boolean isEnumOrUnion(String s) throws ParsingException {
        if ((!Utils.startsWith(s, "enum") && !Utils.startsWith(s, "union"))
                || isMethod(s))
            return false;

        int brace = Utils.indexOf(s, '{');
        int semicolon = Utils.indexOf(s, ';');
        return -1 != brace && (-1 == semicolon || brace < semicolon);
    }

    /**
     * Rules to recognise fields and methods...
     * 
     * Fields must contain a semicolon Methods may or may not contain a
     * semicolon Prototypes must contain a semicolon Fields may or may not
     * contain a brace (array initialisers do) Methods must contain a brace
     * Prototypes must not contain a brace Fields may or may not contain a
     * bracket (casts do) Methods must contain a bracket Prototypes must contain
     * a bracket
     * 
     * It's a method if it contains a bracket and then a brace before the first
     * semicolon (if there is a semicolon). It's a prototype if it's not a
     * method and it contains brackets before a semicolon. It's a field if it's
     * not a method or a prototype and it contains a semicolon. If it's not a
     * field, a method or a prototype and we haven't recognised it previously
     * then it's an error.
     */
    private static boolean isMethod(String s) throws ParsingException {
        int semicolon = Utils.indexOf(s, ';');
        int brace = Utils.indexOf(s, '{');
        int bracket = Utils.indexOf(s, '(');

        return (-1 != bracket && -1 != brace && bracket < brace && (-1 == semicolon || brace < semicolon));
    }

    private static boolean isPrototype(String s) throws ParsingException {
        int semicolon = Utils.indexOf(s, ';');
        int bracket = Utils.indexOf(s, '(');
        return !isMethod(s) && -1 != semicolon && -1 != bracket
                && bracket < semicolon;
    }

    private static boolean isField(String s) throws ParsingException {
        int semicolon = Utils.indexOf(s, ';');
        return !isMethod(s) && !isPrototype(s) && -1 != semicolon;
    }

    public String getName() {
        return name;
    }

    public String toString() {
        StringBuffer text = new StringBuffer();
        for (int i = 0; i < parts.size(); i++) {
            text.append(((FilePart) (parts.get(i))).toString());
        }
        return text.toString();
    }

}