Skip to content

Commit

Permalink
Initial commit.
Browse files Browse the repository at this point in the history
  • Loading branch information
cutsoy committed Oct 10, 2020
0 parents commit 34fed4e
Show file tree
Hide file tree
Showing 220 changed files with 13,825 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 1,4 @@
target
Cargo.lock
.DS_Store
.vscode
18 changes: 18 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 1,18 @@
[workspace]
members = [
"crates/casco",
"crates/polyhorn",
"crates/polyhorn-build",
"crates/polyhorn-build-ios",
"crates/polyhorn-channel",
"crates/polyhorn-core",
"crates/polyhorn-ios",
"crates/polyhorn-ios-sys",
"crates/polyhorn-layout",
"crates/polyhorn-macros",
"crates/polyhorn-style",
"crates/taxi",
"crates/yoyo",
"crates/yoyo-macros",
"crates/yoyo-physics",
]
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 1,19 @@
Copyright 2020 Glacyr B.V.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
18 changes: 18 additions & 0 deletions crates/casco/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 1,18 @@
[package]
name = "casco"
version = "0.1.0"
authors = ["Tim <[email protected]>"]
edition = "2018"
license = "MIT"
description = "CSS-like parser for procedural macros."
repository = "https://github.com/polyhorn/polyhorn/tree/crates/casco"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]

[dependencies]
proc-macro2 = "1.0.19"
itertools = "0.9.0"

[dev-dependencies]
quote = "1.0.7"
27 changes: 27 additions & 0 deletions crates/casco/src/driver.rs
Original file line number Diff line number Diff line change
@@ -0,0 1,27 @@
use super::scanner::{Ident, TokenTree};

/// This trait should be implemented by domain-specific languages. Specifically,
/// Stylo doesn't parse selectors or properties: it simply delegates that work to
/// the domain-specific driver.
pub trait Driver {
type Selector;
type Property;
type Error;

/// This function should read tokens from the given scanner and return a
/// selector (or an error). If this function does not exhaust the scanner, it
/// will be called again until the scanner is exhausted (i.e. all tokens have
/// been read).
fn parse_selector<S>(&self, scanner: &mut S) -> Result<Self::Selector, Self::Error>
where
S: Iterator<Item = TokenTree>;

/// This function should read tokens from the given scanner and return a
/// property. If no property exists with the given name, it may consume the
/// scanner and return an error instead. If this function returns without
/// exhausting the scanner, all remaining tokens in the scanner will produce
/// an unexpected token error.
fn parse_property<S>(&self, name: Ident, value: &mut S) -> Result<Self::Property, Self::Error>
where
S: Iterator<Item = TokenTree>;
}
71 changes: 71 additions & 0 deletions crates/casco/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 1,71 @@
pub mod scanner {
//! This module re-exports the types we borrow from `proc_macro2`.
pub use proc_macro2::{Delimiter, Group, Ident, Literal, Punct, Span, TokenTree};
}

mod driver;
mod parser;
mod types;

pub use driver::Driver;
pub use parser::Parser;
pub use types::{Item, Parse, Rule};

#[cfg(test)]
mod tests {
use super::scanner::{Ident, TokenTree};
use super::{Driver, Parser};
use quote::quote;

#[test]
fn test_end_to_end() {
let input = quote! {
opacity: 1.0;

:hover {
opacity: 0.5;
}
};

pub struct Selector;
pub struct Property;
pub struct Error;

pub struct Example;

impl Driver for Example {
type Selector = Selector;
type Property = Property;
type Error = Error;

fn parse_selector<S>(&self, scanner: &mut S) -> Result<Self::Selector, Self::Error>
where
S: Iterator<Item = TokenTree>,
{
let _ = scanner.collect::<Vec<_>>();
Ok(Selector)
}

fn parse_property<S>(
&self,
name: Ident,
value: &mut S,
) -> Result<Self::Property, Self::Error>
where
S: Iterator<Item = TokenTree>,
{
assert_eq!(name.to_string(), "opacity");
let _ = value.collect::<Vec<_>>();
Ok(Property)
}
}

let driver = Example;
let parser = Parser::new(&driver);
let result = parser.parse(input.into_iter());
assert_eq!(result.items.len(), 2);
assert_eq!(result.items[0].is_property(), true);
assert_eq!(result.items[1].is_rule(), true);
assert_eq!(result.errors.len(), 0);
}
}
156 changes: 156 additions & 0 deletions crates/casco/src/parser.rs
Original file line number Diff line number Diff line change
@@ -0,0 1,156 @@
use itertools::Itertools;

use super::scanner::{Delimiter, Group, TokenTree};
use super::{Driver, Item, Parse, Rule};

pub struct Parser<'a, D>
where
D: Driver ?Sized,
{
driver: &'a D,
errors: Vec<D::Error>,
}

impl<'a, D> Parser<'a, D>
where
D: Driver,
{
/// This function returns a new parser with the given driver.
pub fn new(driver: &'a D) -> Parser<'a, D> {
Parser {
driver,
errors: vec![],
}
}

fn parse_property<S>(&mut self, mut preamble: S) -> Option<D::Property>
where
S: Iterator<Item = TokenTree>,
{
let name = match preamble.next() {
Some(TokenTree::Ident(ident)) => ident,
_ => unreachable!(),
};

let _colon = match preamble.next() {
Some(TokenTree::Punct(punct)) if punct.as_char() == ':' => punct,
_ => unreachable!(),
};

let result = self.driver.parse_property(name, &mut preamble);

// TODO: print an error if the preamble is not empty. In the future,
// this might also be a suitable place to implement support for
// importance specifiers (i.e. `!important`).
if result.is_ok() {
assert!(preamble.next().is_none());
}

match result {
Ok(property) => Some(property),
Err(error) => {
self.errors.push(error);
None
}
}
}

fn parse_selector<S>(&mut self, mut preamble: S) -> Option<D::Selector>
where
S: Iterator<Item = TokenTree>,
{
match self.driver.parse_selector(&mut preamble) {
Ok(selector) => Some(selector),
Err(error) => {
self.errors.push(error);
None
}
}
}

fn parse_rule<S>(&mut self, preamble: S, group: Group) -> Option<Rule<D>>
where
S: Iterator<Item = TokenTree>,
{
let mut selectors = vec![];

let mut preamble = preamble.peekable();

while preamble.peek().is_some() {
if let Some(selector) = self.parse_selector(&mut preamble) {
selectors.push(selector);
}
}

Some(Rule {
selectors,
items: self.parse_block(group.stream().into_iter()),
})
}

fn parse_item<S>(&mut self, preamble: S, terminator: TokenTree) -> Option<Item<D>>
where
S: Iterator<Item = TokenTree>,
{
match terminator {
TokenTree::Punct(punct) if punct.as_char() == ';' => self
.parse_property(preamble.into_iter())
.map(|prop| Item::Property(prop)),
TokenTree::Group(group) if group.delimiter() == Delimiter::Brace => self
.parse_rule(preamble, group)
.map(|rule| Item::Rule(rule)),
_ => unimplemented!(),
}
}

fn parse_block<S>(&mut self, mut scanner: S) -> Vec<Item<D>>
where
S: Clone Iterator<Item = TokenTree>,
{
let mut items = vec![];

loop {
// We parse a single preamble. A line ends before either an `;` punct or
// a `{}` group. More explicitly: the line does not include that
// terminator (mostly because of how `take_while` works).
let preamble = scanner
.take_while_ref(|tree| match tree {
TokenTree::Punct(punct) if punct.as_char() == ';' => false,
TokenTree::Group(group) if group.delimiter() == Delimiter::Brace => false,
_ => true,
})
.collect::<Vec<_>>();

match scanner.next() {
Some(terminator) => {
if let Some(item) = self.parse_item(preamble.into_iter(), terminator) {
items.push(item);
}
}
None => match preamble.len() {
0 => break,
_ => {
// TODO: pretend that it is a property with a missing `;`
// and report an error.
unimplemented!(
"Parsing an unterminated preamble: {:?} is not yet supported.",
preamble
);
}
},
}
}

items
}

pub fn parse<S>(mut self, scanner: S) -> Parse<D>
where
S: Clone Iterator<Item = TokenTree>,
{
Parse {
items: self.parse_block(scanner),
errors: self.errors,
}
}
}
Loading

0 comments on commit 34fed4e

Please sign in to comment.