summaryrefslogtreecommitdiffstats
path: root/src/CodeParser/CParser/CParser.ts
blob: d0d0dcb7662b1fc805dca7638d67e95549249e97 (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
import { Position, TextDocumentContentChangeEvent, TextEditor, TextLine, workspace } from "vscode";
import { Config, ConfigType } from "../../Config";
import Generator from "../../DocGen/CGen";
import { IDocGen } from "../../DocGen/DocGen";
import ICodeParser from "../CodeParser";
import { ParseTree } from "./ParseTree";
import { Token, TokenType } from "./Token";

/**
 *
 * Parses C code for methods and signatures
 *
 * @export
 * @class CParser
 * @implements {ICodeParser}
 */
export default class CParser implements ICodeParser {
    protected activeEditor: TextEditor;
    protected activeSelection: Position;

    private keywords: string[];
    private lexerVocabulary;

    constructor() {
        this.keywords = [
            "static",
            "inline",
            "friend",
            "virtual",
            "extern",
            "explicit",
            "const",
            "struct",
            "class",
            "override",
        ];

        this.lexerVocabulary = {
            ArraySubscript: (x: string): string => (x.match("^\\[[^\\[]*?\\]") || [])[0],
            Arrow: (x: string): string => (x.match("^->") || [])[0],
            Assignment: (x: string): string => (x.match("^=") || [])[0],
            Attribute: (x: string): string => (x.match("^\\[\\[[^\\[]*?\\]\\]") || [])[0],
            CloseParenthesis: (x: string): string => (x.match("^\\)") || [])[0],
            Comma: (x: string): string => (x.match("^,") || [])[0],
            CurlyBlock: (x: string): string => {
                if (x.startsWith("{") === false) {
                    return undefined;
                }
                const startEndOffset: number[] = this.GetSubExprStartEnd(x, 0, "{", "}");
                return startEndOffset[1] === 0 ? undefined : x.slice(0, startEndOffset[1]);
            },
            Ellipsis: (x: string): string => (x.match("^\\.\\.\\.") || [])[0],
            OpenParenthesis: (x: string): string => (x.match("^\\(") || [])[0],
            Pointer: (x: string): string => (x.match("^\\*") || [])[0],
            Reference: (x: string): string => (x.match("^&") || [])[0],
            Symbol: (x: string): string => {
                // Handle operator and decltype special cases.
                if (x.startsWith("operator") === true) {
                    const startBrace: number = x.indexOf("(");
                    return startBrace === -1 ? undefined : x.slice(0, startBrace);
                } else if (x.startsWith("decltype") === true) {
                    const startEndOffset: number[] = this.GetSubExprStartEnd(x, 0, "(", ")");
                    return startEndOffset[1] === 0 ? undefined : x.slice(0, startEndOffset[1]);
                }

                const reMatch: string = (x.match("^[a-z|A-Z|:|_|\\d]+") || [])[0];
                if (reMatch === undefined) {
                    return undefined;
                }

                // Check if symbol includes a template for instance Matrix<T, M, N> and include it if so.
                if (x.slice(reMatch.length, x.length).trim().startsWith("<") === false) {
                    return reMatch;
                }

                const offsets: number[] = this.GetSubExprStartEnd(x, reMatch.length, "<", ">");
                return offsets[1] === 0 ? undefined : x.slice(0, offsets[1]);
            },
        };
    }

    /**
     * @inheritdoc
     */
    public Parse(activeEdit: TextEditor, event: TextDocumentContentChangeEvent): IDocGen {
        this.activeEditor = activeEdit;
        this.activeSelection = this.activeEditor.selection.active;

        const activeLine: TextLine = this.activeEditor.document.lineAt(this.activeEditor.selection.active.line);

        let line: string = this.getLogicalLine();

        // Not a method
        if (line.length === 0) {
            return null;
        }

        // template parsing is simpler by using heuristics rather then tokenizing first.
        const template: string = this.GetTemplate(line);
        const templateArgs: string[] = this.GetArgsFromTemplate(template);
        let args: string[] = [];
        let retVals: string[] = [];

        line = line.slice(template.length, line.length + 1).trim();

        try {
            // Tokenize rest of expression;
            const tokens: Token[] = this.Tokenize(line);
            // Create hierarchical tree based on the parenthesis.
            const tree: ParseTree = ParseTree.CreateTree(tokens).Compact();

            const parsedArgs: ParseTree[] = tree.GetArgTrees();
            const parsedReturns: ParseTree = tree.GetReturnTree();

            args = parsedArgs
                .map((a) => this.GetArgNameFromArgTree(a));

            retVals = this.GetArgTypeFromReturnTree(parsedReturns);

        } catch (err) {
            args = [];
            retVals = [];
        }

        const cppGenerator: IDocGen = new Generator(
            this.activeEditor,
            this.activeSelection,
            args,
            templateArgs,
            retVals,
        );
        return cppGenerator;
    }

    /***************************************************************************
                                    Implementation
     ***************************************************************************/
    protected getLogicalLine(): string {
        let logicalLine: string = "";

        let nextLine: Position = new Position(this.activeSelection.line + 1, this.activeSelection.character);

        let nextLineTxt: string = this.activeEditor.document.lineAt(nextLine.line).text.trim();

        // VSCode may enter a * on itself, we don"t want that in our method
        if (nextLineTxt === "*") {
            nextLineTxt = "";
        }

        while (nextLineTxt.length === 0) { // Get first method line
            nextLine = new Position(nextLine.line + 1, nextLine.character);
            nextLineTxt = this.activeEditor.document.lineAt(nextLine.line).text.trim();
        }

        logicalLine += nextLineTxt;

        // Get method end line
        while (nextLineTxt.indexOf(";") === -1 && nextLineTxt.indexOf("{") === -1) { // Check for method end
            nextLine = new Position(nextLine.line + 1, nextLine.character);
            nextLineTxt = this.activeEditor.document.lineAt(nextLine.line).text.trim();

            logicalLine += " " + nextLineTxt;
        }

        logicalLine = logicalLine.replace(/[{|;]$/, "").trim();

        return logicalLine;
    }

    private Tokenize(expression: string): Token[] {
        const tokens: Token[] = [];
        expression = expression.trim();

        while (expression.length !== 0) {
            const matches: Token[] = Object.keys(this.lexerVocabulary)
                .map((k): Token => new Token(TokenType[k], this.lexerVocabulary[k](expression)))
                .filter((t) => t.Value !== undefined);

            if (matches.length === 0) {
                throw new Error("Next token couldn\'t be determined: " + expression);
            } else if (matches.length > 1) {
                throw new Error("Multiple matches for next token: " + expression);
            }

            const match = matches[0];
            tokens.push(match);
            expression = expression.slice(match.Value.length, expression.length).trim();
        }

        return tokens;
    }

    private GetArgNameFromArgTree(tree: ParseTree): string {
        const hasEllipsis: boolean = tree.nodes
            .filter((n) => n instanceof Token && n.Type === TokenType.Ellipsis)
            .length > 0;

        const indexTrailingReturn: number = tree.nodes
            .findIndex((t) => t instanceof Token ? t.Type === TokenType.Arrow : false);

        const isFuncPtr: boolean = tree.nodes
            .slice(0, indexTrailingReturn === -1 ? tree.nodes.length : indexTrailingReturn)
            .filter((n) => n instanceof ParseTree)
            .length === 2;

        // If it is a function pointer the name is in the first tree.
        if (isFuncPtr === true) {
            const nestedTokens: Token[] = tree.nodes
                .filter((n) => n instanceof ParseTree)
                .map((n) => n as ParseTree)[0]
                .nodes
                .filter((n) => n instanceof Token)
                .map((n) => n as Token)
                .filter((t) => t.Type === TokenType.Symbol)
                .filter((t) => this.keywords.find((k) => k === t.Value) === undefined);

            return nestedTokens[0].Value;
        }

        const tokens: Token[] = tree.nodes
            .filter((n) => n instanceof Token)
            .map((n) => n as Token)
            .filter((t) => t.Type === TokenType.Symbol)
            .filter((t) => this.keywords.find((k) => k === t.Value) === undefined);

        if (tokens.length === 0 && hasEllipsis === true) {
            return "...";
        }

        if (tokens.length < 2) {
            return "";
        }

        return tokens[1].Value;
    }

    private GetArgTypeFromReturnTree(tree: ParseTree): string[] {
        // First strip out the param name or function name since it's not part of the type.
        const indexTrailingReturn: number = tree.nodes
            .findIndex((t) => t instanceof Token ? t.Type === TokenType.Arrow : false);

        const isFuncPtr: boolean = tree.nodes
            .slice(0, indexTrailingReturn === -1 ? tree.nodes.length : indexTrailingReturn)
            .filter((n) => n instanceof ParseTree)
            .length === 2;

        let treeToModify: ParseTree = tree;
        let symbolsFound = 0;
        // If it is a function pointer the name is in the first tree.
        if (isFuncPtr === true) {
            treeToModify = tree.nodes
                .filter((n) => n instanceof ParseTree)
                .map((n) => n as ParseTree)[0];

            // Function pointer so delete the first symbol in the tree
            // Fake that one symbol was found.
            symbolsFound = 1;
        } else {
            // Check for special case if return type is boolean or void.
            for (const token of treeToModify.nodes) {
                if (token instanceof ParseTree) {
                    break;
                }
                if (token.Type !== TokenType.Symbol) {
                    continue;
                }

                if (token.Value === "bool") {
                    return ["true", "false"];
                } else if (token.Value === "void") {
                    return [];
                }
            }
        }

        for (let i = 0; i < treeToModify.nodes.length; i++) {
            const node = treeToModify.nodes[i];
            if (node instanceof ParseTree) {
                break;
            }

            if (node instanceof Token
                && node.Type === TokenType.Symbol
                && this.keywords.find((k) => k === node.Value) === undefined
            ) {
                symbolsFound++;
            }

            if (symbolsFound === 2) {
                treeToModify.nodes.splice(i, 1);
                break;
            }
        }

        return [tree.ToString()];
    }

    private GetSubExprStartEnd(expression: string, startSearch: number, openExpr: string, closeExpr: string): number[] {
        let openExprOffset: number = -1;
        let nestedCount: number = 0;
        for (let i: number = startSearch; i < expression.length; i++) {
            if (expression[i] === openExpr && openExprOffset === -1) {
                openExprOffset = i;
            }

            if (expression[i] === openExpr) {
                nestedCount++;
            } else if (expression[i] === closeExpr && nestedCount > 0) {
                nestedCount--;
            }

            if (expression[i] === closeExpr && nestedCount === 0 && openExprOffset !== -1) {
                return [openExprOffset, i + 1];
            }
        }

        return [0, 0];
    }

    private GetTemplate(expression: string): string {
        if (expression.startsWith("template") === false) {
            return "";
        }

        let startTemplateOffset: number = -1;
        for (let i: number = "template".length; i < expression.length; i++) {
            if (expression[i] === "<") {
                startTemplateOffset = i;
                break;
            } else if (expression[i] !== " ") {
                return "";
            }
        }

        if (startTemplateOffset === -1) {
            return "";
        }

        const [start, end] = this.GetSubExprStartEnd(expression, startTemplateOffset, "<", ">");
        return expression.slice(0, end);
    }

    private GetArgsFromTemplate(template: string): string[] {
        const args: string[] = [];
        if (template === "") {
            return args;
        }

        // Remove <> and add a comma to the end to remove edge case.
        template = template.slice(template.indexOf("<") + 1, template.lastIndexOf(">")).trim() + ",";

        const nestedCounts: { [key: string]: number; } = {
            "(": 0,
            "<": 0,
            "{": 0,
        };

        let lastSeparator: number = 0;
        for (let i: number = 0; i < template.length; i++) {
            const notInSubExpr: boolean = nestedCounts["<"] === 0
                && nestedCounts["("] === 0
                && nestedCounts["{"] === 0;

            if (notInSubExpr === true && template[i] === ",") {
                args.push(template.slice(lastSeparator + 1, i).trim());
            } else if (notInSubExpr === true && (template[i] === " " || template[i] === ".")) {
                lastSeparator = i;
            }

            if (template[i] === "(") {
                nestedCounts["("]++;
            } else if (template[i] === ")" && nestedCounts["("] > 0) {
                nestedCounts["("]--;
            } else if (template[i] === "<") {
                nestedCounts["<"]++;
            } else if (template[i] === ">" && nestedCounts["<"] > 0) {
                nestedCounts["<"]--;
            } else if (template[i] === "{") {
                nestedCounts["{"]++;
            } else if (template[i] === "}" && nestedCounts["{"] > 0) {
                nestedCounts["{"]--;
            }
        }

        return args;
    }
}