Struct Codebase

Source
pub struct Codebase { /* private fields */ }
Expand description

Codebase. A struct that holds all your code in memory (codespan forces this)

Implementations§

Source§

impl Codebase

Source

pub fn new() -> Self

Create a new codebase.

Examples found in repository?
examples/simple_c_lexer.rs (line 12)
4pub fn main() {
5    let args = std::env::args().collect::<Vec<_>>();
6    if args.len() != 2 {
7        eprintln!("Usage: cargo run --example simple_c_lexer -- sample.c");
8        return;
9    }
10
11    let code = std::fs::read_to_string(&args[1]).unwrap();
12    let mut codebase = Codebase::new();
13    let key = codebase.add(args[1].clone(), code);
14
15    let mut reader = TokenReader::new(codebase.get(key).unwrap().source().clone());
16    while let Some(char) = reader.next_char() {
17        if chars::is_digit(char) {
18            // * Number
19            println!("Number {}", reader.next_token(chars::is_digit, char));
20        } else if chars::is_ident_start(char) {
21            // * Identifier
22            println!(
23                "Ident {}",
24                reader.next_token(chars::is_ident_continue, char)
25            );
26        } else if char == '"' {
27            // * String
28            let mut string = String::new();
29            loop {
30                match reader.next_char() {
31                    // Escape sequences
32                    Some('\\') => match reader.next_char() {
33                        Some('n') => string.push('\n'),
34                        Some(char) => string.push(char),
35                        None => codebase.emit( // Technically won't happen
36                            Diagnostic::error()
37                                .with_message("expected escape code")
38                                .with_labels(vec![Label::primary(
39                                    key,
40                                    reader.cursor..reader.cursor + 1,
41                                )
42                                .with_message("here")]),
43                        ),
44                    },
45
46                    // Quote
47                    Some('"') => break,
48
49                    // Char
50                    Some(char) if char != '\n' => string.push(char),
51                    _ => {
52                        codebase.emit(
53                            Diagnostic::error()
54                                .with_message("unterminated string")
55                                .with_labels(vec![Label::primary(
56                                    key,
57                                    reader.cursor..reader.cursor + 1,
58                                )
59                                .with_message("here")]),
60                        );
61                        break;
62                    }
63                }
64            }
65            println!("String {:?}", string);
66        } else if ['(', ')', '{', '}', ';'].contains(&char) {
67            // * Operator
68            println!("Operator {}", char);
69        }
70    }
71}
Source

pub fn add(&mut self, name: String, source: String) -> usize

Add a file to the codebase, returning the handle that can be used to refer to it again.

Examples found in repository?
examples/simple_c_lexer.rs (line 13)
4pub fn main() {
5    let args = std::env::args().collect::<Vec<_>>();
6    if args.len() != 2 {
7        eprintln!("Usage: cargo run --example simple_c_lexer -- sample.c");
8        return;
9    }
10
11    let code = std::fs::read_to_string(&args[1]).unwrap();
12    let mut codebase = Codebase::new();
13    let key = codebase.add(args[1].clone(), code);
14
15    let mut reader = TokenReader::new(codebase.get(key).unwrap().source().clone());
16    while let Some(char) = reader.next_char() {
17        if chars::is_digit(char) {
18            // * Number
19            println!("Number {}", reader.next_token(chars::is_digit, char));
20        } else if chars::is_ident_start(char) {
21            // * Identifier
22            println!(
23                "Ident {}",
24                reader.next_token(chars::is_ident_continue, char)
25            );
26        } else if char == '"' {
27            // * String
28            let mut string = String::new();
29            loop {
30                match reader.next_char() {
31                    // Escape sequences
32                    Some('\\') => match reader.next_char() {
33                        Some('n') => string.push('\n'),
34                        Some(char) => string.push(char),
35                        None => codebase.emit( // Technically won't happen
36                            Diagnostic::error()
37                                .with_message("expected escape code")
38                                .with_labels(vec![Label::primary(
39                                    key,
40                                    reader.cursor..reader.cursor + 1,
41                                )
42                                .with_message("here")]),
43                        ),
44                    },
45
46                    // Quote
47                    Some('"') => break,
48
49                    // Char
50                    Some(char) if char != '\n' => string.push(char),
51                    _ => {
52                        codebase.emit(
53                            Diagnostic::error()
54                                .with_message("unterminated string")
55                                .with_labels(vec![Label::primary(
56                                    key,
57                                    reader.cursor..reader.cursor + 1,
58                                )
59                                .with_message("here")]),
60                        );
61                        break;
62                    }
63                }
64            }
65            println!("String {:?}", string);
66        } else if ['(', ')', '{', '}', ';'].contains(&char) {
67            // * Operator
68            println!("Operator {}", char);
69        }
70    }
71}
Source

pub fn get(&self, file_id: usize) -> Result<&SimpleFile<String, Rc<str>>, Error>

Get the file corresponding to the given id.

Examples found in repository?
examples/simple_c_lexer.rs (line 15)
4pub fn main() {
5    let args = std::env::args().collect::<Vec<_>>();
6    if args.len() != 2 {
7        eprintln!("Usage: cargo run --example simple_c_lexer -- sample.c");
8        return;
9    }
10
11    let code = std::fs::read_to_string(&args[1]).unwrap();
12    let mut codebase = Codebase::new();
13    let key = codebase.add(args[1].clone(), code);
14
15    let mut reader = TokenReader::new(codebase.get(key).unwrap().source().clone());
16    while let Some(char) = reader.next_char() {
17        if chars::is_digit(char) {
18            // * Number
19            println!("Number {}", reader.next_token(chars::is_digit, char));
20        } else if chars::is_ident_start(char) {
21            // * Identifier
22            println!(
23                "Ident {}",
24                reader.next_token(chars::is_ident_continue, char)
25            );
26        } else if char == '"' {
27            // * String
28            let mut string = String::new();
29            loop {
30                match reader.next_char() {
31                    // Escape sequences
32                    Some('\\') => match reader.next_char() {
33                        Some('n') => string.push('\n'),
34                        Some(char) => string.push(char),
35                        None => codebase.emit( // Technically won't happen
36                            Diagnostic::error()
37                                .with_message("expected escape code")
38                                .with_labels(vec![Label::primary(
39                                    key,
40                                    reader.cursor..reader.cursor + 1,
41                                )
42                                .with_message("here")]),
43                        ),
44                    },
45
46                    // Quote
47                    Some('"') => break,
48
49                    // Char
50                    Some(char) if char != '\n' => string.push(char),
51                    _ => {
52                        codebase.emit(
53                            Diagnostic::error()
54                                .with_message("unterminated string")
55                                .with_labels(vec![Label::primary(
56                                    key,
57                                    reader.cursor..reader.cursor + 1,
58                                )
59                                .with_message("here")]),
60                        );
61                        break;
62                    }
63                }
64            }
65            println!("String {:?}", string);
66        } else if ['(', ')', '{', '}', ';'].contains(&char) {
67            // * Operator
68            println!("Operator {}", char);
69        }
70    }
71}
Source

pub fn emit(&mut self, diagnostic: Diagnostic<usize>)

Emit a diagnostic

Examples found in repository?
examples/simple_c_lexer.rs (lines 35-43)
4pub fn main() {
5    let args = std::env::args().collect::<Vec<_>>();
6    if args.len() != 2 {
7        eprintln!("Usage: cargo run --example simple_c_lexer -- sample.c");
8        return;
9    }
10
11    let code = std::fs::read_to_string(&args[1]).unwrap();
12    let mut codebase = Codebase::new();
13    let key = codebase.add(args[1].clone(), code);
14
15    let mut reader = TokenReader::new(codebase.get(key).unwrap().source().clone());
16    while let Some(char) = reader.next_char() {
17        if chars::is_digit(char) {
18            // * Number
19            println!("Number {}", reader.next_token(chars::is_digit, char));
20        } else if chars::is_ident_start(char) {
21            // * Identifier
22            println!(
23                "Ident {}",
24                reader.next_token(chars::is_ident_continue, char)
25            );
26        } else if char == '"' {
27            // * String
28            let mut string = String::new();
29            loop {
30                match reader.next_char() {
31                    // Escape sequences
32                    Some('\\') => match reader.next_char() {
33                        Some('n') => string.push('\n'),
34                        Some(char) => string.push(char),
35                        None => codebase.emit( // Technically won't happen
36                            Diagnostic::error()
37                                .with_message("expected escape code")
38                                .with_labels(vec![Label::primary(
39                                    key,
40                                    reader.cursor..reader.cursor + 1,
41                                )
42                                .with_message("here")]),
43                        ),
44                    },
45
46                    // Quote
47                    Some('"') => break,
48
49                    // Char
50                    Some(char) if char != '\n' => string.push(char),
51                    _ => {
52                        codebase.emit(
53                            Diagnostic::error()
54                                .with_message("unterminated string")
55                                .with_labels(vec![Label::primary(
56                                    key,
57                                    reader.cursor..reader.cursor + 1,
58                                )
59                                .with_message("here")]),
60                        );
61                        break;
62                    }
63                }
64            }
65            println!("String {:?}", string);
66        } else if ['(', ')', '{', '}', ';'].contains(&char) {
67            // * Operator
68            println!("Operator {}", char);
69        }
70    }
71}
Source

pub fn files(&self) -> &Vec<SimpleFile<String, Rc<str>>>

Source

pub fn errors(&self) -> usize

Get the number of errors emitted

Source

pub fn warnings(&self) -> usize

Get the number of warnings emitted

Trait Implementations§

Source§

impl Debug for Codebase

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Codebase

Source§

fn default() -> Codebase

Returns the “default value” for a type. Read more
Source§

impl<'a> Files<'a> for Codebase

Source§

type FileId = usize

A unique identifier for files in the file provider. This will be used for rendering diagnostic::Labels in the corresponding source files.
Source§

type Name = String

The user-facing name of a file, to be displayed in diagnostics.
Source§

type Source = &'a str

The source code of a file.
Source§

fn name(&self, file_id: usize) -> Result<String, Error>

The user-facing name of a file.
Source§

fn source(&self, file_id: usize) -> Result<&str, Error>

The source code of a file.
Source§

fn line_index(&self, file_id: usize, byte_index: usize) -> Result<usize, Error>

The index of the line at the given byte index. If the byte index is past the end of the file, returns the maximum line index in the file. This means that this function only fails if the file is not present. Read more
Source§

fn line_range( &self, file_id: usize, line_index: usize, ) -> Result<Range<usize>, Error>

The byte range of line in the source of the file.
Source§

fn line_number( &'a self, id: Self::FileId, line_index: usize, ) -> Result<usize, Error>

The user-facing line number at the given line index. It is not necessarily checked that the specified line index is actually in the file. Read more
Source§

fn column_number( &'a self, id: Self::FileId, line_index: usize, byte_index: usize, ) -> Result<usize, Error>

The user-facing column number at the given line index and byte index. Read more
Source§

fn location( &'a self, id: Self::FileId, byte_index: usize, ) -> Result<Location, Error>

Convenience method for returning line and column number at the given byte index in the file.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.