Referencing parent(s) of labels

I'm trying to reference a label's parent so it outputs something like "Section, Subsection" or "Section, Subsection, Subsubsection". I've come close with smartref by doing the following:

\usepackage{smartref}



but this unfortunately only outputs the number of the section and not the name of the section. The documentation of smartref alludes to a \byname option but doesn't seem to actually provide a working example of it, making it difficult to implement.

It seems like this should be an easy thing to do, and a useful thing at that, especially if subsections might move between sections making hard-coded references to parents a pain.

Any ideas would be appreciated.

Mike

EDIT:

Ideally, it would look like this:

• I think you want to have a look at nameref and cleveref. – egreg Dec 10 '18 at 12:54
• @egreg I had a look at these packages but couldn't find what I was looking for. Think you could point me in the right direction or put together an answer? – Mackey18 Dec 10 '18 at 12:55
• Please, add a sketch of the expected output. – egreg Dec 10 '18 at 13:09
• @egreg Added to main question – Mackey18 Dec 10 '18 at 13:55

With some tweaks!

However, you need to use \sectionlabel for sections and \subsectionlabel for subsections and not just \label, because we need to add functionality.

\documentclass{article}
\usepackage[byname]{smartref}

\makeatletter
\newcommand{\subsectionlabel}[1]{%
\label{#1}%
\@bsphack
\protected@write\@auxout{}{\string\newparent{#1}{\@currentsectionlabel}}%
\@esphack
}
\newcommand{\sectionlabel}[1]{%
\label{#1}%
\@bsphack\gdef\@currentsectionlabel{#1}\@esphack
}
\newcommand{\newparent}[2]{%
\global\@namedef{parent@#1}{#2}%
}

\byname{\@nameuse{parent@#1}}, \byname{#1}~(\ref{#1})%
}
\makeatother

\begin{document}

\section{My section}\sectionlabel{sec:mysection}

Some text.

\subsection{My subsection}\subsectionlabel{subsec:mysubsection}

Some text.

\section{Reference section}

This is a reference to the subsection: