From ff107cf3e75acf041f8b7631337d299cdeaa1685 Mon Sep 17 00:00:00 2001 From: Laurenz Date: Thu, 12 Dec 2019 22:19:38 +0100 Subject: [PATCH] =?UTF-8?q?Tidying=20up=20=F0=9F=A7=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/bin/main.rs | 56 ++++++++++++++-------------------------- src/export/pdf.rs | 18 ++++++++----- src/layout/mod.rs | 22 +++++++--------- src/layout/text.rs | 3 ++- src/layout/tree.rs | 5 ++++ src/lib.rs | 19 +++++++------- src/library/direction.rs | 2 +- src/library/mod.rs | 23 ++++++++--------- src/size.rs | 3 +-- src/style.rs | 5 ++-- src/syntax/mod.rs | 12 +++------ src/syntax/parsing.rs | 7 +++-- src/syntax/tokens.rs | 17 ++++++------ 13 files changed, 88 insertions(+), 104 deletions(-) diff --git a/src/bin/main.rs b/src/bin/main.rs index f5e4a8444..a2b63d6d7 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -1,67 +1,49 @@ -use std::env; -use std::error::Error; -use std::fs::File; -use std::io::{BufWriter, Read}; +use std::fs::{File, read_to_string}; +use std::io::BufWriter; use std::path::{Path, PathBuf}; -use std::process; -use typstc::export::pdf::PdfExporter; -use typstc::toddle::query::FileSystemFontProvider; use typstc::Typesetter; +use typstc::toddle::query::FileSystemFontProvider; +use typstc::export::pdf::PdfExporter; fn main() { if let Err(err) = run() { eprintln!("error: {}", err); - process::exit(1); + std::process::exit(1); } } -fn run() -> Result<(), Box> { - let args: Vec = env::args().collect(); +fn run() -> Result<(), Box> { + let args: Vec = std::env::args().collect(); if args.len() < 2 || args.len() > 3 { - help_and_quit(); + println!("usage: {} source [destination]", + args.first().map(|s| s.as_str()).unwrap_or("typst")); + std::process::exit(0); } - let source_path = Path::new(&args[1]); - let dest_path = if args.len() <= 2 { - source_path.with_extension("pdf") + let source = Path::new(&args[1]); + let dest = if args.len() <= 2 { + source.with_extension("pdf") } else { PathBuf::from(&args[2]) }; - if dest_path == source_path { - return err("source and destination path are the same"); + if source == dest { + Err("source and destination path are the same")?; } - let mut source_file = File::open(source_path) - .map_err(|_| "failed to open source file")?; - - let mut src = String::new(); - source_file - .read_to_string(&mut src) + let src = read_to_string(source) .map_err(|_| "failed to read from source file")?; let mut typesetter = Typesetter::new(); let provider = FileSystemFontProvider::from_listing("fonts/fonts.toml").unwrap(); typesetter.add_font_provider(provider); - let document = typesetter.typeset(&src)?; + let layouts = typesetter.typeset(&src)?; let exporter = PdfExporter::new(); - let dest_file = File::create(&dest_path)?; - exporter.export(&document, typesetter.loader(), BufWriter::new(dest_file))?; + let writer = BufWriter::new(File::create(&dest)?); + exporter.export(&layouts, typesetter.loader(), writer)?; Ok(()) } - -/// Construct an error `Result` from a message. -fn err, T>(message: S) -> Result> { - Err(message.into().into()) -} - -/// Print a usage message and exit the process. -fn help_and_quit() { - let name = env::args().next().unwrap_or("typst".to_string()); - println!("usage: {} source [destination]", name); - process::exit(0); -} diff --git a/src/export/pdf.rs b/src/export/pdf.rs index 8eca03748..0d097a33d 100644 --- a/src/export/pdf.rs +++ b/src/export/pdf.rs @@ -3,19 +3,23 @@ use std::collections::{HashMap, HashSet}; use std::io::{self, Write}; +use tide::{PdfWriter, Rect, Ref, Trailer, Version}; use tide::content::Content; use tide::doc::{Catalog, Page, PageTree, Resource, Text}; -use tide::font::{CIDFont, CIDFontType, CIDSystemInfo, FontDescriptor, FontFlags, Type0Font}; -use tide::font::{CMap, CMapEncoding, FontStream, GlyphUnit, WidthRecord}; -use tide::{PdfWriter, Rect, Ref, Trailer, Version}; +use tide::font::{ + CIDFont, CIDFontType, CIDSystemInfo, FontDescriptor, FontFlags, Type0Font, + CMap, CMapEncoding, FontStream, GlyphUnit, WidthRecord +}; +use toddle::Error as FontError; use toddle::font::OwnedFont; use toddle::query::SharedFontLoader; -use toddle::tables::{CharMap, Header, HorizontalMetrics, MacStyleFlags}; -use toddle::tables::{Name, NameEntry, Post, OS2}; -use toddle::Error as FontError; +use toddle::tables::{ + CharMap, Header, HorizontalMetrics, MacStyleFlags, + Name, NameEntry, Post, OS2 +}; -use crate::layout::{Layout, LayoutAction, MultiLayout}; +use crate::layout::{MultiLayout, Layout, LayoutAction}; use crate::size::Size; /// Exports layouts into _PDFs_. diff --git a/src/layout/mod.rs b/src/layout/mod.rs index fa3a8866c..363eb14bc 100644 --- a/src/layout/mod.rs +++ b/src/layout/mod.rs @@ -2,14 +2,10 @@ use std::io::{self, Write}; use smallvec::SmallVec; +use toddle::query::SharedFontLoader; -use toddle::query::{FontClass, SharedFontLoader}; - -use crate::TypesetResult; -use crate::func::Command; use crate::size::{Size, Size2D, SizeBox}; -use crate::style::{LayoutStyle, TextStyle}; -use crate::syntax::{Node, SyntaxTree, FuncCall}; +use crate::style::LayoutStyle; mod actions; mod tree; @@ -25,8 +21,11 @@ pub mod layouters { pub use super::text::{layout_text, TextContext}; } -pub use actions::{LayoutAction, LayoutActions}; -pub use layouters::*; +pub use self::actions::{LayoutAction, LayoutActions}; +pub use self::layouters::*; + +/// The result type for layouting. +pub type LayoutResult = crate::TypesetResult; /// A collection of layouts. pub type MultiLayout = Vec; @@ -368,8 +367,8 @@ pub enum SpacingKind { /// The standard spacing kind used for paragraph spacing. const PARAGRAPH_KIND: SpacingKind = SpacingKind::Soft(1); -/// The standard spacing kind used for normal spaces between boxes. -const SPACE_KIND: SpacingKind = SpacingKind::Soft(2); +/// The standard spacing kind used for line spacing. +const LINE_KIND: SpacingKind = SpacingKind::Soft(2); /// The last appeared spacing. #[derive(Debug, Copy, Clone, PartialEq)] @@ -416,6 +415,3 @@ impl Serialize for MultiLayout { Ok(()) } } - -/// The result type for layouting. -pub type LayoutResult = TypesetResult; diff --git a/src/layout/text.rs b/src/layout/text.rs index 5ecc40cc9..af74df136 100644 --- a/src/layout/text.rs +++ b/src/layout/text.rs @@ -1,8 +1,9 @@ use toddle::query::{SharedFontLoader, FontQuery, FontClass}; use toddle::tables::{CharMap, Header, HorizontalMetrics}; -use super::*; use crate::size::{Size, Size2D}; +use crate::style::TextStyle; +use super::*; /// The context for text layouting. /// diff --git a/src/layout/tree.rs b/src/layout/tree.rs index 195b6075e..9c909d9c4 100644 --- a/src/layout/tree.rs +++ b/src/layout/tree.rs @@ -1,4 +1,9 @@ use smallvec::smallvec; +use toddle::query::FontClass; + +use crate::func::Command; +use crate::syntax::{SyntaxTree, Node, FuncCall}; +use crate::style::TextStyle; use super::*; /// Layout a syntax tree into a multibox. diff --git a/src/lib.rs b/src/lib.rs index 5b5e3b0ce..8e5d1441f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,11 +8,13 @@ //! - **Layouting:** The next step is to transform the syntax tree into a //! portable representation of the typesetted document. Types for these can be //! found in the [layout] module. A finished layout reading for exporting is a -//! [multi layout](crate::layout::MultiLayout) consisting of multiple boxes (or -//! pages). -//! - **Exporting:** The finished document can finally be exported into a supported -//! format. Submodules for these formats are located in the [export](crate::export) -//! module. Currently, the only supported output format is _PDF_. +//! [multi-layout](crate::layout::MultiLayout) consisting of multiple boxes +//! (or pages). +//! - **Exporting:** The finished layout can then be exported into a supported +//! format. Submodules for these formats are located in the +//! [export](crate::export) module. Currently, the only supported output +//! format is _PDF_. Alternatively, the layout can be serialized to pass it to +//! a suitable renderer. #![allow(unused)] @@ -25,9 +27,8 @@ use toddle::query::{FontLoader, FontProvider, SharedFontLoader}; use toddle::Error as FontError; use crate::func::Scope; -use crate::layout::{layout_tree, MultiLayout, LayoutContext}; -use crate::layout::{LayoutAxes, LayoutAlignment}; -use crate::layout::{LayoutResult, LayoutSpace, LayoutExpansion}; +use crate::layout::{layout_tree, MultiLayout, LayoutContext, LayoutResult}; +use crate::layout::{LayoutSpace, LayoutExpansion, LayoutAxes, LayoutAlignment}; use crate::syntax::{parse, SyntaxTree, ParseContext, Span, ParseResult}; use crate::style::{LayoutStyle, PageStyle, TextStyle}; @@ -38,9 +39,9 @@ pub mod export; pub mod func; pub mod layout; pub mod library; +pub mod syntax; pub mod size; pub mod style; -pub mod syntax; /// Transforms source code into typesetted layouts. /// diff --git a/src/library/direction.rs b/src/library/direction.rs index 3b9956d1a..7edad323a 100644 --- a/src/library/direction.rs +++ b/src/library/direction.rs @@ -3,7 +3,7 @@ use super::maps::ConsistentMap; use super::keys::AxisKey; function! { - /// `direction`: Sets the directions for the layouting axes. + /// `direction`: Sets the directions of the layouting axes. #[derive(Debug, PartialEq)] pub struct Direction { body: Option, diff --git a/src/library/mod.rs b/src/library/mod.rs index 342b2721d..b6561d5a2 100644 --- a/src/library/mod.rs +++ b/src/library/mod.rs @@ -1,18 +1,17 @@ -//! The standard library for the _Typst_ language. +//! The standard library. -use crate::func::prelude::*; use toddle::query::FontClass; -use keys::*; -use maps::*; - -pub_use_mod!(align); -pub_use_mod!(boxed); -pub_use_mod!(direction); +use crate::func::prelude::*; +use self::keys::*; +use self::maps::*; pub mod maps; pub mod keys; +pub_use_mod!(align); +pub_use_mod!(boxed); +pub_use_mod!(direction); /// Create a scope with all standard functions. pub fn std() -> Scope { @@ -100,7 +99,7 @@ function! { } function! { - /// `page.margins`: Set the margins of pages. + /// `page.margins`: Sets the page margins. #[derive(Debug, PartialEq)] pub struct PageMargins { map: PaddingMap, @@ -121,7 +120,7 @@ function! { } function! { - /// `spacing`, `h`, `v`: Add spacing along an axis. + /// `spacing`, `h`, `v`: Adds spacing along an axis. #[derive(Debug, PartialEq)] pub struct Spacing { axis: AxisKey, @@ -192,7 +191,7 @@ function! { } function! { - /// `font.size`: Set the font size. + /// `font.size`: Sets the font size. #[derive(Debug, PartialEq)] pub struct FontSize { body: Option, @@ -206,7 +205,7 @@ function! { } } - layout(self, mut ctx) { + layout(self, ctx) { let mut style = ctx.style.text.clone(); style.font_size = self.size; diff --git a/src/size.rs b/src/size.rs index 7b0b76aec..97d04815d 100644 --- a/src/size.rs +++ b/src/size.rs @@ -1,12 +1,11 @@ //! Different-dimensional spacing types. -use std::cmp::Ordering; use std::fmt::{self, Display, Formatter}; use std::iter::Sum; use std::ops::*; use std::str::FromStr; -use crate::layout::{LayoutAxes, LayoutAlignment, Axis, GenericAxisKind, Alignment}; +use crate::layout::{LayoutAxes, Axis, GenericAxisKind, LayoutAlignment, Alignment}; /// A general spacing type. diff --git a/src/style.rs b/src/style.rs index aa6f9d6c8..616619e1a 100644 --- a/src/style.rs +++ b/src/style.rs @@ -2,6 +2,7 @@ use toddle::query::FontClass; use FontClass::*; + use crate::size::{Size, Size2D, SizeBox}; /// Defines properties of pages and text. @@ -58,8 +59,8 @@ impl TextStyle { } else { // If we add an Italic or Bold class, we remove // the Regular class. - if class == FontClass::Italic || class == FontClass::Bold { - self.classes.retain(|x| x != &FontClass::Regular); + if class == Italic || class == Bold { + self.classes.retain(|x| x != &Regular); } self.classes.push(class); diff --git a/src/syntax/mod.rs b/src/syntax/mod.rs index a3fe06bd0..2f64bc9b4 100644 --- a/src/syntax/mod.rs +++ b/src/syntax/mod.rs @@ -6,14 +6,9 @@ use unicode_xid::UnicodeXID; use crate::func::LayoutFunc; use crate::size::{Size, ScaleSize}; -mod tokens; -#[macro_use] -mod parsing; -mod span; - -pub use span::{Span, Spanned}; -pub use tokens::{tokenize, Tokens}; -pub use parsing::{parse, ParseContext, ParseResult}; +pub_use_mod!(tokens); +pub_use_mod!(parsing); +pub_use_mod!(span); /// A logical unit of the incoming text stream. #[derive(Debug, Copy, Clone, Eq, PartialEq)] @@ -185,6 +180,7 @@ impl FuncArgs { } } +/// Extract the option expression kind from the option or return an error. fn expect(opt: ParseResult>>) -> ParseResult> { match opt { Ok(Some(spanned)) => Ok(spanned), diff --git a/src/syntax/parsing.rs b/src/syntax/parsing.rs index 9fe6c5846..d887d8981 100644 --- a/src/syntax/parsing.rs +++ b/src/syntax/parsing.rs @@ -1,10 +1,12 @@ //! Parsing of token streams into syntax trees. -use crate::TypesetResult; use crate::func::Scope; use crate::size::Size; use super::*; +/// The result type for parsing. +pub type ParseResult = crate::TypesetResult; + /// Parses source code into a syntax tree given a context. pub fn parse(src: &str, ctx: ParseContext) -> ParseResult { Parser::new(src, ctx).parse() @@ -404,9 +406,6 @@ impl<'s> Iterator for PeekableTokens<'s> { } } -/// The result type for parsing. -pub type ParseResult = TypesetResult; - #[cfg(test)] #[allow(non_snake_case)] diff --git a/src/syntax/tokens.rs b/src/syntax/tokens.rs index 95b2ea3e2..cca8bee34 100644 --- a/src/syntax/tokens.rs +++ b/src/syntax/tokens.rs @@ -1,5 +1,6 @@ use std::str::CharIndices; use smallvec::SmallVec; + use super::*; /// Builds an iterator over the tokens of the source code. @@ -266,7 +267,7 @@ fn is_newline_char(character: char) -> bool { /// A (index, char) iterator with double lookahead. #[derive(Debug, Clone)] -pub struct PeekableChars<'s> { +struct PeekableChars<'s> { string: &'s str, chars: CharIndices<'s>, peeked: SmallVec<[Option<(usize, char)>; 2]>, @@ -276,7 +277,7 @@ pub struct PeekableChars<'s> { impl<'s> PeekableChars<'s> { /// Create a new iterator from a string. - pub fn new(string: &'s str) -> PeekableChars<'s> { + fn new(string: &'s str) -> PeekableChars<'s> { PeekableChars { string, chars: string.char_indices(), @@ -287,17 +288,17 @@ impl<'s> PeekableChars<'s> { } /// Peek at the next element. - pub fn peek(&mut self) -> Option<(usize, char)> { + fn peek(&mut self) -> Option<(usize, char)> { self.peekn(0) } /// Peek at the char of the next element. - pub fn peekc(&mut self) -> Option { + fn peekc(&mut self) -> Option { self.peekn(0).map(|p| p.1) } /// Peek at the element after the next element. - pub fn peekn(&mut self, n: usize) -> Option<(usize, char)> { + fn peekn(&mut self, n: usize) -> Option<(usize, char)> { while self.peeked.len() <= n { let next = self.next_inner(); self.peeked.push(next); @@ -307,15 +308,15 @@ impl<'s> PeekableChars<'s> { } /// Return the next value of the inner iterator mapped with the offset. - pub fn next_inner(&mut self) -> Option<(usize, char)> { + fn next_inner(&mut self) -> Option<(usize, char)> { self.chars.next().map(|(i, c)| (self.base + i, c)) } - pub fn string_index(&mut self) -> usize { + fn string_index(&mut self) -> usize { self.index } - pub fn set_string_index(&mut self, index: usize) { + fn set_string_index(&mut self, index: usize) { self.chars = self.string[index..].char_indices(); self.base = index; self.index = 0;