\documentclass[11pt]{article}  
\usepackage{hyperref}
\usepackage{verbatim}
\usepackage{ifpdf}
\usepackage{url}
\usepackage{setspace}
\usepackage{cite}
\def\citepunct{, }
\usepackage{listings}

\begin{document}



Title: Class 2: Getting Started with Rust Date: 2013-09-02 Category:
Classes Tags: operating system, rust Author: David Evans

\section{Action Items}

If you think you are in the class but did not already submit a cs4414
student survey, you need to meet with me this week. I will assume only
students who submitted the survey are actually in the class, and only
those students will be assigned teammates for Problem Set 2.

You should have at least completed the Exercises for Problem Set 1
before Thursday's class.

\subsection{Programming Languages}

Why are there so many programming languages?

\begin{itemize}
\item
  Languages change the way we \textbf{think}.
\item
  Languages provide \textbf{abstractions} for machine resources. The
  abstractions they provide are engineering tradeoffs between:

  \begin{itemize}
  \itemsep1pt\parskip0pt\parsep0pt
  \item
    \emph{expressiveness} and \emph{``truthiness''}
  \item
    \emph{freedom} and \emph{safety}
  \item
    \emph{flexibility} and \emph{simplicity}
  \item
    \emph{efficiency} and \emph{ease-of-use}
  \end{itemize}
\end{itemize}

Which of these should we prefer for a programming language for systems
programming?

What's the difference between a language and an operating system?

\subsection{Rust}

\href{http://www.rust-lang.org}{Rust} is a systems programming language
developed by \href{http://www.mozilla.org/en-US/research/}{Mozilla
Research}. It is a new and immature language: the release we are using
is Version 0.7 (released in July 2013).

Rust is designed with a particular focus on providing \emph{safety} and
\emph{efficiency}. This means it provides programmers with a lot of
control over how memory is managed, but without the opportunity to shoot
yourself in the foot so readily provided by C/C++. Much of the design is
driven by the needs of \href{https://github.com/mozilla/servo}{Servo},
an experimental, highly-parallelizable web browser engine.

Today, we will introduce some of the basics you'll need to get started
programming in Rust (and for completing PS1). In later classes, we'll
look more deeply as some of the most interesting aspects of how types,
memory management, and concurrency work in Rust.

\subsection{First Rust Program}

Let's get started with a simple Rust program:

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{fn} \NormalTok{max(a: }\KeywordTok{int}\NormalTok{, b: }\KeywordTok{int}\NormalTok{) -> }\KeywordTok{int} \NormalTok{\{}
    \KeywordTok{if} \NormalTok{a > b \{}
        \NormalTok{a}
    \NormalTok{\} }\KeywordTok{else} \NormalTok{\{}
        \NormalTok{b}
    \NormalTok{\}}
\NormalTok{\}}

\KeywordTok{fn} \NormalTok{main() \{}
    \NormalTok{println(fmt!(}\StringTok{"Max: %?"}\NormalTok{, max(}\DecValTok{3}\NormalTok{, }\DecValTok{4}\NormalTok{)));}
\NormalTok{\}}
\end{Highlighting}
\end{Shaded}

If you are familiar with C (or at least C++) and Java, most of this
should look fairly familiar, but some things a bit unusual.

\subsection{Statements and Expressions}

Hypothesized Rust grammar (the Rust manual has a grammar, but ``looking
for consistency in the manual's grammar is bad: it's entirely wrong in
many places''):

\begin{verbatim}
:::BNF
IfExpression ::= <b>if</b> Expression Block [ <b>else</b> Block ]
Block ::= <b>{</b> [Statement<sup>*</sup> Expr] <b>}</b>
Expression ::= Block    
     
\end{verbatim}

How is the meaning of \texttt{;} different in Rust and Java?

\subsection{Higher-Order Functions}

We can make new functions directly:

\begin{verbatim}
:::BNF
LambdaExpression ::= <b>|</b> Parameters <b>|</b> Block
\end{verbatim}

Define a function,
\texttt{make\_adder(int) -\textgreater{} \textasciitilde{}fn(int) -\textgreater{} int},
that takes an integer as input and returns a function that takes and int
and returns the sum of the original and input int.

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{fn} \NormalTok{ntimes(f: }\KeywordTok{extern} \KeywordTok{fn}\NormalTok{(}\KeywordTok{int}\NormalTok{) -> }\KeywordTok{int}\NormalTok{, times: }\KeywordTok{int}\NormalTok{) -> ~}\KeywordTok{fn}\NormalTok{(}\KeywordTok{int}\NormalTok{) -> }\KeywordTok{int} \NormalTok{\{}



\NormalTok{\}}


\KeywordTok{fn} \NormalTok{double(a: }\KeywordTok{int}\NormalTok{) -> }\KeywordTok{int} \NormalTok{\{}
    \NormalTok{a * }\DecValTok{2}
\NormalTok{\}}

\KeywordTok{fn} \NormalTok{main() \{}
    \KeywordTok{let} \NormalTok{quadruple = ntimes(double, }\DecValTok{2}\NormalTok{);}
    \NormalTok{println(fmt!(}\StringTok{"quad: %?"}\NormalTok{, quadruple(}\DecValTok{2}\NormalTok{))); }\CommentTok{// 8}
\NormalTok{\}}
\end{Highlighting}
\end{Shaded}

\subsection{Reading a File}

We will use the
\href{http://static.rust-lang.org/doc/0.7/std/io.html\#function-file_reader}{\texttt{std:io::file\_reader}}
function to read a file (as you'll note if you follow the link, the
current Rust documentation is very sparse and incomplete!):

\begin{verbatim}
:::rust
fn file_reader(path: &Path) -> Result<@Reader, ~str>
\end{verbatim}

This function takes as
\href{http://static.rust-lang.org/doc/0.7/std/path.html}{\texttt{Path}}
as input and returns as
\texttt{Result\textless{}@Reader, \textasciitilde{}str\textgreater{}}.

\href{http://static.rust-lang.org/doc/0.7/std/result.html\#enum-result}{Result}
is an
\href{http://static.rust-lang.org/doc/0.7/rust.html\#enumerated-types}{enumerated
type} with two type parameters. Its value is either:

\begin{itemize}
\itemsep1pt\parskip0pt\parsep0pt
\item
  \texttt{Ok(T)} - A successful value of type \texttt{T}
\item
  \texttt{Err(U)} - An error of type \texttt{U}
\end{itemize}

Result types provide a way of dealing with errors without all the
uncertainty and complexity of exceptions. So, in this case,
\texttt{Result\textless{}@Reader, \textasciitilde{}str\textgreater{}} is
either a \texttt{@Reader}, corresponding to successfully opening the
file, or an \texttt{\textasciitilde{}str}, corresponding to an error
message when the file cannot be opened. (The \texttt{@} and
\texttt{\textasciitilde{}} indicate different types of pointers; we'll
get to that later.)

Why are (Java-style) exceptions a bad thing in a language focused on
safety?

We can use
\href{http://static.rust-lang.org/doc/tutorial.html\#control-structures}{pattern
matching} to control execution based on the type of the \texttt{Enum}:

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{fn} \NormalTok{load_file(pathname : ~}\KeywordTok{str}\NormalTok{) -> ~[~}\KeywordTok{str}\NormalTok{] \{}
    \KeywordTok{let} \NormalTok{filereader : }\KeywordTok{Result}\NormalTok{<@Reader, ~}\KeywordTok{str}\NormalTok{> = io::file_reader(~path::Path(pathname));}
    \KeywordTok{match} \NormalTok{filereader \{}
        \KeywordTok{Ok}\NormalTok{(reader) => reader.read_lines(),}
        \KeywordTok{Err}\NormalTok{(msg) => }\KeywordTok{fail}\NormalTok{!(}\StringTok{"Cannot open file: "} \NormalTok{+ msg),}
    \NormalTok{\}}
\NormalTok{\}}
\end{Highlighting}
\end{Shaded}

Note that \texttt{match} is an expression just like \texttt{if}! There's
no need to \texttt{return reader.read\_lines()}, its the value of the
expression that is the body of \texttt{load\_file}. (Also, note that
this isn't a smart way to do this for large files, since it requires
storing the whole file in memory.)

Match expressions must be \emph{complete}:

\begin{Shaded}
\begin{Highlighting}[]

\end{Highlighting}
\end{Shaded}

Match predicates can be arbitrary expressions: ``` fn collatz(n : int)
-\textgreater{} int \{ let mut count = 0; let mut current = n;

\begin{verbatim}
while current != 1 {
    current = 
        match current {
           current if current % 2 == 0 => current / 2,
           _ => 3 * current + 1
        };
    count += 1
}
count
\end{verbatim}

\}

fn main() \{ for std::int::range(1, 100) \textbar{}i\textbar{} \{
println(fmt!(``hailstone \%d = \%d'', i, collatz(i))); \} \} ```

\subsection{Ways to Get Help}

\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\item
  Search engines are your friend: reading files in rust Hints:
  unfortunately ``rust'' is a common word, and not (yet) a widely used
  language. If you know a specific function, easy to search on that (but
  harder if you don't know).
\item
  \href{http://stackoverflow.com/questions/tagged/rust}{Stackoverflow}
  can be great\ldots{}but not much Rust discussion yet.
\item
  \textbf{Experiment!} The compiler is very helpful, and mostly provides
  good error and warning messages. Use \texttt{fmt!("\%?", x)} to print
  out (almost) anything.
\item
  Ask for help:
\end{enumerate}

\begin{itemize}
\itemsep1pt\parskip0pt\parsep0pt
\item
  \href{https://piazza.com/virginia/fall2013/cs4414}{Piazza course
  forum}
\item
  \href{\textbar{}filename\textbar{}../../pages/tools/irc.md}{IRC} -
  most of the Rust developers hang out there and are quick to answer
  questions
\end{itemize}

If you figure something useful out that is not well documented,
\textbf{document it}! Help out the class, the Rust community, and gain
fame and fortune for yourself by creating good documentation and posting
it in useful ways (course Piazza forum, your blog,
\href{http://www.reddit.com/r/rust/}{reddit}, etc.).

%

\end{document}
