package org.antlr.symtab;

import org.antlr.v4.runtime.ParserRuleContext;

import java.util.Collections;
import java.util.List;

/** An abstract base class used to house common functionality.
 *  You can associate a node in the parse tree that is responsible
 *  for defining this symbol.
 */
public abstract class BaseSymbol implements Symbol {
	protected final String name;   		 // All symbols at least have a name
	protected Type type;				 // If language statically typed, record type
	protected Scope scope;      		 // All symbols know what scope contains them.
	protected ParserRuleContext defNode; // points at definition node in tree
	protected int lexicalOrder; 		 // order seen or insertion order from 0; compilers often need this

	public BaseSymbol(String name) { this.name = name; }

	@Override public String getName() { return name; }
	@Override public Scope getScope() { return scope; }
	@Override public void setScope(Scope scope) { this.scope = scope; }

	public Type getType() { return type; }
	public void setType(Type type) { this.type = type; }

	public void setDefNode(ParserRuleContext defNode) {
		this.defNode = defNode;
	}

	public ParserRuleContext getDefNode() {
		return defNode;
	}

	@Override
	public boolean equals(Object obj) {
		if ( !(obj instanceof Symbol) ) {
			return false;
		}
        if ( obj==this ) {
			return true;
		}
		return name.equals(((Symbol)obj).getName());
	}

	@Override
	public int hashCode() {
		return name.hashCode();
	}

	@Override
	public int getInsertionOrderNumber() {
		return lexicalOrder;
	}

	@Override
	public void setInsertionOrderNumber(int i) {
		this.lexicalOrder = i;
	}

	public String getFullyQualifiedName(String scopePathSeparator) {
		List<Scope> path = scope.getEnclosingPathToRoot();
		Collections.reverse(path);
		String qualifier = Utils.joinScopeNames(path, scopePathSeparator);
		return qualifier + scopePathSeparator + name;
	}

	public String toString() {
		String s = "";
		if ( scope!=null ) s = scope.getName()+".";
		if ( type!=null ) return '<'+s+getName()+":"+type+'>';
		return s+getName();
	}
}

@@ -2018,16 +2018,164 @@
 =null ) 
+%7B%0A%09%09%09String ts = type.toString();%0A%09%09%09if ( type instanceof SymbolWithScope ) %7B%0A%09%09%09%09ts = ((SymbolWithScope) type).getFullyQualifiedName(%22.%22);%0A%09%09%09%7D%0A%09%09%09
 return '
@@ -2198,17 +2198,19 @@
 :%22+t
-ype
+s
 +'%3E';%0A
+%09%09%7D%0A
 %09%09re

improve toString