001 /*
002 * Copyright 2010-2015 JetBrains s.r.o.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017 package org.jetbrains.kotlin.name;
018
019 import org.jetbrains.annotations.NotNull;
020
021 public final class Name implements Comparable<Name> {
022 @NotNull
023 private final String name;
024 private final boolean special;
025
026 private Name(@NotNull String name, boolean special) {
027 this.name = name;
028 this.special = special;
029 }
030
031 @NotNull
032 public String asString() {
033 return name;
034 }
035
036 @NotNull
037 public String getIdentifier() {
038 if (special) {
039 throw new IllegalStateException("not identifier: " + this);
040 }
041 return asString();
042 }
043
044 public boolean isSpecial() {
045 return special;
046 }
047
048 @Override
049 public int compareTo(Name that) {
050 return this.name.compareTo(that.name);
051 }
052
053 @NotNull
054 public static Name identifier(@NotNull String name) {
055 return new Name(name, false);
056 }
057
058 public static boolean isValidIdentifier(@NotNull String name) {
059 return !name.isEmpty() && !name.startsWith("<") && !name.contains(".") && !name.contains("/");
060 }
061
062 @NotNull
063 public static Name special(@NotNull String name) {
064 if (!name.startsWith("<")) {
065 throw new IllegalArgumentException("special name must start with '<': " + name);
066 }
067 return new Name(name, true);
068 }
069
070 @NotNull
071 public static Name guessByFirstCharacter(@NotNull String name) {
072 if (name.startsWith("<")) {
073 return special(name);
074 }
075 else {
076 return identifier(name);
077 }
078 }
079
080 @Override
081 public String toString() {
082 return name;
083 }
084
085 @Override
086 public boolean equals(Object o) {
087 if (this == o) return true;
088 if (!(o instanceof Name)) return false;
089
090 Name name1 = (Name) o;
091
092 if (special != name1.special) return false;
093 if (!name.equals(name1.name)) return false;
094
095 return true;
096 }
097
098 @Override
099 public int hashCode() {
100 int result = name.hashCode();
101 result = 31 * result + (special ? 1 : 0);
102 return result;
103 }
104 }