Java Code Examples for javax.lang.model.SourceVersion#isKeyword()
The following examples show how to use
javax.lang.model.SourceVersion#isKeyword() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JetTemplateCodeVisitor.java From jetbrick-template-1x with Apache License 2.0 | 6 votes |
private String assert_java_identifier(ParseTree node, boolean isDefining) { String name = node.getText(); if ("for".equals(name)) { if (isDefining) { throw reportError("Syntax error on token \"" + name + "\" is not a valid identifier.", node); } return name; } if (Code.CONTEXT_NAME.equals(name)) { if (isDefining) { throw reportError("Duplicate local variable \"" + name + "\" is a reserved identifier.", node); } return name; } if (SourceVersion.isKeyword(name)) { throw reportError("Syntax error on token \"" + name + "\", It is not a valid identifier in Java.", node); } if (name.startsWith("$")) { throw reportError("Local variable \"" + name + "\" can't start with '$', it is a reserved identifier.", node); } return name; }
Example 2
Source File: JavaPluginUtils.java From netbeans with Apache License 2.0 | 6 votes |
static String adjustName(String name) { if (name == null) { return null; } String shortName = null; if (name.startsWith("get") && name.length() > 3) { shortName = name.substring(3); } if (name.startsWith("is") && name.length() > 2) { shortName = name.substring(2); } if (shortName != null) { return firstToLower(shortName); } if (SourceVersion.isKeyword(name)) { return "a" + Character.toUpperCase(name.charAt(0)) + name.substring(1); } else { return name; } }
Example 3
Source File: NameConverter.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
public String toConstantName( String token ) { String name = super.toConstantName(token); if(!SourceVersion.isKeyword(name)) return name; else return '_'+name; }
Example 4
Source File: NameConverter.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
public String toConstantName( String token ) { String name = super.toConstantName(token); if(!SourceVersion.isKeyword(name)) return name; else return '_'+name; }
Example 5
Source File: NameConverter.java From hottub with GNU General Public License v2.0 | 5 votes |
public String toConstantName( String token ) { String name = super.toConstantName(token); if(!SourceVersion.isKeyword(name)) return name; else return '_'+name; }
Example 6
Source File: BaseUtilities.java From netbeans with Apache License 2.0 | 5 votes |
/** Test whether a given string is a valid Java identifier. * @param id string which should be checked * @return <code>true</code> if a valid identifier * @see SourceVersion#isIdentifier * @see SourceVersion#isKeyword */ public static boolean isJavaIdentifier(String id) { if (id == null) { return false; } return SourceVersion.isIdentifier(id) && !SourceVersion.isKeyword(id); }
Example 7
Source File: AutoValueOrOneOfProcessor.java From auto with Apache License 2.0 | 5 votes |
/** * Modifies the values of the given map to avoid reserved words. If we have a getter called {@code * getPackage()} then we can't use the identifier {@code package} to represent its value since * that's a reserved word. */ static void fixReservedIdentifiers(Map<?, String> methodToIdentifier) { for (Map.Entry<?, String> entry : methodToIdentifier.entrySet()) { String name = entry.getValue(); if (SourceVersion.isKeyword(name) || !Character.isJavaIdentifierStart(name.codePointAt(0))) { entry.setValue(disambiguate(name, methodToIdentifier.values())); } } }
Example 8
Source File: FileResourceNameValidator.java From javaide with GNU General Public License v3.0 | 5 votes |
/** * Validate a single-file resource name. * * @param fileNameWithoutExt The resource file name to validate, without an extension. * @return null if no error, otherwise a string describing the error. */ @Nullable public static String getErrorTextForNameWithoutExtension( @NonNull final String fileNameWithoutExt) { char first = fileNameWithoutExt.charAt(0); if (!Character.isJavaIdentifierStart(first)) { return "The resource name must start with a letter"; } // AAPT only allows lowercase+digits+_: // "%s: Invalid file name: must contain only [a-z0-9_.]"," for (int i = 0, n = fileNameWithoutExt.length(); i < n; i++) { char c = fileNameWithoutExt.charAt(i); if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_')) { return String.format("'%1$c' is not a valid file-based resource name character: " + "File-based resource names must contain only lowercase a-z, 0-9," + " or underscore", c); } } if (SourceVersion.isKeyword(fileNameWithoutExt)) { return String.format("%1$s is not a valid resource name (reserved Java keyword)", fileNameWithoutExt); } // Success! return null; }
Example 9
Source File: SourceParser.java From FreeBuilder with Apache License 2.0 | 5 votes |
private void onBlockStart(CharSequence raw) { CharSequence chars = withoutTypeParams(withoutAnnotations(raw)); if (chars == null) { eventHandler.onOtherBlockStart(); return; } Matcher typeMatcher = TYPE.matcher(chars); if (typeMatcher.find()) { Set<String> supertypes = supertypes(chars.subSequence(typeMatcher.end(), chars.length())); eventHandler.onTypeBlockStart(typeMatcher.group(1), typeMatcher.group(2), supertypes); return; } Matcher methodMatcher = METHOD.matcher(chars); if (methodMatcher.find()) { String methodName = methodMatcher.group(1); if (!SourceVersion.isKeyword(methodName)) { Set<String> args = new LinkedHashSet<>(); Matcher argMatcher = ARGUMENTS.matcher(methodMatcher.group(2)); int index = 0; while (argMatcher.find() && argMatcher.start() == index) { args.add(argMatcher.group(1)); index = argMatcher.end(); } if (index == methodMatcher.group(2).length()) { eventHandler.onMethodBlockStart(methodName, args); return; } } } eventHandler.onOtherBlockStart(); }
Example 10
Source File: ValueResourceNameValidator.java From javaide with GNU General Public License v3.0 | 5 votes |
/** * Validate a value resource name. * * @param fullResourceName the resource name to validate. * @param resourceType the resource type. * @return null if no error, otherwise a string describing the error. */ @Nullable public static String getErrorText(@NonNull String fullResourceName, ResourceType resourceType) { if (resourceType == ResourceType.ATTR) { if (fullResourceName.startsWith("android:")) { fullResourceName = fullResourceName.substring(8); } } final String resourceName = fullResourceName.replace('.', '_'); // Resource names must be valid Java identifiers, since they will // be represented as Java identifiers in the R file: if (!SourceVersion.isIdentifier(resourceName)) { if (!Character.isJavaIdentifierStart(resourceName.charAt(0))) { return "The resource name must start with a letter"; } else { for (int i = 1, n = resourceName.length(); i < n; i++) { char c = resourceName.charAt(i); if (!Character.isJavaIdentifierPart(c)) { return String .format("'%1$c' is not a valid resource name character", c); } } } } if (SourceVersion.isKeyword(resourceName)) { return String.format("%1$s is not a valid resource name (reserved Java keyword)", resourceName); } // Success. return null; }
Example 11
Source File: RetroWeiboProcessor.java From SimpleWeibo with Apache License 2.0 | 5 votes |
private void fixReservedIdentifiers(Map<ExecutableElement, String> methodToIdentifier) { for (Map.Entry<ExecutableElement, String> entry : methodToIdentifier.entrySet()) { if (SourceVersion.isKeyword(entry.getValue())) { entry.setValue(disambiguate(entry.getValue(), methodToIdentifier.values())); } } }
Example 12
Source File: NameConverter.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
public String toConstantName( String token ) { String name = super.toConstantName(token); if(!SourceVersion.isKeyword(name)) return name; else return '_'+name; }
Example 13
Source File: CodeGenerator.java From FHIR with Apache License 2.0 | 5 votes |
private String getFieldName(String elementName) { if ("class".equals(elementName)) { return "clazz"; } if (SourceVersion.isKeyword(elementName)) { return "_" + elementName; } return elementName; }
Example 14
Source File: Resource.java From jetbrick-template-1x with Apache License 2.0 | 4 votes |
private String doGetQualifiedClassName() { StringBuilder sb = new StringBuilder(name.length() + 16); String[] identifiers = name.split("/"); for (int i = 1; i < identifiers.length; i++) { // 跳过第一个 "/" String identifier = identifiers[i]; StringBuilder modifiedIdentifier = new StringBuilder(identifier.length() + 16); char c = identifier.charAt(0); if (c < 'A' || (c > 'Z' && c < 'a') || c > 'z') { modifiedIdentifier.append('_'); } for (int j = 0; j < identifier.length(); j++) { c = identifier.charAt(j); if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) { modifiedIdentifier.append(c); } else if (c == '.') { modifiedIdentifier.append('_'); } else { modifiedIdentifier.append('_'); modifiedIdentifier.append(Character.forDigit(c >> 12 & 0xF, 16)); modifiedIdentifier.append(Character.forDigit(c >> 8 & 0xF, 16)); modifiedIdentifier.append(Character.forDigit(c >> 4 & 0xF, 16)); modifiedIdentifier.append(Character.forDigit(c & 0xF, 16)); } } identifier = modifiedIdentifier.toString(); if (i == 1 && "java".equals(identifier)) { // 不能以 “java.” 开头 modifiedIdentifier.append('_'); } else { if (SourceVersion.isKeyword(identifier)) { modifiedIdentifier.append('_'); } } if (sb.length() > 0) { sb.append('.'); } sb.append(modifiedIdentifier); } return sb.toString(); }
Example 15
Source File: NameConverter.java From openjdk-8-source with GNU General Public License v2.0 | 4 votes |
/** * Computes a Java package name from a namespace URI, * as specified in the spec. * * @return * null if it fails to derive a package name. */ public String toPackageName( String nsUri ) { // remove scheme and :, if present // spec only requires us to remove 'http' and 'urn'... int idx = nsUri.indexOf(':'); String scheme = ""; if(idx>=0) { scheme = nsUri.substring(0,idx); if( scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("urn") ) nsUri = nsUri.substring(idx+1); } // tokenize string ArrayList<String> tokens = tokenize( nsUri, "/: " ); if( tokens.size() == 0 ) { return null; } // remove trailing file type, if necessary if( tokens.size() > 1 ) { // for uri's like "www.foo.com" and "foo.com", there is no trailing // file, so there's no need to look at the last '.' and substring // otherwise, we loose the "com" (which would be wrong) String lastToken = tokens.get( tokens.size()-1 ); idx = lastToken.lastIndexOf( '.' ); if( idx > 0 ) { lastToken = lastToken.substring( 0, idx ); tokens.set( tokens.size()-1, lastToken ); } } // tokenize domain name and reverse. Also remove :port if it exists String domain = tokens.get( 0 ); idx = domain.indexOf(':'); if( idx >= 0) domain = domain.substring(0, idx); ArrayList<String> r = reverse( tokenize( domain, scheme.equals("urn")?".-":"." ) ); if( r.get( r.size()-1 ).equalsIgnoreCase( "www" ) ) { // remove leading www r.remove( r.size()-1 ); } // replace the domain name with tokenized items tokens.addAll( 1, r ); tokens.remove( 0 ); // iterate through the tokens and apply xml->java name algorithm for( int i = 0; i < tokens.size(); i++ ) { // get the token and remove illegal chars String token = tokens.get( i ); token = removeIllegalIdentifierChars( token ); // this will check for reserved keywords if (SourceVersion.isKeyword(token.toLowerCase())) { token = '_' + token; } tokens.set( i, token.toLowerCase() ); } // concat all the pieces and return it return combine( tokens, '.' ); }
Example 16
Source File: NameConverter.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
/** * Computes a Java package name from a namespace URI, * as specified in the spec. * * @return * null if it fails to derive a package name. */ public String toPackageName( String nsUri ) { // remove scheme and :, if present // spec only requires us to remove 'http' and 'urn'... int idx = nsUri.indexOf(':'); String scheme = ""; if(idx>=0) { scheme = nsUri.substring(0,idx); if( scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("urn") ) nsUri = nsUri.substring(idx+1); } // tokenize string ArrayList<String> tokens = tokenize( nsUri, "/: " ); if( tokens.size() == 0 ) { return null; } // remove trailing file type, if necessary if( tokens.size() > 1 ) { // for uri's like "www.foo.com" and "foo.com", there is no trailing // file, so there's no need to look at the last '.' and substring // otherwise, we loose the "com" (which would be wrong) String lastToken = tokens.get( tokens.size()-1 ); idx = lastToken.lastIndexOf( '.' ); if( idx > 0 ) { lastToken = lastToken.substring( 0, idx ); tokens.set( tokens.size()-1, lastToken ); } } // tokenize domain name and reverse. Also remove :port if it exists String domain = tokens.get( 0 ); idx = domain.indexOf(':'); if( idx >= 0) domain = domain.substring(0, idx); ArrayList<String> r = reverse( tokenize( domain, scheme.equals("urn")?".-":"." ) ); if( r.get( r.size()-1 ).equalsIgnoreCase( "www" ) ) { // remove leading www r.remove( r.size()-1 ); } // replace the domain name with tokenized items tokens.addAll( 1, r ); tokens.remove( 0 ); // iterate through the tokens and apply xml->java name algorithm for( int i = 0; i < tokens.size(); i++ ) { // get the token and remove illegal chars String token = tokens.get( i ); token = removeIllegalIdentifierChars( token ); // this will check for reserved keywords if (SourceVersion.isKeyword(token.toLowerCase())) { token = '_' + token; } tokens.set( i, token.toLowerCase() ); } // concat all the pieces and return it return combine( tokens, '.' ); }
Example 17
Source File: UniqueNameSet.java From paperparcel with Apache License 2.0 | 4 votes |
private boolean isInvalidName(String name) { return !uniqueNames.add(name) || SourceVersion.isKeyword(name); }
Example 18
Source File: StaticImport.java From netbeans with Apache License 2.0 | 4 votes |
@TriggerTreeKind(Kind.MEMBER_SELECT) public static List<ErrorDescription> run(HintContext ctx) { CompilationInfo info = ctx.getInfo(); TreePath treePath = ctx.getPath(); Element e = info.getTrees().getElement(treePath); EnumSet<ElementKind> supportedTypes = EnumSet.of(ElementKind.METHOD, ElementKind.ENUM_CONSTANT, ElementKind.FIELD); if (e == null || !e.getModifiers().contains(Modifier.STATIC) || !supportedTypes.contains(e.getKind())) { return null; } if (ElementKind.METHOD.equals(e.getKind())) { TreePath mitp = treePath.getParentPath(); if (mitp == null || mitp.getLeaf().getKind() != Kind.METHOD_INVOCATION) { return null; } if (((MethodInvocationTree) mitp.getLeaf()).getMethodSelect() != treePath.getLeaf()) { return null; } List<? extends Tree> typeArgs = ((MethodInvocationTree) mitp.getLeaf()).getTypeArguments(); if (typeArgs != null && !typeArgs.isEmpty()) { return null; } } Element enclosingEl = e.getEnclosingElement(); if (enclosingEl == null) { return null; } String sn = e.getSimpleName().toString(); // rules out .class, but who knows what keywords will be abused in the future. if (SourceVersion.isKeyword(sn)) { return null; } TreePath cc = getContainingClass(treePath); if (cc == null){ return null; } Element klass = info.getTrees().getElement(cc); if (klass == null || klass.getKind() != ElementKind.CLASS) { return null; } String fqn = null; String fqn1 = getFqn(info, e); if (!isSubTypeOrInnerOfSubType(info, klass, enclosingEl) && !isStaticallyImported(info, fqn1)) { if (hasMethodNameClash(info, klass, sn) || hasStaticImportSimpleNameClash(info, sn)) { return null; } fqn = fqn1; } Scope currentScope = info.getTrees().getScope(treePath); TypeMirror enclosingType = e.getEnclosingElement().asType(); if (enclosingType == null || enclosingType.getKind() != TypeKind.DECLARED || !info.getTrees().isAccessible(currentScope, e, (DeclaredType) enclosingType)) { return null; } String desc = NbBundle.getMessage(StaticImport.class, "ERR_StaticImport"); ErrorDescription ed = ErrorDescriptionFactory.forTree(ctx, treePath, desc, new FixImpl(TreePathHandle.create(treePath, info), fqn, sn).toEditorFix()); if (ctx.isCanceled()) { return null; } return Collections.singletonList(ed); }
Example 19
Source File: Utilities.java From netbeans with Apache License 2.0 | 4 votes |
/** * Creates an unique name. * The method takes the proposed `name' and ensures it is unique with respect to `usedVariables' and contents of the target scope `s'. * The `prefix' and `suffix' are joined with the base name. If prefix ends with a letter and name starts with letter, the resulting name * will be converted to CamelCase according to coding conventions. If `acceptExisting' is true, the name will not be decorated, if it * already contains both prefix AND suffix. Names that are the same as keywords are avoided and changed. * * @param info compilation info * @param s target scope for uniqueness checks * @param name proposed base name * @param usedVariables other to-be-introduced names, in addition to scope contents, to be avoided * @param prefix the desired prefix or {@code null} * @param suffix the desired suffix or {@code null} * @param acceptExisting true, if existing prefix and suffix in the `name' should be accepted * @return unique name that contains the prefix and suffix if they are specified. */ public static String makeNameUnique(CompilationInfo info, Scope s, String name, Set<String> usedVariables, String prefix, String suffix, boolean acceptExisting) { boolean prefixOK = false; boolean suffixOK = false; if (acceptExisting) { if (prefix != null) { if (!(prefixOK = prefix.isEmpty())) { // prefixOK is now false if (name.startsWith(prefix)) { int pl = prefix.length(); if(Character.isAlphabetic(prefix.charAt(pl-1))) { if (name.length() > pl && Character.isUpperCase(name.charAt(pl))) { prefixOK = true; } } else { prefixOK = true; } } } } if (suffix != null && (suffix.isEmpty() || name.endsWith(suffix))) { suffixOK = true; } } if (prefixOK && suffixOK) { prefix = suffix = ""; // NOI18N } if(prefix != null && prefix.length() > 0) { if(Character.isAlphabetic(prefix.charAt(prefix.length()-1))) { StringBuilder nameSb = new StringBuilder(name); nameSb.setCharAt(0, Character.toUpperCase(nameSb.charAt(0))); name = nameSb.toString(); } } boolean cont; String proposedName; int counter = 0; do { proposedName = safeString(prefix) + name + (counter != 0 ? String.valueOf(counter) : "") + safeString(suffix); cont = false; String converted = TYPICAL_KEYWORD_CONVERSIONS.get(proposedName); if (converted != null) { proposedName = converted; } if (SourceVersion.isKeyword(proposedName) || usedVariables.contains(proposedName)) { counter++; cont = true; continue; } for (Element e : info.getElementUtilities().getLocalMembersAndVars(s, new VariablesFilter())) { if (proposedName.equals(e.getSimpleName().toString())) { counter++; cont = true; break; } } } while(cont); return proposedName; }
Example 20
Source File: NameConverter.java From hottub with GNU General Public License v2.0 | 4 votes |
/** * Computes a Java package name from a namespace URI, * as specified in the spec. * * @return * null if it fails to derive a package name. */ public String toPackageName( String nsUri ) { // remove scheme and :, if present // spec only requires us to remove 'http' and 'urn'... int idx = nsUri.indexOf(':'); String scheme = ""; if(idx>=0) { scheme = nsUri.substring(0,idx); if( scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("urn") ) nsUri = nsUri.substring(idx+1); } // tokenize string ArrayList<String> tokens = tokenize( nsUri, "/: " ); if( tokens.size() == 0 ) { return null; } // remove trailing file type, if necessary if( tokens.size() > 1 ) { // for uri's like "www.foo.com" and "foo.com", there is no trailing // file, so there's no need to look at the last '.' and substring // otherwise, we loose the "com" (which would be wrong) String lastToken = tokens.get( tokens.size()-1 ); idx = lastToken.lastIndexOf( '.' ); if( idx > 0 ) { lastToken = lastToken.substring( 0, idx ); tokens.set( tokens.size()-1, lastToken ); } } // tokenize domain name and reverse. Also remove :port if it exists String domain = tokens.get( 0 ); idx = domain.indexOf(':'); if( idx >= 0) domain = domain.substring(0, idx); ArrayList<String> r = reverse( tokenize( domain, scheme.equals("urn")?".-":"." ) ); if( r.get( r.size()-1 ).equalsIgnoreCase( "www" ) ) { // remove leading www r.remove( r.size()-1 ); } // replace the domain name with tokenized items tokens.addAll( 1, r ); tokens.remove( 0 ); // iterate through the tokens and apply xml->java name algorithm for( int i = 0; i < tokens.size(); i++ ) { // get the token and remove illegal chars String token = tokens.get( i ); token = removeIllegalIdentifierChars( token ); // this will check for reserved keywords if (SourceVersion.isKeyword(token.toLowerCase())) { token = '_' + token; } tokens.set( i, token.toLowerCase() ); } // concat all the pieces and return it return combine( tokens, '.' ); }