diff --git a/ide/csl.api/test/unit/src/org/netbeans/modules/csl/api/test/CslTestBase.java b/ide/csl.api/test/unit/src/org/netbeans/modules/csl/api/test/CslTestBase.java index 4b2182329d0f..1a9570407b22 100644 --- a/ide/csl.api/test/unit/src/org/netbeans/modules/csl/api/test/CslTestBase.java +++ b/ide/csl.api/test/unit/src/org/netbeans/modules/csl/api/test/CslTestBase.java @@ -403,7 +403,7 @@ protected FileObject getTestFile(String relFilePath) { if (!wholeInputFile.exists()) { NbTestCase.fail("File " + wholeInputFile + " not found."); } - FileObject fo = FileUtil.toFileObject(wholeInputFile); + FileObject fo = FileUtil.toFileObject(FileUtil.normalizeFile(wholeInputFile)); assertNotNull(fo); return fo; diff --git a/webcommon/javascript2.editor/nbproject/project.properties b/webcommon/javascript2.editor/nbproject/project.properties index 8548549a1c03..4db85dc518b0 100644 --- a/webcommon/javascript2.editor/nbproject/project.properties +++ b/webcommon/javascript2.editor/nbproject/project.properties @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -javac.release=11 +javac.release=17 javac.compilerargs=-Xlint -Xlint:-serial javadoc.arch=${basedir}/arch.xml nbm.needs.restart=true diff --git a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/CompletionContextFinder.java b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/CompletionContextFinder.java index 3be694da949b..f9f58b80816a 100644 --- a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/CompletionContextFinder.java +++ b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/CompletionContextFinder.java @@ -304,7 +304,7 @@ protected static boolean isPropertyNameContext(TokenSequence ts) { return false; } - private static boolean acceptTokenChains(TokenSequence tokenSequence, List tokenIdChains, boolean movePrevious) { + private static boolean acceptTokenChains(TokenSequence tokenSequence, List tokenIdChains, boolean movePrevious) { for (Object[] tokenIDChain : tokenIdChains){ if (acceptTokenChain(tokenSequence, tokenIDChain, movePrevious)){ return true; @@ -314,7 +314,7 @@ private static boolean acceptTokenChains(TokenSequence tokenSequence, List tokenSequence, Object[] tokenIdChain, boolean movePrevious) { int orgTokenSequencePos = tokenSequence.offset(); boolean accept = true; boolean moreTokens = movePrevious ? tokenSequence.movePrevious() : true; diff --git a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/FSCompletionItem.java b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/FSCompletionItem.java index 90bd4442082c..99c7248de6d0 100644 --- a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/FSCompletionItem.java +++ b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/FSCompletionItem.java @@ -188,7 +188,7 @@ public ElementKind getKind() { @Override public Set getModifiers() { - return Collections.EMPTY_SET; + return Collections.emptySet(); } @Override diff --git a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsCompletionItem.java b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsCompletionItem.java index 4e4bbf61a061..eadaefaf978b 100644 --- a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsCompletionItem.java +++ b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsCompletionItem.java @@ -142,8 +142,7 @@ protected void formatName(HtmlFormatter formatter) { @Override public String getRhsHtml(HtmlFormatter formatter) { String location = null; - if (element instanceof JsElement) { - JsElement jsElement = (JsElement) element; + if (element instanceof JsElement jsElement) { if (jsElement.isPlatform()) { location = Bundle.JsCompletionItem_lbl_js_platform(); } else if (jsElement.getSourceLabel() != null) { @@ -184,7 +183,7 @@ public Set getModifiers() { Set modifiers; if (getElement() == null || getElement().getModifiers().isEmpty()) { - modifiers = Collections.EMPTY_SET; + modifiers = Collections.emptySet(); } else { modifiers = EnumSet.noneOf(Modifier.class); modifiers.addAll(getElement().getModifiers()); @@ -206,8 +205,8 @@ public boolean isSmart() { @Override public int getSortPrioOverride() { int order = 100; - if (element instanceof JsElement) { - if (((JsElement)element).isPlatform()) { + if (element instanceof JsElement jsElement) { + if (jsElement.isPlatform()) { if (ModelUtils.PROTOTYPE.equals(element.getName())) { //NOI18N order = 1; } else { @@ -261,7 +260,7 @@ public static class JsFunctionCompletionItem extends JsCompletionItem { private final Map> parametersTypes; JsFunctionCompletionItem(ElementHandle element, CompletionRequest request, Set resolvedReturnTypes, Map> parametersTypes) { super(element, request); - this.returnTypes = resolvedReturnTypes != null ? resolvedReturnTypes : Collections.EMPTY_SET; + this.returnTypes = resolvedReturnTypes != null ? resolvedReturnTypes : Collections.emptySet(); this.parametersTypes = parametersTypes != null ? parametersTypes : Collections.>emptyMap(); } @@ -370,8 +369,8 @@ private boolean asObject() { boolean result = false; char firstChar = getName().charAt(0); JsElement.Kind jsKind = null; - if (element instanceof JsElement) { - jsKind = ((JsElement)element).getJSKind(); + if (element instanceof JsElement jsElement) { + jsKind = jsElement.getJSKind(); } if ((jsKind != null && jsKind == JsElement.Kind.CONSTRUCTOR) || Character.isUpperCase(firstChar)) { boolean isAfterNew = isAfterNewKeyword(); @@ -429,7 +428,7 @@ public ImageIcon getIcon() { public static class JsCallbackCompletionItem extends JsCompletionItem { private static ImageIcon callbackIcon = null; - private IndexedElement.FunctionIndexedElement function; + private final IndexedElement.FunctionIndexedElement function; public JsCallbackCompletionItem(IndexedElement.FunctionIndexedElement element, CompletionRequest request) { super(element, request); @@ -592,40 +591,40 @@ public String getCustomInsertTemplate() { } switch(type) { - case SIMPLE: + case SIMPLE -> { builder.append(getName()); - break; - case ENDS_WITH_SPACE: + } + case ENDS_WITH_SPACE -> { builder.append(getName()); builder.append(" ${cursor}"); //NOI18N - break; - case CURSOR_INSIDE_BRACKETS: + } + case CURSOR_INSIDE_BRACKETS -> { builder.append(getName()); builder.append("(${cursor})"); //NOI18N - break; - case ENDS_WITH_CURLY_BRACKETS: + } + case ENDS_WITH_CURLY_BRACKETS -> { builder.append(getName()); builder.append(" {${cursor}}"); //NOI18N - break; - case ENDS_WITH_SEMICOLON: + } + case ENDS_WITH_SEMICOLON -> { builder.append(getName()); CharSequence text = request.info.getSnapshot().getText(); int index = request.anchor + request.prefix.length(); if (index == text.length() || ';' != text.charAt(index)) { //NOI18N builder.append(";"); //NOI18N } - break; - case ENDS_WITH_COLON: + } + case ENDS_WITH_COLON -> { builder.append(getName()); builder.append(" ${cursor}:"); //NOI18N - break; - case ENDS_WITH_DOT: + } + case ENDS_WITH_DOT -> { builder.append(getName()); builder.append(".${cursor}"); //NOI18N - break; - default: + } + default -> { assert false : type.toString(); - break; + } } return builder.toString(); } @@ -642,7 +641,7 @@ public static class JsPropertyCompletionItem extends JsCompletionItem { JsPropertyCompletionItem(ElementHandle element, CompletionRequest request, Set resolvedTypes) { super(element, request); - this.resolvedTypes = resolvedTypes != null ? resolvedTypes : Collections.EMPTY_SET; + this.resolvedTypes = resolvedTypes != null ? resolvedTypes : Collections.emptySet(); } @Override @@ -696,11 +695,7 @@ public static void create( Map> items, CompletionRequest return; } switch (element.getJSKind()) { - case CONSTRUCTOR: - case FUNCTION: - case METHOD: - case GENERATOR: - case ARROW_FUNCTION: + case CONSTRUCTOR, FUNCTION, METHOD, GENERATOR, ARROW_FUNCTION -> { Set returnTypes = new HashSet<>(); HashMap> allParameters = new LinkedHashMap<>(); if (element instanceof JsFunction) { @@ -726,10 +721,10 @@ public static void create( Map> items, CompletionRequest } allParameters.put(jsObject.getName(), paramTypes); } - } else if (element instanceof IndexedElement.FunctionIndexedElement) { + } else if (element instanceof IndexedElement.FunctionIndexedElement functionIndexedElement) { // count return types HashSet returnTypeUsages = new HashSet<>(); - for (String type : ((IndexedElement.FunctionIndexedElement) element).getReturnTypes()) { + for (String type : functionIndexedElement.getReturnTypes()) { returnTypeUsages.add(new TypeUsage(type, -1, false)); } Collection resolveTypes = ModelUtils.resolveTypes(returnTypeUsages, @@ -737,7 +732,7 @@ public static void create( Map> items, CompletionRequest jsIndex, false); returnTypes.addAll(Utils.getDisplayNames(resolveTypes)); // count parameters type - LinkedHashMap> parameters = ((IndexedElement.FunctionIndexedElement) element).getParameters(); + LinkedHashMap> parameters = functionIndexedElement.getParameters(); for (Map.Entry> paramEntry : parameters.entrySet()) { Set paramTypes = new HashSet<>(); for (String type : paramEntry.getValue()) { @@ -763,20 +758,13 @@ public static void create( Map> items, CompletionRequest : new JsGeneratorCompletionItem(element, request, returnTypes, allParameters); signatures.put(signature, item); } - break; - case PARAMETER: - case PROPERTY: - case PROPERTY_GETTER: - case PROPERTY_SETTER: - case FIELD: - case VARIABLE: + } + case PARAMETER, PROPERTY, PROPERTY_GETTER, PROPERTY_SETTER, FIELD, VARIABLE -> { Set typesToDisplay = new HashSet<>(); Collection assignment = null; - if (element instanceof JsObject) { - JsObject jsObject = (JsObject) element; + if (element instanceof JsObject jsObject) { assignment = jsObject.getAssignments(); - } else if (element instanceof IndexedElement) { - IndexedElement iElement = (IndexedElement) element; + } else if (element instanceof IndexedElement iElement) { assignment = iElement.getAssignments(); } if (assignment != null && !assignment.isEmpty()) { @@ -808,19 +796,20 @@ public static void create( Map> items, CompletionRequest } } // signatures - signature = element.getName() + ":" + createTypeSignature(typesToDisplay); + String signature = element.getName() + ":" + createTypeSignature(typesToDisplay); if (!signatures.containsKey(signature)) { // add the item to the cc only if doesn't exist any similar JsCompletionItem item = new JsPropertyCompletionItem(element, request, typesToDisplay); signatures.put(signature, item); } - break; - default: - signature = element.getName(); + } + default -> { + String signature = element.getName(); if (!signatures.containsKey(signature)) { JsCompletionItem item = new JsCompletionItem(element, request); signatures.put(signature, item); } + } } } for (JsCompletionItem item: signatures.values()) { diff --git a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsInstantRenamer.java b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsInstantRenamer.java index 3677f4a73aab..5a1ad850e3bc 100644 --- a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsInstantRenamer.java +++ b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsInstantRenamer.java @@ -47,8 +47,7 @@ public boolean isRenameAllowed(ParserResult info, int caretOffset, String[] expl @Override public Set getRenameRegions(ParserResult info, int caretOffset) { - if (info instanceof JsParserResult) { - JsParserResult pResult = (JsParserResult)info; + if (info instanceof JsParserResult pResult) { Set findOccurrenceRanges = OccurrencesFinderImpl.findOccurrenceRanges(pResult, info.getSnapshot().getEmbeddedOffset(caretOffset)); HashSet sourceRanges = new HashSet<>(findOccurrenceRanges.size()); for (OffsetRange range : findOccurrenceRanges) { @@ -56,7 +55,7 @@ public Set getRenameRegions(ParserResult info, int caretOffset) { } return sourceRanges; } else { - return Collections.EMPTY_SET; + return Collections.emptySet(); } } diff --git a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsKeyStrokeHandler.java b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsKeyStrokeHandler.java index 2fae2b9299a8..545ecf368643 100644 --- a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsKeyStrokeHandler.java +++ b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsKeyStrokeHandler.java @@ -32,6 +32,7 @@ import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; +import java.util.Objects; import java.util.Set; import javax.swing.text.BadLocationException; import javax.swing.text.Document; @@ -55,26 +56,31 @@ public JsKeyStrokeHandler() { } @Override + @SuppressWarnings("deprecation") public boolean beforeCharInserted(Document doc, int caretOffset, JTextComponent target, char ch) throws BadLocationException { return false; } @Override + @SuppressWarnings("deprecation") public boolean afterCharInserted(Document doc, int caretOffset, JTextComponent target, char ch) throws BadLocationException { return false; } @Override + @SuppressWarnings("deprecation") public boolean charBackspaced(Document doc, int caretOffset, JTextComponent target, char ch) throws BadLocationException { return false; } @Override + @SuppressWarnings("deprecation") public int beforeBreak(Document doc, int caretOffset, JTextComponent target) throws BadLocationException { return -1; } @Override + @SuppressWarnings("deprecation") public OffsetRange findMatching(Document doc, int caretOffset) { return OffsetRange.NONE; } @@ -82,13 +88,12 @@ public OffsetRange findMatching(Document doc, int caretOffset) { @Override public List findLogicalRanges(final ParserResult info, final int caretOffset) { final Set ranges = new LinkedHashSet<>(); - if (info instanceof JsParserResult) { - final JsParserResult jsParserResult = (JsParserResult) info; + if (info instanceof JsParserResult jsParserResult) { FunctionNode root = jsParserResult.getRoot(); final TokenSequence ts = LexUtilities.getJsTokenSequence(jsParserResult.getSnapshot(), caretOffset); if (root != null && ts != null) { - root.accept(new NodeVisitor(new LexicalContext()) { + root.accept(new NodeVisitor(new LexicalContext()) { private OffsetRange getOffsetRange(IdentNode node) { // because the truffle parser doesn't set correctly the finish offset, when there are comments after the indent node @@ -96,11 +101,11 @@ private OffsetRange getOffsetRange(IdentNode node) { } private OffsetRange getOffsetRange(Node node) { - if (node instanceof FunctionNode) { - return getOffsetRange((FunctionNode) node); - } - if (node instanceof IdentNode) { - return getOffsetRange((IdentNode)node); + Objects.requireNonNull(node); + if (node instanceof FunctionNode functionNode) { + return getOffsetRange(functionNode); + } else if (node instanceof IdentNode identNode) { + return getOffsetRange(identNode); } return new OffsetRange(node.getStart(), node.getFinish()); } @@ -182,7 +187,7 @@ public boolean enterVarNode(VarNode node) { } @Override - public boolean enterLiteralNode(LiteralNode node) { + public boolean enterLiteralNode(LiteralNode node) { if (node.isString() && node.getStart() <= caretOffset && caretOffset <= node.getFinish()) { // include the " or ' ranges.add(new OffsetRange(node.getStart() - 1, node.getFinish() + 1)); @@ -239,6 +244,7 @@ public boolean enterCallNode(CallNode node) { } @Override + @SuppressWarnings("deprecation") public int getNextWordOffset(Document doc, int caretOffset, boolean reverse) { return -1; } diff --git a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsLanguage.java b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsLanguage.java index 583374967d66..9edfcf8fd9f1 100644 --- a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsLanguage.java +++ b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsLanguage.java @@ -18,6 +18,7 @@ */ package org.netbeans.modules.javascript2.editor; +import org.netbeans.api.lexer.Language; import org.netbeans.core.spi.multiview.MultiViewElement; import org.netbeans.core.spi.multiview.text.MultiViewEditorElement; import org.netbeans.modules.csl.api.*; @@ -69,7 +70,7 @@ public JsLanguage() { } @Override - public org.netbeans.api.lexer.Language getLexerLanguage() { + public Language getLexerLanguage() { // has to be done here since JS hasn't its own project, also see issue #165915 // It was moved here from the JsLanguage initialization since the the language is called much earlier than the // JavaScipt is really needed. Calling it in the #getLexerLanguage() should ensure to be the CP registration @@ -92,6 +93,7 @@ public Parser getParser() { } @Override + @SuppressWarnings("deprecation") public boolean hasStructureScanner() { return true; } diff --git a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsSemanticAnalyzer.java b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsSemanticAnalyzer.java index 38f56bf8230d..34c279cf78b6 100644 --- a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsSemanticAnalyzer.java +++ b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsSemanticAnalyzer.java @@ -39,7 +39,6 @@ import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; @@ -128,15 +127,10 @@ private Map> count (JsParserResult result, if (ModelUtils.wasProcessed(parent, processedObjects)) { return highlights; } - for (Iterator it = parent.getProperties().values().iterator(); it.hasNext();) { - JsObject object = it.next(); + for (JsObject object : parent.getProperties().values()) { if (object.getDeclarationName() != null) { switch (object.getJSKind()) { - case CONSTRUCTOR: - case METHOD: - case FUNCTION: - case GENERATOR: - case ARROW_FUNCTION: + case CONSTRUCTOR, METHOD, FUNCTION, GENERATOR, ARROW_FUNCTION -> { if(object.isDeclared() && !object.isAnonymous() && !object.getDeclarationName().getOffsetRange().isEmpty()) { EnumSet coloring = ColoringAttributes.METHOD_SET; if (object.getModifiers().contains(Modifier.PRIVATE)) { @@ -153,7 +147,7 @@ private Map> count (JsParserResult result, addColoring(result, highlights, object.getDeclarationName().getOffsetRange(), coloring); } for(JsObject param: ((JsFunction)object).getParameters()) { - if (!(object instanceof JsReference && !((JsReference)object).getOriginal().isAnonymous())) { + if (!(object instanceof JsReference jr && !jr.getOriginal().isAnonymous())) { count(result, param, highlights, processedObjects); } if (!hasSourceOccurences(result, param)) { @@ -164,9 +158,8 @@ private Map> count (JsParserResult result, } } } - break; - case PROPERTY_GETTER: - case PROPERTY_SETTER: + } + case PROPERTY_GETTER, PROPERTY_SETTER -> { int offset = LexUtilities.getLexerOffset(result, object.getDeclarationName().getOffsetRange().getStart()); TokenSequence ts = LexUtilities.getJsTokenSequence(result.getSnapshot(), offset); if (ts != null) { @@ -179,12 +172,10 @@ private Map> count (JsParserResult result, } highlights.put(LexUtilities.getLexerOffsets(result, object.getDeclarationName().getOffsetRange()), ColoringAttributes.FIELD_SET); } - break; - case OBJECT: - case OBJECT_LITERAL: - case CLASS: + } + case OBJECT, OBJECT_LITERAL, CLASS -> { if(!"UNKNOWN".equals(object.getName())) { - if (parent.getParent() == null && !GLOBAL_TYPES.contains(object.getName())) { + if (parent.getParent() == null && !GLOBAL_TYPES.contains(object.getName())) { addColoring(result, highlights, object.getDeclarationName().getOffsetRange(), GLOBAL_DEFINITION); for (Occurrence occurence : object.getOccurrences()) { addColoring(result, highlights, occurence.getOffsetRange(), ColoringAttributes.GLOBAL_SET); @@ -208,9 +199,8 @@ private Map> count (JsParserResult result, } } } - break; - case PROPERTY: - case FIELD: + } + case PROPERTY, FIELD -> { if(object.isDeclared()) { addColoring(result, highlights, object.getDeclarationName().getOffsetRange(), ColoringAttributes.FIELD_SET); for(Occurrence occurence: object.getOccurrences()) { @@ -233,8 +223,8 @@ private Map> count (JsParserResult result, } } } - break; - case VARIABLE: + } + case VARIABLE -> { if (parent.getParent() == null && !GLOBAL_TYPES.contains(object.getName())) { addColoring(result, highlights, object.getDeclarationName().getOffsetRange(), ColoringAttributes.GLOBAL_SET); for(Occurrence occurence: object.getOccurrences()) { @@ -275,13 +265,14 @@ private Map> count (JsParserResult result, } } } + } } } if (isCancelled()) { highlights = Collections.emptyMap(); break; } - if (!(object instanceof JsReference && ModelUtils.isDescendant(object, ((JsReference)object).getOriginal()))) { + if (!(object instanceof JsReference jr && ModelUtils.isDescendant(object, jr.getOriginal()))) { highlights = count(result, object, highlights, processedObjects); } } @@ -450,7 +441,7 @@ public boolean enterForNode(ForNode forNode) { private void handleProperty(PropertyNode p, boolean classElement) { int offset = -1; - if ((p.getValue() instanceof FunctionNode) && ((FunctionNode) p.getValue()).isAsync()) { + if ((p.getValue() instanceof FunctionNode fn) && fn.isAsync()) { TokenSequence ts = LexUtilities.getJsPositionedSequence(result.getSnapshot(), p.getStart() - 1); if (ts != null) { Token token = LexUtilities.findPreviousNonWsNonComment(ts); diff --git a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsStructureScanner.java b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsStructureScanner.java index 500559378a47..a4d2142b05d2 100644 --- a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsStructureScanner.java +++ b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsStructureScanner.java @@ -54,7 +54,6 @@ import org.netbeans.modules.javascript2.lexer.api.JsTokenId; import org.netbeans.modules.javascript2.lexer.api.LexUtilities; import org.netbeans.modules.javascript2.model.api.ModelUtils; -import org.netbeans.modules.javascript2.editor.parser.JsParserResult; import org.netbeans.modules.javascript2.model.api.Index; import org.netbeans.modules.javascript2.model.api.JsReference; import org.netbeans.modules.javascript2.types.api.Type; @@ -146,8 +145,8 @@ private List getEmbededItems(ParserResult result, JsObject jsObje collectedItems.add(new JsFunctionStructureItem(function, children, result)); } } - } else if (((child.getJSKind() == JsElement.Kind.OBJECT && (children.size() > 0 || child.isDeclared())) || child.getJSKind() == JsElement.Kind.OBJECT_LITERAL || child.getJSKind() == JsElement.Kind.ANONYMOUS_OBJECT) - && (children.size() > 0 || child.isDeclared())) { + } else if (((child.getJSKind() == JsElement.Kind.OBJECT && (!children.isEmpty() || child.isDeclared())) || child.getJSKind() == JsElement.Kind.OBJECT_LITERAL || child.getJSKind() == JsElement.Kind.ANONYMOUS_OBJECT) + && (!children.isEmpty() || child.isDeclared())) { if(!(jsObject.getJSKind() == JsElement.Kind.FILE && JsTokenId.JSON_MIME_TYPE.equals(jsObject.getMimeType()))) { collectedItems.add(new JsObjectStructureItem(child, children, result)); } else { @@ -172,8 +171,7 @@ private List getEmbededItems(ParserResult result, JsObject jsObje } } - if (jsObject instanceof JsFunction) { - JsFunction jsFunction = (JsFunction)jsObject; + if (jsObject instanceof JsFunction jsFunction) { for (JsObject param: jsFunction.getParameters()) { if (hasDeclaredProperty(param) && !(jsObject instanceof JsReference && !((JsReference)jsObject).getOriginal().isAnonymous())) { final List items = new ArrayList<>(); @@ -224,14 +222,16 @@ private boolean containsFunction(JsObject jsObject) { return false; } - private boolean isNotAnonymousFunction(TokenSequence ts, int functionKeywordPosition) { + private boolean isNotAnonymousFunction(TokenSequence tsInput, int functionKeywordPosition) { + @SuppressWarnings("unchecked") + TokenSequence ts = (TokenSequence) tsInput; // expect that the ts in on "{" int position = ts.offset(); boolean value = false; // find the function keyword ts.move(functionKeywordPosition); ts.moveNext(); - Token token = LexUtilities.findPrevious(ts, Arrays.asList(JsTokenId.WHITESPACE)); + Token token = LexUtilities.findPrevious(ts, Arrays.asList(JsTokenId.WHITESPACE)); if ((token.id() == JsTokenId.OPERATOR_ASSIGNMENT || token.id() == JsTokenId.OPERATOR_COLON) && ts.movePrevious()) { token = LexUtilities.findPrevious(ts, Arrays.asList(JsTokenId.WHITESPACE)); if (token.id() == JsTokenId.IDENTIFIER || token.id() == JsTokenId.PRIVATE_IDENTIFIER) { @@ -274,8 +274,8 @@ public Map> folds(org.netbeans.modules.csl.spi.ParserR folds = foldsJson((ParserResult)info); } else { folds = new HashMap<>(); - TokenHierarchy th = info.getSnapshot().getTokenHierarchy(); - TokenSequence ts = th.tokenSequence(language); + TokenHierarchy th = info.getSnapshot().getTokenHierarchy(); + TokenSequence ts = th.tokenSequence(language); List> list = th.tokenSequenceList(ts.languagePath(), 0, info.getSnapshot().getText().length()); List stack = new ArrayList<>(); for (TokenSequenceIterator tsi = new TokenSequenceIterator(list, false); tsi.hasMore();) { @@ -334,8 +334,8 @@ public Map> folds(org.netbeans.modules.csl.spi.ParserR private Map> foldsJson(ParserResult info) { final Map> folds = new HashMap<>(); - TokenHierarchy th = info.getSnapshot().getTokenHierarchy(); - TokenSequence ts = th.tokenSequence(language); + TokenHierarchy th = info.getSnapshot().getTokenHierarchy(); + TokenSequence ts = th.tokenSequence(language); List> list = th.tokenSequenceList(ts.languagePath(), 0, info.getSnapshot().getText().length()); List stack = new ArrayList<>(); for (TokenSequenceIterator tsi = new TokenSequenceIterator(list, false); tsi.hasMore();) { @@ -421,6 +421,7 @@ public JsStructureItem(JsObject elementHandle, List chi } @Override + @SuppressWarnings("AccessingNonPublicFieldOfAnotherObject") public boolean equals(Object obj) { if (obj == null) { return false; @@ -479,7 +480,7 @@ public Set getModifiers() { Set modifiers; if (modelElement.getModifiers().isEmpty()) { - modifiers = Collections.EMPTY_SET; + modifiers = Collections.emptySet(); } else { modifiers = EnumSet.noneOf(Modifier.class); modifiers.addAll(modelElement.getModifiers()); diff --git a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsTypedBreakInterceptor.java b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsTypedBreakInterceptor.java index e6069f8b2ec7..986abf7488f0 100644 --- a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsTypedBreakInterceptor.java +++ b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsTypedBreakInterceptor.java @@ -25,6 +25,7 @@ import javax.swing.text.BadLocationException; import javax.swing.text.Document; import org.netbeans.api.editor.document.EditorDocumentUtils; +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.editor.mimelookup.MimeRegistrations; @@ -97,8 +98,8 @@ public void insert(MutableContext context) throws BadLocationException { TokenHierarchy tokenHierarchy = TokenHierarchy.get(doc); int offset = context.getCaretOffset(); - int lineBegin = Utilities.getRowStart(doc, offset); - int lineEnd = Utilities.getRowEnd(doc, offset); + int lineBegin = LineDocumentUtils.getLineStart(doc, offset); + int lineEnd = LineDocumentUtils.getLineEnd(doc, offset); if (lineBegin == offset && lineEnd == offset) { // Pressed return on a blank newline - do nothing @@ -123,9 +124,9 @@ public void insert(MutableContext context) throws BadLocationException { // Insert a missing } if (!id.isError() && isInsertMatchingEnabled() && !isDocToken(id) && isAddRightBrace(doc, offset)) { - int indent = GsfUtilities.getLineIndent(doc, offset); + int indent = GsfUtilities.getLineIndent((Document) doc, offset); - int afterLastNonWhite = Utilities.getRowLastNonWhite(doc, offset); + int afterLastNonWhite = LineDocumentUtils.getLineLastNonWhitespace(doc, offset); // We've either encountered a further indented line, or a line that doesn't // look like the end we're after, so insert a matching end. @@ -151,7 +152,7 @@ public void insert(MutableContext context) throws BadLocationException { // I'm inserting a newline in the middle of a sentence, such as the scenario in #118656 // I should insert the end AFTER the text on the line String restOfLine = doc.getText(offset, - Math.min(end, Utilities.getRowEnd(doc, afterLastNonWhite)) - offset); + Math.min(end, LineDocumentUtils.getLineEnd(doc, afterLastNonWhite)) - offset); sb.append("\n"); // XXX On Windows, do \r\n? sb.append(IndentUtils.createIndentString(doc, indent + IndentUtils.indentLevelSize(doc))); // right brace must be included into the correct context - issue #219683 @@ -180,7 +181,7 @@ public void insert(MutableContext context) throws BadLocationException { // See if it's a block comment opener String text = token.text().toString(); if (comments.test(doc) && text.startsWith("/*") ) { - int indent = GsfUtilities.getLineIndent(doc, ts.offset()); + int indent = GsfUtilities.getLineIndent((Document) doc, ts.offset()); StringBuilder sb = new StringBuilder(); sb.append("\n"); // NOI18N sb.append(IndentUtils.createIndentString(doc, indent)); @@ -245,7 +246,7 @@ public void insert(MutableContext context) throws BadLocationException { return; } } else { - final int indent = GsfUtilities.getLineIndent(doc, offset); + final int indent = GsfUtilities.getLineIndent((Document) doc, offset); final StringBuilder sb = new StringBuilder(); sb.append("\n"); // NOI18N sb.append(IndentUtils.createIndentString(doc, indent + IndentUtils.indentLevelSize(doc))); @@ -273,7 +274,7 @@ public void insert(MutableContext context) throws BadLocationException { JsTokenId prevTokenId = prevToken.id(); if (id == JsTokenId.BRACKET_RIGHT_CURLY && prevTokenId == JsTokenId.BRACKET_LEFT_CURLY || id == JsTokenId.BRACKET_RIGHT_BRACKET && prevTokenId == JsTokenId.BRACKET_LEFT_BRACKET) { - int indent = GsfUtilities.getLineIndent(doc, offset); + int indent = GsfUtilities.getLineIndent((Document) doc, offset); StringBuilder sb = new StringBuilder(); // XXX On Windows, do \r\n? sb.append("\n"); // NOI18N @@ -312,14 +313,14 @@ public void insert(MutableContext context) throws BadLocationException { && offset > ts.offset() && offset < ts.offset()+ts.token().length()) { // Continue *'s int begin = Utilities.getRowFirstNonWhite(doc, offset); - int end = Utilities.getRowEnd(doc, offset)+1; + int end = LineDocumentUtils.getLineEnd(doc, offset)+1; if (begin == -1) { begin = end; } String line = doc.getText(begin, end-begin); boolean isBlockStart = line.startsWith("/*") || (begin != -1 && begin < ts.offset()); if (isBlockStart || line.startsWith("*")) { - int indent = GsfUtilities.getLineIndent(doc, offset); + int indent = GsfUtilities.getLineIndent((Document) doc, offset); StringBuilder sb = new StringBuilder("\n"); if (isBlockStart) { indent++; @@ -345,7 +346,7 @@ public void insert(MutableContext context) throws BadLocationException { // Copy existing indentation inside the block sb.append("*"); //NOI18N int afterStar = isBlockStart ? begin+2 : begin+1; - line = doc.getText(afterStar, Utilities.getRowEnd(doc, afterStar)-afterStar); + line = doc.getText(afterStar, LineDocumentUtils.getLineEnd(doc, afterStar)-afterStar); for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); if (c == ' ' || c == '\t') { //NOI18N @@ -385,7 +386,7 @@ public void insert(MutableContext context) throws BadLocationException { // (and a comment from the beginning, not a trailing comment) boolean previousLineWasComment = false; boolean nextLineIsComment = false; - int rowStart = Utilities.getRowStart(doc, offset); + int rowStart = LineDocumentUtils.getLineStart(doc, offset); if (rowStart > 0) { int prevBegin = Utilities.getRowFirstNonWhite(doc, rowStart - 1); if (prevBegin != -1) { @@ -396,7 +397,7 @@ public void insert(MutableContext context) throws BadLocationException { } } } - int rowEnd = Utilities.getRowEnd(doc, offset); + int rowEnd = LineDocumentUtils.getLineEnd(doc, offset); if (rowEnd < doc.getLength()) { int nextBegin = Utilities.getRowFirstNonWhite(doc, rowEnd + 1); if (nextBegin != -1) { @@ -415,7 +416,7 @@ public void insert(MutableContext context) throws BadLocationException { || (offset > ts.offset() && offset < ts.offset() + ts.token().length())) { if (ts.offset() + token.length() > offset + 1) { // See if the remaining text is just whitespace - String trailing = doc.getText(offset, Utilities.getRowEnd(doc, offset) - offset); + String trailing = doc.getText(offset, LineDocumentUtils.getLineEnd(doc, offset) - offset); if (trailing.trim().length() != 0) { continueComment = true; } @@ -431,7 +432,7 @@ public void insert(MutableContext context) throws BadLocationException { if (!continueComment) { // See if the next line is a comment; if so we want to continue // comments editing the middle of the comment - int nextLine = Utilities.getRowEnd(doc, offset) + 1; + int nextLine = LineDocumentUtils.getLineEnd(doc, offset) + 1; if (nextLine < doc.getLength()) { int nextLineFirst = Utilities.getRowFirstNonWhite(doc, nextLine); if (nextLineFirst != -1) { @@ -447,7 +448,7 @@ public void insert(MutableContext context) throws BadLocationException { if (continueComment) { // Line comments should continue - int indent = GsfUtilities.getLineIndent(doc, offset); + int indent = GsfUtilities.getLineIndent((Document) doc, offset); StringBuilder sb = new StringBuilder(); if (offset != begin || offset <= 0) { sb.append("\n"); @@ -456,7 +457,7 @@ public void insert(MutableContext context) throws BadLocationException { sb.append("//"); // NOI18N // Copy existing indentation int afterSlash = begin + 2; - String line = doc.getText(afterSlash, Utilities.getRowEnd(doc, afterSlash) - afterSlash); + String line = doc.getText(afterSlash, LineDocumentUtils.getLineEnd(doc, afterSlash) - afterSlash); for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); if (c == ' ' || c == '\t') { @@ -515,12 +516,12 @@ public void cancelled(Context context) { * @throws BadLocationException */ private int getNextLineIndentation(BaseDocument doc, int offset) throws BadLocationException { - int indent = GsfUtilities.getLineIndent(doc, offset); + int indent = GsfUtilities.getLineIndent((Document) doc, offset); int currentOffset = offset; while (currentOffset > 0) { - if (!Utilities.isRowEmpty(doc, currentOffset) && !Utilities.isRowWhite(doc, currentOffset) + if (!LineDocumentUtils.isLineEmpty(doc, currentOffset) && !LineDocumentUtils.isLineWhitespace(doc, currentOffset) && !isCommentOnlyLine(doc, currentOffset, language)) { - indent = GsfUtilities.getLineIndent(doc, currentOffset); + indent = GsfUtilities.getLineIndent((Document) doc, currentOffset); int parenBalance = getLineBalance(doc, currentOffset, JsTokenId.BRACKET_LEFT_PAREN, JsTokenId.BRACKET_RIGHT_PAREN); if (parenBalance < 0) { @@ -533,7 +534,7 @@ private int getNextLineIndentation(BaseDocument doc, int offset) throws BadLocat } return indent; } - currentOffset = Utilities.getRowStart(doc, currentOffset) - 1; + currentOffset = LineDocumentUtils.getLineStart(doc, currentOffset) - 1; } return indent; @@ -573,7 +574,7 @@ private boolean isAddRightBrace(BaseDocument doc, int caretOffset) throws BadLoc boolean balancedAfter = false; do { - Token t = ts.token(); + Token t = ts.token(); if (t.id() == JsTokenId.BRACKET_LEFT_CURLY) { balance++; @@ -584,7 +585,7 @@ private boolean isAddRightBrace(BaseDocument doc, int caretOffset) throws BadLoc for (TokenSequenceIterator tsi = new TokenSequenceIterator(TokenHierarchy.get(doc).tokenSequenceList(ts.languagePath(), caretOffset, doc.getLength()), false); tsi.hasMore();) { TokenSequence sq = tsi.getSequence(); - Token t = sq.token(); + Token t = sq.token(); if (t.id() == JsTokenId.BRACKET_LEFT_CURLY) { balance++; @@ -602,7 +603,7 @@ private boolean isAddRightBrace(BaseDocument doc, int caretOffset) throws BadLoc return false; } - int caretRowStartOffset = org.netbeans.editor.Utilities.getRowStart(doc, caretOffset); + int caretRowStartOffset = LineDocumentUtils.getLineStart(doc, caretOffset); ts = LexUtilities.getPositionedSequence(doc, caretOffset, language); if (ts == null) { return false; @@ -617,20 +618,21 @@ private boolean isAddRightBrace(BaseDocument doc, int caretOffset) throws BadLoc } JsTokenId id = ts.token().id(); switch (id) { - case WHITESPACE: - case LINE_COMMENT: - break; - case BLOCK_COMMENT: - case DOC_COMMENT: + case WHITESPACE, LINE_COMMENT -> { + } + case BLOCK_COMMENT, DOC_COMMENT -> { if (first && caretOffset > ts.offset() && caretOffset < ts.offset() + ts.token().length()) { // Caret contained within block comment -> do not add anything return false; } - break; // Skip - case BRACKET_LEFT_CURLY: + // Skip + } + case BRACKET_LEFT_CURLY -> { return !balancedAfter; - default: + } + default -> { return false; + } } first = false; } while (ts.movePrevious()); @@ -645,7 +647,7 @@ private boolean isAddRightBrace(BaseDocument doc, int caretOffset) throws BadLoc * character on the caret row is returned. */ private int getRowOrBlockEnd(BaseDocument doc, int caretOffset, boolean[] insert) throws BadLocationException { - int rowEnd = org.netbeans.editor.Utilities.getRowLastNonWhite(doc, caretOffset); + int rowEnd = LineDocumentUtils.getLineLastNonWhitespace(doc, caretOffset); if (rowEnd == -1 || caretOffset >= rowEnd) { return caretOffset; } @@ -661,34 +663,30 @@ private int getRowOrBlockEnd(BaseDocument doc, int caretOffset, boolean[] insert while (ts.offset() < rowEnd) { JsTokenId id = ts.token().id(); switch (id) { - case OPERATOR_SEMICOLON: + case OPERATOR_SEMICOLON -> { return ts.offset() + 1; - case OPERATOR_COMMA: + } + case OPERATOR_COMMA -> { return ts.offset(); - case BRACKET_LEFT_PAREN: - parenBalance++; - break; - case BRACKET_RIGHT_PAREN: + } + case BRACKET_LEFT_PAREN -> parenBalance++; + case BRACKET_RIGHT_PAREN -> { if (parenBalance-- == 0) { return ts.offset(); } - break; - case BRACKET_LEFT_CURLY: - braceBalance++; - break; - case BRACKET_RIGHT_CURLY: + } + case BRACKET_LEFT_CURLY -> braceBalance++; + case BRACKET_RIGHT_CURLY -> { if (braceBalance-- == 0) { return ts.offset(); } - break; - case BRACKET_LEFT_BRACKET: - bracketBalance++; - break; - case BRACKET_RIGHT_BRACKET: + } + case BRACKET_LEFT_BRACKET -> bracketBalance++; + case BRACKET_RIGHT_BRACKET -> { if (bracketBalance-- == 0) { return ts.offset(); } - break; + } } if (!ts.moveNext()) { // this might happen in embedded case - line is not at the end @@ -714,7 +712,7 @@ private int getUnbalancedCurlyOffset(BaseDocument doc, int offset) throws BadLoc int balance = 0; while (ts.movePrevious()) { - Token t = ts.token(); + Token t = ts.token(); if (t.id() == JsTokenId.BRACKET_RIGHT_CURLY) { balance++; @@ -730,7 +728,7 @@ private int getUnbalancedCurlyOffset(BaseDocument doc, int offset) throws BadLoc private int getCurlyIndent(BaseDocument doc, int offset) { try { - int lineStart = Utilities.getRowStart(doc, offset, 0); + int lineStart = LineDocumentUtils.getLineStart(doc, offset); TokenSequence ts = LexUtilities.getTokenSequence( doc, lineStart, language); @@ -742,7 +740,7 @@ private int getCurlyIndent(BaseDocument doc, int offset) { if (prevLineStart >= 0) { return IndentUtils.lineIndent(doc, lineStart); } else { - return GsfUtilities.getLineIndent(doc, offset); + return GsfUtilities.getLineIndent((Document) doc, offset); } } @@ -770,21 +768,21 @@ private int getCurlyIndent(BaseDocument doc, int offset) { } catch (BadLocationException ex) { LOGGER.log(Level.INFO, null, ex); } - return GsfUtilities.getLineIndent(doc, offset); + return GsfUtilities.getLineIndent((Document) doc, offset); } private boolean isDocToken(JsTokenId id) { return id == JsTokenId.BLOCK_COMMENT || id == JsTokenId.DOC_COMMENT; } - private static boolean hasCommentEnd(TokenSequence ts) { + private static boolean hasCommentEnd(TokenSequence ts) { while (ts.moveNext()) { - Token token = ts.token(); + Token token = ts.token(); if (token.id() == JsDocumentationTokenId.COMMENT_END) { return true; } else if (CharSequenceUtilities.endsWith(token.text(), "/")) { //NOI18N if (ts.moveNext()) { - Token nextToken = ts.token(); + Token nextToken = ts.token(); if (CharSequenceUtilities.textEquals(nextToken.text(), "/")) { //NOI18N ts.movePrevious(); continue; @@ -822,8 +820,8 @@ private static boolean isCommentOnlyLine(BaseDocument doc, int offset, Language< /** Compute the balance of begin/end tokens on the line */ private static int getLineBalance(BaseDocument doc, int offset, TokenId up, TokenId down) { try { - int begin = Utilities.getRowStart(doc, offset); - int end = Utilities.getRowEnd(doc, offset); + int begin = LineDocumentUtils.getLineStart(doc, offset); + int end = LineDocumentUtils.getLineEnd(doc, offset); TokenSequence ts = LexUtilities.getJsTokenSequence(doc, begin); if (ts == null) { diff --git a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsonCodeCompletion.java b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsonCodeCompletion.java index eb9d8515c46c..367edd4b29e1 100644 --- a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsonCodeCompletion.java +++ b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsonCodeCompletion.java @@ -67,7 +67,7 @@ public CodeCompletionResult complete(CodeCompletionContext context) { long start = System.currentTimeMillis(); - Document doc = (Document) context.getParserResult().getSnapshot().getSource().getDocument(false); + Document doc = context.getParserResult().getSnapshot().getSource().getDocument(false); if (doc == null) { return CodeCompletionResult.NONE; } @@ -212,7 +212,7 @@ public String getPrefix( int caretOffset, boolean upToOffset) { String prefix = ""; - Document doc = (Document) info.getSnapshot().getSource().getDocument(false); + Document doc = info.getSnapshot().getSource().getDocument(false); if (doc == null) { return null; } diff --git a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsonLanguage.java b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsonLanguage.java index dbbae04cbdac..29d7eae4e162 100644 --- a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsonLanguage.java +++ b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsonLanguage.java @@ -18,12 +18,14 @@ */ package org.netbeans.modules.javascript2.editor; +import org.netbeans.api.lexer.Language; import org.netbeans.core.spi.multiview.MultiViewElement; import org.netbeans.core.spi.multiview.text.MultiViewEditorElement; import org.netbeans.modules.csl.api.CodeCompletionHandler; import org.netbeans.modules.csl.api.Formatter; import org.netbeans.modules.csl.api.InstantRenamer; import org.netbeans.modules.csl.api.OccurrencesFinder; +import org.netbeans.modules.csl.api.SemanticAnalyzer; import org.netbeans.modules.csl.api.StructureScanner; import org.netbeans.modules.csl.spi.DefaultLanguageConfig; import org.netbeans.modules.csl.spi.LanguageRegistration; @@ -82,7 +84,7 @@ public JsonLanguage() { } @Override - public org.netbeans.api.lexer.Language getLexerLanguage() { + public Language getLexerLanguage() { return JsTokenId.jsonLanguage(); } @@ -97,6 +99,7 @@ public Parser getParser() { } @Override + @SuppressWarnings("deprecation") public boolean hasStructureScanner() { return NAVIGATOR; } @@ -108,10 +111,10 @@ public StructureScanner getStructureScanner() { null; } -// @Override -// public SemanticAnalyzer getSemanticAnalyzer() { -// return new JsSemanticAnalyzer(); -// } + @Override + public SemanticAnalyzer getSemanticAnalyzer() { + return new JsonSemanticAnalyzer(); + } // todo: tzezula - disable for now // @Override diff --git a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsonSemanticAnalyzer.java b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsonSemanticAnalyzer.java new file mode 100644 index 000000000000..c499044f7417 --- /dev/null +++ b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsonSemanticAnalyzer.java @@ -0,0 +1,122 @@ +/* + * 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.javascript2.editor; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import org.netbeans.modules.csl.api.ColoringAttributes; +import org.netbeans.modules.csl.api.OffsetRange; +import org.netbeans.modules.csl.api.SemanticAnalyzer; +import org.netbeans.modules.javascript2.editor.parser.JsonParserResult; +import org.netbeans.modules.javascript2.model.api.JsObject; +import org.netbeans.modules.javascript2.model.api.JsReference; +import org.netbeans.modules.javascript2.model.api.Model; +import org.netbeans.modules.javascript2.model.api.ModelUtils; +import org.netbeans.modules.parsing.spi.Scheduler; +import org.netbeans.modules.parsing.spi.SchedulerEvent; + +public class JsonSemanticAnalyzer extends SemanticAnalyzer { + + private Map> semanticHighlights; + private volatile boolean canceled; + + public JsonSemanticAnalyzer() { + this.canceled = false; + this.semanticHighlights = Collections.emptyMap(); + } + + @Override + @SuppressWarnings("ReturnOfCollectionOrArrayField") + public Map> getHighlights() { + return semanticHighlights; + } + + @Override + public void run(JsonParserResult result, SchedulerEvent event) { + canceled = false; + + if (canceled) { + return; + } + + Map> highlights = new HashMap<>(100); + Model model = Model.getModel(result, false); + highlights = count(result, model.getGlobalObject(), highlights, new HashSet<>()); + + assert highlights != null; + + semanticHighlights = highlights; + } + + @SuppressWarnings("AssignmentToMethodParameter") + private Map> count (JsonParserResult result, JsObject parent, Map> highlights, Set processedObjects) { + if (ModelUtils.wasProcessed(parent, processedObjects)) { + return highlights; + } + for (JsObject object : parent.getProperties().values()) { + if (object.getDeclarationName() != null) { + switch (object.getJSKind()) { + case OBJECT_LITERAL -> { + if(object.getDeclarationName() != null) { + addColoring(result, highlights, object.getDeclarationName().getOffsetRange(), ColoringAttributes.FIELD_SET); + } + } + case PROPERTY -> addColoring(result, highlights, object.getDeclarationName().getOffsetRange(), ColoringAttributes.FIELD_SET); + } + } + if (canceled) { + highlights = Collections.emptyMap(); + break; + } + if (!(object instanceof JsReference jr && ModelUtils.isDescendant(object, jr.getOriginal()))) { + highlights = count(result, object, highlights, processedObjects); + } + } + + return highlights; + } + + private void addColoring(JsonParserResult result, Map> highlights, OffsetRange astRange, Set coloring) { + int start = result.getSnapshot().getOriginalOffset(astRange.getStart()); + int end = result.getSnapshot().getOriginalOffset(astRange.getEnd()); + if (start > -1 && end > -1 && start < end) { + OffsetRange range = start == astRange.getStart() ? astRange : new OffsetRange(start, end); + highlights.put(range, coloring); + } + } + + @Override + public int getPriority() { + return 0; + } + + @Override + public Class getSchedulerClass() { + return Scheduler.EDITOR_SENSITIVE_TASK_SCHEDULER; + } + + @Override + public void cancel() { + this.canceled = true; + } + +} diff --git a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/doc/JsDocCodeTemplateFilter.java b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/doc/JsDocCodeTemplateFilter.java index 5432a3551b62..52df259761af 100644 --- a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/doc/JsDocCodeTemplateFilter.java +++ b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/doc/JsDocCodeTemplateFilter.java @@ -24,10 +24,6 @@ import org.netbeans.lib.editor.codetemplates.api.CodeTemplate; import org.netbeans.lib.editor.codetemplates.spi.CodeTemplateFilter; -/** - * - * @author Petr Pisl - */ /** * * @author Petr Pisl diff --git a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/doc/JsDocumentationCompleter.java b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/doc/JsDocumentationCompleter.java index 50950613e3f7..91c44ec753e4 100644 --- a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/doc/JsDocumentationCompleter.java +++ b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/doc/JsDocumentationCompleter.java @@ -93,8 +93,7 @@ public void run() { @Override public void run(ResultIterator resultIterator) throws Exception { ParserResult parserResult = (ParserResult) resultIterator.getParserResult(offset); - if (parserResult instanceof JsParserResult) { - final JsParserResult jsParserResult = (JsParserResult) parserResult; + if (parserResult instanceof JsParserResult jsParserResult) { if (jsParserResult.getRoot() == null) { // broken source return; @@ -158,12 +157,12 @@ public void run(ResultIterator resultIterator) throws Exception { private static JsObject getWrapperScope(JsParserResult jsParserResult, JsObject jsObject, Node nearestNode, int offset) { JsObject result = null; - if (jsObject instanceof JsFunction) { + if (jsObject instanceof JsFunction jsFunction) { result = jsObject; - for (DeclarationScope declarationScope : ((JsFunction) jsObject).getChildrenScopes()) { - if (declarationScope instanceof JsFunction) { - if (((JsFunction) declarationScope).getOffsetRange(jsParserResult).containsInclusive(offset)) { - result = getWrapperScope(jsParserResult, (JsFunction) declarationScope, nearestNode, offset); + for (DeclarationScope declarationScope : jsFunction.getChildrenScopes()) { + if (declarationScope instanceof JsFunction declarationFunction) { + if (declarationFunction.getOffsetRange(jsParserResult).containsInclusive(offset)) { + result = getWrapperScope(jsParserResult, declarationFunction, nearestNode, offset); } } } @@ -334,8 +333,7 @@ private static Node getNearestNode(JsParserResult parserResult, int offset) { return offsetVisitor.getNearestNode(); } - private static JsObject findJsObjectFunctionVariable(JsObject object, int offset) { - JsObject jsObject = (JsObject) object; + private static JsObject findJsObjectFunctionVariable(JsObject jsObject, int offset) { JsObject result = null; JsObject tmpObject = null; if (jsObject.getOffsetRange().containsInclusive(offset)) { diff --git a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/embedding/JsEmbeddingProvider.java b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/embedding/JsEmbeddingProvider.java index 35a24f76ddba..cfd4261bf62b 100644 --- a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/embedding/JsEmbeddingProvider.java +++ b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/embedding/JsEmbeddingProvider.java @@ -128,28 +128,18 @@ public static boolean containsGeneratedIdentifier(String ident) { // Private implementation // ------------------------------------------------------------------------ private static final Logger LOG = Logger.getLogger(JsEmbeddingProvider.class.getName()); -// private static final String JSP_MIME_TYPE = "text/x-jsp"; // NOI18N -// private static final String TAG_MIME_TYPE = "text/x-tag"; // NOI18N private static final String RHTML_MIME_TYPE = "application/x-httpd-eruby"; // NOI18N private static final String HTML_MIME_TYPE = "text/html"; // NOI18N -// private static final String XHTML_MIME_TYPE = "text/xhtml"; // NOI18N -// private static final String PHP_MIME_TYPE = "text/x-php5"; // NOI18N private static final String TPL_MIME_TYPE = "text/x-tpl"; // NOI18N private static final String TWIG_MIME_TYPE = "text/x-twig"; // NOI18N private static final String LATTE_MIME_TYPE = "text/x-latte"; // NOI18N private static final String JSX_MIME_TYPE = "text/x-jsx"; //NOI18N - //private static final String GSP_TAG_MIME_TYPE = "application/x-gsp"; // NOI18N private static final Map translators = new HashMap<>(); static { -// translators.put(JSP_MIME_TYPE, new JspTranslator()); -// translators.put(TAG_MIME_TYPE, new JspTranslator()); translators.put(RHTML_MIME_TYPE, new RhtmlTranslator()); //the creation of javascript virtual source for files with text/html mimetype //is now handled by o.n.m.html.editor.embedding.JsEmbeddingProvider -// translators.put(HTML_MIME_TYPE, new HtmlTranslator()); -// translators.put(XHTML_MIME_TYPE, new XhtmlTranslator()); -// translators.put(PHP_MIME_TYPE, new PhpTranslator()); translators.put(TPL_MIME_TYPE, new TplTranslator()); translators.put(TWIG_MIME_TYPE, new TwigTranslator()); translators.put(LATTE_MIME_TYPE, new LatteTranslator()); @@ -158,8 +148,6 @@ public static boolean containsGeneratedIdentifier(String ident) { // If you change this, update the testcase reference private static final String GENERATED_IDENTIFIER = "__UNKNOWN__"; // NOI18N - /** PHPTokenId's T_INLINE_HTML name */ - private static final String T_INLINE_HTML = "T_INLINE_HTML"; private final String sourceMimeType; private final Translator translator; @@ -172,159 +160,6 @@ protected interface Translator { public List translate(Snapshot snapshot); } - private static final class JspTranslator implements Translator { - - /** Create a JavaScript model of the given JSP buffer. - * @todo Make this more general purpose (so it can be used from HTML, JSP etc.) - * @param outputBuffer The buffer to emit the translation to - * @param tokenHierarchy The token hierarchy for the RHTML code - * @param tokenSequence The token sequence for the RHTML code - */ - @Override - public List translate(Snapshot snapshot) { - TokenHierarchy th = snapshot.getTokenHierarchy(); - if (th == null) { - //the token hierarchy may be null if the language is not initialized yet - //for example if ergonomics is used and j2ee cluster not activated - return Collections.emptyList(); - } - - TokenSequence tokenSequence = th.tokenSequence(); - List embeddings = new ArrayList<>(); - - //TODO - implement the "classpath" import for other projects - //how is the javascript classpath done????????/ - - JsAnalyzerState state = new JsAnalyzerState(); - - while (tokenSequence.moveNext()) { - Token token = tokenSequence.token(); - - if (token.id().primaryCategory().equals("text")) { // NOI18N - TokenSequence ts = tokenSequence.embedded(HTMLTokenId.language()); - if (ts == null) { - continue; - } - extractJavaScriptFromHtml(snapshot, ts, state, embeddings); - - } else if (token.id().primaryCategory().equals("expression-language") || token.id().primaryCategory().equals("scriptlet") || token.id().primaryCategory().equals("symbol") && "/>".equals(token.text().toString())) { // NOI18N - //The test for jsp /> symbol means - //that we just encountered an end of jsp tag without body - //so it is possible/likely the tag generates something - - //TODO Add a list of know tags and adjust the heuristics according - //to the tag declaration. It may work nicely using the - //JSP parser for getting custom jsp tags metadata. - - //TODO The whole implementation of the JsJspModel - //should be in separate file in JSP module and should - //depend on both lexers instead of these string dependencies. - - if (state.in_inlined_javascript || state.in_javascript) { - embeddings.add(snapshot.create(GENERATED_IDENTIFIER, JsTokenId.JAVASCRIPT_MIME_TYPE)); -// embeddings.add(snapshot.create("/*", JsTokenId.JAVASCRIPT_MIME_TYPE)); -// embeddings.add(snapshot.create(tokenSequence.offset(), token.length() , JsTokenId.JAVASCRIPT_MIME_TYPE)); -// embeddings.add(snapshot.create("*/", JsTokenId.JAVASCRIPT_MIME_TYPE)); - } - } - } - - return embeddings; - } - } // End JspTranslator class - - - private static final class XhtmlTranslator implements Translator { - - @Override - public List translate(Snapshot snapshot) { - TokenHierarchy th = snapshot.getTokenHierarchy(); - if (th == null) { - //the token hierarchy may be null if the language is not initialized yet - //for example if ergonomics is used and j2ee cluster not activated - return Collections.emptyList(); - } - - TokenSequence tokenSequence = th.tokenSequence(); - List embeddings = new ArrayList<>(); - - JsAnalyzerState state = new JsAnalyzerState(); - - while (tokenSequence.moveNext()) { - Token token = tokenSequence.token(); - - if (token.id().primaryCategory().equals("html")) { // NOI18N - TokenSequence ts = tokenSequence.embedded(HTMLTokenId.language()); - if (ts == null) { - continue; - } - extractJavaScriptFromHtml(snapshot, ts, state, embeddings); - - } else if (token.id().primaryCategory().equals("expression-language") ) { // NOI18N - if (state.in_inlined_javascript || state.in_javascript) { - embeddings.add(snapshot.create(GENERATED_IDENTIFIER, JsTokenId.JAVASCRIPT_MIME_TYPE)); - } - } - } - - return embeddings; - } - } - - private static final class PhpTranslator implements Translator { - - @Override - public List translate(Snapshot snapshot) { - TokenHierarchy th = snapshot.getTokenHierarchy(); - if (th == null) { - //likely the php language couldn't be found - LOG.log(Level.INFO, - "Cannot get TokenHierarchy from snapshot {0}", //NOI18N - snapshot); - return Collections.emptyList(); - } - - TokenSequence tokenSequence = th.tokenSequence(); - List embeddings = new ArrayList<>(); - - //TODO - implement the "classpath" import for other projects - //how is the javascript classpath done????????/ - - JsAnalyzerState state = new JsAnalyzerState(); - - while (tokenSequence.moveNext()) { - Token token = tokenSequence.token(); - - if (token.id().name().equals(T_INLINE_HTML)) { // NOI18N - TokenSequence ts = tokenSequence.embedded(HTMLTokenId.language()); - if (ts == null) { - continue; - } - extractJavaScriptFromHtml(snapshot, ts, state, embeddings); - } - if (state.in_inlined_javascript || state.in_javascript) { - //find end of the php code - boolean wasInPhp = false; - boolean hasNext; - while ((hasNext = tokenSequence.moveNext()) && !tokenSequence.token().id().name().equals(T_INLINE_HTML)) { - wasInPhp = true; - } - - if (hasNext) { //do not move back if we are at the end of the sequence = cycle! - //we are out of php code, lets move back to the previous token - tokenSequence.movePrevious(); - } - - if (wasInPhp) { - embeddings.add(snapshot.create(GENERATED_IDENTIFIER, JsTokenId.JAVASCRIPT_MIME_TYPE)); - } - } - } - - return embeddings; - } - } // End of PhpTranslator class - protected static final class TplTranslator implements Translator { private static final String T_HTML = "T_HTML"; //NOI18N @@ -650,7 +485,7 @@ public List translate(Snapshot snapshot) { int from = -1; int len = 0; while (sequence.moveNext()) { - Token t = sequence.token(); + Token t = sequence.token(); if (t.id() == JsTokenId.JSX_TEXT) { if (from < 0) { from = sequence.offset(); @@ -689,21 +524,6 @@ private static void createHtmlEmbedding(List embeddings, Snapshot sna } } - private static final class HtmlTranslator implements Translator { - - @Override - public List translate(Snapshot snapshot) { - TokenSequence tokenSequence = snapshot.getTokenHierarchy().tokenSequence(); - List embeddings = new ArrayList<>(); - JsAnalyzerState state = new JsAnalyzerState(); - @SuppressWarnings("unchecked") - TokenSequence htmlTokenSequence = (TokenSequence) tokenSequence; - extractJavaScriptFromHtml(snapshot, htmlTokenSequence, state, embeddings); - - return embeddings; - } - } // End of HtmlTranslator class - /** @return True if we're still in the middle of an embedded token */ private static void extractJavaScriptFromHtml(Snapshot snapshot, TokenSequence ts, JsAnalyzerState state, List embeddings) { // NOI18N diff --git a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/formatter/JsFormatVisitor.java b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/formatter/JsFormatVisitor.java index 97c12db80085..d629e6b20af5 100644 --- a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/formatter/JsFormatVisitor.java +++ b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/formatter/JsFormatVisitor.java @@ -57,6 +57,7 @@ import java.util.Collections; import java.util.EnumSet; import java.util.List; +import java.util.Objects; import java.util.Set; import org.netbeans.api.lexer.Token; import org.netbeans.api.lexer.TokenSequence; @@ -66,7 +67,7 @@ * * @author Petr Hejl */ -public class JsFormatVisitor extends NodeVisitor { +public class JsFormatVisitor extends NodeVisitor { private static final Set UNARY_TYPES = EnumSet.noneOf(TokenType.class); @@ -217,7 +218,7 @@ public boolean enterWhileNode(WhileNode whileNode) { if (whileNode.isDoWhile()) { // within parens spaces int leftStart; - Block body = whileNode.getBody(); +// Block body = whileNode.getBody(); // if (isVirtual(body)) { // // unfortunately due to condition at the end of do-while // // we have to care about virtual block @@ -236,7 +237,7 @@ public boolean enterWhileNode(WhileNode whileNode) { if (whileToken != null) { FormatToken beforeWhile = whileToken.previous(); if (beforeWhile != null) { - tokenUtils.appendToken(beforeWhile, FormatToken.forFormat(FormatToken.Kind.BEFORE_WHILE_KEYWORD)); + TokenUtils.appendToken(beforeWhile, FormatToken.forFormat(FormatToken.Kind.BEFORE_WHILE_KEYWORD)); } } if (handleLoop(whileNode, FormatToken.Kind.AFTER_DO_START)) { @@ -403,13 +404,13 @@ public boolean enterFunctionNode(FunctionNode functionNode) { List statements = body.getStatements(); if (!statements.isEmpty()) { Statement last = statements.get(statements.size() - 1); - if (last instanceof BlockStatement) { - body = ((BlockStatement) last).getBlock(); + if (last instanceof BlockStatement blockStatement) { + body = blockStatement.getBlock(); } } } if (isVirtual(body) && functionNode.getKind() == FunctionNode.Kind.ARROW) { - Token nonEmpty = tokenUtils.getPreviousNonEmptyToken(getStart(body)); + Token nonEmpty = tokenUtils.getPreviousNonEmptyToken(getStart(body)); if (nonEmpty != null) { FormatToken token = tokenStream.getToken(ts.offset()); if (token != null) { @@ -703,11 +704,11 @@ public boolean enterObjectNode(ObjectNode objectNode) { PropertyNode propertyNode = (PropertyNode) property; if (propertyNode.getGetter() != null) { - FunctionNode getter = (FunctionNode) propertyNode.getGetter(); + FunctionNode getter = propertyNode.getGetter(); markPropertyFinish(getFinish(getter), objectFinish, false); } if (propertyNode.getSetter() != null) { - FunctionNode setter = (FunctionNode) propertyNode.getSetter(); + FunctionNode setter = propertyNode.getSetter(); markPropertyFinish(getFinish(setter), objectFinish, false); } @@ -899,7 +900,7 @@ public boolean enterTryNode(TryNode tryNode) { } @Override - public boolean enterLiteralNode(LiteralNode literalNode) { + public boolean enterLiteralNode(LiteralNode literalNode) { Object value = literalNode.getValue(); if (value instanceof Node[]) { int start = getStart(literalNode); @@ -953,7 +954,7 @@ public boolean enterVarNode(VarNode varNode) { return false; } int finish = getFinish(varNode) - 1; - Token nextToken = tokenUtils.getNextNonEmptyToken(finish); + Token nextToken = tokenUtils.getNextNonEmptyToken(finish); if (nextToken != null && nextToken.id() == JsTokenId.OPERATOR_COMMA) { FormatToken formatToken = tokenStream.getToken(ts.offset()); if (formatToken != null) { @@ -1017,7 +1018,7 @@ private void handleFunctionParameters(FunctionNode functionNode, FormatToken lef if (paramToken != null) { // there might be "a, ...z" for example so we want the mark before the rest // parameter - Token previousNonEmpty = tokenUtils.getPreviousNonEmptyToken(paramToken.getOffset()); + Token previousNonEmpty = tokenUtils.getPreviousNonEmptyToken(paramToken.getOffset()); if (previousNonEmpty != null && previousNonEmpty.id() == JsTokenId.OPERATOR_REST) { paramToken = tokenStream.getToken(ts.offset()); } @@ -1033,10 +1034,9 @@ private void handleFunctionParameters(FunctionNode functionNode, FormatToken lef private void handleFunctionCallChain(CallNode callNode) { Node function = callNode.getFunction(); - if (function instanceof AccessNode) { - Node base = ((AccessNode) function).getBase(); - if (base instanceof CallNode) { - CallNode chained = (CallNode) base; + if (function instanceof AccessNode accessNode) { + Node base = accessNode.getBase(); + if (base instanceof CallNode chained) { int finish = getFinish(chained); FormatToken formatToken = tokenUtils.getNextToken(finish, JsTokenId.OPERATOR_DOT); if (formatToken != null) { @@ -1087,6 +1087,7 @@ private void handleVirtualBlock(Block block, FormatToken.Kind afterBlock) { afterBlock, true); } + @SuppressWarnings({"NestedAssignment", "AssertWithSideEffects"}) private void handleVirtualBlock(Block block, FormatToken.Kind indentationInc, FormatToken.Kind indentationDec, FormatToken.Kind afterBlock, boolean markStatements) { @@ -1117,7 +1118,7 @@ private void handleVirtualBlock(Block block, FormatToken.Kind indentationInc, //Node statement = block.getStatements().get(0); // indentation mark & block start - Token token = tokenUtils.getPreviousNonEmptyToken(getStart(block)); + Token token = tokenUtils.getPreviousNonEmptyToken(getStart(block)); if (token != null) { FormatToken formatToken = tokenStream.getToken(ts.offset()); @@ -1176,12 +1177,12 @@ private void handleBlockContent(List statements, boolean markStatemen * the second b=2. So we iterate subsequent VarNodes searching the * last one and the proper finish token. */ - if (statement instanceof VarNode) { - if (((VarNode) statement).isDestructuring()) { + if (statement instanceof VarNode varNode) { + if (varNode.isDestructuring()) { destructuring = true; continue; } - if (!isDeclaration((VarNode) statement)) { + if (!isDeclaration(varNode)) { int index = i + 1; Node lastVarNode = statement; @@ -1191,7 +1192,7 @@ private void handleBlockContent(List statements, boolean markStatemen i--; break; } else { - Token token = tokenUtils.getPreviousNonEmptyToken(getStart(next)); + Token token = tokenUtils.getPreviousNonEmptyToken(getStart(next)); if (token != null && (JsTokenId.KEYWORD_VAR == token.id() || JsTokenId.KEYWORD_CONST == token.id() || JsTokenId.RESERVED_LET == token.id())) { @@ -1233,23 +1234,22 @@ private void handleBlockContent(List statements, boolean markStatemen } } - private void handleClassElement(PropertyNode property, int start) { - property.accept(this); + private void handleClassElement(PropertyNode propertyNode, int start) { + propertyNode.accept(this); - PropertyNode propertyNode = (PropertyNode) property; if (propertyNode.getGetter() != null) { - FunctionNode getter = (FunctionNode) propertyNode.getGetter(); + FunctionNode getter = propertyNode.getGetter(); markClassElementFinish(getStart(getter), getFinish(getter), start, false, propertyNode.getGetter()); } if (propertyNode.getSetter() != null) { - FunctionNode setter = (FunctionNode) propertyNode.getSetter(); + FunctionNode setter = propertyNode.getSetter(); markClassElementFinish(getStart(setter), getFinish(setter), start, false, propertyNode.getSetter()); } // mark property end - markClassElementFinish(getStart(property), getFinish(property), start, + markClassElementFinish(getStart(propertyNode), getFinish(propertyNode), start, true, propertyNode.getValue()); } @@ -1402,9 +1402,9 @@ private FormatToken getCaseEndToken(int start, int finish) { return null; } - Token ret = null; + Token ret = null; while (ts.moveNext()) { - Token token = ts.token(); + Token token = ts.token(); if ((token.id() != JsTokenId.BLOCK_COMMENT && token.id() != JsTokenId.DOC_COMMENT && token.id() != JsTokenId.LINE_COMMENT && token.id() != JsTokenId.EOL && token.id() != JsTokenId.WHITESPACE)) { @@ -1415,7 +1415,7 @@ private FormatToken getCaseEndToken(int start, int finish) { if (ret != null) { while (ts.movePrevious() && ts.offset() >= start) { - Token current = ts.token(); + Token current = ts.token(); if (current.id() != JsTokenId.WHITESPACE) { ret = current; break; @@ -1428,13 +1428,14 @@ private FormatToken getCaseEndToken(int start, int finish) { } private int getStart(Node node) { + Objects.requireNonNull(node); // unfortunately in binary node the token represents operator // so string fix would not work - if (node instanceof BinaryNode) { - return getStart((BinaryNode) node); + if (node instanceof BinaryNode binaryNode) { + return getStart(binaryNode); } - if (node instanceof FunctionNode) { - return getFunctionStart((FunctionNode) node); + if (node instanceof FunctionNode functionNode) { + return getFunctionStart(functionNode); } // All this magic is because nashorn nodes and tokens don't contain the // quotes for string. Due to this we call this method to add 1 to start @@ -1466,8 +1467,7 @@ private static int getFunctionStart(FunctionNode node) { private int getFinish(Node node) { // we are fixing the wrong finish offset here // only function node has last token - if (node instanceof FunctionNode) { - FunctionNode function = (FunctionNode) node; + if (node instanceof FunctionNode function) { if (node.getStart() == node.getFinish()) { long lastToken = function.getLastToken(); TokenType type = com.oracle.js.parser.Token.descType(lastToken); @@ -1495,12 +1495,11 @@ private int getFinish(Node node) { return getFinish(fn); } } - } else if (node instanceof VarNode) { - VarNode var = (VarNode) node; + } else if (node instanceof VarNode var) { if (var.getInit() instanceof ClassNode) { return getFinish(var.getInit()); } - Token token = tokenUtils.getNextNonEmptyToken(getFinishFixed(node) - 1); + Token token = tokenUtils.getNextNonEmptyToken(getFinishFixed(node) - 1); if (token != null && JsTokenId.OPERATOR_SEMICOLON == token.id()) { return ts.offset() + 1; } else { @@ -1546,8 +1545,8 @@ private boolean isDeclaration(VarNode varNode) { if (varNode.isFunctionDeclaration() || varNode.isExport() || varNode.isDestructuring()) { return true; } - if (varNode.getInit() instanceof ClassNode) { - IdentNode cIdent = ((ClassNode) varNode.getInit()).getIdent(); + if (varNode.getInit() instanceof ClassNode classNode) { + IdentNode cIdent = classNode.getIdent(); IdentNode vIdent = varNode.getName(); // this is artificial var node for simple class declaration if (cIdent != null diff --git a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/formatter/TokenUtils.java b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/formatter/TokenUtils.java index 1a4546664b6a..04228959e7fc 100644 --- a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/formatter/TokenUtils.java +++ b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/formatter/TokenUtils.java @@ -94,16 +94,16 @@ private FormatToken getToken(int offset, JsTokenId expected, boolean backward, return null; } - public Token getPreviousNonEmptyToken(int offset) { + public Token getPreviousNonEmptyToken(int offset) { ts.move(offset); if (!ts.moveNext() && !ts.movePrevious()) { return null; } - Token ret = null; + Token ret = null; while (ts.movePrevious()) { - Token token = ts.token(); + Token token = ts.token(); if ((token.id() != JsTokenId.BLOCK_COMMENT && token.id() != JsTokenId.DOC_COMMENT && token.id() != JsTokenId.LINE_COMMENT && token.id() != JsTokenId.EOL && token.id() != JsTokenId.WHITESPACE)) { @@ -114,16 +114,16 @@ public Token getPreviousNonEmptyToken(int offset) { return ret; } - public Token getNextNonEmptyToken(int offset) { + public Token getNextNonEmptyToken(int offset) { ts.move(offset); if (!ts.moveNext() && !ts.movePrevious()) { return null; } - Token ret = null; + Token ret = null; while (ts.moveNext()) { - Token token = ts.token(); + Token token = ts.token(); if ((token.id() != JsTokenId.BLOCK_COMMENT && token.id() != JsTokenId.DOC_COMMENT && token.id() != JsTokenId.LINE_COMMENT && token.id() != JsTokenId.EOL && token.id() != JsTokenId.WHITESPACE)) { @@ -146,9 +146,9 @@ public FormatToken getPreviousNonWhiteToken(int offset, int stop, JsTokenId expe return ret; } - Token token = null; + Token token = null; while (ts.movePrevious() && ts.offset() >= stop) { - Token current = ts.token(); + Token current = ts.token(); if (current.id() != JsTokenId.WHITESPACE) { token = current; break; diff --git a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/hints/GlobalIsNotDefined.java b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/hints/GlobalIsNotDefined.java index 96a9e80d15ee..e138b6724dcb 100644 --- a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/hints/GlobalIsNotDefined.java +++ b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/hints/GlobalIsNotDefined.java @@ -206,7 +206,10 @@ public AddJsHintFix(final Snapshot snapshot, final int offset, final String name @Override - @NbBundle.Messages({"AddGlobalJsHint_Description=Generate JsHint global directive for variable {0}"}) + @NbBundle.Messages({ + "# {0} - name of variable", + "AddGlobalJsHint_Description=Generate JsHint global directive for variable {0}" + }) public String getDescription() { return Bundle.AddGlobalJsHint_Description(this.name); } diff --git a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/parser/JsParser.java b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/parser/JsParser.java index 2f6fc62dc93a..8c91c04b6b6b 100644 --- a/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/parser/JsParser.java +++ b/webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/parser/JsParser.java @@ -81,7 +81,9 @@ protected JsParserResult parseSource(SanitizingParser.Context context, JsErrorMa } parsableText = sb.toString(); } - if (caretOffset > 0 && parsableText.charAt(caretOffset - 1) == '.' + if (caretOffset > 0 + && caretOffset < parsableText.length() + && parsableText.charAt(caretOffset - 1) == '.' && (parsableText.length() > caretOffset) && Character.isWhitespace(parsableText.charAt(caretOffset))) { // we are expecting that the dot was just written. See issue #246006 diff --git a/webcommon/javascript2.editor/test/qa-functional/src/org/netbeans/modules/javascript2/editor/qaf/cc/EmbeddedHTMLTest.java b/webcommon/javascript2.editor/test/qa-functional/src/org/netbeans/modules/javascript2/editor/qaf/cc/EmbeddedHTMLTest.java index 81ece511ba55..5fd1b39bce81 100644 --- a/webcommon/javascript2.editor/test/qa-functional/src/org/netbeans/modules/javascript2/editor/qaf/cc/EmbeddedHTMLTest.java +++ b/webcommon/javascript2.editor/test/qa-functional/src/org/netbeans/modules/javascript2/editor/qaf/cc/EmbeddedHTMLTest.java @@ -82,7 +82,7 @@ public void testSimplePrototype() { checkCompletionItems(cjo, res); String[] res2 = {"foo"}; checkCompletionDoesntContainItems(cjo, res2); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -108,7 +108,7 @@ public void testPrototypeInheritance() { String[] res = {"test", "value"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -129,7 +129,7 @@ public void testLearning() { String[] res = {"learn"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -148,7 +148,7 @@ public void testSetterGetter() { String[] res = {"name", "myname"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -169,7 +169,7 @@ public void testDOMReferences() { String[] res = {"firstChild", "removeChild"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -187,7 +187,7 @@ public void testObjectLiteral() { String[] res = {"value", "increment"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -208,7 +208,7 @@ public void testObjectFunction() { String[] res = {"param1"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); type(eo, "param1; var pr = 1; this.start = function(){}; "); type(eo, " function secret(){};\n "); @@ -221,7 +221,7 @@ public void testObjectFunction() { String[] res5 = {"name", "start", "pr", "param1", "secret"}; cjo = completion.listItself; checkCompletionItems(cjo, res5); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); type(eo, "Foo.prototype.setName = function(n){ this.;}"); @@ -233,7 +233,7 @@ public void testObjectFunction() { String[] res4 = {"name", "start"}; cjo = completion.listItself; checkCompletionItems(cjo, res4); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); type(eo, "name"); eo.setCaretPosition("", true); @@ -247,7 +247,7 @@ public void testObjectFunction() { String[] res6 = {"Foo"}; cjo = completion.listItself; checkCompletionItems(cjo, res6); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); type(eo, "Foo(); o. "); eo.setCaretPosition("Foo(); o.", false); @@ -258,12 +258,12 @@ public void testObjectFunction() { String[] res2 = {"name", "start", "setName"}; cjo = completion.listItself; checkCompletionItems(cjo, res2); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); // private variable & method String[] res3 = {"secret", "pr"}; checkCompletionDoesntContainItems(cjo, res3); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -294,7 +294,7 @@ public void testAllCompletionMultipleFiles() { String[] res2 = {"cc", "dd"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res2); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } diff --git a/webcommon/javascript2.editor/test/qa-functional/src/org/netbeans/modules/javascript2/editor/qaf/cc/JSObjectsTest.java b/webcommon/javascript2.editor/test/qa-functional/src/org/netbeans/modules/javascript2/editor/qaf/cc/JSObjectsTest.java index aa6b92436889..17fb52061f6c 100644 --- a/webcommon/javascript2.editor/test/qa-functional/src/org/netbeans/modules/javascript2/editor/qaf/cc/JSObjectsTest.java +++ b/webcommon/javascript2.editor/test/qa-functional/src/org/netbeans/modules/javascript2/editor/qaf/cc/JSObjectsTest.java @@ -96,7 +96,7 @@ public void testObject(String[] lines, String[] result) { CompletionInfo completion = getCompletion(); CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, result); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); } public void testLiteralArray() { diff --git a/webcommon/javascript2.editor/test/qa-functional/src/org/netbeans/modules/javascript2/editor/qaf/cc/TestCC.java b/webcommon/javascript2.editor/test/qa-functional/src/org/netbeans/modules/javascript2/editor/qaf/cc/TestCC.java index 57705ce47850..6ae268376df5 100644 --- a/webcommon/javascript2.editor/test/qa-functional/src/org/netbeans/modules/javascript2/editor/qaf/cc/TestCC.java +++ b/webcommon/javascript2.editor/test/qa-functional/src/org/netbeans/modules/javascript2/editor/qaf/cc/TestCC.java @@ -89,7 +89,7 @@ public void testSimplePrototype() { checkCompletionItems(cjo, res); String[] res2 = {"foo"}; checkCompletionDoesntContainItems(cjo, res2); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); cleanFile(eo); endTest(); @@ -120,7 +120,7 @@ public void testPrototypeInheritance() { String[] res = {"test", "value"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -143,7 +143,7 @@ public void testCallAndApply() { String[] res = {"call", "apply"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -166,7 +166,7 @@ public void testLearning() { String[] res = {"learn"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -186,7 +186,7 @@ public void testSetterGetter(){ String[] res = {"name", "myname"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -208,7 +208,7 @@ public void testDOMReferences() { String[] res = {"firstChild", "removeChild"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -227,7 +227,7 @@ public void testIssue215394() { CompletionInfo completion = getCompletion(); CompletionJListOperator cjo = completion.listItself; assertTrue("", (cjo.getCompletionItems().size() > 2 ? true : false)); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } catch (Exception ex) { @@ -251,7 +251,7 @@ public void testObjectLiteral() { String[] res = {"value", "increment"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); @@ -271,7 +271,7 @@ public void testObjectFunction() { String[] res = {"param1"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); type(eo, "param1;\n var pr = 1;\n this.start = function(){\n"); eo.setCaretPositionToEndOfLine(eo.getLineNumber() + 1); @@ -286,7 +286,7 @@ public void testObjectFunction() { String[] res5 = {"name", "start", "pr", "param1", "secret"}; cjo = completion.listItself; checkCompletionItems(cjo, res5); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); type(eo, "\n Foo.prototype.setName = function(n){\n this."); @@ -296,7 +296,7 @@ public void testObjectFunction() { String[] res4 = {"name", "start", "setName"}; cjo = completion.listItself; checkCompletionItems(cjo, res4); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); type(eo, "name;"); eo.setCaretPositionToEndOfLine(eo.getLineNumber() + 2); @@ -311,7 +311,7 @@ public void testObjectFunction() { String[] res6 = {"Foo"}; cjo = completion.listItself; checkCompletionItems(cjo, res6); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); type(eo, "Foo();\n o."); // public variable & method & prototype @@ -320,12 +320,12 @@ public void testObjectFunction() { String[] res2 = {"name", "start", "setName"}; cjo = completion.listItself; checkCompletionItems(cjo, res2); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); // private variable & method String[] res3 = {"secret", "pr"}; checkCompletionDoesntContainItems(cjo, res3); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -347,7 +347,7 @@ public void testIssue215393() { String[] res = {"insertBefore"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -376,7 +376,7 @@ public void testAllCompletionSingleFile() { String[] res2 = {"aa", "bb"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res2); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); type(eo, "aa"); eo.save(); @@ -406,7 +406,7 @@ public void testAllCompletionMultipleFiles() { String[] res2 = {"aa", "bb", "cc", "dd"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res2); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } diff --git a/webcommon/javascript2.editor/test/qa-functional/src/org/netbeans/modules/javascript2/editor/qaf/cc/TestCCInsideWith.java b/webcommon/javascript2.editor/test/qa-functional/src/org/netbeans/modules/javascript2/editor/qaf/cc/TestCCInsideWith.java index f1ccd9185823..fcbcc6239e55 100644 --- a/webcommon/javascript2.editor/test/qa-functional/src/org/netbeans/modules/javascript2/editor/qaf/cc/TestCCInsideWith.java +++ b/webcommon/javascript2.editor/test/qa-functional/src/org/netbeans/modules/javascript2/editor/qaf/cc/TestCCInsideWith.java @@ -88,7 +88,7 @@ public void testSimplePrototype() { checkCompletionItems(cjo, res); String[] res2 = {"foo"}; checkCompletionDoesntContainItems(cjo, res2); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); cleanFile(eo); endTest(); @@ -119,7 +119,7 @@ public void testPrototypeInheritance() { String[] res = {"test", "value"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -142,7 +142,7 @@ public void testCallAndApply() { String[] res = {"call", "apply"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -165,7 +165,7 @@ public void testLearning() { String[] res = {"learn"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -185,7 +185,7 @@ public void testSetterGetter() { String[] res = {"name", "myname"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -207,7 +207,7 @@ public void testDOMReferences() { String[] res = {"firstChild", "removeChild"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -226,7 +226,7 @@ public void testIssue215394() { GeneralJavaScript.CompletionInfo completion = getCompletion(); CompletionJListOperator cjo = completion.listItself; assertTrue("", (cjo.getCompletionItems().size() > 2 ? true : false)); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } catch (Exception ex) { @@ -251,7 +251,7 @@ public void testObjectLiteral() { String[] res = {"value", "increment"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -271,7 +271,7 @@ public void testObjectFunction() { String[] res = {"param1"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); type(eo, "param1;\n var pr = 1;\n this.start = function(){\n"); eo.setCaretPositionToEndOfLine(eo.getLineNumber() + 1); @@ -286,7 +286,7 @@ public void testObjectFunction() { String[] res5 = {"name", "start", "pr", "param1", "secret"}; cjo = completion.listItself; checkCompletionItems(cjo, res5); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); type(eo, "\n Foo.prototype.setName = function(n){\n this."); @@ -296,7 +296,7 @@ public void testObjectFunction() { String[] res4 = {"name", "start", "setName"}; cjo = completion.listItself; checkCompletionItems(cjo, res4); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); type(eo, "name;"); eo.setCaretPositionToEndOfLine(eo.getLineNumber() + 2); @@ -311,7 +311,7 @@ public void testObjectFunction() { String[] res6 = {"Foo"}; cjo = completion.listItself; checkCompletionItems(cjo, res6); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); type(eo, "Foo();\n o."); // public variable & method & prototype @@ -320,12 +320,12 @@ public void testObjectFunction() { String[] res2 = {"name", "start", "setName"}; cjo = completion.listItself; checkCompletionItems(cjo, res2); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); // private variable & method String[] res3 = {"secret", "pr"}; checkCompletionDoesntContainItems(cjo, res3); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -347,7 +347,7 @@ public void testIssue215393() { String[] res = {"insertBefore"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -376,7 +376,7 @@ public void testAllCompletionSingleFile() { String[] res2 = {"aa", "bb"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res2); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); type(eo, "aa"); eo.save(); @@ -406,7 +406,7 @@ public void testAllCompletionMultipleFiles() { String[] res2 = {"aa", "bb", "cc", "dd"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res2); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } diff --git a/webcommon/javascript2.editor/test/qa-functional/src/org/netbeans/modules/javascript2/editor/qaf/cc/TestJQuery.java b/webcommon/javascript2.editor/test/qa-functional/src/org/netbeans/modules/javascript2/editor/qaf/cc/TestJQuery.java index 5bdc45a47456..e5331e4941fd 100644 --- a/webcommon/javascript2.editor/test/qa-functional/src/org/netbeans/modules/javascript2/editor/qaf/cc/TestJQuery.java +++ b/webcommon/javascript2.editor/test/qa-functional/src/org/netbeans/modules/javascript2/editor/qaf/cc/TestJQuery.java @@ -99,7 +99,7 @@ public void testChainCC() { String[] res = {"add", "addClass", "ajaxComplete", "ajaxError", "ajaxSend", "ajaxStart", "animate", "before"}; CompletionJListOperator cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); type(eo, "add()."); evt.waitNoEvent(100); @@ -107,7 +107,7 @@ public void testChainCC() { completion = getCompletion(); cjo = completion.listItself; checkCompletionItems(cjo, res); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -129,7 +129,7 @@ public void testCCMethod() { checkCompletionItems(cjo, res); String[] res2 = {"add"}; checkCompletionDoesntContainItems(cjo, res2); - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); endTest(); } @@ -190,7 +190,7 @@ public void simpleCase(String toType, String[] toFind, String[] notToFind) { if (notToFind.length > 0) { checkCompletionDoesntContainItems(cjo, notToFind); } - completion.listItself.hideAll(); + CompletionJListOperator.hideAll(); } public void testMultipleSelectors() { diff --git a/webcommon/javascript2.editor/test/unit/data/testfiles/simple.json.semantic b/webcommon/javascript2.editor/test/unit/data/testfiles/simple.json.semantic new file mode 100644 index 000000000000..59f09ec38169 --- /dev/null +++ b/webcommon/javascript2.editor/test/unit/data/testfiles/simple.json.semantic @@ -0,0 +1,14 @@ +{|>FIELD:"menu"<|: { + |>FIELD:"id"<|: 2e10, + |>FIELD:"value"<|: "File", + |>FIELD:"x"<| : 1.5, + |>FIELD:"y"<| : 2.5e-5, + |>FIELD:"q"<| : -7, + |>FIELD:"popup"<|: { + |>FIELD:"menuitem"<|: ["", + {|>FIELD:"value"<|: "New", |>FIELD:"onclick"<|: "CreateNewDoc()"}, + {|>FIELD:"value"<|: "Open", |>FIELD:"onclick"<|: "OpenDoc()"}, + {|>FIELD:"value"<|: "Close", |>FIELD:"onclick"<|: "CloseDoc()"} + ] + } +}} \ No newline at end of file diff --git a/webcommon/javascript2.editor/test/unit/src/org/netbeans/modules/javascript2/editor/JsCamelCaseInterceptorTest.java b/webcommon/javascript2.editor/test/unit/src/org/netbeans/modules/javascript2/editor/JsCamelCaseInterceptorTest.java index 7ff4a4ab584a..ee20e73dfa8b 100644 --- a/webcommon/javascript2.editor/test/unit/src/org/netbeans/modules/javascript2/editor/JsCamelCaseInterceptorTest.java +++ b/webcommon/javascript2.editor/test/unit/src/org/netbeans/modules/javascript2/editor/JsCamelCaseInterceptorTest.java @@ -62,7 +62,12 @@ public void checkNextWordOffset(String text, int expected, boolean reverse) { sb.append(text.substring(0, index)); sb.append(text.substring(index + 1)); BaseDocument document = getDocument(sb.toString(), JsTokenId.JAVASCRIPT_MIME_TYPE); - int newOffset = JsCamelCaseInterceptor.getWordOffset(document, index, reverse); - assertEquals(expected, newOffset); + document.readLock(); + try { + int newOffset = JsCamelCaseInterceptor.getWordOffset(document, index, reverse); + assertEquals(expected, newOffset); + } finally { + document.readUnlock(); + } } } diff --git a/webcommon/javascript2.editor/test/unit/src/org/netbeans/modules/javascript2/editor/JsWithBase.java b/webcommon/javascript2.editor/test/unit/src/org/netbeans/modules/javascript2/editor/JsWithBase.java index 7540c7abaf1a..b2e36dbdc75b 100644 --- a/webcommon/javascript2.editor/test/unit/src/org/netbeans/modules/javascript2/editor/JsWithBase.java +++ b/webcommon/javascript2.editor/test/unit/src/org/netbeans/modules/javascript2/editor/JsWithBase.java @@ -79,6 +79,7 @@ protected void assertDescriptionMatches(FileObject fileObject, } @Override + @SuppressWarnings({"rawtypes", "unchecked"}) protected void checkOccurrences(String relFilePath, String caretLine, final boolean symmetric) throws Exception { Source testSource = getTestSource(getTestFile(relFilePath)); @@ -146,7 +147,7 @@ protected void checkSemantic(final String relFilePath, final String caretLine) t highlights = Collections.emptyMap(); } - Document doc = GsfUtilities.getDocument(pr.getSnapshot().getSource().getFileObject(), true); + Document doc = GsfUtilities.getADocument(pr.getSnapshot().getSource().getFileObject(), true); checkNoOverlaps(highlights.keySet(), doc); String annotatedSource = annotateSemanticResults(doc, highlights); diff --git a/webcommon/javascript2.editor/test/unit/src/org/netbeans/modules/javascript2/editor/JsonSemanticAnalyzerTest.java b/webcommon/javascript2.editor/test/unit/src/org/netbeans/modules/javascript2/editor/JsonSemanticAnalyzerTest.java new file mode 100644 index 000000000000..184a02fbf64e --- /dev/null +++ b/webcommon/javascript2.editor/test/unit/src/org/netbeans/modules/javascript2/editor/JsonSemanticAnalyzerTest.java @@ -0,0 +1,47 @@ +/* + * 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.javascript2.editor; + +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import org.netbeans.spi.queries.FileEncodingQueryImplementation; +import org.openide.filesystems.FileObject; + +public class JsonSemanticAnalyzerTest extends JsonTestBase { + + public JsonSemanticAnalyzerTest(String testName) { + super(testName); + } + + @Override + protected Object[] createExtraMockLookupContent() { + return new Object[]{ + new FileEncodingQueryImplementation() { + @Override + public Charset getEncoding(FileObject file) { + return StandardCharsets.UTF_8; + } + } + }; + } + + public void testJsonSemanticHighlighting() throws Exception { + checkSemantic("testfiles/simple.json"); + } +} diff --git a/webcommon/javascript2.editor/test/unit/src/org/netbeans/modules/javascript2/editor/hint/JsGlobalIsNotDeclaredTest.java b/webcommon/javascript2.editor/test/unit/src/org/netbeans/modules/javascript2/editor/hint/JsGlobalIsNotDeclaredTest.java index abda511b5dac..43911f763085 100644 --- a/webcommon/javascript2.editor/test/unit/src/org/netbeans/modules/javascript2/editor/hint/JsGlobalIsNotDeclaredTest.java +++ b/webcommon/javascript2.editor/test/unit/src/org/netbeans/modules/javascript2/editor/hint/JsGlobalIsNotDeclaredTest.java @@ -38,6 +38,7 @@ * @author Petr Pisl */ public class JsGlobalIsNotDeclaredTest extends HintTestBase { + private static boolean CLEAN_CACHE_DIR = true; public JsGlobalIsNotDeclaredTest(String testName) { @@ -45,6 +46,7 @@ public JsGlobalIsNotDeclaredTest(String testName) { } private static class GlobalIsNotDefinedHint extends GlobalIsNotDefined { + @Override public HintSeverity getDefaultSeverity() { return HintSeverity.WARNING; @@ -135,7 +137,7 @@ protected boolean cleanCacheDir() { // The cache dir also holds the index cache - if the cache is cleared, // the runtime of the tests increased ten-fold (the core stubs take // around 2s, the dom stubs 8s)) - if(CLEAN_CACHE_DIR) { + if (CLEAN_CACHE_DIR) { CLEAN_CACHE_DIR = false; return true; } else { @@ -149,8 +151,8 @@ protected Map createClassPathsForTest() { // Both the core stubs and the dom-stubs need to be made available cpRoots.addAll(ClasspathProviderImplAccessor.getJsStubs()); return Collections.singletonMap( - JS_SOURCE_ID, - ClassPathSupport.createClassPath(cpRoots.toArray(new FileObject[0])) + JS_SOURCE_ID, + ClassPathSupport.createClassPath(cpRoots.toArray(new FileObject[0])) ); }