% -*- mode: latex; coding: utf-8 -*-
% !TEX TS-program = pdflatexmk
% !TEX encoding = UTF-8 Unicode

%\RequirePackage[hyphens]{url}
\documentclass[%
  a4paper,
  twoside,
  numbers=noenddot,
  parskip=half,
  open=any,
  headsepline,
  english, % german, english
  ba  % ba, pa
]{zhawthesis}

\usepackage{etoolbox}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Parameters
% - Adjust these to your needs:

\title{Functional Go}
\subtitle{...An Easier Introduction to Functional Programming}
\author{% Komma getrennt
    Ramon Rüttimann
}
\newcommand\twodigits[1]{\ifnum#1<10 0#1\else #1\fi}
\date{\twodigits{\the\day}.\twodigits{\number\month}.\the\year}

\major{Computer Science}  % Studiengang
\zhawsemester{Spring 2020}
\zhawinstitute{init}
\zhawlogocolour{pantone2945}  % pantone2945, cmyk, sw
\mainsupervisor{Dr. G. Burkert}
\subsupervisor{Dr. K. Rege}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Base packages used by the template (any commonly used packages)

%\PassOptionsToPackage{hyphens}{url}\usepackage{hyperref}

\usepackage{float}
\usepackage{graphicx}
\graphicspath{{figures/}}
\DeclareGraphicsExtensions{.pdf,.png,.jpg,.gif}

\usepackage{tabularx}
\usepackage{longtable}
\usepackage{booktabs}
\usepackage{todonotes}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Custom packages
% - Add packages used by your thesis here:

%\usepackage{hyperref}
%\PassOptionsToPackage{hyphens}{url}\usepackage{hyperref}

\hypersetup{
  colorlinks   = true, %Colours links instead of ugly boxes
  %urlcolor     = blue, %Colour for external hyperlinks
  linkcolor    = blue, %Colour of internal links
  citecolor   = blue %Colour of citations
}
\usepackage[newfloat]{minted}
\usepackage{listings}
\newenvironment{code}{\captionsetup{type=listing}}{}
\SetupFloatingEnvironment{listing}{name=Source Code,placement=H}
\definecolor{bg}{rgb}{0.95,0.95,0.95}
\newminted{bash}{breaklines,breakbytoken,tabsize=2,bgcolor=bg}
\newminted{bnf}{breaklines,breakbytoken,tabsize=2,bgcolor=bg}
\newminted{c}{breaklines,breakbytoken,tabsize=2,bgcolor=bg}
\newminted{go}{breaklines,breakbytoken,tabsize=2,bgcolor=bg}
\newminted{haskell}{breaklines,breakbytoken,tabsize=2,bgcolor=bg}
\newminted{java}{breaklines,breakbytoken,tabsize=2,bgcolor=bg}
\newmintedfile{go}{breaklines,breakanywhere,tabsize=2,bgcolor=bg,linenos,stepnumber=5,numberfirstline}


\newcommand{\gofilerange}[4][]{%
    \immediate\write18{./utils/delim -file="#2" -start="#3" -end="#4"}%
    \IfFileExists{code.lineno}%
      {\CatchFileEdef{\linenumber}{./code.lineno}{\endlinechar=-1 }}%
      {\def\linenumber{0}}%
    \edef\flags{firstnumber=\linenumber,#1}%
    \expandafter\gofile\expandafter[\flags]{./code.snippet}}

\newcommand{\unchapter}[1]{%
  \begingroup
  \let\@makesectionhead\@gobble % make \@makechapterhead do nothing
  \section{#1}
  \endgroup
}
\makeatother
%\sloppy

\usepackage[
    backend=biber,
    hyperref=true,
    style=ieee,
    dashed=false,
]{biblatex}
\usepackage{xurl}
\usepackage[skip=0pt]{caption}
\usepackage[toc,page]{appendix}
\usepackage{hyperref}
\usepackage{glossaries}

\usepackage{pdfpages}
%\usepackage{listings}
\makeglossaries
%\usepackage{csquotes}
\AtBeginEnvironment{quote}{\itshape}
%\bibliography{thesis}
\addbibresource{thesis.bib}

\begin{document}

\frontmatter

\maketitle

\cleardoublepage % chktex 1


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Declaration of Originality

\makedeclarationoforiginality % chktex 1


\cleardoublepage % chktex 1


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


\chapter{Abstract}
\label{ch:abstract} % chktex 24
\input{chapters/01_abstract.tex}

\chapter{Zusammenfassung}
\label{ch:summary} % chktex 24
\input{chapters/02_zusammenfassung.tex}

\IfLanguageName{nswissgerman}{\chapter{Vorwort}}{\chapter{Preface}}
\label{ch:preface} % chktex 24
\input{chapters/10_preface.tex}

\cleardoublepage % chktex 1


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\mainmatter % chktex 1

\tableofcontents

\IfLanguageName{nswissgerman}{\chapter{Einleitung}}{\chapter{Introduction}}
\label{ch:introduction} % chktex 24
\input{chapters/20_introduction.tex}

\chapter{About Go}
\label{ch:about-go}
\input{chapters/25_about_go.tex}

% DISABLE RELATED WORK AS I PUT THAT INTO THE INTRO
%\IfLanguageName{nswissgerman}{\chapter{Verwandte Arbeit}}{\chapter{Related Work}}
%\label{ch:related-work} % chktex 24
%\input{chapters/30_related_work.tex}

\IfLanguageName{nswissgerman}{\chapter{Methoden}}{\chapter{Methodology}}
\label{ch:methodology} % chktex 24
\input{chapters/30_methodology.tex}

\chapter{Implementation}
\label{ch:implementation} % chktex 24
\input{chapters/40_implementation.tex}

\chapter{Application}
\label{ch:application} % chktex 24
\input{chapters/50_application.tex}

\IfLanguageName{nswissgerman}{\chapter{Resultate}}{\chapter{Results}}
\label{ch:results} % chktex 24
\input{chapters/60_results.tex}

\IfLanguageName{nswissgerman}{\chapter{Diskussion}}{\chapter{Discussion}}
\label{ch:discussion} % chktex 24
\input{chapters/70_discussion.tex}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\backmatter % chktex 1

% \let\clearpage\relax
% \vspace{-4em}
\printbibliography
% \endgroup

\renewcommand{\lstlistlistingname}{List of source codes}

\lstlistoflistings

% \begingroup
% \let\clearpage\relax
% \vspace{-4em}
\listoffigures
% \endgroup

% \begingroup
% \let\clearpage\relax
% \vspace{-4em}
\listoftables

\clearpage
\phantomsection
\addtocounter{chapter}{1}
\addcontentsline{toc}{chapter}{%
	Glossary}
\printglossaries
% \endgroup
\cleardoublepage % chktex 1


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%\appendix
\begin{appendices}
\input{chapters/80_appendix.tex}

%\section{Example for Functional Options}\label{appendix:funcopts}
%\begin{code}
    %\captionof{listing}{Functional Options for a simple Webserver}
    %\gofile{../work/examples/functional-options/main.go}
%\end{code}

%\section{Analysis of function occurrences in Haskell code}\label{appendix:function-occurrences}
%The results of the analysis have been aquired by running the following command
%from the root of the git repository\cite{git-repo}:
%\begin{bashcode}
%./work/common-list-functions/count-function.sh "map " " : " "fold" "filter " "reverse " "take " "drop " "maximum" "sum " "zip " "product " "minimum " "reduce "
%\end{bashcode}

%\section{Mutating variables in Go}\label{appendix:mutation}
%\begin{code}
	%\captionof{listing}{Example on how to mutate complex types in Go}
	%\gofile{../work/examples/mutate/main.go}
%\end{code}

%\section{Shadowing variables in Go}\label{appendix:shadowing}
%\begin{code}
	%\captionof{listing}{Example on how shadowing works on block scopes}
	%\gofile{../work/examples/shadowing/main.go}
%\end{code}

%\section{Workaround for the missing foldl' implementation in Go}\label{appendix:foldl-go}
%\begin{code}
	%\captionof{listing}{Working around the missing foldl implementation in Go}
	%\label{code:foldl-go}
	%\gofile{../work/examples/foldl-workaround/main.go}
	%\begin{bashcode}
%$> fgo run .
%0
%panic: runtime error: invalid memory address or nil pointer dereference
%[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x109e945]

%goroutine 1 [running]:
%main.what(0x2, 0x0, 0x2)
		%/tmp/map/main.go:16 +0x5
%main.main()
		%/tmp/map/main.go:12 +0x187
%exit status 2
	%\end{bashcode}
%\end{code}

%\section{Prettyprint implementation}\label{appendix:prettyprint-func}
%\begin{code}
	%\captionof{listing}{The original prettyprint implementation}
	%\gofile{../work/funcheck/prettyprint/prettyprint.go}
%\end{code}
%\begin{code}
	%\captionof{listing}{The refactored, functional prettyprint implementation}
	%\begin{gocode}
%package prettyprint

%import (
	%"bytes"
	%"fmt"
	%"go/ast"
	%"go/printer"
	%"go/token"

	%"golang.org/x/tools/go/analysis"
%)

%var Analyzer = &analysis.Analyzer{
	%Name: "prettyprint",
	%Doc:  "prints positions",
	%Run:  run,
%}

%type null struct{}

%func checkDecl(as *ast.DeclStmt, fset *token.FileSet) {
	%fmt.Printf("Declaration %q: %v\n", render(fset, as), as.Pos())

	%check := func(_ null, spec ast.Spec) (n null) {
		%val, ok := spec.(*ast.ValueSpec)
		%if !ok {
			%return
		%}
		%if val.Values != nil {
			%return
		%}
		%if _, ok := val.Type.(*ast.FuncType); !ok {
			%return
		%}
		%fmt.Printf("\tIdent %q: %v\n", render(fset, val), val.Names[0].Pos())
		%return
	%}

	%if decl, ok := as.Decl.(*ast.GenDecl); ok {
		%_ = foldl(check, null{}, decl.Specs)
	%}
%}

%func checkAssign(as *ast.AssignStmt, fset *token.FileSet) {
	%fmt.Printf("Assignment %q: %v\n", render(fset, as), as.Pos())

	%check := func(_ null, expr ast.Expr) (n null) {
		%ident, ok := expr.(*ast.Ident) // Lhs always is an "IdentifierList"
		%if !ok {
			%return
		%}

		%fmt.Printf("\tIdent %q: %v\n", ident.String(), ident.Pos())

		%switch {
		%case ident.Name == "_":
			%fmt.Printf("\t\tBlank Identifier!\n")
		%case ident.Obj == nil:
			%fmt.Printf("\t\tDecl is not in the same file!\n")
		%default:
			%// make sure the declaration has a Pos func and get it
			%declPos := ident.Obj.Decl.(ast.Node).Pos()
			%fmt.Printf("\t\tDecl %q: %v\n", render(fset, ident.Obj.Decl), declPos)
		%}

		%return
	%}
	%_ = foldl(check, null{}, as.Lhs)
%}

%func run(pass *analysis.Pass) (interface{}, error) {
	%inspect := func(_ null, file *ast.File) (n null) {
		%ast.Inspect(file, func(n ast.Node) bool {
			%switch as := n.(type) {
			%case *ast.DeclStmt:
				%checkDecl(as, pass.Fset)
			%case *ast.AssignStmt:
				%checkAssign(as, pass.Fset)
			%}
			%return true
		%})
		%return
	%}
	%_ = foldl(inspect, null{}, pass.Files)

	%return nil, nil
%}

%// render returns the pretty-print of the given node
%func render(fset *token.FileSet, x interface{}) string {
	%var buf bytes.Buffer
	%if err := printer.Fprint(&buf, fset, x); err != nil {
		%panic(err)
	%}
	%return buf.String()
%}
	%\end{gocode}
%\end{code}

%% - Add your appendix here:

%\todo[inline]{
  %Anhang/Appendix:

  %\quad -- Projektmanagement: \\ % chktex 8
  %\qquad -- Offizielle Aufgabenstellung, Projektauftrag \\ % chktex 8
  %\qquad -- (Zeitplan) \\ % chktex 8
  %\qquad -- (Besprechungsprotokolle oder Journals) % chktex 8

  %\quad -- Weiteres: \\ % chktex 8
  %\qquad -- CD/USB-Stick mit dem vollständigen Bericht als PDF-File inklusive Film- und Fotomaterial \\ % chktex 8
  %\qquad -- (Schaltpläne und Ablaufschemata) \\ % chktex 8
  %\qquad -- (Spezifikation u. Datenblätter der verwendeten Messgeräte und/oder Komponenten) \\ % chktex 8
  %\qquad -- (Berechnungen, Messwerte, Simulationsresultate) \\ % chktex 8
  %\qquad -- (Stoffdaten) \\ % chktex 8
  %\qquad -- (Fehlerrechnungen mit Messunsicherheiten) \\ % chktex 8
  %\qquad -- (Grafische Darstellungen, Fotos) \\ % chktex 8
  %\qquad -- (Datenträger mit weiteren Daten (z. B. Software-Komponenten) inkl. Verzeichnis der auf diesem Datenträger abgelegten Dateien) \\ % chktex 8
  %\qquad -- (Softwarecode) % chktex 8
%}

\end{appendices}

\end{document}
