use crate::prelude::*;
use crate::qterm::QTerm;
use std::fmt::Debug;
use std::sync::Arc;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum InnerKind {
Expr,
Stmt,
Item,
Block,
#[default]
File,
}
impl InnerKind {
#[must_use]
pub fn is_stmt_like(self) -> bool {
matches!(self, InnerKind::Stmt | InnerKind::Item)
}
#[must_use]
pub fn is_code_like(self) -> bool {
self.is_stmt_like() || matches!(self, InnerKind::File)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Arity {
#[default]
Unknown,
Const(u8),
Variadic,
}
impl Arity {
#[must_use]
pub fn from_table(table: &[&str], tag: &str) -> Arity {
if table.binary_search(&tag).is_ok() {
Arity::Variadic
} else {
Arity::Unknown
}
}
}
#[must_use]
pub fn comma_separator(table: &[&str], tag: &str) -> Option<&'static str> {
table.binary_search(&tag).is_ok().then_some(",")
}
#[derive(Debug, Clone, Default)]
pub struct Hole {
pub otag: Box<str>, pub ikind: Option<InnerKind>,
pub prefix: Box<[Box<str>]>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FlatNode<'a> {
Hole,
Splice,
Str(&'a str),
NewLine,
}
impl FlatNode<'_> {
#[must_use]
pub fn is_hole(&self) -> bool {
matches!(self, Self::Hole | Self::Splice)
}
}
#[must_use]
pub fn is_comment_tag(tag: &str) -> bool {
tag == "comment" || tag.ends_with("_comment")
}
pub trait Comments {
const LINE: Option<&'static str> = Some("//");
const HEADER: Option<&'static str> = Self::LINE;
}
pub fn one_liner(s: &str) -> [FlatNode<'_>; 1] {
[FlatNode::Str(s)]
}
pub fn flat_nodes(s: &str) -> Vec<FlatNode<'_>> {
let lines = s.split('\n').collect::<Vec<_>>();
let mut nodes = Vec::new();
for (i, line) in lines.iter().enumerate() {
if i > 0 {
nodes.push(FlatNode::NewLine);
}
if !line.is_empty() {
nodes.push(FlatNode::Str(line));
}
}
nodes
}
impl std::ops::Add for &Hole {
type Output = Hole;
fn add(self, rhs: Self) -> Self::Output {
let otag = rhs.otag.clone();
let ikind = rhs.ikind;
let mut prefix = self.prefix.to_vec();
prefix.extend_from_slice(&rhs.prefix);
let prefix = prefix.into();
Hole {
otag,
ikind,
prefix,
}
}
}
pub trait Language {
type Post: LanguagePost;
fn parse_pre(&mut self, ikind: Option<InnerKind>, code: &[FlatNode]) -> Result<Self::Post>;
fn parse_with(&mut self, code: &[FlatNode], plugs: &[Arc<QTerm>]) -> Result<Arc<QTerm>> {
self.parse_pre(Default::default(), code)?.parse_post(plugs)
}
fn parse(&mut self, code: &[FlatNode]) -> Result<Arc<QTerm>> {
self.parse_with(code, &[])
}
fn parse_as(&mut self, ikind: Option<InnerKind>, code: &[FlatNode]) -> Result<Arc<QTerm>> {
self.parse_pre(ikind, code)?.parse_post(&[])
}
fn parse_expr(&mut self, code: &[FlatNode]) -> Result<Arc<QTerm>> {
self.parse_as(Some(InnerKind::Expr), code)
}
fn parse_stmt(&mut self, code: &[FlatNode]) -> Result<Arc<QTerm>> {
self.parse_as(Some(InnerKind::Stmt), code)
}
fn parse_file(&mut self, code: &[FlatNode]) -> Result<Arc<QTerm>> {
self.parse_as(Some(InnerKind::File), code)
}
fn parse_auto(&mut self, code: &[FlatNode]) -> Result<Arc<QTerm>> {
self.parse_as(None, code)
}
fn arity(&self, _tag: &str) -> Arity {
Default::default()
}
fn separator(&self, _tag: &str) -> Option<&'static str> {
None
}
fn typ(&self, _tag: &str) -> InnerKind {
Default::default()
}
fn classify_term(&self, term: &QTerm) -> InnerKind {
match term {
QTerm::Tuple { tag, .. } => self.typ(tag),
_ => InnerKind::default(),
}
}
fn ident_tag(&self) -> &'static str {
"identifier"
}
fn hashbang(&self) -> Option<&'static str> {
None
}
fn machine_spec(&self) -> Option<crate::machine::MachineSpec> {
None
}
fn repl_spec(&self) -> Option<crate::machine::ReplSpec> {
None
}
fn native_machine(&self) -> Option<Box<dyn crate::machine::Machine>> {
None
}
}
#[must_use]
pub fn parse_hashbang(hashbang: &str) -> Option<(&str, Vec<&str>)> {
let mut words = hashbang.trim_start_matches("#!").split_whitespace();
let first = words.next()?;
if basename(first) != "env" {
return Some((first, words.collect()));
}
let mut program = None;
while let Some(word) = words.next() {
match word {
"-u" | "--unset" => {
words.next();
}
"--" => {}
_ if word.starts_with('-') => {}
_ if word.contains('=') => {}
_ => {
program = Some(word);
break;
}
}
}
Some((program?, words.collect()))
}
fn basename(path: &str) -> &str {
path.rsplit('/').next().unwrap_or(path)
}
pub trait LanguagePost: Debug {
fn holes(&self) -> &[Hole];
fn parse_post(&self, plugs: &[Arc<QTerm>]) -> Result<Arc<QTerm>>;
}
impl Language for Box<dyn Language<Post = Box<dyn LanguagePost>>> {
type Post = Box<dyn LanguagePost>;
fn parse_pre(&mut self, ikind: Option<InnerKind>, code: &[FlatNode]) -> Result<Self::Post> {
self.as_mut().parse_pre(ikind, code)
}
fn arity(&self, tag: &str) -> Arity {
self.as_ref().arity(tag)
}
fn separator(&self, tag: &str) -> Option<&'static str> {
self.as_ref().separator(tag)
}
fn typ(&self, tag: &str) -> InnerKind {
self.as_ref().typ(tag)
}
fn classify_term(&self, term: &QTerm) -> InnerKind {
self.as_ref().classify_term(term)
}
fn ident_tag(&self) -> &'static str {
self.as_ref().ident_tag()
}
fn hashbang(&self) -> Option<&'static str> {
self.as_ref().hashbang()
}
fn machine_spec(&self) -> Option<crate::machine::MachineSpec> {
self.as_ref().machine_spec()
}
fn repl_spec(&self) -> Option<crate::machine::ReplSpec> {
self.as_ref().repl_spec()
}
fn native_machine(&self) -> Option<Box<dyn crate::machine::Machine>> {
self.as_ref().native_machine()
}
}
impl LanguagePost for Box<dyn LanguagePost> {
fn holes(&self) -> &[Hole] {
self.as_ref().holes()
}
fn parse_post(&self, plugs: &[Arc<QTerm>]) -> Result<Arc<QTerm>> {
self.as_ref().parse_post(plugs)
}
}
#[cfg(test)]
mod tests {
use super::parse_hashbang;
#[test]
fn parses_the_declared_hashbangs() {
let cases = [
("#!/usr/bin/env rust-script", "rust-script", vec![]),
("#!/usr/bin/env python3", "python3", vec![]),
("#!/usr/bin/env bash", "bash", vec![]),
("#!/usr/bin/env zsh", "zsh", vec![]),
(
"#!/usr/bin/env -S node --experimental-strip-types",
"node",
vec!["--experimental-strip-types"],
),
];
for (hashbang, program, args) in cases {
assert_eq!(
parse_hashbang(hashbang),
Some((program, args)),
"{hashbang:?} did not resolve to its interpreter"
);
}
}
#[test]
fn parses_other_env_shapes() {
assert_eq!(
parse_hashbang("#!/bin/sh -e"),
Some(("/bin/sh", vec!["-e"]))
);
assert_eq!(
parse_hashbang("#!/usr/bin/env FOO=1 python3 -X dev"),
Some(("python3", vec!["-X", "dev"]))
);
assert_eq!(
parse_hashbang("#!/usr/bin/env -u FOO -S node"),
Some(("node", vec![]))
);
assert_eq!(parse_hashbang("#!/usr/bin/env -S"), None);
assert_eq!(parse_hashbang("#!"), None);
}
}