Rename crate typst -> typstc

This commit is contained in:
Laurenz 2019-12-05 20:29:55 +01:00
parent 72a9631b03
commit f5b104d0da
16 changed files with 82 additions and 167 deletions

View File

@ -1,5 +1,5 @@
[package]
name = "typst"
name = "typstc"
version = "0.1.0"
authors = ["Laurenz Mädje <laurmaedje@gmail.com>"]
edition = "2018"
@ -12,7 +12,7 @@ smallvec = "0.6.10"
unicode-xid = "0.1.0"
[[bin]]
name = "typstc"
name = "typst-bin"
path = "src/bin/main.rs"
[[test]]

View File

@ -5,9 +5,9 @@ use std::io::{BufWriter, Read};
use std::path::{Path, PathBuf};
use std::process;
use typst::export::pdf::PdfExporter;
use typst::toddle::query::FileSystemFontProvider;
use typst::Typesetter;
use typstc::export::pdf::PdfExporter;
use typstc::toddle::query::FileSystemFontProvider;
use typstc::Typesetter;
fn main() {
if let Err(err) = run() {

View File

@ -23,7 +23,6 @@ pub struct PdfExporter {}
impl PdfExporter {
/// Create a new exporter.
#[inline]
pub fn new() -> PdfExporter {
PdfExporter {}
}
@ -31,7 +30,6 @@ impl PdfExporter {
/// Export a finished multi-layout. The layout needs to have been created with the same
/// font loader passed in here since the indices must match. The PDF data is written into
/// the target writable and the number of bytes written is returned.
#[inline]
pub fn export<W: Write>(
&self,
layout: &MultiLayout,

View File

@ -7,8 +7,10 @@ use std::fmt::{self, Debug, Formatter};
use self::prelude::*;
#[macro_use]
pub mod macros;
pub mod map;
mod macros;
mod map;
pub use map::ConsistentMap;
/// Useful imports for creating your own functions.
pub mod prelude {

View File

@ -63,7 +63,7 @@ debug_display!(LayoutAction);
/// be added at a position, effectively translating all movement actions inside the layout
/// by the position.
#[derive(Debug, Clone)]
pub struct LayoutActionList {
pub struct LayoutActions {
pub origin: Size2D,
actions: Vec<LayoutAction>,
active_font: (usize, Size),
@ -71,10 +71,10 @@ pub struct LayoutActionList {
next_font: Option<(usize, Size)>,
}
impl LayoutActionList {
impl LayoutActions {
/// Create a new action list.
pub fn new() -> LayoutActionList {
LayoutActionList {
pub fn new() -> LayoutActions {
LayoutActions {
actions: vec![],
origin: Size2D::zero(),
active_font: (std::usize::MAX, Size::zero()),

View File

@ -1,5 +1,7 @@
use super::*;
/// The flex layouter first arranges boxes along a primary and if necessary also
/// along a secondary axis.
#[derive(Debug, Clone)]
pub struct FlexLayouter {
axes: LayoutAxes,
@ -22,7 +24,7 @@ enum FlexUnit {
#[derive(Debug, Clone)]
struct FlexLine {
usable: Size,
actions: LayoutActionList,
actions: LayoutActions,
combined_dimensions: Size2D,
}
@ -30,7 +32,7 @@ impl FlexLine {
fn new(usable: Size) -> FlexLine {
FlexLine {
usable,
actions: LayoutActionList::new(),
actions: LayoutActions::new(),
combined_dimensions: Size2D::zero(),
}
}

View File

@ -26,7 +26,7 @@ pub mod layouters {
pub use super::text::{layout_text, TextContext};
}
pub use actions::{LayoutAction, LayoutActionList};
pub use actions::{LayoutAction, LayoutActions};
pub use layouters::*;
/// A collection of layouts.
@ -75,7 +75,7 @@ pub struct LayoutSpace {
pub padding: SizeBox,
/// Whether to expand the dimensions of the resulting layout to the full
/// dimensions of this space or to shrink them to fit the content for the
/// vertical and horizontal axis.
/// horizontal and vertical axis.
pub expand: (bool, bool),
}
@ -324,17 +324,6 @@ impl Alignment {
}
}
/// The specialized anchor position for an item with the given alignment in a
/// container with a given size along the given axis.
pub fn anchor(axis: Axis, size: Size, alignment: Alignment) -> Size {
use Alignment::*;
match (axis.is_positive(), alignment) {
(true, Origin) | (false, End) => Size::zero(),
(_, Center) => size / 2,
(true, End) | (false, Origin) => size,
}
}
/// Whitespace between boxes with different interaction properties.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum SpacingKind {
@ -368,6 +357,18 @@ impl LastSpacing {
}
}
/// The specialized anchor position for an item with the given alignment in a
/// container with a given size along the given axis.
#[allow(dead_code)]
fn anchor(axis: Axis, size: Size, alignment: Alignment) -> Size {
use Alignment::*;
match (axis.is_positive(), alignment) {
(true, Origin) | (false, End) => Size::zero(),
(_, Center) => size / 2,
(true, End) | (false, Origin) => size,
}
}
/// Layout components that can be serialized.
pub trait Serialize {
/// Serialize the data structure into an output writable.

View File

@ -26,7 +26,7 @@ pub fn layout_text(text: &str, ctx: TextContext) -> LayoutResult<Layout> {
struct TextLayouter<'a, 'p> {
ctx: TextContext<'a, 'p>,
text: &'a str,
actions: LayoutActionList,
actions: LayoutActions,
buffer: String,
active_font: usize,
width: Size,
@ -39,7 +39,7 @@ impl<'a, 'p> TextLayouter<'a, 'p> {
TextLayouter {
ctx,
text,
actions: LayoutActionList::new(),
actions: LayoutActions::new(),
buffer: String::new(),
active_font: std::usize::MAX,
width: Size::zero(),

View File

@ -1,6 +1,7 @@
use smallvec::smallvec;
use super::*;
/// Layout a syntax tree into a multibox.
pub fn layout_tree(tree: &SyntaxTree, ctx: LayoutContext) -> LayoutResult<MultiLayout> {
let mut layouter = TreeLayouter::new(ctx);
layouter.layout(tree)?;
@ -75,7 +76,7 @@ impl<'a, 'p> TreeLayouter<'a, 'p> {
fn layout_func(&mut self, func: &FuncCall) -> LayoutResult<()> {
let spaces = self.flex.remaining();
let commands = func.call.layout(LayoutContext {
let commands = func.0.layout(LayoutContext {
loader: self.ctx.loader,
style: &self.style,
top_level: false,

View File

@ -52,7 +52,6 @@ pub struct Typesetter<'p> {
impl<'p> Typesetter<'p> {
/// Create a new typesetter.
#[inline]
pub fn new() -> Typesetter<'p> {
Typesetter {
loader: RefCell::new(FontLoader::new()),
@ -61,26 +60,22 @@ impl<'p> Typesetter<'p> {
}
/// Set the base page style.
#[inline]
pub fn set_page_style(&mut self, style: PageStyle) {
self.style.page = style;
}
/// Set the base text style.
#[inline]
pub fn set_text_style(&mut self, style: TextStyle) {
self.style.text = style;
}
/// Add a font provider to the context of this typesetter.
#[inline]
pub fn add_font_provider<P: 'p>(&mut self, provider: P)
where P: FontProvider {
self.loader.get_mut().add_provider(provider);
}
/// A reference to the backing font loader.
#[inline]
pub fn loader(&self) -> &SharedFontLoader<'p> {
&self.loader
}
@ -111,7 +106,7 @@ impl<'p> Typesetter<'p> {
}
/// Process source code directly into a layout.
pub fn typeset(&self, src: &str) -> Result<MultiLayout, TypesetError> {
pub fn typeset(&self, src: &str) -> TypesetResult<MultiLayout> {
let tree = self.parse(src)?;
let layout = self.layout(&tree)?;
Ok(layout)
@ -123,8 +118,8 @@ pub type TypesetResult<T> = Result<T, TypesetError>;
/// The error type for typesetting.
pub struct TypesetError {
message: String,
span: Option<Span>,
pub message: String,
pub span: Option<Span>,
}
impl TypesetError {

View File

@ -24,10 +24,8 @@ pub fn std() -> Scope {
std.add::<PageBreak>("page.break");
std.add_with_metadata::<Spacing, Option<AxisKey>>("spacing", None);
for (name, key) in &[
("h", AxisKey::Horizontal),
("v", AxisKey::Vertical),
] {
for (name, key) in &[("h", AxisKey::Horizontal), ("v", AxisKey::Vertical)] {
std.add_with_metadata::<Spacing, Option<AxisKey>>(name, Some(*key));
}
@ -200,7 +198,7 @@ function! {
}
function! {
/// Sets text with a different style.
/// `bold`, `italic`, `mono`: Sets text with a different style.
#[derive(Debug, PartialEq)]
pub struct StyleChange {
body: Option<SyntaxTree>,

View File

@ -7,14 +7,14 @@ use std::ops::*;
use std::str::FromStr;
/// A general space type.
#[derive(Copy, Clone, PartialEq, Default)]
#[derive(Copy, Clone, PartialEq)]
pub struct Size {
/// The size in typographic points (1/72 inches).
points: f32,
}
/// A position or extent in 2-dimensional space.
#[derive(Copy, Clone, PartialEq, Default)]
#[derive(Copy, Clone, PartialEq)]
pub struct Size2D {
/// The horizontal coordinate.
pub x: Size,
@ -23,7 +23,7 @@ pub struct Size2D {
}
/// A size in four directions.
#[derive(Copy, Clone, PartialEq, Default)]
#[derive(Copy, Clone, PartialEq)]
pub struct SizeBox {
/// The left extent.
pub left: Size,
@ -35,76 +35,48 @@ pub struct SizeBox {
pub bottom: Size,
}
/// A size or scale.
/// Either an absolute size or a factor of some metric.
#[derive(Copy, Clone, PartialEq)]
pub enum ScaleSize {
Absolute(Size),
Scaled(f32),
}
/// A size that is possibly scaled by the font size.
/// A scale size that is scaled by the font size.
pub type FSize = ScaleSize;
/// A size that is possibly scaled by the size of the padded parent container.
/// A scale size that is scaled by the size of the padded parent container.
pub type PSize = ScaleSize;
impl Size {
/// Create a zeroed size.
#[inline]
pub fn zero() -> Size {
Size::default()
}
pub fn zero() -> Size { Size { points: 0.0 } }
/// Create a size from an amount of points.
#[inline]
pub fn pt(points: f32) -> Size {
Size { points }
}
pub fn pt(points: f32) -> Size { Size { points } }
/// Create a size from an amount of millimeters.
#[inline]
pub fn mm(mm: f32) -> Size {
Size { points: 2.83465 * mm }
}
pub fn mm(mm: f32) -> Size { Size { points: 2.83465 * mm } }
/// Create a size from an amount of centimeters.
#[inline]
pub fn cm(cm: f32) -> Size {
Size { points: 28.3465 * cm }
}
pub fn cm(cm: f32) -> Size { Size { points: 28.3465 * cm } }
/// Create a size from an amount of inches.
#[inline]
pub fn inches(inches: f32) -> Size {
Size { points: 72.0 * inches }
}
pub fn inches(inches: f32) -> Size { Size { points: 72.0 * inches } }
/// Convert this size into points.
#[inline]
pub fn to_pt(&self) -> f32 {
self.points
}
pub fn to_pt(&self) -> f32 { self.points }
/// Convert this size into millimeters.
#[inline]
pub fn to_mm(&self) -> f32 {
self.points * 0.352778
}
pub fn to_mm(&self) -> f32 { self.points * 0.352778 }
/// Convert this size into centimeters.
#[inline]
pub fn to_cm(&self) -> f32 {
self.points * 0.0352778
}
pub fn to_cm(&self) -> f32 { self.points * 0.0352778 }
/// Convert this size into inches.
#[inline]
pub fn to_inches(&self) -> f32 {
self.points * 0.0138889
}
pub fn to_inches(&self) -> f32 { self.points * 0.0138889 }
/// Set this size to the maximum of itself and the other size.
#[inline]
pub fn max_eq(&mut self, other: Size) {
*self = max(*self, other);
}
@ -112,37 +84,31 @@ impl Size {
impl Size2D {
/// Create a new 2D-size from two sizes.
#[inline]
pub fn new(x: Size, y: Size) -> Size2D {
Size2D { x, y }
}
/// Create a 2D-size with both sizes set to zero.
#[inline]
pub fn zero() -> Size2D {
Size2D::default()
Size2D { x: Size::zero(), y: Size::zero() }
}
/// Create a 2D-size with `x` and `y` set to the same value `s`.
#[inline]
pub fn with_all(s: Size) -> Size2D {
Size2D { x: s, y: s }
}
/// Create a new 2D-size with `x` set to a value and `y` zero.
#[inline]
pub fn with_x(x: Size) -> Size2D {
Size2D { x, y: Size::zero() }
}
/// Create a new 2D-size with `y` set to a value and `x` zero.
#[inline]
pub fn with_y(y: Size) -> Size2D {
Size2D { x: Size::zero(), y }
}
/// Return a 2D-size padded by the paddings of the given box.
#[inline]
pub fn padded(&self, padding: SizeBox) -> Size2D {
Size2D {
x: self.x + padding.left + padding.right,
@ -151,7 +117,6 @@ impl Size2D {
}
/// Return a 2D-size reduced by the paddings of the given box.
#[inline]
pub fn unpadded(&self, padding: SizeBox) -> Size2D {
Size2D {
x: self.x - padding.left - padding.right,
@ -161,14 +126,12 @@ impl Size2D {
/// Whether the given 2D-size fits into this one, that is,
/// both coordinate values are smaller or equal.
#[inline]
pub fn fits(&self, other: Size2D) -> bool {
self.x >= other.x && self.y >= other.y
}
/// Set this size to the maximum of itself and the other size
/// (for both dimensions).
#[inline]
pub fn max_eq(&mut self, other: Size2D) {
self.x.max_eq(other.x);
self.y.max_eq(other.y);
@ -177,7 +140,6 @@ impl Size2D {
impl SizeBox {
/// Create a new box from four sizes.
#[inline]
pub fn new(left: Size, top: Size, right: Size, bottom: Size) -> SizeBox {
SizeBox {
left,
@ -188,32 +150,28 @@ impl SizeBox {
}
/// Create a box with all values set to zero.
#[inline]
pub fn zero() -> SizeBox {
SizeBox::default()
let zero = Size::zero();
SizeBox::new(zero, zero, zero, zero)
}
/// Create a box with all four fields set to the same value `s`.
#[inline]
pub fn with_all(value: Size) -> SizeBox {
SizeBox { left: value, top: value, right: value, bottom: value }
}
/// Set the `left` and `right` values.
#[inline]
pub fn set_all(&mut self, value: Size) {
*self = SizeBox::with_all(value);
}
/// Set the `left` and `right` values.
#[inline]
pub fn set_horizontal(&mut self, value: Size) {
self.left = value;
self.right = value;
}
/// Set the `top` and `bottom` values.
#[inline]
pub fn set_vertical(&mut self, value: Size) {
self.top = value;
self.bottom = value;
@ -221,23 +179,13 @@ impl SizeBox {
}
/// The maximum of two sizes.
#[inline]
pub fn max(a: Size, b: Size) -> Size {
if a >= b {
a
} else {
b
}
if a >= b { a } else { b }
}
/// The minimum of two sizes.
#[inline]
pub fn min(a: Size, b: Size) -> Size {
if a <= b {
a
} else {
b
}
if a <= b { a } else { b }
}
//------------------------------------------------------------------------------------------------//
@ -281,7 +229,6 @@ impl FromStr for Size {
}
impl PartialOrd for Size {
#[inline]
fn partial_cmp(&self, other: &Size) -> Option<Ordering> {
self.points.partial_cmp(&other.points)
}
@ -290,16 +237,12 @@ impl PartialOrd for Size {
impl Neg for Size {
type Output = Size;
#[inline]
fn neg(self) -> Size {
Size {
points: -self.points,
}
Size { points: -self.points }
}
}
impl Sum for Size {
#[inline]
fn sum<I>(iter: I) -> Size
where I: Iterator<Item = Size> {
iter.fold(Size::zero(), Add::add)
@ -311,16 +254,12 @@ macro_rules! impl_reflexive {
impl $trait for Size {
type Output = Size;
#[inline]
fn $func(self, other: Size) -> Size {
Size {
points: $trait::$func(self.points, other.points),
}
Size { points: $trait::$func(self.points, other.points) }
}
}
impl $assign_trait for Size {
#[inline]
fn $assign_func(&mut self, other: Size) {
$assign_trait::$assign_func(&mut self.points, other.points);
}
@ -333,16 +272,12 @@ macro_rules! impl_num_back {
impl $trait<$ty> for Size {
type Output = Size;
#[inline]
fn $func(self, other: $ty) -> Size {
Size {
points: $trait::$func(self.points, other as f32),
}
Size { points: $trait::$func(self.points, other as f32) }
}
}
impl $assign_trait<$ty> for Size {
#[inline]
fn $assign_func(&mut self, other: $ty) {
$assign_trait::$assign_func(&mut self.points, other as f32);
}
@ -357,11 +292,8 @@ macro_rules! impl_num_both {
impl $trait<Size> for $ty {
type Output = Size;
#[inline]
fn $func(self, other: Size) -> Size {
Size {
points: $trait::$func(self as f32, other.points),
}
Size { points: $trait::$func(self as f32, other.points) }
}
}
);
@ -387,7 +319,6 @@ debug_display!(Size2D);
impl Neg for Size2D {
type Output = Size2D;
#[inline]
fn neg(self) -> Size2D {
Size2D {
x: -self.x,
@ -401,7 +332,6 @@ macro_rules! impl_reflexive2d {
impl $trait for Size2D {
type Output = Size2D;
#[inline]
fn $func(self, other: Size2D) -> Size2D {
Size2D {
x: $trait::$func(self.x, other.x),
@ -411,7 +341,6 @@ macro_rules! impl_reflexive2d {
}
impl $assign_trait for Size2D {
#[inline]
fn $assign_func(&mut self, other: Size2D) {
$assign_trait::$assign_func(&mut self.x, other.x);
$assign_trait::$assign_func(&mut self.y, other.y);
@ -425,7 +354,6 @@ macro_rules! impl_num_back2d {
impl $trait<$ty> for Size2D {
type Output = Size2D;
#[inline]
fn $func(self, other: $ty) -> Size2D {
Size2D {
x: $trait::$func(self.x, other as f32),
@ -435,7 +363,6 @@ macro_rules! impl_num_back2d {
}
impl $assign_trait<$ty> for Size2D {
#[inline]
fn $assign_func(&mut self, other: $ty) {
$assign_trait::$assign_func(&mut self.x, other as f32);
$assign_trait::$assign_func(&mut self.y, other as f32);
@ -451,7 +378,6 @@ macro_rules! impl_num_both2d {
impl $trait<Size2D> for $ty {
type Output = Size2D;
#[inline]
fn $func(self, other: Size2D) -> Size2D {
Size2D {
x: $trait::$func(self as f32, other.x),
@ -473,11 +399,8 @@ impl_num_back2d!(Div, div, DivAssign, div_assign, i32);
impl Display for SizeBox {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(
f,
"[left: {}, top: {}, right: {}, bottom: {}]",
self.left, self.top, self.right, self.bottom
)
write!(f, "[left: {}, top: {}, right: {}, bottom: {}]",
self.left, self.top, self.right, self.bottom)
}
}

View File

@ -91,13 +91,11 @@ pub enum Node {
/// An invocation of a function.
#[derive(Debug)]
pub struct FuncCall {
pub call: Box<dyn LayoutFunc>,
}
pub struct FuncCall(pub Box<dyn LayoutFunc>);
impl PartialEq for FuncCall {
fn eq(&self, other: &FuncCall) -> bool {
&self.call == &other.call
&self.0 == &other.0
}
}

View File

@ -6,7 +6,6 @@ use crate::size::Size;
use super::*;
/// Parses source code into a syntax tree given a context.
#[inline]
pub fn parse(src: &str, ctx: ParseContext) -> ParseResult<SyntaxTree> {
Parser::new(src, ctx).parse()
}
@ -105,11 +104,11 @@ impl<'s> Parser<'s> {
_ => error!("expected arguments or closing bracket"),
};
let call = self.parse_func_call(name, args)?;
let func = FuncCall(self.parse_func_call(name, args)?);
span.end = self.tokens.string_index();
// Finally this function is parsed to the end.
self.append(Node::Func(FuncCall { call }), span);
self.append(Node::Func(func), span);
Ok(())
}
@ -531,13 +530,13 @@ mod tests {
/// Shortcut macro to create a function.
macro_rules! func {
() => (
FuncCall { call: Box::new(BodylessFn(vec![], vec![])) }
FuncCall(Box::new(BodylessFn(vec![], vec![])))
);
(body: $tree:expr $(,)*) => (
FuncCall { call: Box::new(TreeFn { tree: $tree }) }
FuncCall(Box::new(TreeFn { tree: $tree }))
);
(args: $pos:expr, $key:expr) => (
FuncCall { call: Box::new(BodylessFn($pos, $key)) }
FuncCall(Box::new(BodylessFn($pos, $key)))
);
}
@ -710,7 +709,7 @@ mod tests {
assert_eq!(tree[2].span.pair(), (5, 37));
let func = if let Node::Func(f) = &tree[2].v { f } else { panic!() };
let body = &func.call.downcast::<TreeFn>().unwrap().tree.nodes;
let body = &func.0.downcast::<TreeFn>().unwrap().tree.nodes;
assert_eq!(body[0].span.pair(), (0, 4));
assert_eq!(body[1].span.pair(), (4, 5));
assert_eq!(body[2].span.pair(), (5, 6));

View File

@ -3,7 +3,6 @@ use smallvec::SmallVec;
use super::*;
/// Builds an iterator over the tokens of the source code.
#[inline]
pub fn tokenize(src: &str) -> Tokens {
Tokens::new(src)
}

View File

@ -2,12 +2,12 @@ use std::fs::{self, File};
use std::io::{BufWriter, Read, Write};
use std::process::Command;
use typst::export::pdf::PdfExporter;
use typst::layout::{LayoutAction, Serialize};
use typst::size::{Size, Size2D, SizeBox};
use typst::style::PageStyle;
use typst::toddle::query::FileSystemFontProvider;
use typst::Typesetter;
use typstc::export::pdf::PdfExporter;
use typstc::layout::{LayoutAction, Serialize};
use typstc::size::{Size, Size2D, SizeBox};
use typstc::style::PageStyle;
use typstc::toddle::query::FileSystemFontProvider;
use typstc::Typesetter;
const CACHE_DIR: &str = "tests/cache";
@ -98,10 +98,9 @@ fn test(name: &str, src: &str) {
#[cfg(not(debug_assertions))]
println!();
return;
},
}
};
// Write the serialed layout file.
let path = format!("{}/serialized/{}.tld", CACHE_DIR, name);
let mut file = File::create(path).unwrap();