Bugfix and tidying

This commit is contained in:
Laurenz 2021-09-15 12:29:42 +02:00
parent 87e776fceb
commit c18321a4c2
13 changed files with 54 additions and 48 deletions

View File

@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize};
use crate::syntax::{Span, Spanned}; use crate::syntax::{Span, Spanned};
/// Early-return with a vec-boxed [`Error`]. /// Early-return with a vec-boxed [`Error`].
#[macro_export]
macro_rules! bail { macro_rules! bail {
($span:expr, $message:expr $(,)?) => { ($span:expr, $message:expr $(,)?) => {
return Err($crate::diag::Error::boxed($span, $message,)) return Err($crate::diag::Error::boxed($span, $message,))

View File

@ -309,10 +309,10 @@ impl<'a> PdfExporter<'a> {
let face = self.fonts.get(face_id); let face = self.fonts.get(face_id);
let ttf = face.ttf(); let ttf = face.ttf();
let postcript_name = find_name(ttf.names(), name_id::POST_SCRIPT_NAME) let postscript_name = find_name(ttf.names(), name_id::POST_SCRIPT_NAME)
.unwrap_or_else(|| "unknown".to_string()); .unwrap_or_else(|| "unknown".to_string());
let base_font = format!("ABCDEF+{}", postcript_name); let base_font = format!("ABCDEF+{}", postscript_name);
let base_font = Name(base_font.as_bytes()); let base_font = Name(base_font.as_bytes());
let cmap_name = Name(b"Custom"); let cmap_name = Name(b"Custom");
let system_info = SystemInfo { let system_info = SystemInfo {
@ -356,7 +356,7 @@ impl<'a> PdfExporter<'a> {
}); });
let mut flags = FontFlags::empty(); let mut flags = FontFlags::empty();
flags.set(FontFlags::SERIF, postcript_name.contains("Serif")); flags.set(FontFlags::SERIF, postscript_name.contains("Serif"));
flags.set(FontFlags::FIXED_PITCH, ttf.is_monospaced()); flags.set(FontFlags::FIXED_PITCH, ttf.is_monospaced());
flags.set(FontFlags::ITALIC, ttf.is_italic()); flags.set(FontFlags::ITALIC, ttf.is_italic());
flags.insert(FontFlags::SYMBOLIC); flags.insert(FontFlags::SYMBOLIC);

View File

@ -2,13 +2,12 @@ use std::fmt::{self, Debug, Formatter};
use super::*; use super::*;
use std::any::Any;
#[cfg(feature = "layout-cache")] #[cfg(feature = "layout-cache")]
use std::hash::{Hash, Hasher}; use {
fxhash::FxHasher64,
#[cfg(feature = "layout-cache")] std::any::Any,
use fxhash::FxHasher64; std::hash::{Hash, Hasher},
};
/// A tree of layout nodes. /// A tree of layout nodes.
#[derive(Debug)] #[derive(Debug)]

View File

@ -1,6 +1,5 @@
use crate::layout::{Decoration, LineDecoration, LineKind, Paint};
use super::*; use super::*;
use crate::layout::{Decoration, LineDecoration, LineKind, Paint};
/// `font`: Configure the font. /// `font`: Configure the font.
pub fn font(ctx: &mut EvalContext, args: &mut Args) -> TypResult<Value> { pub fn font(ctx: &mut EvalContext, args: &mut Args) -> TypResult<Value> {
@ -163,22 +162,22 @@ fn lang_dir(iso: &str) -> Dir {
} }
} }
/// `strike`: Set striken-through text. /// `strike`: Typeset striken-through text.
pub fn strike(ctx: &mut EvalContext, args: &mut Args) -> TypResult<Value> { pub fn strike(_: &mut EvalContext, args: &mut Args) -> TypResult<Value> {
line_impl(ctx, args, LineKind::Strikethrough) line_impl(args, LineKind::Strikethrough)
} }
/// `underline`: Set underlined text. /// `underline`: Typeset underlined text.
pub fn underline(ctx: &mut EvalContext, args: &mut Args) -> TypResult<Value> { pub fn underline(_: &mut EvalContext, args: &mut Args) -> TypResult<Value> {
line_impl(ctx, args, LineKind::Underline) line_impl(args, LineKind::Underline)
} }
/// `overline`: Set text with an overline. /// `overline`: Typeset text with an overline.
pub fn overline(ctx: &mut EvalContext, args: &mut Args) -> TypResult<Value> { pub fn overline(_: &mut EvalContext, args: &mut Args) -> TypResult<Value> {
line_impl(ctx, args, LineKind::Overline) line_impl(args, LineKind::Overline)
} }
fn line_impl(_: &mut EvalContext, args: &mut Args, kind: LineKind) -> TypResult<Value> { fn line_impl(args: &mut Args, kind: LineKind) -> TypResult<Value> {
let stroke = args.named("stroke")?.or_else(|| args.eat()); let stroke = args.named("stroke")?.or_else(|| args.eat());
let thickness = args.named::<Linear>("thickness")?.or_else(|| args.eat()); let thickness = args.named::<Linear>("thickness")?.or_else(|| args.eat());
let offset = args.named("offset")?; let offset = args.named("offset")?;
@ -196,7 +195,7 @@ fn line_impl(_: &mut EvalContext, args: &mut Args, kind: LineKind) -> TypResult<
Ok(Value::Template(body)) Ok(Value::Template(body))
} }
/// `link`: Set a link. /// `link`: Typeset text as a link.
pub fn link(_: &mut EvalContext, args: &mut Args) -> TypResult<Value> { pub fn link(_: &mut EvalContext, args: &mut Args) -> TypResult<Value> {
let url = args.expect::<Str>("url")?; let url = args.expect::<Str>("url")?;

View File

@ -1,9 +1,8 @@
use std::cmp::Ordering; use std::cmp::Ordering;
use std::str::FromStr; use std::str::FromStr;
use crate::color::{Color, RgbaColor};
use super::*; use super::*;
use crate::color::{Color, RgbaColor};
/// `type`: The name of a value's type. /// `type`: The name of a value's type.
pub fn type_(_: &mut EvalContext, args: &mut Args) -> TypResult<Value> { pub fn type_(_: &mut EvalContext, args: &mut Args) -> TypResult<Value> {

View File

@ -17,7 +17,7 @@ use crate::source::SourceFile;
use crate::syntax::*; use crate::syntax::*;
use crate::util::EcoString; use crate::util::EcoString;
/// Parse a string of source code. /// Parse a source file.
pub fn parse(source: &SourceFile) -> TypResult<SyntaxTree> { pub fn parse(source: &SourceFile) -> TypResult<SyntaxTree> {
let mut p = Parser::new(source); let mut p = Parser::new(source);
let tree = tree(&mut p); let tree = tree(&mut p);
@ -48,13 +48,14 @@ fn tree_indented(p: &mut Parser, column: usize) -> SyntaxTree {
}) })
} }
/// Parse a syntax tree. /// Parse a syntax tree while the peeked token satisifies a condition.
///
/// If `at_start` is true, things like headings that may only appear at the
/// beginning of a line or template are allowed.
fn tree_while<F>(p: &mut Parser, mut at_start: bool, f: &mut F) -> SyntaxTree fn tree_while<F>(p: &mut Parser, mut at_start: bool, f: &mut F) -> SyntaxTree
where where
F: FnMut(&mut Parser) -> bool, F: FnMut(&mut Parser) -> bool,
{ {
// We use `at_start` to keep track of whether we are at the start of a line
// or template to know whether things like headings are allowed.
let mut tree = vec![]; let mut tree = vec![];
while !p.eof() && f(p) { while !p.eof() && f(p) {
if let Some(node) = node(p, &mut at_start) { if let Some(node) = node(p, &mut at_start) {
@ -94,8 +95,8 @@ fn node(p: &mut Parser, at_start: &mut bool) -> Option<SyntaxNode> {
Token::Underscore => SyntaxNode::Emph(span), Token::Underscore => SyntaxNode::Emph(span),
Token::Raw(t) => raw(p, t), Token::Raw(t) => raw(p, t),
Token::Eq if *at_start => return Some(heading(p)), Token::Eq if *at_start => return Some(heading(p)),
Token::Hyph if *at_start => return Some(list_item(p)), Token::Hyph if *at_start => return Some(list_node(p)),
Token::Numbering(number) if *at_start => return Some(enum_item(p, number)), Token::Numbering(number) if *at_start => return Some(enum_node(p, number)),
// Line-based markup that is not currently at the start of the line. // Line-based markup that is not currently at the start of the line.
Token::Eq | Token::Hyph | Token::Numbering(_) => { Token::Eq | Token::Hyph | Token::Numbering(_) => {
@ -196,7 +197,7 @@ fn heading(p: &mut Parser) -> SyntaxNode {
} }
/// Parse a single list item. /// Parse a single list item.
fn list_item(p: &mut Parser) -> SyntaxNode { fn list_node(p: &mut Parser) -> SyntaxNode {
let start = p.next_start(); let start = p.next_start();
let column = p.column(start); let column = p.column(start);
p.eat_assert(Token::Hyph); p.eat_assert(Token::Hyph);
@ -205,7 +206,7 @@ fn list_item(p: &mut Parser) -> SyntaxNode {
} }
/// Parse a single enum item. /// Parse a single enum item.
fn enum_item(p: &mut Parser, number: Option<usize>) -> SyntaxNode { fn enum_node(p: &mut Parser, number: Option<usize>) -> SyntaxNode {
let start = p.next_start(); let start = p.next_start();
let column = p.column(start); let column = p.column(start);
p.eat_assert(Token::Numbering(number)); p.eat_assert(Token::Numbering(number));
@ -243,10 +244,7 @@ fn expr_with(p: &mut Parser, atomic: bool, min_prec: usize) -> Option<Expr> {
loop { loop {
// Exclamation mark, parenthesis or bracket means this is a function // Exclamation mark, parenthesis or bracket means this is a function
// call. // call.
if matches!( if matches!(p.peek_direct(), Some(Token::LeftParen | Token::LeftBracket)) {
p.peek_direct(),
Some(Token::Excl | Token::LeftParen | Token::LeftBracket),
) {
lhs = call(p, lhs)?; lhs = call(p, lhs)?;
continue; continue;
} }
@ -520,7 +518,7 @@ fn idents(p: &mut Parser, items: Vec<CallArg>) -> Vec<Ident> {
iter.collect() iter.collect()
} }
// Parse a template value: `[...]`. // Parse a template block: `[...]`.
fn template(p: &mut Parser) -> Expr { fn template(p: &mut Parser) -> Expr {
p.start_group(Group::Bracket, TokenMode::Markup); p.start_group(Group::Bracket, TokenMode::Markup);
let tree = tree(p); let tree = tree(p);
@ -528,7 +526,7 @@ fn template(p: &mut Parser) -> Expr {
Expr::Template(Box::new(TemplateExpr { span, tree })) Expr::Template(Box::new(TemplateExpr { span, tree }))
} }
/// Parse a block expression: `{...}`. /// Parse a code block: `{...}`.
fn block(p: &mut Parser, scoping: bool) -> Expr { fn block(p: &mut Parser, scoping: bool) -> Expr {
p.start_group(Group::Brace, TokenMode::Code); p.start_group(Group::Brace, TokenMode::Code);
let mut exprs = vec![]; let mut exprs = vec![];

View File

@ -142,7 +142,6 @@ impl<'s> Tokens<'s> {
'-' => Token::Hyph, '-' => Token::Hyph,
'*' => Token::Star, '*' => Token::Star,
'/' => Token::Slash, '/' => Token::Slash,
'!' => Token::Excl,
'=' => Token::Eq, '=' => Token::Eq,
'<' => Token::Lt, '<' => Token::Lt,
'>' => Token::Gt, '>' => Token::Gt,

View File

@ -6,14 +6,15 @@ use std::ops::Range;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::rc::Rc; use std::rc::Rc;
#[cfg(feature = "codespan-reporting")]
use codespan_reporting::files::{self, Files};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::loading::{FileHash, Loader}; use crate::loading::{FileHash, Loader};
use crate::parse::{is_newline, Scanner}; use crate::parse::{is_newline, Scanner};
use crate::util::PathExt; use crate::util::PathExt;
#[cfg(feature = "codespan-reporting")]
use codespan_reporting::files::{self, Files};
/// A unique identifier for a loaded source file. /// A unique identifier for a loaded source file.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)] #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct SourceId(u32); pub struct SourceId(u32);

View File

@ -1,3 +1,4 @@
use std::borrow::Borrow;
use std::ops::Deref; use std::ops::Deref;
use unicode_xid::UnicodeXID; use unicode_xid::UnicodeXID;
@ -53,6 +54,18 @@ impl AsRef<str> for Ident {
} }
} }
impl Borrow<str> for Ident {
fn borrow(&self) -> &str {
self
}
}
impl From<&Ident> for EcoString {
fn from(ident: &Ident) -> Self {
ident.string.clone()
}
}
/// Whether a string is a valid identifier. /// Whether a string is a valid identifier.
pub fn is_ident(string: &str) -> bool { pub fn is_ident(string: &str) -> bool {
let mut chars = string.chars(); let mut chars = string.chars();

View File

@ -39,8 +39,6 @@ pub enum Token<'s> {
Hyph, Hyph,
/// A slash: `/`. /// A slash: `/`.
Slash, Slash,
/// An exlamation mark.
Excl,
/// A single equals sign: `=`. /// A single equals sign: `=`.
Eq, Eq,
/// Two equals signs: `==`. /// Two equals signs: `==`.
@ -223,7 +221,6 @@ impl<'s> Token<'s> {
Self::Plus => "plus", Self::Plus => "plus",
Self::Hyph => "minus", Self::Hyph => "minus",
Self::Slash => "slash", Self::Slash => "slash",
Self::Excl => "exclamation mark",
Self::Eq => "assignment operator", Self::Eq => "assignment operator",
Self::EqEq => "equality operator", Self::EqEq => "equality operator",
Self::ExclEq => "inequality operator", Self::ExclEq => "inequality operator",

View File

@ -1,10 +1,10 @@
//! Utilities. //! Utilities.
mod eco; mod eco_string;
mod mac; mod mac_roman;
pub use eco::EcoString; pub use eco_string::EcoString;
pub use mac::decode_mac_roman; pub use mac_roman::decode_mac_roman;
use std::cell::RefMut; use std::cell::RefMut;
use std::cmp::Ordering; use std::cmp::Ordering;