Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: b7b5638db8c3872939f04f60931f3afe1178e147 (plain) (blame)
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
/*******************************************************************************
 * Copyright (c) 2008 Phil Muldoon <pkmuldoon@picobot.org>.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Phil Muldoon <pkmuldoon@picobot.org> - initial API and implementation.
 *******************************************************************************/
package org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.Pattern;

import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPartitioningException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentExtension3;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.contentassist.CompletionProposal;
import org.eclipse.jface.text.contentassist.ContextInformation;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jface.text.contentassist.IContextInformationValidator;
import org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp.proposals.STPFunctionCompletionProposal;
import org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp.proposals.STPProbeCompletionProposal;
import org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp.proposals.STPProbevarCompletionProposal;
import org.eclipse.linuxtools.internal.systemtap.ui.ide.structures.ManpageCacher;
import org.eclipse.linuxtools.internal.systemtap.ui.ide.structures.TapsetItemType;
import org.eclipse.linuxtools.systemtap.structures.TreeNode;

public class STPCompletionProcessor implements IContentAssistProcessor, ITextHover {

    private final IContextInformation[] NO_CONTEXTS = new IContextInformation[0];
    private final char[] PROPOSAL_ACTIVATION_CHARS = new char[] { '.' };
    private ICompletionProposal[] NO_COMPLETIONS = new ICompletionProposal[0];

    private static final String GLOBAL_KEYWORD = "global "; //$NON-NLS-1$
    private static final String PROBE_KEYWORD = "probe "; //$NON-NLS-1$
    private static final String FUNCTION_KEYWORD = "function "; //$NON-NLS-1$

    private static final String[][] GLOBAL_KEYWORDS = {
            { GLOBAL_KEYWORD, Messages.STPCompletionProcessor_global },
            { PROBE_KEYWORD, Messages.STPCompletionProcessor_probe },
            { FUNCTION_KEYWORD, Messages.STPCompletionProcessor_function } };

    private STPMetadataSingleton stpMetadataSingleton;

    private static class Token implements IRegion {
        String tokenString;
        int offset;

        public Token(String string, int n) {
            this.tokenString = string;
            this.offset = n;
        }

        @Override
        public int getLength() {
            return this.tokenString.length();
        }

        @Override
        public int getOffset() {
            return this.offset;
        }
    }

    public STPCompletionProcessor() {
        this.stpMetadataSingleton = STPMetadataSingleton.getInstance();
    }

    @Override
    public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
            int offset) {
        return computeCompletionProposals(viewer.getDocument(), offset);
    }

    public ICompletionProposal[] computeCompletionProposals(IDocument document, int offset) {

        ITypedRegion partition = null;
        boolean useGlobal = false;

        try {
            partition =
                    ((IDocumentExtension3) document).getPartition(STPProbeScanner.STP_PROBE_PARTITIONING, offset, false);
            if (partition.getOffset() == offset) {
                if (partition.getType() != IDocument.DEFAULT_CONTENT_TYPE && partition.getType() != STPProbeScanner.STP_PROBE) {
                    if (offset > 0) {
                        ITypedRegion prevPartition =
                                ((IDocumentExtension3) document).getPartition(STPProbeScanner.STP_PROBE_PARTITIONING, offset - 1, false);
                        useGlobal = prevPartition.getType() == IDocument.DEFAULT_CONTENT_TYPE;
                    } else {
                        useGlobal = true;
                    }
                }
            }
        } catch (BadLocationException|BadPartitioningException e) {
            return NO_COMPLETIONS;
        }

        String prefix = ""; //$NON-NLS-1$
        String prePrefix = ""; //$NON-NLS-1$

        // Get completion hint from document
        try {
            prefix = getPrefix(document, offset);
            Token previousToken = getPrecedingToken(document, offset - prefix.length() - 1);

            while (previousToken.tokenString.equals("=") || //$NON-NLS-1$
                    previousToken.tokenString.equals(",") ) { //$NON-NLS-1$
                previousToken = getPrecedingToken(document, previousToken.offset - 1);
                previousToken = getPrecedingToken(document, previousToken.offset - 1);
            }

            prePrefix = previousToken.tokenString;

        } catch (BadLocationException e) {
            return NO_COMPLETIONS;
        }

        if (prePrefix.startsWith("probe")) { //$NON-NLS-1$
            return getProbeCompletionList(prefix, offset);
        }

        // If inside a probe return probe variable completions and functions
        // which can be called.
        if (partition.getType() == STPProbeScanner.STP_PROBE) {
            ICompletionProposal[] variableCompletions = getProbeVariableCompletions(document, offset, prefix);
            ICompletionProposal[] functionCompletions = getFunctionCompletions(offset, prefix);

            ArrayList<ICompletionProposal> completions = new ArrayList<>(
                    variableCompletions.length + functionCompletions.length);
            completions.addAll(Arrays.asList(variableCompletions));
            completions.addAll(Arrays.asList(functionCompletions));

            return completions.toArray(new ICompletionProposal[0]);
        } else if (partition.getType() == IDocument.DEFAULT_CONTENT_TYPE || useGlobal) {
            // In the global scope return global keyword completion.
            return getGlobalKeywordCompletion(prefix, offset);
        }

        return NO_COMPLETIONS;
    }

    private ICompletionProposal[] getFunctionCompletions(int offset,
            String prefix) {
        TreeNode[] completionData = stpMetadataSingleton.getFunctionCompletions(prefix);
        ICompletionProposal[] result = new ICompletionProposal[completionData.length];
        for (int i = 0; i < completionData.length; i++) {
            result[i] = new STPFunctionCompletionProposal(
                    completionData[i],
                    prefix.length(),
                    offset);
        }

        return result;
    }

    private ICompletionProposal[] getProbeVariableCompletions(IDocument document, int offset, String prefix) {
        try {
            String probeName = getProbe(document, offset);
            TreeNode[] completionData = stpMetadataSingleton
                    .getProbeVariableCompletions(probeName, prefix);
            ICompletionProposal[] result = new ICompletionProposal[completionData.length];

            for (int i = 0; i < completionData.length; i++) {
                result[i] = new STPProbevarCompletionProposal(
                        completionData[i],
                        prefix.length(),
                        offset,
                        probeName);
            }
            return result;
        } catch (BadLocationException|BadPartitioningException e) {
            return NO_COMPLETIONS;
        }
    }

    /**
     * Returns the full name of the probe surrounding the given
     * offset. This function assumes that the given offset is inside
     * of a {@link STPPartitionScanner#STP_PROBE} section.
     * @param document
     * @param offset
     * @return the probe name
     * @throws BadLocationException
     * @throws BadPartitioningException
     */
    private String getProbe(IDocument document, int offset) throws BadLocationException, BadPartitioningException {
        String probePoint = null;

        ITypedRegion partition
          = ((IDocumentExtension3)document).getPartition(STPProbeScanner.STP_PROBE_PARTITIONING,
                  offset, false);
        String probe = document.get(partition.getOffset(), partition.getLength());

        // make sure that we are inside a probe
        if (probe.startsWith(PROBE_KEYWORD)) {
            probePoint = probe.substring(PROBE_KEYWORD.length(), probe.indexOf('{'));
            probePoint = probePoint.trim();
        }

        return probePoint;
    }

    private ICompletionProposal[] getProbeCompletionList(String prefix, int offset) {
        prefix = canonicalizePrefix(prefix);
        TreeNode[] completionData = stpMetadataSingleton.getProbeCompletions(prefix);

        ICompletionProposal[] result = new ICompletionProposal[completionData.length];
        for (int i = 0; i < completionData.length; i++) {
            result[i] = new STPProbeCompletionProposal(
                            completionData[i],
                            prefix.length(),
                            offset);
        }
        return result;

    }

    /**
     * Returns a standardized version of the given prefix so that completion matching
     * can be performed.
     * For example for process("/some/long/path") this returns process(string);
     * @param prefix
     * @return
     */
    private String canonicalizePrefix(String prefix) {

        if (prefix.isEmpty()) {
            return ""; //$NON-NLS-1$
        }
        prefix = prefix.replaceAll("(?s)\\(\\s*\".*\"\\s*\\)", "(string)"); //$NON-NLS-1$ //$NON-NLS-2$
        prefix = prefix.replaceAll("(?s)\\(\\s*\\d*\\s*\\)", "(number)"); //$NON-NLS-1$ //$NON-NLS-2$
        return prefix;
    }

    private ICompletionProposal[] getGlobalKeywordCompletion(String prefix, int offset) {

        ArrayList<ICompletionProposal> completions = new ArrayList<>();
        int prefixLength = prefix.length();
        for (String[] keyword : GLOBAL_KEYWORDS) {
            if (keyword[0].startsWith(prefix)) {
                CompletionProposal proposal = new CompletionProposal(
                        keyword[0].substring(prefixLength),
                        offset,
                        0,
                        keyword[0].length() - prefixLength,
                        null,
                        keyword[0],
                        new ContextInformation("contextDisplayString", "informationDisplayString"), //$NON-NLS-1$ //$NON-NLS-2$
                        keyword[1]);
                completions.add(proposal);
            }
        }
        return completions.toArray(new ICompletionProposal[0]);
    }

    /**
     * Returns the token preceding the current completion position.
     * @param doc The document for the which the completion is requested.
     * @param prefix The prefix for which the user has requested completion.
     * @param offset Current offset in the document
     * @return The preceding token.
     * @throws BadLocationException
     */
    private Token getPrecedingToken(IDocument doc, int offset) throws BadLocationException {
        // Skip trailing space
        int n = offset;
        while (n >= 0 && Character.isSpaceChar(doc.getChar(n))) {
            n--;
        }

        char c = doc.getChar(n);
        if (isTokenDelimiter(c)) {
            return new Token(Character.toString(c), n);
        }

        int end = n;
        while (n >= 0 && !isTokenDelimiter(doc.getChar(n))) {
            n--;
        }

        return new Token(doc.get(n+1, end-n), n+1);
    }

    private Token getCurrentToken(IDocument doc, int offset) throws BadLocationException {
        char c = doc.getChar(offset);

        if (isDelimiter(c)) {
            return new Token(Character.toString(c), offset);
        }

        int start = offset;
        while (start >= 0 && !isDelimiter(doc.getChar(start))) {
            start--;
        }

        int end = offset;
        while (end < doc.getLength() && !isDelimiter(doc.getChar(end))) {
            end++;
        }

        start++;
        return new Token(doc.get(start, end-start), start);
    }

    private boolean isFunctionRegion(IDocument doc, IRegion region) throws BadLocationException {
        int start = region.getLength() + region.getOffset();
        while (isTokenDelimiter(doc.getChar(start))) {
            start++;
        }
        return doc.getChar(start) == '(';
    }

    /**
     *
     * Return the word the user wants to submit for completion proposals.
     *
     * @param doc - document to insert completion.
     * @param offset - offset of where completion hint was first generated.
     * @return - word to generate completion proposals.
     *
     * @throws BadLocationException
     */
    private String getPrefix(IDocument doc, int offset)
            throws BadLocationException {

        for (int n = offset - 1; n >= 0; n--) {
            char c = doc.getChar(n);
            if (isTokenDelimiter(c)) {
                return doc.get(n + 1, offset - n - 1);
            }
        }
        return ""; //$NON-NLS-1$
    }

    private boolean isTokenDelimiter(char c) {
        if (Character.isWhitespace(c)) {
            return true;
        }

        switch (c) {
        case '\n':
        case '\0':
        case ',':
        case '{':
        case '}':
        case ']':
        case '[':
            return true;
        }
        return false;
    }

    private boolean isDelimiter(char c) {

        if (isTokenDelimiter(c)) {
            return true;
        }

        return c != '.' && Pattern.matches("\\W", Character.toString(c)); //$NON-NLS-1$
    }

    public void waitForInitialization() {
        this.stpMetadataSingleton.waitForInitialization();
    }

    @Override
    public IContextInformation[] computeContextInformation(ITextViewer viewer,
            int offset) {
        return NO_CONTEXTS;
    }

    @Override
    public char[] getCompletionProposalAutoActivationCharacters() {
        return PROPOSAL_ACTIVATION_CHARS;
    }

    @Override
    public char[] getContextInformationAutoActivationCharacters() {
        return PROPOSAL_ACTIVATION_CHARS;
    }

    @Override
    public IContextInformationValidator getContextInformationValidator() {
        return null;
    }

    @Override
    public String getErrorMessage() {
        // TODO: When does this trigger?
        return "Error."; //$NON-NLS-1$
    }

    @Override
    public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
        String documentation = null;
        try {
            String keyword = textViewer.getDocument().get(hoverRegion.getOffset(), hoverRegion.getLength());
            int offset = hoverRegion.getOffset();
            IDocument document = textViewer.getDocument();

            if (getPrecedingToken(document, offset - 1).tokenString.equals(PROBE_KEYWORD.trim())) {
                documentation = ManpageCacher.getDocumentation(TapsetItemType.PROBE, keyword);
            } else {
                ITypedRegion partition =
                        ((IDocumentExtension3)document).getPartition(STPProbeScanner.STP_PROBE_PARTITIONING,
                                offset, false);
                if (partition.getType() == STPProbeScanner.STP_PROBE) {
                    if (isFunctionRegion(document, hoverRegion)) {
                        documentation = ManpageCacher.getDocumentation(TapsetItemType.FUNCTION, keyword);
                    } else {
                        String probe = getProbe(document, offset);
                        if (stpMetadataSingleton.isVariableInProbe(probe, keyword)) {
                            documentation = ManpageCacher.getDocumentation(TapsetItemType.PROBEVAR, probe, keyword);
                        }
                    }
                }
            }

        } catch (BadLocationException|BadPartitioningException e) {
            // Bad hover location/scenario; just ignore it.
        }

        return documentation;
    }

    @Override
    public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
        try {
            return getCurrentToken(textViewer.getDocument(), offset);
        } catch (BadLocationException e) {
            // Bad hover location; just ignore it.
        }

        return null;
    }
}

Back to the top