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 // TODO: wrong
071 @NotNull
072 public static Name guess(@NotNull String name) {
073 if (name.startsWith("<")) {
074 return special(name);
075 }
076 else {
077 return identifier(name);
078 }
079 }
080
081 @Override
082 public String toString() {
083 return name;
084 }
085
086 @Override
087 public boolean equals(Object o) {
088 if (this == o) return true;
089 if (!(o instanceof Name)) return false;
090
091 Name name1 = (Name) o;
092
093 if (special != name1.special) return false;
094 if (!name.equals(name1.name)) return false;
095
096 return true;
097 }
098
099 @Override
100 public int hashCode() {
101 int result = name.hashCode();
102 result = 31 * result + (special ? 1 : 0);
103 return result;
104 }
105 }