2016-10-02 22:30:28 -07:00
#[ cfg(test) ]
mod tests ;
2016-10-23 16:43:52 -07:00
mod app ;
pub use app ::app ;
2016-10-22 23:18:26 -07:00
#[ macro_use ]
extern crate lazy_static ;
2016-10-02 22:30:28 -07:00
extern crate regex ;
2016-10-07 17:56:52 -07:00
extern crate tempdir ;
2016-10-02 22:30:28 -07:00
use std ::io ::prelude ::* ;
2016-10-05 13:58:18 -07:00
use std ::{ fs , fmt , process , io } ;
2016-10-23 23:38:49 -07:00
use std ::collections ::{ BTreeMap , BTreeSet , HashSet } ;
2016-10-02 22:30:28 -07:00
use std ::fmt ::Display ;
use regex ::Regex ;
2016-10-07 17:56:52 -07:00
use std ::os ::unix ::fs ::PermissionsExt ;
2016-10-02 22:30:28 -07:00
macro_rules ! warn {
( $( $arg :tt ) * ) = > { {
extern crate std ;
use std ::io ::prelude ::* ;
let _ = writeln! ( & mut std ::io ::stderr ( ) , $( $arg ) * ) ;
} } ;
}
macro_rules ! die {
( $( $arg :tt ) * ) = > { {
extern crate std ;
warn! ( $( $arg ) * ) ;
std ::process ::exit ( - 1 )
} } ;
}
2016-10-23 16:43:52 -07:00
trait Slurp {
2016-10-02 22:30:28 -07:00
fn slurp ( & mut self ) -> Result < String , std ::io ::Error > ;
}
impl Slurp for fs ::File {
fn slurp ( & mut self ) -> Result < String , std ::io ::Error > {
let mut destination = String ::new ( ) ;
try ! ( self . read_to_string ( & mut destination ) ) ;
Ok ( destination )
}
}
fn re ( pattern : & str ) -> Regex {
Regex ::new ( pattern ) . unwrap ( )
}
2016-10-23 16:43:52 -07:00
#[ derive(PartialEq, Debug) ]
struct Recipe < ' a > {
2016-10-06 17:43:30 -07:00
line_number : usize ,
2016-10-02 22:30:28 -07:00
name : & ' a str ,
2016-10-06 17:43:30 -07:00
lines : Vec < & ' a str > ,
2016-10-23 23:38:49 -07:00
fragments : Vec < Vec < Fragment < ' a > > > ,
variables : BTreeSet < & ' a str > ,
2016-10-26 20:54:44 -07:00
variable_tokens : Vec < Token < ' a > > ,
2016-10-09 00:30:33 -07:00
dependencies : Vec < & ' a str > ,
2016-10-23 16:43:52 -07:00
dependency_tokens : Vec < Token < ' a > > ,
arguments : Vec < & ' a str > ,
argument_tokens : Vec < Token < ' a > > ,
2016-10-06 17:43:30 -07:00
shebang : bool ,
2016-10-02 22:30:28 -07:00
}
2016-10-23 23:38:49 -07:00
#[ derive(PartialEq, Debug) ]
2016-10-16 18:59:49 -07:00
enum Fragment < ' a > {
Text { text : & ' a str } ,
Variable { name : & ' a str } ,
}
2016-10-25 19:11:58 -07:00
enum Expression < ' a > {
2016-10-26 20:54:44 -07:00
Variable { name : & ' a str , token : Token < ' a > } ,
2016-10-25 19:11:58 -07:00
String { contents : & ' a str } ,
Concatination { lhs : Box < Expression < ' a > > , rhs : Box < Expression < ' a > > } ,
}
impl < ' a > Display for Expression < ' a > {
fn fmt ( & self , f : & mut fmt ::Formatter ) -> Result < ( ) , fmt ::Error > {
match * self {
2016-10-26 20:54:44 -07:00
Expression ::Variable { name , .. } = > try ! ( write! ( f , " {} " , name ) ) ,
2016-10-25 19:11:58 -07:00
Expression ::String { contents } = > try ! ( write! ( f , " \" {} \" " , contents ) ) ,
Expression ::Concatination { ref lhs , ref rhs } = > try ! ( write! ( f , " {} + {} " , lhs , rhs ) ) ,
}
Ok ( ( ) )
}
}
2016-10-05 13:58:18 -07:00
#[ cfg(unix) ]
2016-10-23 20:39:50 -07:00
fn error_from_signal ( recipe : & str , exit_status : process ::ExitStatus ) -> RunError {
2016-10-05 13:58:18 -07:00
use std ::os ::unix ::process ::ExitStatusExt ;
match exit_status . signal ( ) {
Some ( signal ) = > RunError ::Signal { recipe : recipe , signal : signal } ,
None = > RunError ::UnknownFailure { recipe : recipe } ,
}
}
#[ cfg(windows) ]
2016-10-23 20:39:50 -07:00
fn error_from_signal ( recipe : & str , exit_status : process ::ExitStatus ) -> RunError {
2016-10-05 13:58:18 -07:00
RunError ::UnknownFailure { recipe : recipe }
}
2016-10-03 23:55:55 -07:00
impl < ' a > Recipe < ' a > {
fn run ( & self ) -> Result < ( ) , RunError < ' a > > {
2016-10-07 17:56:52 -07:00
if self . shebang {
let tmp = try ! (
tempdir ::TempDir ::new ( " j " )
. map_err ( | error | RunError ::TmpdirIoError { recipe : self . name , io_error : error } )
) ;
let mut path = tmp . path ( ) . to_path_buf ( ) ;
path . push ( self . name ) ;
{
let mut f = try ! (
fs ::File ::create ( & path )
. map_err ( | error | RunError ::TmpdirIoError { recipe : self . name , io_error : error } )
) ;
let mut text = String ::new ( ) ;
// add the shebang
text + = self . lines [ 0 ] ;
text + = " \n " ;
// add blank lines so that lines in the generated script
// have the same line number as the corresponding lines
// in the justfile
for _ in 1 .. ( self . line_number + 2 ) {
text + = " \n "
}
for line in & self . lines [ 1 .. ] {
text + = line ;
text + = " \n " ;
}
try ! (
f . write_all ( text . as_bytes ( ) )
. map_err ( | error | RunError ::TmpdirIoError { recipe : self . name , io_error : error } )
) ;
2016-10-05 13:58:18 -07:00
}
2016-10-07 17:56:52 -07:00
// get current permissions
let mut perms = try ! (
fs ::metadata ( & path )
. map_err ( | error | RunError ::TmpdirIoError { recipe : self . name , io_error : error } )
) . permissions ( ) ;
// make the script executable
let current_mode = perms . mode ( ) ;
perms . set_mode ( current_mode | 0o100 ) ;
try ! ( fs ::set_permissions ( & path , perms ) . map_err ( | error | RunError ::TmpdirIoError { recipe : self . name , io_error : error } ) ) ;
// run it!
let status = process ::Command ::new ( path ) . status ( ) ;
2016-10-05 13:58:18 -07:00
try ! ( match status {
Ok ( exit_status ) = > if let Some ( code ) = exit_status . code ( ) {
if code = = 0 {
Ok ( ( ) )
} else {
Err ( RunError ::Code { recipe : self . name , code : code } )
}
} else {
Err ( error_from_signal ( self . name , exit_status ) )
} ,
2016-10-07 17:56:52 -07:00
Err ( io_error ) = > Err ( RunError ::TmpdirIoError { recipe : self . name , io_error : io_error } )
2016-10-05 13:58:18 -07:00
} ) ;
2016-10-07 17:56:52 -07:00
} else {
for command in & self . lines {
let mut command = * command ;
2016-10-23 20:39:50 -07:00
if ! command . starts_with ( '@' ) {
2016-10-07 17:56:52 -07:00
warn! ( " {} " , command ) ;
} else {
command = & command [ 1 .. ] ;
}
let status = process ::Command ::new ( " sh " )
. arg ( " -cu " )
. arg ( command )
. status ( ) ;
try ! ( match status {
Ok ( exit_status ) = > if let Some ( code ) = exit_status . code ( ) {
if code = = 0 {
Ok ( ( ) )
} else {
Err ( RunError ::Code { recipe : self . name , code : code } )
}
} else {
Err ( error_from_signal ( self . name , exit_status ) )
} ,
Err ( io_error ) = > Err ( RunError ::IoError { recipe : self . name , io_error : io_error } )
} ) ;
}
2016-10-03 23:55:55 -07:00
}
Ok ( ( ) )
}
}
2016-10-23 16:43:52 -07:00
impl < ' a > Display for Recipe < ' a > {
fn fmt ( & self , f : & mut fmt ::Formatter ) -> Result < ( ) , fmt ::Error > {
try ! ( write! ( f , " {} " , self . name ) ) ;
for argument in & self . arguments {
try ! ( write! ( f , " {} " , argument ) ) ;
}
try ! ( write! ( f , " : " ) ) ;
for dependency in & self . dependencies {
try ! ( write! ( f , " {} " , dependency ) )
}
2016-10-23 23:38:49 -07:00
for ( i , fragments ) in self . fragments . iter ( ) . enumerate ( ) {
2016-10-23 16:43:52 -07:00
if i = = 0 {
try ! ( writeln! ( f , " " ) ) ;
}
2016-10-23 23:38:49 -07:00
for ( j , fragment ) in fragments . iter ( ) . enumerate ( ) {
if j = = 0 {
try ! ( write! ( f , " " ) ) ;
}
match * fragment {
Fragment ::Text { text } = > try ! ( write! ( f , " {} " , text ) ) ,
Fragment ::Variable { name } = > try ! ( write! ( f , " {}{}{} " , " {{ " , name , " }} " ) ) ,
}
}
if i + 1 < self . fragments . len ( ) {
try ! ( write! ( f , " \n " ) ) ;
2016-10-23 16:43:52 -07:00
}
}
Ok ( ( ) )
}
}
2016-10-25 19:11:58 -07:00
fn resolve < ' a > ( recipes : & BTreeMap < & ' a str , Recipe < ' a > > ) -> Result < ( ) , Error < ' a > > {
let mut resolver = Resolver {
seen : HashSet ::new ( ) ,
stack : vec ! [ ] ,
resolved : HashSet ::new ( ) ,
recipes : recipes ,
} ;
for recipe in recipes . values ( ) {
try ! ( resolver . resolve ( & recipe ) ) ;
}
Ok ( ( ) )
}
struct Resolver < ' a : ' b , ' b > {
stack : Vec < & ' a str > ,
seen : HashSet < & ' a str > ,
resolved : HashSet < & ' a str > ,
recipes : & ' b BTreeMap < & ' a str , Recipe < ' a > >
}
impl < ' a , ' b > Resolver < ' a , ' b > {
fn resolve ( & mut self , recipe : & Recipe < ' a > ) -> Result < ( ) , Error < ' a > > {
if self . resolved . contains ( recipe . name ) {
return Ok ( ( ) )
}
self . stack . push ( recipe . name ) ;
self . seen . insert ( recipe . name ) ;
for dependency_token in & recipe . dependency_tokens {
match self . recipes . get ( dependency_token . lexeme ) {
Some ( dependency ) = > if ! self . resolved . contains ( dependency . name ) {
if self . seen . contains ( dependency . name ) {
let first = self . stack [ 0 ] ;
self . stack . push ( first ) ;
return Err ( dependency_token . error ( ErrorKind ::CircularRecipeDependency {
recipe : recipe . name ,
circle : self . stack . iter ( )
. skip_while ( | name | * * name ! = dependency . name )
. cloned ( ) . collect ( )
} ) ) ;
}
return self . resolve ( dependency ) ;
} ,
None = > return Err ( dependency_token . error ( ErrorKind ::UnknownDependency {
recipe : recipe . name ,
unknown : dependency_token . lexeme
} ) ) ,
}
}
self . resolved . insert ( recipe . name ) ;
self . stack . pop ( ) ;
Ok ( ( ) )
}
}
fn evaluate < ' a > (
assignments : & BTreeMap < & ' a str , Expression < ' a > > ,
assignment_tokens : & BTreeMap < & ' a str , Token < ' a > > ,
) -> Result < BTreeMap < & ' a str , String > , Error < ' a > > {
let mut evaluator = Evaluator {
seen : HashSet ::new ( ) ,
stack : vec ! [ ] ,
evaluated : BTreeMap ::new ( ) ,
assignments : assignments ,
assignment_tokens : assignment_tokens ,
} ;
for name in assignments . keys ( ) {
try ! ( evaluator . evaluate_assignment ( name ) ) ;
}
Ok ( evaluator . evaluated )
}
struct Evaluator < ' a : ' b , ' b > {
stack : Vec < & ' a str > ,
seen : HashSet < & ' a str > ,
evaluated : BTreeMap < & ' a str , String > ,
assignments : & ' b BTreeMap < & ' a str , Expression < ' a > > ,
assignment_tokens : & ' b BTreeMap < & ' a str , Token < ' a > > ,
}
impl < ' a , ' b > Evaluator < ' a , ' b > {
fn evaluate_assignment ( & mut self , name : & ' a str ) -> Result < ( ) , Error < ' a > > {
if self . evaluated . contains_key ( name ) {
return Ok ( ( ) ) ;
}
self . stack . push ( name ) ;
self . seen . insert ( name ) ;
if let Some ( expression ) = self . assignments . get ( name ) {
let value = try ! ( self . evaluate_expression ( expression ) ) ;
self . evaluated . insert ( name , value ) ;
} else {
let token = self . assignment_tokens . get ( name ) . unwrap ( ) ;
return Err ( token . error ( ErrorKind ::UnknownVariable { variable : name } ) ) ;
}
self . stack . pop ( ) ;
Ok ( ( ) )
}
fn evaluate_expression ( & mut self , expression : & Expression < ' a > , ) -> Result < String , Error < ' a > > {
Ok ( match * expression {
2016-10-26 20:54:44 -07:00
Expression ::Variable { name , ref token } = > {
2016-10-25 19:11:58 -07:00
if self . evaluated . contains_key ( name ) {
self . evaluated . get ( name ) . unwrap ( ) . clone ( )
} else if self . seen . contains ( name ) {
let token = self . assignment_tokens . get ( name ) . unwrap ( ) ;
self . stack . push ( name ) ;
return Err ( token . error ( ErrorKind ::CircularVariableDependency {
variable : name ,
circle : self . stack . clone ( ) ,
2016-10-03 23:55:55 -07:00
} ) ) ;
2016-10-26 20:54:44 -07:00
} else if ! self . assignments . contains_key ( name ) {
return Err ( token . error ( ErrorKind ::UnknownVariable { variable : name } ) ) ;
2016-10-25 19:11:58 -07:00
} else {
try ! ( self . evaluate_assignment ( name ) ) ;
self . evaluated . get ( name ) . unwrap ( ) . clone ( )
2016-10-03 23:55:55 -07:00
}
2016-10-25 19:11:58 -07:00
}
Expression ::String { contents } = > {
contents . to_string ( )
}
Expression ::Concatination { ref lhs , ref rhs } = > {
try ! ( self . evaluate_expression ( lhs ) )
+
& try ! ( self . evaluate_expression ( rhs ) )
}
} )
2016-10-03 23:55:55 -07:00
}
}
2016-10-22 23:18:26 -07:00
#[ derive(Debug, PartialEq) ]
2016-10-23 16:43:52 -07:00
struct Error < ' a > {
2016-10-22 23:18:26 -07:00
text : & ' a str ,
index : usize ,
line : usize ,
column : usize ,
2016-10-23 16:43:52 -07:00
width : Option < usize > ,
2016-10-22 23:18:26 -07:00
kind : ErrorKind < ' a > ,
2016-10-02 22:30:28 -07:00
}
#[ derive(Debug, PartialEq) ]
enum ErrorKind < ' a > {
2016-10-23 16:43:52 -07:00
BadName { name : & ' a str } ,
2016-10-25 19:11:58 -07:00
CircularRecipeDependency { recipe : & ' a str , circle : Vec < & ' a str > } ,
CircularVariableDependency { variable : & ' a str , circle : Vec < & ' a str > } ,
2016-10-23 16:43:52 -07:00
DuplicateDependency { recipe : & ' a str , dependency : & ' a str } ,
DuplicateArgument { recipe : & ' a str , argument : & ' a str } ,
DuplicateRecipe { recipe : & ' a str , first : usize } ,
2016-10-25 19:11:58 -07:00
DuplicateVariable { variable : & ' a str } ,
ArgumentShadowsVariable { argument : & ' a str } ,
2016-10-23 16:43:52 -07:00
MixedLeadingWhitespace { whitespace : & ' a str } ,
2016-10-26 20:54:44 -07:00
UnclosedInterpolationDelimiter ,
2016-10-23 23:38:49 -07:00
BadInterpolationVariableName { recipe : & ' a str , text : & ' a str } ,
2016-10-23 16:43:52 -07:00
ExtraLeadingWhitespace ,
2016-10-02 22:30:28 -07:00
InconsistentLeadingWhitespace { expected : & ' a str , found : & ' a str } ,
2016-10-06 17:43:30 -07:00
OuterShebang ,
2016-10-23 16:43:52 -07:00
UnknownDependency { recipe : & ' a str , unknown : & ' a str } ,
2016-10-25 19:11:58 -07:00
UnknownVariable { variable : & ' a str } ,
2016-10-16 18:59:49 -07:00
UnknownStartOfToken ,
2016-10-23 18:46:04 -07:00
UnexpectedToken { expected : Vec < TokenKind > , found : TokenKind } ,
2016-10-22 23:18:26 -07:00
InternalError { message : String } ,
2016-10-02 22:30:28 -07:00
}
fn show_whitespace ( text : & str ) -> String {
text . chars ( ) . map ( | c | match c { '\t' = > 't' , ' ' = > 's' , _ = > c } ) . collect ( )
}
2016-10-23 16:43:52 -07:00
fn mixed_whitespace ( text : & str ) -> bool {
2016-10-02 22:30:28 -07:00
! ( text . chars ( ) . all ( | c | c = = ' ' ) | | text . chars ( ) . all ( | c | c = = '\t' ) )
}
2016-10-23 16:43:52 -07:00
struct Or < ' a , T : ' a + Display > ( & ' a [ T ] ) ;
impl < ' a , T : Display > Display for Or < ' a , T > {
fn fmt ( & self , f : & mut fmt ::Formatter ) -> Result < ( ) , fmt ::Error > {
match self . 0. len ( ) {
0 = > { } ,
1 = > try ! ( write! ( f , " {} " , self . 0 [ 0 ] ) ) ,
2 = > try ! ( write! ( f , " {} or {} " , self . 0 [ 0 ] , self . 0 [ 1 ] ) ) ,
_ = > for ( i , item ) in self . 0. iter ( ) . enumerate ( ) {
try ! ( write! ( f , " {} " , item ) ) ;
if i = = self . 0. len ( ) - 1 {
} else if i = = self . 0. len ( ) - 2 {
try ! ( write! ( f , " , or " ) ) ;
} else {
try ! ( write! ( f , " , " ) )
}
2016-10-02 22:30:28 -07:00
} ,
}
2016-10-23 16:43:52 -07:00
Ok ( ( ) )
2016-10-02 22:30:28 -07:00
}
}
impl < ' a > Display for Error < ' a > {
fn fmt ( & self , f : & mut fmt ::Formatter ) -> Result < ( ) , fmt ::Error > {
try ! ( write! ( f , " justfile:{}: " , self . line ) ) ;
match self . kind {
2016-10-23 16:43:52 -07:00
ErrorKind ::BadName { name } = > {
try ! ( writeln! ( f , " name did not match /[a-z](-?[a-z0-9])*/: {} " , name ) ) ;
}
2016-10-25 19:11:58 -07:00
ErrorKind ::CircularRecipeDependency { recipe , ref circle } = > {
if circle . len ( ) = = 2 {
try ! ( write! ( f , " recipe 1{} depends on itself " , recipe ) ) ;
} else {
try ! ( write! ( f , " recipe {} has circular dependency: {} " , recipe , circle . join ( " -> " ) ) ) ;
}
return Ok ( ( ) ) ;
}
ErrorKind ::CircularVariableDependency { variable , ref circle } = > {
try ! ( write! ( f , " assignment to {} has circular dependency: {} " , variable , circle . join ( " -> " ) ) ) ;
2016-10-23 16:43:52 -07:00
return Ok ( ( ) ) ;
}
ErrorKind ::DuplicateArgument { recipe , argument } = > {
try ! ( writeln! ( f , " recipe {} has duplicate argument: {} " , recipe , argument ) ) ;
}
2016-10-25 19:11:58 -07:00
ErrorKind ::DuplicateVariable { variable } = > {
try ! ( writeln! ( f , " variable \" {} \" is has multiple definitions " , variable ) ) ;
}
2016-10-23 16:43:52 -07:00
ErrorKind ::UnexpectedToken { ref expected , found } = > {
try ! ( writeln! ( f , " expected {} but found {} " , Or ( expected ) , found ) ) ;
}
ErrorKind ::DuplicateDependency { recipe , dependency } = > {
try ! ( writeln! ( f , " recipe {} has duplicate dependency: {} " , recipe , dependency ) ) ;
}
ErrorKind ::DuplicateRecipe { recipe , first } = > {
try ! ( write! ( f , " duplicate recipe: {} appears on lines {} and {} " ,
recipe , first , self . line ) ) ;
return Ok ( ( ) ) ;
}
2016-10-25 19:11:58 -07:00
ErrorKind ::ArgumentShadowsVariable { argument } = > {
try ! ( writeln! ( f , " argument {} shadows variable of the same name " , argument ) ) ;
}
2016-10-23 16:43:52 -07:00
ErrorKind ::MixedLeadingWhitespace { whitespace } = > {
try ! ( writeln! ( f ,
" found a mix of tabs and spaces in leading whitespace: {} \n leading whitespace may consist of tabs or spaces, but not both " ,
show_whitespace ( whitespace )
) ) ;
}
ErrorKind ::ExtraLeadingWhitespace = > {
try ! ( writeln! ( f , " recipe line has extra leading whitespace " ) ) ;
}
2016-10-02 22:30:28 -07:00
ErrorKind ::InconsistentLeadingWhitespace { expected , found } = > {
try ! ( writeln! ( f ,
2016-10-22 23:18:26 -07:00
" inconsistant leading whitespace: recipe started with \" {} \" but found line with \" {} \" : " ,
2016-10-02 22:30:28 -07:00
show_whitespace ( expected ) , show_whitespace ( found )
) ) ;
}
2016-10-06 17:43:30 -07:00
ErrorKind ::OuterShebang = > {
try ! ( writeln! ( f , " a shebang \" #! \" is reserved syntax outside of recipes " ) )
}
2016-10-26 20:54:44 -07:00
ErrorKind ::UnclosedInterpolationDelimiter = > {
try ! ( writeln! ( f , " unmatched {} " , " {{ " ) )
2016-10-23 23:38:49 -07:00
}
ErrorKind ::BadInterpolationVariableName { recipe , text } = > {
try ! ( writeln! ( f , " recipe {} contains a bad variable interpolation: {} " , recipe , text ) )
}
2016-10-23 16:43:52 -07:00
ErrorKind ::UnknownDependency { recipe , unknown } = > {
try ! ( writeln! ( f , " recipe {} has unknown dependency {} " , recipe , unknown ) ) ;
}
2016-10-25 19:11:58 -07:00
ErrorKind ::UnknownVariable { variable } = > {
try ! ( writeln! ( f , " variable \" {} \" is unknown " , variable ) ) ;
}
2016-10-16 18:59:49 -07:00
ErrorKind ::UnknownStartOfToken = > {
2016-10-25 19:11:58 -07:00
try ! ( writeln! ( f , " unknown start of token: " ) ) ;
2016-10-16 18:59:49 -07:00
}
2016-10-22 23:18:26 -07:00
ErrorKind ::InternalError { ref message } = > {
try ! ( writeln! ( f , " internal error, this may indicate a bug in j: {} \n consider filing an issue: https://github.com/casey/j/issues/new " , message ) ) ;
}
2016-10-02 22:30:28 -07:00
}
match self . text . lines ( ) . nth ( self . line ) {
Some ( line ) = > try ! ( write! ( f , " {} " , line ) ) ,
2016-10-23 16:43:52 -07:00
None = > if self . index ! = self . text . len ( ) {
try ! ( write! ( f , " internal error: Error has invalid line number: {} " , self . line ) )
} ,
2016-10-07 17:56:52 -07:00
} ;
2016-10-02 22:30:28 -07:00
Ok ( ( ) )
}
}
2016-10-23 16:43:52 -07:00
struct Justfile < ' a > {
2016-10-25 19:11:58 -07:00
recipes : BTreeMap < & ' a str , Recipe < ' a > > ,
assignments : BTreeMap < & ' a str , Expression < ' a > > ,
values : BTreeMap < & ' a str , String > ,
2016-10-02 22:30:28 -07:00
}
impl < ' a > Justfile < ' a > {
2016-10-23 16:43:52 -07:00
fn first ( & self ) -> Option < & ' a str > {
2016-10-02 22:30:28 -07:00
let mut first : Option < & Recipe < ' a > > = None ;
2016-10-23 20:39:50 -07:00
for recipe in self . recipes . values ( ) {
2016-10-02 22:30:28 -07:00
if let Some ( first_recipe ) = first {
2016-10-06 17:43:30 -07:00
if recipe . line_number < first_recipe . line_number {
2016-10-02 22:30:28 -07:00
first = Some ( recipe )
}
} else {
first = Some ( recipe ) ;
}
}
first . map ( | recipe | recipe . name )
}
2016-10-23 16:43:52 -07:00
fn count ( & self ) -> usize {
2016-10-03 23:55:55 -07:00
self . recipes . len ( )
}
2016-10-23 16:43:52 -07:00
fn recipes ( & self ) -> Vec < & ' a str > {
2016-10-03 23:55:55 -07:00
self . recipes . keys ( ) . cloned ( ) . collect ( )
}
fn run_recipe ( & self , recipe : & Recipe < ' a > , ran : & mut HashSet < & ' a str > ) -> Result < ( ) , RunError > {
for dependency_name in & recipe . dependencies {
if ! ran . contains ( dependency_name ) {
try ! ( self . run_recipe ( & self . recipes [ dependency_name ] , ran ) ) ;
}
}
try ! ( recipe . run ( ) ) ;
ran . insert ( recipe . name ) ;
Ok ( ( ) )
}
2016-10-23 16:43:52 -07:00
fn run < ' b > ( & ' a self , names : & [ & ' b str ] ) -> Result < ( ) , RunError < ' b > >
2016-10-03 23:55:55 -07:00
where ' a : ' b
{
let mut missing = vec! [ ] ;
for recipe in names {
if ! self . recipes . contains_key ( recipe ) {
missing . push ( * recipe ) ;
2016-10-02 22:30:28 -07:00
}
}
2016-10-23 20:39:50 -07:00
if ! missing . is_empty ( ) {
2016-10-03 23:55:55 -07:00
return Err ( RunError ::UnknownRecipes { recipes : missing } ) ;
}
let recipes = names . iter ( ) . map ( | name | self . recipes . get ( name ) . unwrap ( ) ) . collect ::< Vec < _ > > ( ) ;
let mut ran = HashSet ::new ( ) ;
for recipe in recipes {
try ! ( self . run_recipe ( recipe , & mut ran ) ) ;
}
Ok ( ( ) )
2016-10-02 22:30:28 -07:00
}
2016-10-05 16:03:11 -07:00
2016-10-23 16:43:52 -07:00
fn get ( & self , name : & str ) -> Option < & Recipe < ' a > > {
2016-10-05 16:03:11 -07:00
self . recipes . get ( name )
}
2016-10-03 23:55:55 -07:00
}
2016-10-02 22:30:28 -07:00
2016-10-25 19:11:58 -07:00
impl < ' a > Display for Justfile < ' a > {
fn fmt ( & self , f : & mut fmt ::Formatter ) -> Result < ( ) , fmt ::Error > {
let mut items = self . recipes . len ( ) + self . assignments . len ( ) ;
for ( name , expression ) in & self . assignments {
try ! ( write! ( f , " {} = {} # \" {} \" " , name , expression , self . values . get ( name ) . unwrap ( ) ) ) ;
items - = 1 ;
if items ! = 0 {
try ! ( write! ( f , " \n " ) ) ;
}
}
for recipe in self . recipes . values ( ) {
try ! ( write! ( f , " {} " , recipe ) ) ;
items - = 1 ;
if items ! = 0 {
try ! ( write! ( f , " \n " ) ) ;
}
}
Ok ( ( ) )
}
}
2016-10-05 13:58:18 -07:00
#[ derive(Debug) ]
2016-10-23 16:43:52 -07:00
enum RunError < ' a > {
2016-10-03 23:55:55 -07:00
UnknownRecipes { recipes : Vec < & ' a str > } ,
2016-10-05 13:58:18 -07:00
Signal { recipe : & ' a str , signal : i32 } ,
2016-10-03 23:55:55 -07:00
Code { recipe : & ' a str , code : i32 } ,
2016-10-05 13:58:18 -07:00
UnknownFailure { recipe : & ' a str } ,
IoError { recipe : & ' a str , io_error : io ::Error } ,
2016-10-07 17:56:52 -07:00
TmpdirIoError { recipe : & ' a str , io_error : io ::Error } ,
2016-10-03 23:55:55 -07:00
}
impl < ' a > Display for RunError < ' a > {
fn fmt ( & self , f : & mut fmt ::Formatter ) -> Result < ( ) , fmt ::Error > {
2016-10-23 20:39:50 -07:00
match * self {
RunError ::UnknownRecipes { ref recipes } = > {
2016-10-03 23:55:55 -07:00
if recipes . len ( ) = = 1 {
try ! ( write! ( f , " Justfile does not contain recipe: {} " , recipes [ 0 ] ) ) ;
} else {
try ! ( write! ( f , " Justfile does not contain recipes: {} " , recipes . join ( " " ) ) ) ;
} ;
} ,
2016-10-23 20:39:50 -07:00
RunError ::Code { recipe , code } = > {
2016-10-03 23:55:55 -07:00
try ! ( write! ( f , " Recipe \" {} \" failed with code {} " , recipe , code ) ) ;
} ,
2016-10-23 20:39:50 -07:00
RunError ::Signal { recipe , signal } = > {
2016-10-05 13:58:18 -07:00
try ! ( write! ( f , " Recipe \" {} \" wast terminated by signal {} " , recipe , signal ) ) ;
}
2016-10-23 20:39:50 -07:00
RunError ::UnknownFailure { recipe } = > {
2016-10-05 13:58:18 -07:00
try ! ( write! ( f , " Recipe \" {} \" failed for an unknown reason " , recipe ) ) ;
} ,
2016-10-23 20:39:50 -07:00
RunError ::IoError { recipe , ref io_error } = > {
2016-10-05 13:58:18 -07:00
try ! ( match io_error . kind ( ) {
io ::ErrorKind ::NotFound = > write! ( f , " Recipe \" {} \" could not be run because j could not find `sh` the command: \n {} " , recipe , io_error ) ,
io ::ErrorKind ::PermissionDenied = > write! ( f , " Recipe \" {} \" could not be run because j could not run `sh`: \n {} " , recipe , io_error ) ,
_ = > write! ( f , " Recipe \" {} \" could not be run because of an IO error while launching the `sh`: \n {} " , recipe , io_error ) ,
} ) ;
} ,
2016-10-23 20:39:50 -07:00
RunError ::TmpdirIoError { recipe , ref io_error } = >
2016-10-07 17:56:52 -07:00
try ! ( write! ( f , " Recipe \" {} \" could not be run because of an IO error while trying to create a temporary directory or write a file to that directory`: \n {} " , recipe , io_error ) ) ,
2016-10-03 23:55:55 -07:00
}
Ok ( ( ) )
2016-10-02 22:30:28 -07:00
}
}
2016-10-23 16:43:52 -07:00
#[ derive(Debug, PartialEq) ]
2016-10-16 18:59:49 -07:00
struct Token < ' a > {
2016-10-22 23:18:26 -07:00
index : usize ,
2016-10-16 18:59:49 -07:00
line : usize ,
2016-10-22 23:18:26 -07:00
column : usize ,
2016-10-23 16:43:52 -07:00
text : & ' a str ,
2016-10-16 18:59:49 -07:00
prefix : & ' a str ,
lexeme : & ' a str ,
2016-10-23 18:46:04 -07:00
class : TokenKind ,
2016-10-16 18:59:49 -07:00
}
2016-10-22 23:18:26 -07:00
impl < ' a > Token < ' a > {
2016-10-23 16:43:52 -07:00
fn error ( & self , kind : ErrorKind < ' a > ) -> Error < ' a > {
2016-10-22 23:18:26 -07:00
Error {
2016-10-23 16:43:52 -07:00
text : self . text ,
index : self . index + self . prefix . len ( ) ,
2016-10-22 23:18:26 -07:00
line : self . line ,
2016-10-23 16:43:52 -07:00
column : self . column + self . prefix . len ( ) ,
width : Some ( self . lexeme . len ( ) ) ,
2016-10-22 23:18:26 -07:00
kind : kind ,
}
}
2016-10-26 20:54:44 -07:00
/*
fn split (
self ,
leading_prefix_len : usize ,
lexeme_len : usize ,
trailing_prefix_len : usize ,
) -> ( Token < ' a > , Token < ' a > ) {
let len = self . prefix . len ( ) + self . lexeme . len ( ) ;
// let length = self.prefix.len() + self.lexeme.len();
// if lexeme_start > lexeme_end || lexeme_end > length {
// }
// panic!("Tried to split toke
}
* /
2016-10-22 23:18:26 -07:00
}
2016-10-16 18:59:49 -07:00
#[ derive(Debug, PartialEq, Clone, Copy) ]
2016-10-23 18:46:04 -07:00
enum TokenKind {
2016-10-16 18:59:49 -07:00
Name ,
Colon ,
2016-10-25 19:11:58 -07:00
StringToken ,
Plus ,
2016-10-16 18:59:49 -07:00
Equals ,
Comment ,
Indent ,
Dedent ,
2016-10-26 20:54:44 -07:00
InterpolationStart ,
InterpolationEnd ,
Text ,
Line ,
2016-10-16 18:59:49 -07:00
Eol ,
Eof ,
}
2016-10-23 18:46:04 -07:00
impl Display for TokenKind {
2016-10-23 16:43:52 -07:00
fn fmt ( & self , f : & mut fmt ::Formatter ) -> Result < ( ) , fmt ::Error > {
try ! ( write! ( f , " {} " , match * self {
2016-10-26 20:54:44 -07:00
Name = > " name " ,
Colon = > " \" : \" " ,
Plus = > " \" + \" " ,
Equals = > " \" = \" " ,
StringToken = > " string " ,
Text = > " command text " ,
InterpolationStart = > " {{ " ,
InterpolationEnd = > " }} " ,
Comment = > " comment " ,
Line = > " command " ,
Indent = > " indent " ,
Dedent = > " dedent " ,
Eol = > " end of line " ,
Eof = > " end of file " ,
2016-10-23 16:43:52 -07:00
} ) ) ;
Ok ( ( ) )
}
}
2016-10-23 18:46:04 -07:00
use TokenKind ::* ;
2016-10-16 18:59:49 -07:00
fn token ( pattern : & str ) -> Regex {
let mut s = String ::new ( ) ;
s + = r "^(?m)([ \t]*)(" ;
s + = pattern ;
s + = " ) " ;
re ( & s )
}
2016-10-26 20:54:44 -07:00
fn tokenize < ' a > ( text : & ' a str ) -> Result < Vec < Token > , Error > {
2016-10-22 23:18:26 -07:00
lazy_static! {
2016-10-26 20:54:44 -07:00
static ref EOF : Regex = token ( r "(?-m)$" ) ;
static ref NAME : Regex = token ( r "([a-zA-Z0-9_-]+)" ) ;
static ref COLON : Regex = token ( r ":" ) ;
static ref EQUALS : Regex = token ( r "=" ) ;
static ref PLUS : Regex = token ( r "[+]" ) ;
static ref COMMENT : Regex = token ( r "#([^!].*)?$" ) ;
static ref STRING : Regex = token ( " \" [a-z0-9] \" " ) ;
static ref EOL : Regex = token ( r "\n|\r\n" ) ;
2016-10-26 22:04:12 -07:00
static ref INTERPOLATION_END : Regex = token ( r "[}][}]" ) ;
2016-10-26 20:54:44 -07:00
static ref LINE : Regex = re ( r "^(?m)[ \t]+[^ \t\n\r].*$" ) ;
static ref INDENT : Regex = re ( r "^([ \t]*)[^ \t\n\r]" ) ;
static ref INTERPOLATION_START : Regex = re ( r "^[{][{]" ) ;
2016-10-26 22:04:12 -07:00
static ref LEADING_TEXT : Regex = re ( r "^(?m)(.+?)[{][{]" ) ;
static ref TEXT : Regex = re ( r "^(?m)(.+)" ) ;
2016-10-26 20:54:44 -07:00
}
#[ derive(PartialEq) ]
enum State < ' a > {
Start ,
Indent ( & ' a str ) ,
Text ,
Interpolation ,
}
/*
struct Stack < ' a > {
states : Vec < StateKind < ' a > >
}
impl < ' a > State < ' a > {
fn current ( & self ) -> State {
self . states . last ( )
}
2016-10-16 18:59:49 -07:00
}
2016-10-26 20:54:44 -07:00
* /
2016-10-16 18:59:49 -07:00
fn indentation ( text : & str ) -> Option < & str > {
2016-10-22 23:18:26 -07:00
INDENT . captures ( text ) . map ( | captures | captures . at ( 1 ) . unwrap ( ) )
2016-10-16 18:59:49 -07:00
}
2016-10-22 23:18:26 -07:00
let mut tokens = vec! [ ] ;
let mut rest = text ;
let mut index = 0 ;
let mut line = 0 ;
let mut column = 0 ;
2016-10-26 20:54:44 -07:00
// let mut indent: Option<&str> = None;
// let mut state = StateKind::Start;
let mut state = vec! [ State ::Start ] ;
2016-10-22 23:18:26 -07:00
macro_rules ! error {
( $kind :expr ) = > { {
Err ( Error {
text : text ,
index : index ,
line : line ,
column : column ,
2016-10-23 16:43:52 -07:00
width : None ,
2016-10-22 23:18:26 -07:00
kind : $kind ,
} )
} } ;
}
2016-10-16 18:59:49 -07:00
loop {
2016-10-22 23:18:26 -07:00
if column = = 0 {
2016-10-26 20:54:44 -07:00
if let Some ( class ) = match ( state . last ( ) . unwrap ( ) , indentation ( rest ) ) {
2016-10-22 23:18:26 -07:00
// ignore: was no indentation and there still isn't
2016-10-23 20:39:50 -07:00
// or current line is blank
2016-10-26 20:54:44 -07:00
( & State ::Start , Some ( " " ) ) | ( _ , None ) = > {
2016-10-22 23:18:26 -07:00
None
}
// indent: was no indentation, now there is
2016-10-26 20:54:44 -07:00
( & State ::Start , Some ( current ) ) = > {
2016-10-23 16:43:52 -07:00
if mixed_whitespace ( current ) {
return error! ( ErrorKind ::MixedLeadingWhitespace { whitespace : current } )
}
2016-10-26 20:54:44 -07:00
//indent = Some(current);
state . push ( State ::Indent ( current ) ) ;
2016-10-16 18:59:49 -07:00
Some ( Indent )
}
2016-10-22 23:18:26 -07:00
// dedent: there was indentation and now there isn't
2016-10-26 20:54:44 -07:00
( & State ::Indent ( _ ) , Some ( " " ) ) = > {
// indent = None;
state . pop ( ) ;
2016-10-22 23:18:26 -07:00
Some ( Dedent )
}
// was indentation and still is, check if the new indentation matches
2016-10-26 20:54:44 -07:00
( & State ::Indent ( previous ) , Some ( current ) ) = > {
2016-10-16 18:59:49 -07:00
if ! current . starts_with ( previous ) {
2016-10-22 23:18:26 -07:00
return error! ( ErrorKind ::InconsistentLeadingWhitespace {
expected : previous ,
found : current
} ) ;
2016-10-16 18:59:49 -07:00
}
None
}
2016-10-26 20:54:44 -07:00
// at column 0 in some other state: this should never happen
( & State ::Text , _ ) | ( & State ::Interpolation , _ ) = > {
return error! ( ErrorKind ::InternalError {
message : " unexpected state at column 0 " . to_string ( )
} ) ;
}
2016-10-16 18:59:49 -07:00
} {
tokens . push ( Token {
2016-10-22 23:18:26 -07:00
index : index ,
2016-10-16 18:59:49 -07:00
line : line ,
2016-10-22 23:18:26 -07:00
column : column ,
2016-10-23 16:43:52 -07:00
text : text ,
2016-10-16 18:59:49 -07:00
prefix : " " ,
lexeme : " " ,
class : class ,
} ) ;
}
}
2016-10-23 16:43:52 -07:00
// insert a dedent if we're indented and we hit the end of the file
2016-10-26 20:54:44 -07:00
if & State ::Start ! = state . last ( ) . unwrap ( ) {
if EOF . is_match ( rest ) {
tokens . push ( Token {
index : index ,
line : line ,
column : column ,
text : text ,
prefix : " " ,
lexeme : " " ,
class : Dedent ,
} ) ;
}
2016-10-23 16:43:52 -07:00
}
2016-10-16 18:59:49 -07:00
let ( prefix , lexeme , class ) =
2016-10-26 20:54:44 -07:00
if let ( 0 , & State ::Indent ( indent ) , Some ( captures ) ) = ( column , state . last ( ) . unwrap ( ) , LINE . captures ( rest ) ) {
2016-10-16 18:59:49 -07:00
let line = captures . at ( 0 ) . unwrap ( ) ;
if ! line . starts_with ( indent ) {
2016-10-22 23:18:26 -07:00
return error! ( ErrorKind ::InternalError { message : " unexpected indent " . to_string ( ) } ) ;
2016-10-16 18:59:49 -07:00
}
2016-10-26 20:54:44 -07:00
//let (prefix, lexeme) = line.split_at(indent.len());
state . push ( State ::Text ) ;
//(prefix, lexeme, Line)
// state we can produce text, {{, or eol tokens
// will produce text, name, {{, tokens }}, until end of line
( & line [ 0 .. indent . len ( ) ] , " " , Line )
} else if let Some ( captures ) = EOF . captures ( rest ) {
( captures . at ( 1 ) . unwrap ( ) , captures . at ( 2 ) . unwrap ( ) , Eof )
} else if let & State ::Text = state . last ( ) . unwrap ( ) {
if let Some ( captures ) = INTERPOLATION_START . captures ( rest ) {
state . push ( State ::Interpolation ) ;
( " " , captures . at ( 0 ) . unwrap ( ) , InterpolationStart )
} else if let Some ( captures ) = LEADING_TEXT . captures ( rest ) {
( " " , captures . at ( 1 ) . unwrap ( ) , Text )
} else if let Some ( captures ) = TEXT . captures ( rest ) {
( " " , captures . at ( 1 ) . unwrap ( ) , Text )
} else if let Some ( captures ) = EOL . captures ( rest ) {
state . pop ( ) ;
( captures . at ( 1 ) . unwrap ( ) , captures . at ( 2 ) . unwrap ( ) , Eol )
} else {
return error! ( ErrorKind ::InternalError {
message : format ! ( " Could not match token in text state: \" {} \" " , rest )
} ) ;
}
} else if let Some ( captures ) = INTERPOLATION_END . captures ( rest ) {
if state . last ( ) . unwrap ( ) ! = & State ::Interpolation {
// improve error
panic! ( " interpolation end outside of interpolation state " ) ;
}
state . pop ( ) ;
( captures . at ( 1 ) . unwrap ( ) , captures . at ( 2 ) . unwrap ( ) , InterpolationEnd )
2016-10-22 23:18:26 -07:00
} else if let Some ( captures ) = NAME . captures ( rest ) {
2016-10-16 18:59:49 -07:00
( captures . at ( 1 ) . unwrap ( ) , captures . at ( 2 ) . unwrap ( ) , Name )
2016-10-22 23:18:26 -07:00
} else if let Some ( captures ) = EOL . captures ( rest ) {
2016-10-26 20:54:44 -07:00
if state . last ( ) . unwrap ( ) = = & State ::Interpolation {
panic! ( " interpolation must be closed at end of line " ) ;
}
2016-10-16 18:59:49 -07:00
( captures . at ( 1 ) . unwrap ( ) , captures . at ( 2 ) . unwrap ( ) , Eol )
2016-10-22 23:18:26 -07:00
} else if let Some ( captures ) = COLON . captures ( rest ) {
2016-10-16 18:59:49 -07:00
( captures . at ( 1 ) . unwrap ( ) , captures . at ( 2 ) . unwrap ( ) , Colon )
2016-10-25 19:11:58 -07:00
} else if let Some ( captures ) = PLUS . captures ( rest ) {
( captures . at ( 1 ) . unwrap ( ) , captures . at ( 2 ) . unwrap ( ) , Plus )
2016-10-22 23:18:26 -07:00
} else if let Some ( captures ) = EQUALS . captures ( rest ) {
2016-10-16 18:59:49 -07:00
( captures . at ( 1 ) . unwrap ( ) , captures . at ( 2 ) . unwrap ( ) , Equals )
2016-10-22 23:18:26 -07:00
} else if let Some ( captures ) = COMMENT . captures ( rest ) {
2016-10-16 18:59:49 -07:00
( captures . at ( 1 ) . unwrap ( ) , captures . at ( 2 ) . unwrap ( ) , Comment )
2016-10-25 19:11:58 -07:00
} else if let Some ( captures ) = STRING . captures ( rest ) {
( captures . at ( 1 ) . unwrap ( ) , captures . at ( 2 ) . unwrap ( ) , StringToken )
} else if rest . starts_with ( " #! " ) {
return error! ( ErrorKind ::OuterShebang )
2016-10-16 18:59:49 -07:00
} else {
2016-10-25 19:11:58 -07:00
return error! ( ErrorKind ::UnknownStartOfToken )
2016-10-16 18:59:49 -07:00
} ;
let len = prefix . len ( ) + lexeme . len ( ) ;
tokens . push ( Token {
2016-10-22 23:18:26 -07:00
index : index ,
line : line ,
column : column ,
2016-10-16 18:59:49 -07:00
prefix : prefix ,
2016-10-23 16:43:52 -07:00
text : text ,
2016-10-16 18:59:49 -07:00
lexeme : lexeme ,
class : class ,
} ) ;
2016-10-26 20:54:44 -07:00
if len = = 0 {
match tokens . last ( ) . unwrap ( ) . class {
Eof = > { } ,
_ = > return Err ( tokens . last ( ) . unwrap ( ) . error (
ErrorKind ::InternalError { message : format ! ( " zero length token: {:?} " , tokens . last ( ) . unwrap ( ) ) } ) ) ,
}
}
2016-10-16 18:59:49 -07:00
match tokens . last ( ) . unwrap ( ) . class {
Eol = > {
line + = 1 ;
2016-10-22 23:18:26 -07:00
column = 0 ;
2016-10-16 18:59:49 -07:00
} ,
Eof = > {
break ;
} ,
_ = > {
2016-10-22 23:18:26 -07:00
column + = len ;
2016-10-16 18:59:49 -07:00
}
}
rest = & rest [ len .. ] ;
2016-10-22 23:18:26 -07:00
index + = len ;
2016-10-16 18:59:49 -07:00
}
Ok ( tokens )
}
2016-10-23 20:39:50 -07:00
fn parse ( text : & str ) -> Result < Justfile , Error > {
2016-10-22 23:18:26 -07:00
let tokens = try ! ( tokenize ( text ) ) ;
2016-10-23 16:43:52 -07:00
let filtered : Vec < _ > = tokens . into_iter ( ) . filter ( | token | token . class ! = Comment ) . collect ( ) ;
if let Some ( token ) = filtered . iter ( ) . find ( | token | {
lazy_static! {
static ref GOOD_NAME : Regex = re ( " ^[a-z](-?[a-z0-9])*$ " ) ;
}
token . class = = Name & & ! GOOD_NAME . is_match ( token . lexeme )
} ) {
return Err ( token . error ( ErrorKind ::BadName { name : token . lexeme } ) ) ;
}
2016-10-22 23:18:26 -07:00
let parser = Parser {
text : text ,
tokens : filtered . into_iter ( ) . peekable ( )
} ;
let justfile = try ! ( parser . file ( ) ) ;
Ok ( justfile )
2016-10-16 18:59:49 -07:00
}
2016-10-22 23:18:26 -07:00
struct Parser < ' a > {
text : & ' a str ,
tokens : std ::iter ::Peekable < std ::vec ::IntoIter < Token < ' a > > >
2016-10-16 18:59:49 -07:00
}
2016-10-22 23:18:26 -07:00
impl < ' a > Parser < ' a > {
2016-10-23 18:46:04 -07:00
fn peek ( & mut self , class : TokenKind ) -> bool {
2016-10-23 16:43:52 -07:00
self . tokens . peek ( ) . unwrap ( ) . class = = class
}
2016-10-23 18:46:04 -07:00
fn accept ( & mut self , class : TokenKind ) -> Option < Token < ' a > > {
2016-10-22 23:18:26 -07:00
if self . peek ( class ) {
self . tokens . next ( )
2016-10-16 18:59:49 -07:00
} else {
None
}
}
2016-10-23 18:46:04 -07:00
fn accepted ( & mut self , class : TokenKind ) -> bool {
2016-10-16 18:59:49 -07:00
self . accept ( class ) . is_some ( )
}
2016-10-23 18:46:04 -07:00
fn expect ( & mut self , class : TokenKind ) -> Option < Token < ' a > > {
2016-10-23 16:43:52 -07:00
if self . peek ( class ) {
self . tokens . next ( ) ;
None
} else {
self . tokens . next ( )
}
2016-10-22 23:18:26 -07:00
}
2016-10-23 16:43:52 -07:00
fn expect_eol ( & mut self ) -> Option < Token < ' a > > {
if self . peek ( Eol ) {
self . accept ( Eol ) ;
None
} else if self . peek ( Eof ) {
None
} else {
self . tokens . next ( )
2016-10-16 18:59:49 -07:00
}
}
2016-10-25 19:11:58 -07:00
fn unexpected_token ( & self , found : & Token < ' a > , expected : & [ TokenKind ] ) -> Error < ' a > {
found . error ( ErrorKind ::UnexpectedToken {
expected : expected . to_vec ( ) ,
found : found . class ,
} )
}
2016-10-23 16:43:52 -07:00
fn recipe ( & mut self , name : & ' a str , line_number : usize ) -> Result < Recipe < ' a > , Error < ' a > > {
2016-10-16 18:59:49 -07:00
let mut arguments = vec! [ ] ;
2016-10-23 16:43:52 -07:00
let mut argument_tokens = vec! [ ] ;
while let Some ( argument ) = self . accept ( Name ) {
if arguments . contains ( & argument . lexeme ) {
return Err ( argument . error ( ErrorKind ::DuplicateArgument {
recipe : name , argument : argument . lexeme
} ) ) ;
2016-10-16 18:59:49 -07:00
}
2016-10-23 16:43:52 -07:00
arguments . push ( argument . lexeme ) ;
argument_tokens . push ( argument ) ;
2016-10-16 18:59:49 -07:00
}
2016-10-23 16:43:52 -07:00
if let Some ( token ) = self . expect ( Colon ) {
2016-10-25 19:11:58 -07:00
// if we haven't accepted any arguments, an equals
2016-10-26 20:54:44 -07:00
// would have been fine as part of an assignment
2016-10-25 19:11:58 -07:00
if arguments . is_empty ( ) {
return Err ( self . unexpected_token ( & token , & [ Name , Colon , Equals ] ) ) ;
} else {
return Err ( self . unexpected_token ( & token , & [ Name , Colon ] ) ) ;
}
2016-10-23 16:43:52 -07:00
}
2016-10-16 18:59:49 -07:00
let mut dependencies = vec! [ ] ;
2016-10-23 16:43:52 -07:00
let mut dependency_tokens = vec! [ ] ;
while let Some ( dependency ) = self . accept ( Name ) {
if dependencies . contains ( & dependency . lexeme ) {
return Err ( dependency . error ( ErrorKind ::DuplicateDependency {
recipe : name ,
dependency : dependency . lexeme
} ) ) ;
2016-10-16 18:59:49 -07:00
}
2016-10-23 16:43:52 -07:00
dependencies . push ( dependency . lexeme ) ;
dependency_tokens . push ( dependency ) ;
}
if let Some ( token ) = self . expect_eol ( ) {
return Err ( self . unexpected_token ( & token , & [ Name , Eol , Eof ] ) ) ;
2016-10-16 18:59:49 -07:00
}
2016-10-26 22:04:12 -07:00
enum Piece < ' a > {
Text { text : Token < ' a > } ,
Expression { expression : Expression < ' a > } ,
}
let mut new_lines = vec! [ ] ;
if self . accepted ( Indent ) {
while ! self . accepted ( Dedent ) {
if let Some ( token ) = self . expect ( Line ) {
return Err ( token . error ( ErrorKind ::InternalError {
message : format ! ( " Expected a dedent but got {} " , token . class )
} ) )
}
let mut pieces = vec! [ ] ;
while ! self . accepted ( Eol ) {
if let Some ( token ) = self . accept ( Text ) {
pieces . push ( Piece ::Text { text : token } ) ;
} else if let Some ( token ) = self . expect ( InterpolationStart ) {
return Err ( self . unexpected_token ( & token , & [ Text , InterpolationStart , Eol ] ) ) ;
} else {
pieces . push ( Piece ::Expression { expression : try ! ( self . expression ( true ) ) } ) ;
if let Some ( token ) = self . expect ( InterpolationEnd ) {
return Err ( self . unexpected_token ( & token , & [ InterpolationEnd ] ) ) ;
}
}
}
new_lines . push ( pieces ) ;
}
}
panic! ( " done! " ) ;
2016-10-23 16:43:52 -07:00
let mut lines = vec! [ ] ;
2016-10-23 23:38:49 -07:00
let mut line_tokens = vec! [ ] ;
2016-10-23 16:43:52 -07:00
let mut shebang = false ;
if self . accepted ( Indent ) {
while ! self . peek ( Dedent ) {
if let Some ( line ) = self . accept ( Line ) {
2016-10-23 20:39:50 -07:00
if lines . is_empty ( ) {
2016-10-23 16:43:52 -07:00
if line . lexeme . starts_with ( " #! " ) {
shebang = true ;
}
2016-10-23 20:39:50 -07:00
} else if ! shebang & & ( line . lexeme . starts_with ( ' ' ) | | line . lexeme . starts_with ( '\t' ) ) {
2016-10-23 16:43:52 -07:00
return Err ( line . error ( ErrorKind ::ExtraLeadingWhitespace ) ) ;
}
lines . push ( line . lexeme ) ;
2016-10-23 23:38:49 -07:00
line_tokens . push ( line ) ;
2016-10-23 16:43:52 -07:00
if ! self . peek ( Dedent ) {
if let Some ( token ) = self . expect_eol ( ) {
return Err ( self . unexpected_token ( & token , & [ Eol ] ) ) ;
}
}
} else if let Some ( _ ) = self . accept ( Eol ) {
} else {
let token = self . tokens . next ( ) . unwrap ( ) ;
return Err ( self . unexpected_token ( & token , & [ Line , Eol ] ) ) ;
}
}
if let Some ( token ) = self . expect ( Dedent ) {
return Err ( self . unexpected_token ( & token , & [ Dedent ] ) ) ;
}
}
2016-10-16 18:59:49 -07:00
2016-10-23 23:38:49 -07:00
let mut fragments = vec! [ ] ;
let mut variables = BTreeSet ::new ( ) ;
2016-10-26 20:54:44 -07:00
let mut variable_tokens = vec! [ ] ;
2016-10-23 23:38:49 -07:00
lazy_static! {
static ref FRAGMENT : Regex = re ( r "^(.*?)\{\{(.*?)\}\}" ) ;
static ref UNMATCHED : Regex = re ( r "^.*?\{\{" ) ;
2016-10-26 20:54:44 -07:00
static ref VARIABLE : Regex = re ( r "^([ \t]*)([a-z](-?[a-z0-9])*)[ \t]*$" ) ;
2016-10-23 23:38:49 -07:00
}
for line in & line_tokens {
let mut line_fragments = vec! [ ] ;
let mut rest = line . lexeme ;
2016-10-26 20:54:44 -07:00
let mut index = line . index ;
let mut column = line . column ;
2016-10-23 23:38:49 -07:00
while ! rest . is_empty ( ) {
2016-10-26 20:54:44 -07:00
let advanced ;
2016-10-23 23:38:49 -07:00
if let Some ( captures ) = FRAGMENT . captures ( rest ) {
let prefix = captures . at ( 1 ) . unwrap ( ) ;
if ! prefix . is_empty ( ) {
line_fragments . push ( Fragment ::Text { text : prefix } ) ;
}
let interior = captures . at ( 2 ) . unwrap ( ) ;
if let Some ( captures ) = VARIABLE . captures ( interior ) {
2016-10-26 20:54:44 -07:00
let prefix = captures . at ( 1 ) . unwrap ( ) ;
let name = captures . at ( 2 ) . unwrap ( ) ;
2016-10-23 23:38:49 -07:00
line_fragments . push ( Fragment ::Variable { name : name } ) ;
variables . insert ( name ) ;
2016-10-26 20:54:44 -07:00
variable_tokens . push ( Token {
index : index + line . prefix . len ( ) ,
line : line . line ,
column : column + line . prefix . len ( ) ,
text : line . text ,
prefix : prefix ,
lexeme : name ,
class : Name ,
} ) ;
2016-10-23 23:38:49 -07:00
} else {
return Err ( line . error ( ErrorKind ::BadInterpolationVariableName {
recipe : name ,
text : interior ,
} ) ) ;
}
2016-10-26 20:54:44 -07:00
advanced = captures . at ( 0 ) . unwrap ( ) . len ( ) ;
2016-10-23 23:38:49 -07:00
} else if UNMATCHED . is_match ( rest ) {
2016-10-26 20:54:44 -07:00
return Err ( line . error ( ErrorKind ::UnclosedInterpolationDelimiter ) ) ;
2016-10-23 23:38:49 -07:00
} else {
line_fragments . push ( Fragment ::Text { text : rest } ) ;
2016-10-26 20:54:44 -07:00
advanced = rest . len ( ) ;
} ;
index + = advanced ;
column + = advanced ;
rest = & rest [ advanced .. ] ;
2016-10-23 23:38:49 -07:00
}
fragments . push ( line_fragments ) ;
}
2016-10-23 16:43:52 -07:00
Ok ( Recipe {
line_number : line_number ,
name : name ,
dependencies : dependencies ,
dependency_tokens : dependency_tokens ,
arguments : arguments ,
argument_tokens : argument_tokens ,
2016-10-23 23:38:49 -07:00
fragments : fragments ,
variables : variables ,
2016-10-26 20:54:44 -07:00
variable_tokens : variable_tokens ,
2016-10-23 16:43:52 -07:00
lines : lines ,
shebang : shebang ,
} )
2016-10-16 18:59:49 -07:00
}
2016-10-22 23:18:26 -07:00
2016-10-26 22:04:12 -07:00
fn expression ( & mut self , interpolation : bool ) -> Result < Expression < ' a > , Error < ' a > > {
2016-10-25 19:11:58 -07:00
let first = self . tokens . next ( ) . unwrap ( ) ;
let lhs = match first . class {
2016-10-26 20:54:44 -07:00
Name = > Expression ::Variable { name : first . lexeme , token : first } ,
2016-10-25 19:11:58 -07:00
StringToken = > Expression ::String { contents : & first . lexeme [ 1 .. 2 ] } ,
_ = > return Err ( self . unexpected_token ( & first , & [ Name , StringToken ] ) ) ,
} ;
if self . accepted ( Plus ) {
2016-10-26 22:04:12 -07:00
let rhs = try ! ( self . expression ( interpolation ) ) ;
2016-10-25 19:11:58 -07:00
Ok ( Expression ::Concatination { lhs : Box ::new ( lhs ) , rhs : Box ::new ( rhs ) } )
2016-10-26 22:04:12 -07:00
} else if interpolation & & self . peek ( InterpolationEnd ) {
Ok ( lhs )
2016-10-25 19:11:58 -07:00
} else if let Some ( token ) = self . expect_eol ( ) {
2016-10-26 22:04:12 -07:00
if interpolation {
Err ( self . unexpected_token ( & token , & [ Plus , Eol , InterpolationEnd ] ) )
} else {
Err ( self . unexpected_token ( & token , & [ Plus , Eol ] ) )
}
2016-10-25 19:11:58 -07:00
} else {
Ok ( lhs )
}
2016-10-22 23:18:26 -07:00
}
2016-10-16 18:59:49 -07:00
2016-10-22 23:18:26 -07:00
fn file ( mut self ) -> Result < Justfile < ' a > , Error < ' a > > {
2016-10-23 16:43:52 -07:00
let mut recipes = BTreeMap ::< & str , Recipe > ::new ( ) ;
2016-10-25 19:11:58 -07:00
let mut assignments = BTreeMap ::< & str , Expression > ::new ( ) ;
let mut assignment_tokens = BTreeMap ::< & str , Token < ' a > > ::new ( ) ;
2016-10-22 23:18:26 -07:00
loop {
match self . tokens . next ( ) {
Some ( token ) = > match token . class {
Eof = > break ,
Eol = > continue ,
2016-10-25 19:11:58 -07:00
Name = > if self . accepted ( Equals ) {
if assignments . contains_key ( token . lexeme ) {
return Err ( token . error ( ErrorKind ::DuplicateVariable {
variable : token . lexeme ,
} ) ) ;
}
2016-10-26 22:04:12 -07:00
assignments . insert ( token . lexeme , try ! ( self . expression ( false ) ) ) ;
2016-10-25 19:11:58 -07:00
assignment_tokens . insert ( token . lexeme , token ) ;
2016-10-23 16:43:52 -07:00
} else {
if let Some ( recipe ) = recipes . remove ( token . lexeme ) {
return Err ( token . error ( ErrorKind ::DuplicateRecipe {
recipe : recipe . name ,
first : recipe . line_number
} ) ) ;
}
recipes . insert ( token . lexeme , try ! ( self . recipe ( token . lexeme , token . line ) ) ) ;
} ,
Comment = > return Err ( token . error ( ErrorKind ::InternalError {
message : " found comment in token stream " . to_string ( )
} ) ) ,
_ = > return Err ( token . error ( ErrorKind ::InternalError {
2016-10-22 23:18:26 -07:00
message : format ! ( " unhandled token class: {:?} " , token . class )
} ) ) ,
} ,
None = > return Err ( Error {
text : self . text ,
index : 0 ,
line : 0 ,
column : 0 ,
2016-10-23 16:43:52 -07:00
width : None ,
2016-10-22 23:18:26 -07:00
kind : ErrorKind ::InternalError {
message : " unexpected end of token stream " . to_string ( )
}
} ) ,
}
}
2016-10-16 18:59:49 -07:00
2016-10-23 16:43:52 -07:00
if let Some ( token ) = self . tokens . next ( ) {
return Err ( token . error ( ErrorKind ::InternalError {
2016-10-22 23:18:26 -07:00
message : format ! ( " unexpected token remaining after parsing completed: {:?} " , token . class )
} ) )
2016-10-06 17:43:30 -07:00
}
2016-10-25 19:11:58 -07:00
try ! ( resolve ( & recipes ) ) ;
2016-10-23 16:43:52 -07:00
for recipe in recipes . values ( ) {
2016-10-25 19:11:58 -07:00
for argument in & recipe . argument_tokens {
if assignments . contains_key ( argument . lexeme ) {
return Err ( argument . error ( ErrorKind ::ArgumentShadowsVariable {
argument : argument . lexeme
} ) ) ;
}
}
2016-10-26 20:54:44 -07:00
for variable in & recipe . variable_tokens {
let name = variable . lexeme ;
if ! ( assignments . contains_key ( & name ) | | recipe . arguments . contains ( & name ) ) {
return Err ( variable . error ( ErrorKind ::UnknownVariable { variable : name } ) ) ;
2016-10-25 19:11:58 -07:00
}
}
2016-10-23 16:43:52 -07:00
}
2016-10-25 19:11:58 -07:00
let values = try ! ( evaluate ( & assignments , & assignment_tokens ) ) ;
Ok ( Justfile {
recipes : recipes ,
assignments : assignments ,
values : values ,
} )
2016-10-02 22:30:28 -07:00
}
}