You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@netbeans.apache.org by GitBox <gi...@apache.org> on 2022/08/15 20:52:52 UTC

[GitHub] [netbeans] sdedic commented on a diff in pull request #4503: Some support for TOML files

sdedic commented on code in PR #4503:
URL: https://github.com/apache/netbeans/pull/4503#discussion_r945470388


##########
ide/languages.toml/nbproject/project.properties:
##########
@@ -0,0 +1,19 @@
+is.eager=true

Review Comment:
   The module status (enable / disable) is out of user's control - other language modules (PHP, XML, ...) can be controlled by the user. What's the difference with TOML ?



##########
ide/languages.toml/src/org/netbeans/modules/languages/toml/LexerInputCharStream.java:
##########
@@ -0,0 +1,109 @@
+/*
+ * 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.
+ */
+package org.netbeans.modules.languages.toml;
+
+import java.util.Stack;
+import org.antlr.v4.runtime.CharStream;
+import org.antlr.v4.runtime.misc.Interval;
+import org.netbeans.spi.lexer.*;
+
+/**
+ *
+ * @author lkishalmi
+ */
+public class LexerInputCharStream implements CharStream {
+    private final LexerInput input;
+    private final Stack<Integer> markers = new Stack<>();
+
+    public LexerInputCharStream(LexerInput input) {
+        this.input = input;
+
+    }
+
+    @Override
+    public String getText(Interval intrvl) {
+        return input.readText(intrvl.a, intrvl.b).toString();
+    }
+
+    @Override
+    public void consume() {
+        input.read();
+    }
+
+    @Override
+    public int LA(int count) {
+        if (count == 0) {
+            return 0; //the behaviour is not defined
+        }
+
+        int c = 0;
+        if (count > 0) {
+            for (int i = 0; i < count; i++) {
+                c = input.read();
+            }
+            input.backup(count);
+        } else {
+            input.backup(count);
+            c = input.read();
+        }
+        return c;
+    }
+
+    @Override
+    public int mark() {
+        markers.push(index());
+        return markers.size() - 1;
+    }
+
+    @Override
+    public void release(int marker) {
+        while (marker < markers.size()) {
+            markers.pop();
+        }
+    }
+
+    @Override
+    public int index() {
+        return input.readLengthEOF();

Review Comment:
   Q: is `index()` supposed to return an index within the next to-be-token, or an index within the entire character stream ?



##########
ide/languages.toml/src/org/netbeans/modules/languages/toml/TomlTypedTextInterceptor.java:
##########
@@ -0,0 +1,177 @@
+/*
+ * 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.
+ */
+package org.netbeans.modules.languages.toml;
+
+import java.util.EnumSet;
+import java.util.Set;
+import javax.swing.text.BadLocationException;
+import javax.swing.text.Document;
+import org.netbeans.api.editor.document.LineDocumentUtils;
+import org.netbeans.api.editor.mimelookup.MimePath;
+import org.netbeans.api.editor.mimelookup.MimeRegistration;
+import org.netbeans.api.lexer.TokenHierarchy;
+import org.netbeans.api.lexer.TokenId;
+import org.netbeans.api.lexer.TokenSequence;
+import org.netbeans.editor.BaseDocument;
+import org.netbeans.spi.editor.typinghooks.TypedTextInterceptor;
+
+/**
+ *
+ * @author lkishalmi
+ */
+public class TomlTypedTextInterceptor implements TypedTextInterceptor {
+
+    private int caretPosition = -1;
+
+    @Override
+    public boolean beforeInsert(Context context) throws BadLocationException {
+        return false;
+    }
+
+    @Override
+    public void insert(MutableContext context) throws BadLocationException {
+        String txt = context.getText();
+        if (context.getReplacedText().length() == 0) {
+            switch (txt) {
+                case "{":
+                    context.setText("{}", 1);
+                    break;
+                case "}":
+                    if ("}".equals(textAfter(context, 1))) {
+                        skipNext(context);
+                    }
+                    break;
+                case "[":
+                    context.setText("[]", 1);
+                    break;
+                case "]":
+                    if ("]".equals(textAfter(context, 1))){
+                        skipNext(context);
+                    }
+                    break;
+                case " ":
+                    String b = textBefore(context, 1);
+                    String a = textAfter(context, 1);
+                    if ( ("{".equals(b) && "}".equals(a))
+                            || ("[".equals(b) && "]".equals(a))) {
+                        context.setText("  ", 1);
+                    }
+                    break;
+                case "\"":
+                    if (!isInMultilineString(context)) {
+                        if (!"\"\"".equals(textBefore(context, 2))) {
+                            if ("\"".equals(textAfter(context, 1))){
+                                skipNext(context);
+                            } else {
+                                int quotes = quotesInLine(context, '"');
+                                if (quotes % 2 == 0) {
+                                    context.setText("\"\"", 1);
+                                }
+                            }
+                        }
+                    }
+                    break;
+                case "'":
+                    if (!isInMultilineString(context)) {
+                        if (!"''".equals(textBefore(context, 2))) {
+                            if ("'".equals(textAfter(context, 1))){
+                                skipNext(context);
+                            } else {
+                                int quotes = quotesInLine(context, '\'');
+                                if (quotes % 2 == 0) {
+                                    context.setText("''", 1);
+                                }
+                            }
+                        }
+                    }
+                    break;
+            }
+        } else if (("\"".equals(txt) || "'".equals(txt)) && !isInMultilineString(context)) {
+            context.setText(txt + context.getReplacedText() + txt, context.getReplacedText().length() + 2);
+        }
+    }
+
+    private void skipNext(MutableContext context) {
+        context.setText("", 0);
+        caretPosition = context.getOffset() + 1;
+    }
+
+    private static String textAfter(Context context, int length) throws BadLocationException {
+        int next = Math.min(length, context.getDocument().getLength() - context.getOffset());
+        return context.getDocument().getText(context.getOffset(), next);
+    }
+
+    private static String textBefore(Context context, int lenght) throws BadLocationException {
+        int pre = Math.min(lenght, context.getOffset());
+        return context.getDocument().getText(context.getOffset() - pre, pre);
+    }
+
+    private static final Set<? extends TokenId> STRING_OR_WS = EnumSet.of(TomlTokenId.STRING, TomlTokenId.WHITESPACE);
+    
+    private static boolean isInMultilineString(Context context){
+        TokenHierarchy<Document> th = TokenHierarchy.get(context.getDocument());
+        TokenSequence<?> ts = th.tokenSequence();
+        ts.move(context.getOffset());
+        ts.movePrevious();
+        while ((ts.token() != null) && STRING_OR_WS.contains(ts.token().id())) {
+            ts.movePrevious();
+        }
+        return (ts.token() != null) && TomlTokenId.ML_STRING_START == ts.token().id();
+    }
+
+    private static int quotesInLine(Context context, char quote) throws BadLocationException {
+        BaseDocument doc = (BaseDocument) context.getDocument();

Review Comment:
   Use `LineDocument`, no dependency on editor.lib needed.



##########
ide/languages.toml/src/org/netbeans/modules/languages/toml/TomlCompletionProvider.java:
##########
@@ -0,0 +1,127 @@
+/*
+ * 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.
+ */
+package org.netbeans.modules.languages.toml;
+
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.Set;
+import javax.swing.text.AbstractDocument;
+import javax.swing.text.BadLocationException;
+import javax.swing.text.Document;
+import javax.swing.text.JTextComponent;
+import org.netbeans.api.editor.mimelookup.MimeRegistration;
+import org.netbeans.api.lexer.TokenHierarchy;
+import org.netbeans.api.lexer.TokenSequence;
+import org.netbeans.spi.editor.completion.CompletionProvider;
+import org.netbeans.spi.editor.completion.CompletionResultSet;
+import org.netbeans.spi.editor.completion.CompletionTask;
+import org.netbeans.spi.editor.completion.support.AsyncCompletionQuery;
+import org.netbeans.spi.editor.completion.support.AsyncCompletionTask;
+import org.netbeans.spi.editor.completion.support.CompletionUtilities;
+import org.tomlj.Toml;
+import org.tomlj.TomlParseResult;
+
+/**
+ *
+ * @author Laszlo Kishalmi
+ */
+@MimeRegistration(mimeType = TomlTokenId.TOML_MIME_TYPE, service = CompletionProvider.class)
+public class TomlCompletionProvider implements CompletionProvider {
+
+    @Override
+    public CompletionTask createTask(int queryType, JTextComponent component) {
+        return new AsyncCompletionTask(new TomlCompletionQuery(), component);
+    }
+
+    @Override
+    public int getAutoQueryTypes(JTextComponent component, String typedText) {
+        return 0;
+    }
+
+    private class TomlCompletionQuery extends AsyncCompletionQuery {
+
+        @Override
+        protected void query(CompletionResultSet resultSet, Document doc, int caretOffset) {
+            Set<String> candidates = new HashSet<>();
+            try {
+                int prefixOfs = keyPrefixOffset(doc, caretOffset);
+                String prefix = doc.getText(prefixOfs, caretOffset - prefixOfs);
+                int lastDot = prefix.lastIndexOf('.');
+                String simplePrefix = lastDot != -1 ? prefix.substring(lastDot + 1) : prefix;
+
+                StringBuilder toml = new StringBuilder(doc.getLength());
+                //Remove the current prefix for the parser to get better results
+                toml.append(doc.getText(0, prefixOfs));
+                toml.append(doc.getText(caretOffset, doc.getLength() - caretOffset));
+
+                TomlParseResult parse = Toml.parse(toml.toString());
+                for (String key : parse.dottedKeySet()) {
+                    String candidate = matchKey(key, prefix);
+                    if (candidate != null) {
+                        candidates.add(candidate);
+                    }
+                }
+                for (String candidate : candidates) {
+                    String insert = candidate.substring(simplePrefix.length());
+                    resultSet.addItem(CompletionUtilities.newCompletionItemBuilder(insert)
+                            .leftHtmlText(candidate)
+                            .sortText(candidate)
+                            .build());
+                }
+            } catch (BadLocationException ex) {
+            } finally {
+                resultSet.finish();
+            }
+        }
+
+    }
+
+
+    static String matchKey(String key, String prefix) {
+        String ret = null;
+        int keyStart = key.indexOf(prefix);
+        if (keyStart == 0 || ((keyStart > 0) && (key.charAt(keyStart - 1) == '.'))) {
+            int lastDot = prefix.lastIndexOf('.');
+            String m = key.substring(keyStart + lastDot + 1);
+            int dot = m.indexOf('.');
+            ret = (dot > -1) ? m.substring(0, dot) : m;
+        }
+        return ret;
+    }
+
+    private static final Set<TomlTokenId> DOT_OR_KEY = EnumSet.of(TomlTokenId.DOT, TomlTokenId.KEY);
+
+    static int keyPrefixOffset(Document doc, int offset) throws BadLocationException {
+        AbstractDocument d = (AbstractDocument) doc;
+        try {
+            d.readLock();
+            TokenHierarchy th = TokenHierarchy.get(doc);
+            TokenSequence<TomlTokenId> ts = th.tokenSequence();
+            ts.move(offset);
+            ts.movePrevious();

Review Comment:
   Maybe check the result of `movePrevious`; indicates end(begin)-of-token stream



##########
ide/languages.toml/src/org/netbeans/modules/languages/toml/layer.xml:
##########
@@ -0,0 +1,168 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    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.
+
+-->
+<!DOCTYPE filesystem PUBLIC "-//NetBeans//DTD Filesystem 1.1//EN" "http://www.netbeans.org/dtds/filesystem-1_1.dtd">
+<filesystem>
+    <folder name="Editors">
+        <folder name="text">
+            <folder name="x-toml">
+                <attr name="SystemFileSystem.localizingBundle" stringvalue="org.netbeans.modules.languages.toml.Bundle"/>
+
+                <file name="language.instance">
+                    <attr name="instanceCreate" methodvalue="org.netbeans.modules.languages.toml.TomlTokenId.language"/>
+                    <attr name="instanceOf" stringvalue="org.netbeans.api.lexer.Language"/>
+                </file>
+
+                <folder name="FontsColors">
+                    <folder name="NetBeans">
+                        <folder name="Defaults">
+                            <file name="FontAndColors.xml" url="FontAndColors.xml">
+                                <attr name="SystemFileSystem.localizingBundle" stringvalue="org.netbeans.modules.languages.toml.Bundle"/>
+                            </file>
+                        </folder>
+                    </folder>
+                </folder>
+                <folder name="Preferences">
+                    <folder name="Defaults">
+                        <file name="org-netbeans-modules-languages-toml-preferences.xml" url="preferences.xml"/>
+                    </folder>
+                </folder>
+            </folder>
+        </folder>
+    </folder>
+    <folder name="OptionsDialog">
+        <folder name="PreviewExamples">
+            <folder name="text">
+                <file name="x-toml" url="TomlExample.toml"/>
+            </folder>
+        </folder>
+        <folder name="Editor">
+            <folder name="Formatting">
+                <folder name="text">
+                    <folder name="x-toml">
+                        <file name="TabsAndIndents.instance">
+                            <attr name="instanceOf" stringvalue="org.netbeans.modules.options.editor.spi.PreferencesCustomizer$Factory"/>
+                            <attr name="instanceCreate" methodvalue="org.netbeans.modules.options.editor.spi.CustomizerFactories.createDefaultTabsAndIndentsCustomizerFactory"/>
+                            <attr name="previewTextFile" stringvalue="org/netbeans/modules/languages/toml/TomlExample.toml"/>
+                            <attr name="position" intvalue="100"/>
+                        </file>
+                    </folder>
+                </folder>
+            </folder>
+        </folder>
+    </folder>
+    <!--folder name="Templates">

Review Comment:
   Leftover ?



##########
ide/languages.toml/src/org/netbeans/modules/languages/toml/TomlCompletionProvider.java:
##########
@@ -0,0 +1,127 @@
+/*
+ * 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.
+ */
+package org.netbeans.modules.languages.toml;
+
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.Set;
+import javax.swing.text.AbstractDocument;
+import javax.swing.text.BadLocationException;
+import javax.swing.text.Document;
+import javax.swing.text.JTextComponent;
+import org.netbeans.api.editor.mimelookup.MimeRegistration;
+import org.netbeans.api.lexer.TokenHierarchy;
+import org.netbeans.api.lexer.TokenSequence;
+import org.netbeans.spi.editor.completion.CompletionProvider;
+import org.netbeans.spi.editor.completion.CompletionResultSet;
+import org.netbeans.spi.editor.completion.CompletionTask;
+import org.netbeans.spi.editor.completion.support.AsyncCompletionQuery;
+import org.netbeans.spi.editor.completion.support.AsyncCompletionTask;
+import org.netbeans.spi.editor.completion.support.CompletionUtilities;
+import org.tomlj.Toml;
+import org.tomlj.TomlParseResult;
+
+/**
+ *
+ * @author Laszlo Kishalmi
+ */
+@MimeRegistration(mimeType = TomlTokenId.TOML_MIME_TYPE, service = CompletionProvider.class)
+public class TomlCompletionProvider implements CompletionProvider {
+
+    @Override
+    public CompletionTask createTask(int queryType, JTextComponent component) {
+        return new AsyncCompletionTask(new TomlCompletionQuery(), component);
+    }
+
+    @Override
+    public int getAutoQueryTypes(JTextComponent component, String typedText) {
+        return 0;
+    }
+
+    private class TomlCompletionQuery extends AsyncCompletionQuery {
+
+        @Override
+        protected void query(CompletionResultSet resultSet, Document doc, int caretOffset) {
+            Set<String> candidates = new HashSet<>();
+            try {
+                int prefixOfs = keyPrefixOffset(doc, caretOffset);
+                String prefix = doc.getText(prefixOfs, caretOffset - prefixOfs);

Review Comment:
   Q: is `doc` read-locked at this time ?



##########
ide/languages.toml/src/org/netbeans/modules/languages/toml/TomlLexer.java:
##########
@@ -0,0 +1,168 @@
+/*
+ * 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.
+ */
+package org.netbeans.modules.languages.toml;
+
+import org.antlr.v4.runtime.misc.IntegerList;
+import org.netbeans.api.lexer.Token;
+import org.netbeans.spi.lexer.Lexer;
+import org.netbeans.spi.lexer.LexerRestartInfo;
+import org.netbeans.spi.lexer.TokenFactory;
+
+import static org.tomlj.internal.TomlLexer.*;
+import static org.netbeans.modules.languages.toml.TomlTokenId.*;
+
+/**
+ *
+ * @author lkishalmi
+ */
+public final class TomlLexer implements Lexer<TomlTokenId> {
+
+    private final TokenFactory<TomlTokenId> tokenFactory;
+    private org.tomlj.internal.TomlLexer lexer;
+
+    public TomlLexer(LexerRestartInfo<TomlTokenId> info) {
+        this.tokenFactory = info.tokenFactory();
+        try {
+            this.lexer = new org.tomlj.internal.TomlLexer(new LexerInputCharStream(info.input()));
+            if (info.state() != null) {
+                ((LexerState) info.state()).restore(lexer);
+            }
+        } catch (Throwable ex) {
+            ex.printStackTrace();

Review Comment:
   If catching Throwable | Error, make sure to rethrow ThreadDeath.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@netbeans.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@netbeans.apache.org
For additional commands, e-mail: notifications-help@netbeans.apache.org

For further information about the NetBeans mailing lists, visit:
https://cwiki.apache.org/confluence/display/NETBEANS/Mailing+lists