Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Explicit imports: import 'Raw "sample.html" #2036

Merged
merged 9 commits into from
Sep 18, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion core/src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,31 @@ impl InputFormat {
_ => None,
}
}
pub fn from_tag(tag: &str) -> Option<InputFormat> {
vi marked this conversation as resolved.
Show resolved Hide resolved
Some(match tag {
"Json" => InputFormat::Json,
"Nickel" => InputFormat::Nickel,
"Raw" => InputFormat::Raw,
"Yaml" => InputFormat::Yaml,
"Toml" => InputFormat::Toml,
#[cfg(feature = "nix-experimental")]
"Nix" => InputFormat::Nix,
_ => return None,
})
}

pub fn to_tag(&self) -> &'static str {
match self {
InputFormat::Nickel => "Nickel",
InputFormat::Json => "Json",
InputFormat::Yaml => "Yaml",
InputFormat::Toml => "Toml",
InputFormat::Raw => "Raw",
#[cfg(feature = "nix-experimental")]
InputFormat::Nix => "Nix",
}
}

/// Renturns an [InputFormat] based on the extension of a source path.
pub fn from_source_path(source_path: &SourcePath) -> Option<InputFormat> {
if let SourcePath::Path(p) = source_path {
Expand Down Expand Up @@ -1319,6 +1344,7 @@ pub trait ImportResolver {
fn resolve(
&mut self,
path: &OsStr,
format: InputFormat,
parent: Option<FileId>,
pos: &TermPos,
) -> Result<(ResolvedTerm, FileId), ImportError>;
Expand All @@ -1333,6 +1359,7 @@ impl ImportResolver for Cache {
fn resolve(
&mut self,
path: &OsStr,
format: InputFormat,
parent: Option<FileId>,
pos: &TermPos,
) -> Result<(ResolvedTerm, FileId), ImportError> {
Expand Down Expand Up @@ -1367,7 +1394,6 @@ impl ImportResolver for Cache {
)
})?;

let format = InputFormat::from_path(&path_buf).unwrap_or_default();
let (result, file_id) = match id_op {
CacheOp::Cached(id) => (ResolvedTerm::FromCache, id),
CacheOp::Done(id) => (ResolvedTerm::FromFile { path: path_buf }, id),
Expand Down Expand Up @@ -1467,6 +1493,7 @@ pub mod resolvers {
fn resolve(
&mut self,
_path: &OsStr,
_format: InputFormat,
_parent: Option<FileId>,
_pos: &TermPos,
) -> Result<(ResolvedTerm, FileId), ImportError> {
Expand Down Expand Up @@ -1508,6 +1535,7 @@ pub mod resolvers {
fn resolve(
&mut self,
path: &OsStr,
_format: InputFormat,
_parent: Option<FileId>,
pos: &TermPos,
) -> Result<(ResolvedTerm, FileId), ImportError> {
Expand Down
12 changes: 12 additions & 0 deletions core/src/error/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,8 @@ pub enum ParseError {
/// time, there are a set of expressions that can be excluded syntactically. Currently, it's
/// mostly constants.
InvalidContract(RawSpan),
/// Unrecognized explicit import format tag
InvalidImportFormat { span: RawSpan },
}

/// An error occurring during the resolution of an import.
Expand Down Expand Up @@ -815,6 +817,9 @@ impl ParseError {
}
}
InternalParseError::InvalidContract(span) => ParseError::InvalidContract(span),
InternalParseError::InvalidImportFormat { span } => {
ParseError::InvalidImportFormat { span }
}
},
}
}
Expand Down Expand Up @@ -2113,6 +2118,13 @@ impl IntoDiagnostics<FileId> for ParseError {
.to_owned(),
"Only functions and records might be valid contracts".to_owned(),
]),
ParseError::InvalidImportFormat{span} => Diagnostic::error()
.with_message("unknown import format tag")
.with_labels(vec![primary(&span)])
.with_notes(vec![
"Examples of valid format tags: 'Nickel 'Json 'Yaml 'Toml 'Raw"
.to_owned()
]),
};

vec![diagnostic]
Expand Down
4 changes: 2 additions & 2 deletions core/src/eval/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -796,7 +796,7 @@ impl<R: ImportResolver, C: Cache> VirtualMachine<R, C> {
));
}
}
Term::Import(path) => {
Term::Import { path, .. } => {
return Err(EvalError::InternalError(
format!("Unresolved import ({})", path.to_string_lossy()),
pos,
Expand Down Expand Up @@ -1169,7 +1169,7 @@ pub fn subst<C: Cache>(
| v @ Term::ForeignId(_)
| v @ Term::SealingKey(_)
| v @ Term::Enum(_)
| v @ Term::Import(_)
| v @ Term::Import{..}
| v @ Term::ResolvedImport(_)
// We could recurse here, because types can contain terms which would then be subject to
// substitution. Not recursing should be fine, though, because a type in term position
Expand Down
12 changes: 8 additions & 4 deletions core/src/eval/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,15 +131,15 @@ fn imports() {
.add_source(String::from("bad"), String::from("^$*/.23ab 0°@"));
vm.import_resolver_mut().add_source(
String::from("nested"),
String::from("let x = import \"two\" in x + 1"),
String::from("let x = import 'Nickel \"two\" in x + 1"),
);
vm.import_resolver_mut().add_source(
String::from("cycle"),
String::from("let x = import \"cycle_b\" in {a = 1, b = x.a}"),
String::from("let x = import 'Nickel \"cycle_b\" in {a = 1, b = x.a}"),
);
vm.import_resolver_mut().add_source(
String::from("cycle_b"),
String::from("let x = import \"cycle\" in {a = x.a}"),
String::from("let x = import 'Nickel \"cycle\" in {a = x.a}"),
);

fn mk_import<R>(
Expand All @@ -152,7 +152,11 @@ fn imports() {
R: ImportResolver,
{
resolve_imports(
mk_term::let_one_in(var, mk_term::import(import), body),
mk_term::let_one_in(
var,
mk_term::import(import, crate::cache::InputFormat::Nickel),
body,
),
vm.import_resolver_mut(),
)
.map(|resolve_result| resolve_result.transformed_term)
Expand Down
2 changes: 2 additions & 0 deletions core/src/parser/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,4 +153,6 @@ pub enum ParseError {
/// time, there are a set of expressions that can be excluded syntactically. Currently, it's
/// mostly constants.
InvalidContract(RawSpan),
/// Unrecognized explicit import format tag
InvalidImportFormat { span: RawSpan },
}
7 changes: 6 additions & 1 deletion core/src/parser/grammar.lalrpop
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,12 @@ UniTerm: UniTerm = {
<err: Error> => {
UniTerm::from(err)
},
"import" <s: StandardStaticString> => UniTerm::from(Term::Import(OsString::from(s))),
"import" <l: @L> <s: StandardStaticString> <r: @R> =>? {
Ok(UniTerm::from(mk_import_based_on_filename(s, mk_span(src_id, l, r))?))
},
"import" <l: @L> <t: EnumTag> <r: @R> <s: StandardStaticString> =>? {
Ok(UniTerm::from(mk_import_explicit(s, t, mk_span(src_id, l, r))?))
},
};

AnnotatedInfixExpr: UniTerm = {
Expand Down
4 changes: 2 additions & 2 deletions core/src/parser/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -555,7 +555,7 @@ fn ty_var_kind_mismatch() {
fn import() {
assert_eq!(
parse_without_pos("import \"file.ncl\""),
mk_term::import("file.ncl")
mk_term::import("file.ncl", crate::cache::InputFormat::Nickel)
);
assert_matches!(
parse("import \"file.ncl\" some args"),
Expand All @@ -564,7 +564,7 @@ fn import() {
assert_eq!(
parse_without_pos("(import \"file.ncl\") some args"),
mk_app!(
mk_term::import("file.ncl"),
mk_term::import("file.ncl", crate::cache::InputFormat::Nickel),
mk_term::var("some"),
mk_term::var("args")
)
Expand Down
25 changes: 25 additions & 0 deletions core/src/parser/utils.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Various helpers and companion code for the parser are put here to keep the grammar definition
//! uncluttered.
use indexmap::map::Entry;
use std::ffi::OsString;
use std::rc::Rc;
use std::{collections::HashSet, fmt::Debug};

Expand All @@ -10,6 +11,7 @@ use self::pattern::bindings::Bindings as _;

use super::error::ParseError;

use crate::cache::InputFormat;
use crate::{
combine::Combine,
eval::{
Expand Down Expand Up @@ -699,6 +701,29 @@ pub fn mk_fun(pat: Pattern, body: RichTerm) -> Term {
}
}

pub fn mk_import_based_on_filename(path: String, _span: RawSpan) -> Result<Term, ParseError> {
let path = OsString::from(path);
let format: Option<InputFormat> =
InputFormat::from_path(std::path::Path::new(path.as_os_str()));

// Fall back to InputFormat::Nickel in case of unknown filename extension for backwards compatiblilty.
let format = format.unwrap_or_default();

Ok(Term::Import { path, format })
}

pub fn mk_import_explicit(
path: String,
format: LocIdent,
span: RawSpan,
) -> Result<Term, ParseError> {
let path = OsString::from(path);
let Some(format) = InputFormat::from_tag(format.label()) else {
return Err(ParseError::InvalidImportFormat { span });
};
Ok(Term::Import { path, format })
}

/// Determine the minimal level of indentation of a multi-line string.
///
/// The result is determined by computing the minimum indentation level among all lines, where the
Expand Down
13 changes: 9 additions & 4 deletions core/src/pretty.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::fmt;

use crate::cache::InputFormat;
use crate::identifier::LocIdent;
use crate::parser::lexer::KEYWORDS;
use crate::term::{
Expand Down Expand Up @@ -143,7 +144,7 @@ fn needs_parens_in_type_pos(typ: &Type) -> bool {
| Term::Let(..)
| Term::LetPattern(..)
| Term::Op1(UnaryOp::IfThenElse, _)
| Term::Import(..)
| Term::Import { .. }
| Term::ResolvedImport(..)
)
} else {
Expand Down Expand Up @@ -1056,9 +1057,13 @@ where
SealingKey(sym) => allocator.text(format!("%<sealing key: {sym}>")),
Sealed(_i, _rt, _lbl) => allocator.text("%<sealed>"),
Annotated(annot, rt) => allocator.atom(rt).append(annot.pretty(allocator)),
Import(f) => allocator
.text("import ")
.append(allocator.as_string(f.to_string_lossy()).double_quotes()),
Import { path, format } => {
let mut a = allocator.text("import ");
if Some(*format) != InputFormat::from_path(std::path::Path::new(path.as_os_str())) {
a = a.append("'").append(format.to_tag()).append(" ");
}
a.append(allocator.as_string(path.to_string_lossy()).double_quotes())
vi marked this conversation as resolved.
Show resolved Hide resolved
}
ResolvedImport(id) => allocator.text(format!("import <file_id: {id:?}>")),
// This type is in term position, so we don't need to add parentheses.
Type { typ, contract: _ } => typ.pretty(allocator),
Expand Down
10 changes: 8 additions & 2 deletions core/src/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,13 +252,19 @@ impl<EC: EvalCache> Program<EC> {
let merge_term = inputs
.into_iter()
.map(|input| match input {
Input::Path(path) => RichTerm::from(Term::Import(path.into())),
Input::Path(path) => RichTerm::from(Term::Import {
path: path.into(),
format: InputFormat::Nickel,
}),
Input::Source(source, name) => {
let path = PathBuf::from(name.into());
cache
.add_source(SourcePath::Path(path.clone()), source)
.unwrap();
RichTerm::from(Term::Import(path.into()))
RichTerm::from(Term::Import {
path: path.into(),
format: InputFormat::Nickel,
})
}
})
.reduce(|acc, f| mk_term::op2(BinaryOp::Merge(Label::default().into()), acc, f))
Expand Down
32 changes: 23 additions & 9 deletions core/src/term/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use smallvec::SmallVec;
use string::NickelString;

use crate::{
cache::InputFormat,
error::{EvalError, ParseError},
eval::{cache::CacheIndex, Environment},
identifier::LocIdent,
Expand Down Expand Up @@ -207,7 +208,7 @@ pub enum Term {

/// An unresolved import.
#[serde(skip)]
Import(OsString),
Import { path: OsString, format: InputFormat },

/// A resolved import (which has already been loaded and parsed).
#[serde(skip)]
Expand Down Expand Up @@ -365,7 +366,16 @@ impl PartialEq for Term {
l0 == r0 && l1 == r1 && l2 == r2
}
(Self::Annotated(l0, l1), Self::Annotated(r0, r1)) => l0 == r0 && l1 == r1,
(Self::Import(l0), Self::Import(r0)) => l0 == r0,
(
Self::Import {
path: l0,
format: l1,
},
Self::Import {
path: r0,
format: r1,
},
) => l0 == r0 && l1 == r1,
(Self::ResolvedImport(l0), Self::ResolvedImport(r0)) => l0 == r0,
(
Self::Type {
Expand Down Expand Up @@ -973,7 +983,7 @@ impl Term {
| Term::Op1(_, _)
| Term::Op2(_, _, _)
| Term::OpN(..)
| Term::Import(_)
| Term::Import { .. }
| Term::ResolvedImport(_)
| Term::StrChunks(_)
| Term::ParseError(_)
Expand Down Expand Up @@ -1026,7 +1036,7 @@ impl Term {
| Term::OpN(..)
| Term::Sealed(..)
| Term::Annotated(..)
| Term::Import(_)
| Term::Import{..}
| Term::ResolvedImport(_)
| Term::StrChunks(_)
| Term::RecRecord(..)
Expand Down Expand Up @@ -1088,7 +1098,7 @@ impl Term {
| Term::OpN(..)
| Term::Sealed(..)
| Term::Annotated(..)
| Term::Import(_)
| Term::Import { .. }
| Term::ResolvedImport(_)
| Term::StrChunks(_)
| Term::RecRecord(..)
Expand Down Expand Up @@ -1144,7 +1154,7 @@ impl Term {
| Term::OpN(..)
| Term::Sealed(..)
| Term::Annotated(..)
| Term::Import(..)
| Term::Import{..}
| Term::ResolvedImport(..)
| Term::Closure(_)
| Term::ParseError(_)
Expand Down Expand Up @@ -2383,7 +2393,7 @@ impl Traverse<RichTerm> for RichTerm {
| Term::Var(_)
| Term::Closure(_)
| Term::Enum(_)
| Term::Import(_)
| Term::Import { .. }
| Term::ResolvedImport(_)
| Term::SealingKey(_)
| Term::ForeignId(_)
Expand Down Expand Up @@ -2852,11 +2862,15 @@ pub mod make {
mk_fun!("x", var("x"))
}

pub fn import<S>(path: S) -> RichTerm
pub fn import<S>(path: S, format: InputFormat) -> RichTerm
where
S: Into<OsString>,
{
Term::Import(path.into()).into()
Term::Import {
path: path.into(),
format,
}
.into()
}

pub fn integer(n: impl Into<i64>) -> RichTerm {
Expand Down
Loading