Skip to content

Commit 73c0472

Browse files
committed
---
yaml --- r: 148460 b: refs/heads/try2 c: 80a2306 h: refs/heads/master v: v3
1 parent 9c827a6 commit 73c0472

File tree

145 files changed

+2410
-1662
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

145 files changed

+2410
-1662
lines changed

[refs]

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ refs/heads/snap-stage3: 78a7676898d9f80ab540c6df5d4c9ce35bb50463
55
refs/heads/try: 519addf6277dbafccbb4159db4b710c37eaa2ec5
66
refs/tags/release-0.1: 1f5c5126e96c79d22cb7862f75304136e204f105
77
refs/heads/ndm: f3868061cd7988080c30d6d5bf352a5a5fe2460b
8-
refs/heads/try2: 1f542cd2640fd969cba328ca3b4059acd6428a83
8+
refs/heads/try2: 80a2306aee6bb6ccde8692521c32eb96fe942991
99
refs/heads/dist-snap: ba4081a5a8573875fed17545846f6f6902c8ba8d
1010
refs/tags/release-0.2: c870d2dffb391e14efb05aa27898f1f6333a9596
1111
refs/tags/release-0.3: b5f0d0f648d9a6153664837026ba1be43d3e2503

branches/try2/doc/guide-ffi.md

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,143 @@ fn main() {
249249
}
250250
~~~~
251251

252+
# Callbacks from C code to Rust functions
253+
254+
Some external libraries require the usage of callbacks to report back their
255+
current state or intermediate data to the caller.
256+
It is possible to pass functions defined in Rust to an external library.
257+
The requirement for this is that the callback function is marked as `extern`
258+
with the correct calling convention to make it callable from C code.
259+
260+
The callback function that can then be sent to through a registration call
261+
to the C library and afterwards be invoked from there.
262+
263+
A basic example is:
264+
265+
Rust code:
266+
~~~~ {.xfail-test}
267+
extern fn callback(a:i32) {
268+
println!("I'm called from C with value {0}", a);
269+
}
270+
271+
#[link(name = "extlib")]
272+
extern {
273+
fn register_callback(cb: extern "C" fn(i32)) -> i32;
274+
fn trigger_callback();
275+
}
276+
277+
fn main() {
278+
unsafe {
279+
register_callback(callback);
280+
trigger_callback(); // Triggers the callback
281+
}
282+
}
283+
~~~~
284+
285+
C code:
286+
~~~~ {.xfail-test}
287+
typedef void (*rust_callback)(int32_t);
288+
rust_callback cb;
289+
290+
int32_t register_callback(rust_callback callback) {
291+
cb = callback;
292+
return 1;
293+
}
294+
295+
void trigger_callback() {
296+
cb(7); // Will call callback(7) in Rust
297+
}
298+
~~~~
299+
300+
In this example will Rust's `main()` will call `do_callback()` in C,
301+
which would call back to `callback()` in Rust.
302+
303+
304+
## Targetting callbacks to Rust objects
305+
306+
The former example showed how a global function can be called from C-Code.
307+
However it is often desired that the callback is targetted to a special
308+
Rust object. This could be the object that represents the wrapper for the
309+
respective C object.
310+
311+
This can be achieved by passing an unsafe pointer to the object down to the
312+
C library. The C library can then include the pointer to the Rust object in
313+
the notification. This will provide a unsafe possibility to access the
314+
referenced Rust object in callback.
315+
316+
Rust code:
317+
~~~~ {.xfail-test}
318+
319+
struct RustObject {
320+
a: i32,
321+
// other members
322+
}
323+
324+
extern fn callback(target: *RustObject, a:i32) {
325+
println!("I'm called from C with value {0}", a);
326+
(*target).a = a; // Update the value in RustObject with the value received from the callback
327+
}
328+
329+
#[link(name = "extlib")]
330+
extern {
331+
fn register_callback(target: *RustObject, cb: extern "C" fn(*RustObject, i32)) -> i32;
332+
fn trigger_callback();
333+
}
334+
335+
fn main() {
336+
// Create the object that will be referenced in the callback
337+
let rust_object = ~RustObject{a: 5, ...};
338+
339+
unsafe {
340+
// Gets a raw pointer to the object
341+
let target_addr:*RustObject = ptr::to_unsafe_ptr(rust_object);
342+
register_callback(target_addr, callback);
343+
trigger_callback(); // Triggers the callback
344+
}
345+
}
346+
~~~~
347+
348+
C code:
349+
~~~~ {.xfail-test}
350+
typedef void (*rust_callback)(int32_t);
351+
void* cb_target;
352+
rust_callback cb;
353+
354+
int32_t register_callback(void* callback_target, rust_callback callback) {
355+
cb_target = callback_target;
356+
cb = callback;
357+
return 1;
358+
}
359+
360+
void trigger_callback() {
361+
cb(cb_target, 7); // Will call callback(&rustObject, 7) in Rust
362+
}
363+
~~~~
364+
365+
## Asynchronous callbacks
366+
367+
In the already given examples the callbacks are invoked as a direct reaction
368+
to a function call to the external C library.
369+
The control over the current thread switched from Rust to C to Rust for the
370+
execution of the callback, but in the end the callback is executed on the
371+
same thread (and Rust task) that lead called the function which triggered
372+
the callback.
373+
374+
Things get more complicated when the external library spawns it's own threads
375+
and invokes callbacks from there.
376+
In these cases access to Rust data structures inside he callbacks is
377+
especially unsafe and proper synchronization mechanisms must be used.
378+
Besides classical synchronization mechanisms like mutexes one possibility in
379+
Rust is to use channels (in `std::comm`) to forward data from the C thread
380+
that invoked the callback into a Rust task.
381+
382+
If an asychronous callback targets a special object in the Rust address space
383+
it is also absolutely necessary that no more callbacks are performed by the
384+
C library after the respective Rust object get's destroyed.
385+
This can be achieved by unregistering the callback it the object's
386+
destructor and designing the library in a way that guarantees that no
387+
callback will be performed after unregistration.
388+
252389
# Linking
253390

254391
The `link` attribute on `extern` blocks provides the basic building block for

branches/try2/doc/guide-tasks.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,7 @@ be distributed on the available cores.
290290
fn partial_sum(start: uint) -> f64 {
291291
let mut local_sum = 0f64;
292292
for num in range(start*100000, (start+1)*100000) {
293-
local_sum += (num as f64 + 1.0).pow(&-2.0);
293+
local_sum += (num as f64 + 1.0).powf(&-2.0);
294294
}
295295
local_sum
296296
}
@@ -326,7 +326,7 @@ a single large vector of floats. Each task needs the full vector to perform its
326326
use extra::arc::Arc;
327327
328328
fn pnorm(nums: &~[f64], p: uint) -> f64 {
329-
nums.iter().fold(0.0, |a,b| a+(*b).pow(&(p as f64)) ).pow(&(1.0 / (p as f64)))
329+
nums.iter().fold(0.0, |a,b| a+(*b).powf(&(p as f64)) ).powf(&(1.0 / (p as f64)))
330330
}
331331
332332
fn main() {

branches/try2/doc/guide-testing.md

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
3333
# Unit testing in Rust
3434

3535
Rust has built in support for simple unit testing. Functions can be
36-
marked as unit tests using the 'test' attribute.
36+
marked as unit tests using the `test` attribute.
3737

3838
~~~
3939
#[test]
@@ -44,13 +44,13 @@ fn return_none_if_empty() {
4444

4545
A test function's signature must have no arguments and no return
4646
value. To run the tests in a crate, it must be compiled with the
47-
'--test' flag: `rustc myprogram.rs --test -o myprogram-tests`. Running
47+
`--test` flag: `rustc myprogram.rs --test -o myprogram-tests`. Running
4848
the resulting executable will run all the tests in the crate. A test
4949
is considered successful if its function returns; if the task running
5050
the test fails, through a call to `fail!`, a failed `check` or
5151
`assert`, or some other (`assert_eq`, ...) means, then the test fails.
5252

53-
When compiling a crate with the '--test' flag '--cfg test' is also
53+
When compiling a crate with the `--test` flag `--cfg test` is also
5454
implied, so that tests can be conditionally compiled.
5555

5656
~~~
@@ -63,18 +63,18 @@ mod tests {
6363
}
6464
~~~
6565

66-
Additionally #[test] items behave as if they also have the
67-
#[cfg(test)] attribute, and will not be compiled when the --test flag
66+
Additionally `#[test]` items behave as if they also have the
67+
`#[cfg(test)]` attribute, and will not be compiled when the `--test` flag
6868
is not used.
6969

70-
Tests that should not be run can be annotated with the 'ignore'
70+
Tests that should not be run can be annotated with the `ignore`
7171
attribute. The existence of these tests will be noted in the test
7272
runner output, but the test will not be run. Tests can also be ignored
7373
by configuration so, for example, to ignore a test on windows you can
7474
write `#[ignore(cfg(target_os = "win32"))]`.
7575

7676
Tests that are intended to fail can be annotated with the
77-
'should_fail' attribute. The test will be run, and if it causes its
77+
`should_fail` attribute. The test will be run, and if it causes its
7878
task to fail then the test will be counted as successful; otherwise it
7979
will be counted as a failure. For example:
8080

@@ -87,11 +87,11 @@ fn test_out_of_bounds_failure() {
8787
}
8888
~~~
8989

90-
A test runner built with the '--test' flag supports a limited set of
90+
A test runner built with the `--test` flag supports a limited set of
9191
arguments to control which tests are run: the first free argument
9292
passed to a test runner specifies a filter used to narrow down the set
93-
of tests being run; the '--ignored' flag tells the test runner to run
94-
only tests with the 'ignore' attribute.
93+
of tests being run; the `--ignored` flag tells the test runner to run
94+
only tests with the `ignore` attribute.
9595

9696
## Parallelism
9797

branches/try2/doc/rust.md

Lines changed: 50 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -2211,12 +2211,9 @@ dereferences (`*expr`), [indexing expressions](#index-expressions)
22112211
(`expr[expr]`), and [field references](#field-expressions) (`expr.f`).
22122212
All other expressions are rvalues.
22132213

2214-
The left operand of an [assignment](#assignment-expressions),
2215-
[binary move](#binary-move-expressions) or
2214+
The left operand of an [assignment](#assignment-expressions) or
22162215
[compound-assignment](#compound-assignment-expressions) expression is an lvalue context,
2217-
as is the single operand of a unary [borrow](#unary-operator-expressions),
2218-
or [move](#unary-move-expressions) expression,
2219-
and _both_ operands of a [swap](#swap-expressions) expression.
2216+
as is the single operand of a unary [borrow](#unary-operator-expressions).
22202217
All other expression contexts are rvalue contexts.
22212218

22222219
When an lvalue is evaluated in an _lvalue context_, it denotes a memory location;
@@ -2229,9 +2226,8 @@ A temporary's lifetime equals the largest lifetime of any reference that points
22292226

22302227
When a [local variable](#memory-slots) is used
22312228
as an [rvalue](#lvalues-rvalues-and-temporaries)
2232-
the variable will either be [moved](#move-expressions) or copied,
2233-
depending on its type.
2234-
For types that contain [owning pointers](#owning-pointers)
2229+
the variable will either be moved or copied, depending on its type.
2230+
For types that contain [owning pointers](#pointer-types)
22352231
or values that implement the special trait `Drop`,
22362232
the variable is moved.
22372233
All other types are copied.
@@ -2890,16 +2886,26 @@ match x {
28902886

28912887
The first pattern matches lists constructed by applying `Cons` to any head value, and a
28922888
tail value of `~Nil`. The second pattern matches _any_ list constructed with `Cons`,
2893-
ignoring the values of its arguments. The difference between `_` and `*` is that the pattern `C(_)` is only type-correct if
2894-
`C` has exactly one argument, while the pattern `C(..)` is type-correct for any enum variant `C`, regardless of how many arguments `C` has.
2895-
2896-
To execute an `match` expression, first the head expression is evaluated, then
2897-
its value is sequentially compared to the patterns in the arms until a match
2889+
ignoring the values of its arguments. The difference between `_` and `*` is that the pattern
2890+
`C(_)` is only type-correct if `C` has exactly one argument, while the pattern `C(..)` is
2891+
type-correct for any enum variant `C`, regardless of how many arguments `C` has.
2892+
2893+
A `match` behaves differently depending on whether or not the head expression
2894+
is an [lvalue or an rvalue](#lvalues-rvalues-and-temporaries).
2895+
If the head expression is an rvalue, it is
2896+
first evaluated into a temporary location, and the resulting value
2897+
is sequentially compared to the patterns in the arms until a match
28982898
is found. The first arm with a matching pattern is chosen as the branch target
28992899
of the `match`, any variables bound by the pattern are assigned to local
29002900
variables in the arm's block, and control enters the block.
29012901

2902-
An example of an `match` expression:
2902+
When the head expression is an lvalue, the match does not allocate a
2903+
temporary location (however, a by-value binding may copy or move from
2904+
the lvalue). When possible, it is preferable to match on lvalues, as the
2905+
lifetime of these matches inherits the lifetime of the lvalue, rather
2906+
than being restricted to the inside of the match.
2907+
2908+
An example of a `match` expression:
29032909

29042910
~~~~
29052911
# fn process_pair(a: int, b: int) { }
@@ -2929,19 +2935,31 @@ Patterns that bind variables
29292935
default to binding to a copy or move of the matched value
29302936
(depending on the matched value's type).
29312937
This can be changed to bind to a reference by
2932-
using the ```ref``` keyword,
2933-
or to a mutable reference using ```ref mut```.
2934-
2935-
A pattern that's just an identifier,
2936-
like `Nil` in the previous answer,
2937-
could either refer to an enum variant that's in scope,
2938-
or bind a new variable.
2939-
The compiler resolves this ambiguity by forbidding variable bindings that occur in ```match``` patterns from shadowing names of variants that are in scope.
2940-
For example, wherever ```List``` is in scope,
2941-
a ```match``` pattern would not be able to bind ```Nil``` as a new name.
2942-
The compiler interprets a variable pattern `x` as a binding _only_ if there is no variant named `x` in scope.
2943-
A convention you can use to avoid conflicts is simply to name variants with upper-case letters,
2944-
and local variables with lower-case letters.
2938+
using the `ref` keyword,
2939+
or to a mutable reference using `ref mut`.
2940+
2941+
Patterns can also dereference pointers by using the `&`,
2942+
`~` or `@` symbols, as appropriate. For example, these two matches
2943+
on `x: &int` are equivalent:
2944+
2945+
~~~~
2946+
# let x = &3;
2947+
let y = match *x { 0 => "zero", _ => "some" };
2948+
let z = match x { &0 => "zero", _ => "some" };
2949+
2950+
assert_eq!(y, z);
2951+
~~~~
2952+
2953+
A pattern that's just an identifier, like `Nil` in the previous answer,
2954+
could either refer to an enum variant that's in scope, or bind a new variable.
2955+
The compiler resolves this ambiguity by forbidding variable bindings that occur
2956+
in `match` patterns from shadowing names of variants that are in scope.
2957+
For example, wherever `List` is in scope,
2958+
a `match` pattern would not be able to bind `Nil` as a new name.
2959+
The compiler interprets a variable pattern `x` as a binding _only_ if there is
2960+
no variant named `x` in scope.
2961+
A convention you can use to avoid conflicts is simply to name variants with
2962+
upper-case letters, and local variables with lower-case letters.
29452963

29462964
Multiple match patterns may be joined with the `|` operator.
29472965
A range of values may be specified with `..`.
@@ -3122,19 +3140,20 @@ A `struct` *type* is a heterogeneous product of other types, called the *fields*
31223140
the *record* types of the ML family,
31233141
or the *structure* types of the Lisp family.]
31243142

3125-
New instances of a `struct` can be constructed with a [struct expression](#struct-expressions).
3143+
New instances of a `struct` can be constructed with a [struct expression](#structure-expressions).
31263144

31273145
The memory order of fields in a `struct` is given by the item defining it.
31283146
Fields may be given in any order in a corresponding struct *expression*;
31293147
the resulting `struct` value will always be laid out in memory in the order specified by the corresponding *item*.
31303148

3131-
The fields of a `struct` may be qualified by [visibility modifiers](#visibility-modifiers),
3149+
The fields of a `struct` may be qualified by [visibility modifiers](#re-exporting-and-visibility),
31323150
to restrict access to implementation-private data in a structure.
31333151

31343152
A _tuple struct_ type is just like a structure type, except that the fields are anonymous.
31353153

31363154
A _unit-like struct_ type is like a structure type, except that it has no fields.
3137-
The one value constructed by the associated [structure expression](#structure-expression) is the only value that inhabits such a type.
3155+
The one value constructed by the associated [structure expression](#structure-expressions)
3156+
is the only value that inhabits such a type.
31383157

31393158
### Enumerated types
31403159

@@ -3805,7 +3824,7 @@ over the output format of a Rust crate.
38053824
### Logging system
38063825

38073826
The runtime contains a system for directing [logging
3808-
expressions](#log-expressions) to a logging console and/or internal logging
3827+
expressions](#logging-expressions) to a logging console and/or internal logging
38093828
buffers. Logging can be enabled per module.
38103829

38113830
Logging output is enabled by setting the `RUST_LOG` environment

branches/try2/doc/tutorial.md

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1020,10 +1020,15 @@ being destroyed along with the owner. Since the `list` variable above is
10201020
immutable, the whole list is immutable. The memory allocation itself is the
10211021
box, while the owner holds onto a pointer to it:
10221022

1023-
Cons cell Cons cell Cons cell
1024-
+-----------+ +-----+-----+ +-----+-----+
1025-
| 1 | ~ | -> | 2 | ~ | -> | 3 | ~ | -> Nil
1026-
+-----------+ +-----+-----+ +-----+-----+
1023+
List box List box List box List box
1024+
+--------------+ +--------------+ +--------------+ +--------------+
1025+
list -> | Cons | 1 | ~ | -> | Cons | 2 | ~ | -> | Cons | 3 | ~ | -> | Nil |
1026+
+--------------+ +--------------+ +--------------+ +--------------+
1027+
1028+
> Note: the above diagram shows the logical contents of the enum. The actual
1029+
> memory layout of the enum may vary. For example, for the `List` enum shown
1030+
> above, Rust guarantees that there will be no enum tag field in the actual
1031+
> structure. See the language reference for more details.
10271032
10281033
An owned box is a common example of a type with a destructor. The allocated
10291034
memory is cleaned up when the box is destroyed.

0 commit comments

Comments
 (0)