1 / 25

The Rust programming language

Timothy Smith COP 4020. The Rust programming language. Rust. Rust is a curly brace, block-structured expression language. Visually resembles C but differs in syntactic and semantic details.

didina
Download Presentation

The Rust programming language

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Timothy Smith COP 4020 The Rust programming language

  2. Rust • Rust is a curly brace, block-structured expression language. • Visually resembles C but differs in syntactic and semantic details. • Design oriented toward “programming in the large”, mainly towards creating and maintaining different boundaries. • Helping to preserve system integrity, availability and concurrency.

  3. Development: Graydon Hoare • Graydon worked on compilers/tools for other languages and decided to develop his own. • Created the Servo Parallel Browser Project, which is a prototype web browser engine. • Started Rust in 2006, Mozilla became interested in 2009 after a showcase from Graydon. • Bootstrap compiler released in 2010, then a self-hosted compiler released in 2011.

  4. Grayson’s Focus for Rust • Type safety • Memory Safety • Concurrency • Performance • Friendlier syntax

  5. Syntax and EBNF of grammar • grammar : rule + ; • rule : nonterminal ':' productionrule ';' ; • productionrule : production [ '|' production ] * ; • production : term * ; • term : element repeats ; • element : LITERAL | IDENTIFIER | '[' productionrule ']' ; • repeats : [ '*' | '+' ] NUMBER ? | NUMBER ? | '?' ; • LITERAL is a single printable ASCII character, or an escaped hexadecimal ASCII code of the form \xQQ. • IDENTIFIER is a nonempty string of ASCII letters and underscores.

  6. Continued: character and strings • char_lit : '\x27' char_body '\x27' ; • string_lit : '"' string_body * '"' ; • char_body : non_single_quote | '\x5c' [ '\x27' | common_escape ] ; • string_body : non_double_quote | '\x5c' [ '\x22' | common_escape ] ; • common_escape : '\x5c' | 'n' | 'r' | 't' | 'x' hex_digit 2 | 'u' hex_digit 4 | 'U' hex_digit 8 ; • hex_digit : 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | dec_digit ; • dec_digit : '0' | nonzero_dec ; • nonzero_dec: '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' ; • Example: let laptop: %str = “dell”;

  7. Continued: Numbers • num_lit : nonzero_dec [ dec_digit | '_' ] * num_suffix ? | '0' [ [ dec_digit | '_' ] + num_suffix ? | 'b' [ '1' | '0' | '_' ] + int_suffix ? | 'x' [ hex_digit | '_' ] + int_suffix ? ] ; • num_suffix : int_suffix | float_suffix ; • int_suffix : 'u' int_suffix_size ? | 'i' int_suffix_size ; • int_suffix_size : [ '8' | '1' '6' | '3' '2' | '6' '4' ] ; • float_suffix : [ exponent | '.' dec_lit exponent ? ] float_suffix_ty ? ; • float_suffix_ty : 'f' [ '3' '2' | '6' '4' ] ; • exponent : ['E' | 'e'] ['-' | '+' ] ? dec_lit ; • dec_lit : [ dec_digit | '_' ] + ; • A decimal literal starts with a decimal digit and continues with any mixture of decimal digits and underscores.

  8. Examples: • 123; 0xff00 //type determined by program context // defaults to integer • 123u; //type uint • 123_u //type uint • 0xff_u8 //type u8 • 0b1111_1111_1001_0000_i32 //type i32 • Floats • 123.0; //type float • 3f; //type float • 0.1f32 //type f32 • 12E+99_f64 //type f64

  9. Syntax extensions for Rust • fmt! : format data into a string • env! : look up an environment variable's value at compile time • stringify! : pretty-print the Rust expression given as an argument • proto! : dene a protocol for inter-task communication • include! : include the Rust expression in the given file • Include.str! : include the contents of the given file as a string • Include.bin! : include the contents of the given file as a binary blob • error!, warn!, info!, debug! : provide diagnostic information. • All expressions above give values except for proto!, which is an item, defining a new name.

  10. Crates: items and modules • A crate is a unit of compilation and linking, as well as versioning, distribution, and runtime loading. • Contains a tree of nested module scopes. Top level of tree is anonymous and any item within a crate has a module path denoting its location within the crate’s tree. • Source files: example.rs • Crate files: example.rc • item : mod_item | fn_item | type_item | struct_item | enum_item | static_item | trait_item | impl_item | foreign_mod_item ; • mod_item : "mod" ident ( ';' | '{' mod '}' ); • mod : [ view_item | item ] * ; • View_item specifies visibility to other crates, such as extern_mod and use_mod, which point to different paths. • Example: use core::float::sin

  11. functions • Example: • fn add(x: int, y: int) -> int { return x+ y; } Unsafe Functions: (must be prefixed with ‘unsafe’) • Dereferencing a raw pointer • Casting a raw pointer to a safe pointer type • Calling an unsafe function • Violate the memory-safety guarantee of Rust’s static semantics.

  12. Function Divergence • fn my_error(s: &str) -> ! { info!(s); fail!(); } • Never returns a value to the caller, every function must end with either a return or a diverging function. Example: Fn f(i: int) -> int { if I == 42 { return 42; } else { my_error!(“Bad Number!”) }} - Adding the ! Annotation to my_error informs Rust’s typechecker that, should the control ever enter my_error, no further type judgements about f need to hold.

  13. Structs and Enums Struct example: • struct Point {x: int, y: int} • let p = Point {x: 10, y: 11}; • let px: int = p.x; Enum example: • enum Animal { Dog, Cat }

  14. Traits Describes a set of method types. • Trait Shape { fn draw(&self, Surface); fn bounding_box(&self) -> BoundingBox; } Defines a trait with two methods and example of using this trait would be calling something such as: Value.bounding_box();

  15. Statements and Expressions • A statement is a component of a block, which is in turn a component of an outer expression or function. • Examples would be declaring variables and creating structs. • An expression in Rust must produce a value and have an effect on; such as part of a condition statement. • Examples would be literals, paths, tuple, structs, etc. that produce a value somehow. • Other types of expressions are Records, method calls, fields, index, unary operator, and binary operator. • Arithmetic and bitwise operations are identical to C++ along with operator precendence. • Swap: x <-> a

  16. Loops and If statements • while i < 10 { io::println("hello\n"); i = i + 1; } • for_expr : "for" expr [ '|' ident_list '|' ] ? '{' block '}' ; for v.each |e| { println(v.e); } • if_expr : "if" expr '{' block '}' else_tail ? ; • else_tail : "else" [ if_expr | '{' block '}' ] ; • If I < 10 { io::println(“hello\n”); }

  17. Keywords • Break • Copy • Do drop • Else enum extern • False fn for • If • Let loop • Match mod mut • Priv pub • Ref return • Self static struct • True trait type • Unsafe use • while

  18. Unique to Rust • Infinite loops can be defined as just ‘loop’ and adding of break/return statements. • For variables, the addition of ‘mut’ must be added in order to change the value of it later on. Also ‘let’ must be used when declaring variables. • Rust can almost always infer the types of local variables, but a type annotation is provided. • let stuff: int = 20;

  19. Unique (continued) • let price; • if item == "salad" { price = 3.50; } else if item == "muffin" { price = 2.25; } else { price = 2.00; } To simplify this, you do not need to copy price over each time, since the expression syntax is simplified: let price = if item == “salad” { 3.50 } else if item == “muffin” { 2.25 } else { 2.00 };

  20. Unique (syntax extensions) • // %? will conveniently print any type • Println(fmt!(“All the things: %?”, stuff)); • Macros can be used to create other syntax extensions, especially when yo uwant to abstract over compile-time syntax rather than run-time values. Such as turning: match input_1 { special_a(x) => { return x; } _ => {} } • Into just: early_return!(input_1 special_a);

  21. Match vs. Switch • match my_number { 0 => println("zero"), 1 | 2 => println("one or two"), 3..10 => println("three to ten"), _ => println("something else")

  22. Compiler • Required packages to build from source: • g++ 4.4 or clang++ 3.x • Python 2.6 or later • Perl 5.0 or later • Gnu make 3.81 • Curl • Then run configure, total time to build the compiler on my machine: 2.5 hours

  23. Examples:

  24. Examples:

  25. Sources: • http://web.mit.edu/rust-lang_v0.6/rust.pdf • http://www.rust-lang.org/ • http://static.rust-lang.org/doc/0.7/tutorial.html • http://en.wikipedia.org/wiki/Rust_%28programming_language%29

More Related