├── run-tests.sh ├── .gitignore ├── src ├── test.ml ├── examples │ ├── fib.c │ └── caramel_guide.txt ├── make ├── message.ml ├── stringify.ml ├── scanner.mll ├── standard_lib.ml ├── ast.ml ├── preprocessor.mll ├── parser.mly ├── executor.ml ├── stdlib.ss ├── finaltest.ml ├── type_infer.ml └── generator.ml ├── circle.yml ├── README.md └── LICENSE /run-tests.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | mkdir build 3 | eval `opam config env`; ocamlfind ocamlc -package oUnit -linkpkg -o build/test src/test.ml 4 | ./build/test 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.annot 2 | *.cmo 3 | *.cma 4 | *.cmi 5 | *.a 6 | *.o 7 | *.cmx 8 | *.cmxs 9 | *.cmxa 10 | 11 | # ocamlbuild working directory 12 | _build/ 13 | 14 | # ocamlbuild targets 15 | *.byte 16 | *.native 17 | 18 | # oasis generated files 19 | setup.data 20 | setup.log 21 | 22 | # OUnit 23 | *.cache 24 | test 25 | -------------------------------------------------------------------------------- /src/test.ml: -------------------------------------------------------------------------------- 1 | open OUnit 2 | 3 | let empty_list = [] 4 | let singleton_list = [1] 5 | 6 | let dummy_test _ = 7 | assert_equal 0 (List.length empty_list); 8 | assert_equal 1 (List.length singleton_list) 9 | 10 | let suite = "OUnit Example" >::: ["dummy_test" >:: dummy_test] 11 | 12 | let _ = 13 | run_test_tt_main suite 14 | -------------------------------------------------------------------------------- /circle.yml: -------------------------------------------------------------------------------- 1 | dependencies: 2 | pre: 3 | - sudo add-apt-repository -y ppa:avsm/ppa 4 | - sudo apt-get update 5 | - sudo apt-get install ocaml ocaml-native-compilers camlp4-extra opam 6 | - yes '' | opam init 7 | - eval `opam config env` 8 | - opam install -y ounit 9 | 10 | test: 11 | post: 12 | - ./run-tests.sh 13 | -------------------------------------------------------------------------------- /src/examples/fib.c: -------------------------------------------------------------------------------- 1 | 2 | = (fib 3 | fn (x) 4 | if {x is 0} 5 | 0 6 | if {x is 1} 7 | 1 8 | {fib({x-1}) + fib({x-2})}) 9 | = (fib 10 | fn (x) 11 | if {x is 0} 12 | 0 13 | if {x is 1} 14 | 1 15 | +(fib({x-1}) fib({x-2}))) 16 | prn(string_of_int( fib({1 + 3}))) 17 | -------------------------------------------------------------------------------- /src/make: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | ocamllex preprocessor.mll 3 | ocamlc -o preprocessor str.cma preprocessor.ml 4 | ocamlc -c message.ml # compile error message reporter 5 | ocamllex scanner.mll # create scanner.ml 6 | ocamlyacc parser.mly # create parser.ml and parser.mli 7 | ocamlc -c ast.ml # compile AST types 8 | ocamlc -c parser.mli # compile parser types 9 | ocamlc -c scanner.ml # compile the scanner 10 | ocamlc -c parser.ml # compile the parser 11 | ocamlc -c str.cma generator.ml # compile the generator 12 | ocamlc -c finaltest.ml # compile the tester 13 | ocamlc -c type_infer.ml # compile type inference checker 14 | ocamlc -c executor.ml # compile the executor 15 | ocamlc -o tests unix.cma str.cma generator.cmo message.cmo scanner.cmo ast.cmo parser.cmo type_infer.cmo finaltest.cmo # generate test runner 16 | ocamlc -o geb unix.cma str.cma generator.cmo message.cmo scanner.cmo ast.cmo parser.cmo type_infer.cmo executor.cmo # generate Godel, Escher, Bach Compiler 17 | -------------------------------------------------------------------------------- /src/message.ml: -------------------------------------------------------------------------------- 1 | (** Error messages for Lexing & Parsing *) 2 | 3 | open Printf 4 | open Lexing 5 | open Parsing 6 | 7 | exception LexingErr of string 8 | 9 | let print_position lexbuf msg = 10 | let start = lexeme_start_p lexbuf in 11 | let finish = lexeme_end_p lexbuf in 12 | (fprintf stderr "Line %d: char %d..%d: %s: \"%s\" \n" 13 | start.pos_lnum 14 | (start.pos_cnum - start.pos_bol) 15 | (finish.pos_cnum - finish.pos_bol) 16 | msg 17 | (Lexing.lexeme lexbuf)) 18 | 19 | (** [lexer_from_channel fname ch] returns a lexer stream which takes 20 | input from channel [ch]. The input filename (for reporting errors) is 21 | set to [fname]. 22 | *) 23 | let lexer_from_channel fname ch = 24 | let lex = Lexing.from_channel ch in 25 | let pos = lex.lex_curr_p in 26 | lex.lex_curr_p <- { pos with pos_fname = fname; pos_lnum = 1; } ; 27 | lex 28 | 29 | (** [lexer_from_string str] returns a lexer stream which takes input 30 | from a string [str]. The input filename (for reporting errors) is set to 31 | [""]. *) 32 | let lexer_from_string str = 33 | let lex = Lexing.from_string str in 34 | let pos = lex.lex_curr_p in 35 | lex.lex_curr_p <- { pos with pos_fname = ""; pos_lnum = 1; } ; 36 | lex 37 | 38 | -------------------------------------------------------------------------------- /src/examples/caramel_guide.txt: -------------------------------------------------------------------------------- 1 | (* To test the preprocessor: 2 | ocamllex preprocessor.mll 3 | ocamlc -o preprocessor str.cma preprocessor.ml 4 | ./preprocessor < test_pre.c 5 | output is in "program.ss" 6 | TODO: newline must be inserted before first expression of program before preprocessing *) 7 | (* testing indentation using tabs *) 8 | def fac(n) 9 | if {n <= 1} 10 | 1 11 | {n * fac({n - 1})} 12 | 13 | (* testing indentation using spaces *) 14 | def fac(n) 15 | if {n <= 1} 16 | f(a b c) 17 | {n * fac({n - 1})} 18 | 19 | 20 | 21 | def fac (a) 22 | if {a is 1} 23 | 1 24 | 0 25 | 26 | (* this will not work since args to if must be indented *) 27 | def fac (a) 28 | if(a b c) 29 | 30 | =( fac(n) 31 | if {n <= 1} 32 | f(a b c) 33 | {n * fac({n - 1})}) 34 | 35 | (* this should not work since the arguments to "if" are not indented properly *) 36 | + ( f(a b c) 37 | if{n < 0} 38 | f(a b) 39 | {1 + 2}) 40 | 41 | (* the above sum (+) function with corrected indenting *) 42 | + ( f(a b c ) 43 | if{n < 0} 44 | f(a b) 45 | {1 + 2}) 46 | 47 | 48 | def fac (a) 49 | if {a is 1} 50 | my_func ( 1 51 | "aa" 52 | your_func( 2 53 | "bb" 54 | 3 55 | ) 56 | ) 57 | if isnt(a 0) 58 | 0 59 | 1 60 | 0 61 | -------------------------------------------------------------------------------- /src/stringify.ml: -------------------------------------------------------------------------------- 1 | open Ast 2 | 3 | let rec stringify e = 4 | let stringify_op o = match o with 5 | Add -> "Add" | Sub -> "Sub" | Mult -> "Mult" | Div -> "Div" 6 | | Addf -> "Addf" | Subf -> "Subf" | Multf -> "Multf" | Divf -> "Divf" 7 | | Equal -> "Equal" | Neq -> "Neq" | Less -> "Less" | Leq -> "Leq" 8 | | Greater -> "Greater" | Geq -> "Geq" | And -> "And" | Or -> "Or" 9 | | Assign -> "Assign" 10 | in 11 | let concat l = (String.concat "" l) in 12 | match e with 13 | Int(x) -> concat ["Int("; string_of_int x; ")"] 14 | | Float(x) -> concat ["Float("; string_of_float x; ")"] 15 | | Boolean(x) -> concat ["Boolean("; if x = true then "true" else "false"; ")"] 16 | | String(x) -> concat ["String(\""; x; "\")"] 17 | | Id(x) -> concat ["Id(\""; x; "\")"] 18 | | Assign(el) -> concat ["Assign("; stringify (List(el)); ")"] 19 | | Eval(str, el) -> concat ["Eval("; str; ", "; stringify (List(el)); ")"] 20 | | Nil -> "Nil" 21 | | List(expl) -> concat ["List("; (String.concat ", " (List.map (fun x -> stringify x) expl)); ")"] 22 | | Fdecl(args, e) -> concat ["Fdecl(["; String.concat ", " (List.map (fun x -> concat ["\""; x; "\""]) args); "], "; stringify e; ")"] 23 | | If(cond, thenb, elseb) -> concat ["If("; stringify cond; ", "; stringify thenb; ", "; stringify elseb; ")"] 24 | | For(init, cond, update, exp) -> concat ["For("; stringify init; ", "; stringify cond; ", "; stringify update; ", "; stringify exp; ")"] 25 | | While(cond, exp) -> concat ["While("; stringify cond; ", "; stringify exp; ")"] 26 | | Let(str, exp1, exp2) -> concat ["Let(\""; str; "\", "; stringify exp1; ", "; stringify exp2; ")"] 27 | 28 | let stringify_prog exp_list = 29 | String.concat "" ["["; (String.concat ", " (List.map stringify exp_list)); "]"] 30 | -------------------------------------------------------------------------------- /src/scanner.mll: -------------------------------------------------------------------------------- 1 | { 2 | open Parser 3 | open Message 4 | open Lexing 5 | } 6 | 7 | rule token = parse 8 | 9 | | "###ENDSTDLIB###" { ignore 10 | (lexbuf.lex_curr_p <- {(lexeme_start_p lexbuf) 11 | with pos_lnum = 0 ; }); 12 | token lexbuf } 13 | | [' ' '\t' '\\'] { token lexbuf } (* Whitespace *) 14 | | [ '\n' '\r' ] { ignore(Lexing.new_line lexbuf); token lexbuf } 15 | | "/*" { comment lexbuf } (* Comments *) 16 | | ";;" { SEMI } 17 | | '(' { LPAREN } 18 | | ')' { RPAREN } 19 | | '{' { LBRACE } 20 | | '}' { RBRACE } 21 | | '+' { PLUS } 22 | | '-' { MINUS } 23 | | '*' { TIMES } 24 | | '/' { DIVIDE } 25 | | "+." { PLUSF } 26 | | "-." { MINUSF } 27 | | "*." { TIMESF } 28 | | "/." { DIVIDEF } 29 | | "and" { AND } 30 | | "or" { OR } 31 | | "not" { NOT } 32 | | '\'' { QUOTE } 33 | | '=' { ASSIGN } 34 | | "is" { EQ } 35 | | "isnt" { NEQ } 36 | | "true" as lxm { BOOL(bool_of_string lxm) } 37 | | "false" as lxm { BOOL(bool_of_string lxm) } 38 | | "nil" { NIL } 39 | | '<' { LT } 40 | | "<=" { LEQ } 41 | | ">" { GT } 42 | | ">=" { GEQ } 43 | | "++" { CONCAT } 44 | | "fn" { FUNC } 45 | | "if" { IF } 46 | | "do" { DO } 47 | | "eval" { EVAL } 48 | | "evaluate" { raise(Failure "Lexer error: evaluate is a reserved keyword and may not be used. ") } 49 | | "exec" { raise(Failure "Lexer error: exec is a reserved keyword and may not be used. ") } 50 | | '\"'[^'\"']*'\"' as lxm { STRING(String.sub lxm 1 (String.length lxm - 2)) } (* String *) 51 | | ['0'-'9']*'.'['0'-'9']+ as lxm { FLOAT(float_of_string lxm) } (* Float *) 52 | | ['0'-'9']+'.'['0'-'9']* as lxm { FLOAT(float_of_string lxm) } (* Float *) 53 | | ['0'-'9']+ as lxm { INT(int_of_string lxm) } (* Int *) 54 | | ['a'-'z' 'A'-'Z']['a'-'z' 'A'-'Z' '0'-'9' '_']* as lxm { ID(lxm) } (* Identifier *) 55 | | eof { EOF } 56 | | _ { raise (Message.LexingErr("Illegal input")) } 57 | 58 | and comment = parse 59 | "*/" { token lexbuf } (* comments *) 60 | | _ { comment lexbuf } 61 | -------------------------------------------------------------------------------- /src/standard_lib.ml: -------------------------------------------------------------------------------- 1 | 2 | let get_stdlib = String.concat "" [ 3 | 4 | "(= identity (fn (x) x));;"; 5 | 6 | "(= length (fn (l) (if (is l '()) 0 (+ 1 (length (tail l))))));;"; 7 | 8 | "(= nth (fn (n l) (if (is n 0) (head l) (nth (- n 1) (tail l))) ));;"; (* change this *) 9 | 10 | "(= first (fn (l) (nth 0 l)));;"; 11 | 12 | "(= second (fn (l) (nth 1 l)));;"; 13 | 14 | "(= third (fn (l) (nth 2 l)));;"; 15 | 16 | "(= fourth (fn (l) (nth 3 l)));;"; 17 | 18 | "(= fifth (fn (l) (nth 4 l)));;"; 19 | 20 | "(= sixth (fn (l) (nth 5 l)));;"; 21 | 22 | "(= seventh (fn (l) (nth 6 l)));;"; 23 | 24 | "(= eighth (fn (l) (nth 7 l)));;"; 25 | 26 | "(= ninth (fn (l) (nth 8 l)));;"; 27 | 28 | "(= tenth (fn (l) (nth 9 l)));;"; 29 | 30 | "(= last (fn (l) (nth (- (length l) 1) l)));;"; 31 | 32 | "(= make (fn (n f) (if (> n 0) (if (> n 1) (cons (f n) (make f (- n 1))) '((f 1))) '())));;"; 33 | 34 | "(= map (fn (f l) (if (is (tail l) '()) (cons (f (head l)) '()) (cons (f (head l)) (map f (tail l))))));;"; 35 | 36 | "(= fold_left (fn (f a l) (if (is l '()) a (fold_left f (eval '(f a (head l))) (tail l)) )));;"; 37 | 38 | "(= fold_right (fn (f l a) (if (is l '()) (eval '(identity a)) (eval '(f (head l) (fold_right f (tail l) a))))));;"; 39 | 40 | "(= filter (fn (f l) (fold_right (fn (x y) (if (f x) (cons x y) y)) l '())));;"; 41 | 42 | "(= append (fn (a b) (if (is a '()) b (cons (head a) (append (tail a) b)))));;"; 43 | 44 | "(= take (fn (i l) (if (or (not (> i 0)) (is l '())) '() (cons (head l) (take (- i 1) (tail l))))));;"; 45 | 46 | "(= drop (fn (i l) (if (< i 1) l (drop (- i 1) (tail l)))));;"; 47 | 48 | "(= zipwith (fn (f a b) (if (or (is a '()) (is b '())) '() (cons (f (head a) (head b)) (zipwith f (tail a) (tail b))))));;"; 49 | 50 | "(= zipwith3 (fn (f a b c) (if (or (or (is a '()) (is b '())) (is c '())) '() (cons (f (head a) (head b) (head c)) (zipwith3 f (tail a) (tail b) (tail c))))));;"; 51 | 52 | "(= zip (fn (a b) (zipwith (fn (x y) (cons x (cons y '()))) a b)));;"; 53 | 54 | (*"(= zip3 (fn (a b c) (zipwith (fn (x y z) (cons x (cons y (cons z '())))) a b c)));;"; *) 55 | 56 | "(= unzip (fn (l) (fold_right (fn (x y) '((cons (first x) (first y)) (cons (second x) (second y)))) l '('() '()))));;"; 57 | 58 | "(= reverse (fn (l) (if (is l '()) l (append (reverse (tail l)) (cons (head l) '())))));;"; 59 | 60 | "(= member (fn (e l) (if (is l '()) false (if (boolean (eval '(is (head l) e))) true (member e (tail l))))));;"; 61 | 62 | "(= intersperse (fn (e l) (if (or (is l '()) (is (tail l) '())) l (cons (head l) (cons e (intersperse e (tail l)))))));;"; 63 | 64 | "(= stringify_list (fn (f l) (++ \"[\" (fold_left ++ \"\" (intersperse \",\" (map f l))) \"]\")));;"; 65 | 66 | "(= print_list (fn (f l) (prn (stringify_list f l))));;"; 67 | 68 | 69 | ] -------------------------------------------------------------------------------- /src/ast.ml: -------------------------------------------------------------------------------- 1 | type op = Add | Sub | Mult | Div | Addf | Subf | Multf | Divf 2 | | Equal | Neq | Less | Leq | Greater | Geq | And | Or | Assign | Concat 3 | 4 | type htype = 5 | | TInt (** integers [int] *) 6 | | TFloat (** floats [floats] *) 7 | | TBool (** booleans [bool] *) 8 | | TString (** strings [string] *) 9 | | TParam of int (** parameter *) 10 | | TArrow of htype list (** Function type [s -> t] *) 11 | | TSomeList of htype (** Lists *) 12 | | TUnit (* unit type for printing *) 13 | | TSome (* sometype - used only for lists *) 14 | | TJblob (* JavaScript object type *) 15 | | TException (* Exceptions *) 16 | 17 | type expr = (* Expressions *) 18 | Int of int (* 4 *) 19 | | Float of float (* 4.444 *) 20 | | Boolean of bool (* true, false *) 21 | | String of string (* "hello world" *) 22 | | Id of string (* caml_riders *) 23 | | Assign of expr list (* {x = 5} OR (= x 5 y 6 z 7) *) 24 | | Eval of expr * expr list (* (foo 5 21) *) 25 | | Nil (* empty list '() *) 26 | | List of expr list (* heterogeneous list '(1 true 2.4) *) 27 | | Fdecl of string list * expr (* (fn (a b) {a + b}) *) 28 | | If of expr * expr * expr (* (if a b c) *) 29 | 30 | type program = expr list 31 | 32 | (** [rename t] renames parameters in type [t] so that they count from 33 | [0] up. This is useful for pretty printing. *) 34 | let rename (ty: htype) = 35 | let rec ren ((j,s) as c) = function 36 | | TInt -> TInt, c 37 | | TBool -> TBool, c 38 | | TFloat -> TFloat, c 39 | | TString -> TString, c 40 | | TSome -> TSome, c 41 | | TJblob -> TJblob, c 42 | | TException -> TException, c 43 | | TParam k -> 44 | (try 45 | TParam (List.assoc k s), c 46 | with 47 | Not_found -> TParam j, (j+1, (k, j)::s)) 48 | | TArrow t_list -> 49 | let rec tarrow_ren ts us c' = 50 | match ts with 51 | | [] -> us, c' 52 | | hd::tl -> 53 | (let u1, c'' = ren c' hd in 54 | tarrow_ren tl (us@[u1]) c'') 55 | in let u_list, final_c = (tarrow_ren t_list [] c) in 56 | TArrow u_list, final_c 57 | | TSomeList t -> let u, c' = ren c t in TSomeList u, c' 58 | | TUnit -> TUnit, c 59 | in 60 | fst (ren (0,[]) ty) 61 | 62 | (** [rename t1 t2] simultaneously renames types [t1] and [t2] so that 63 | parameters appearing in them are numbered from [0] on. *) 64 | 65 | let rename2 t1 t2 = 66 | match rename (TArrow [t1;t2]) with 67 | TArrow [u1;u2] -> u1, u2 68 | | _ -> assert false 69 | 70 | 71 | (** [string_of_type] converts a Poly type to string. *) 72 | let string_of_type ty = 73 | let a = [|"a";"b";"c";"d";"e";"f";"g";"h";"i"; 74 | "j";"k";"l";"m";"n";"o";"p";"q";"r"; 75 | "s";"t";"u";"v";"w";"x";"y";"z"|] 76 | in 77 | let rec to_str n ty = 78 | let (m, str) = 79 | match ty with 80 | | TSome -> (3, "sometype") 81 | | TSomeList ty -> (3, to_str 3 ty ^ " list") 82 | | TUnit -> (4, "unit") 83 | | TInt -> (4, "int") 84 | | TFloat -> (4, "float") 85 | | TString -> (4, "string") 86 | | TBool -> (4, "bool") 87 | | TJblob -> (4, "JavaScript object") 88 | | TParam k -> (4, (if k < Array.length a then "'" ^ a.(k) else "'ty" ^ string_of_int k)) 89 | | TException -> (1, "exception") 90 | | TArrow t_list -> let len = (List.length t_list)-1 in 91 | let rec tarrow_type ts s = 92 | match ts with 93 | | [] -> s 94 | | hd::tl -> 95 | if (List.length tl > 0) then 96 | tarrow_type tl (s^(to_str ((List.length ts)-1) hd)^" -> ") 97 | else ( 98 | tarrow_type tl (s^(to_str ((List.length ts)-1) hd)) 99 | ) 100 | in 101 | (len, tarrow_type t_list "") 102 | in 103 | if m > n then str else "(" ^ str ^ ")" 104 | in 105 | to_str (-1) ty 106 | 107 | (** [tsubst [(k1,t1); ...; (kn,tn)] t] replaces in type [t] parameters 108 | [TParam ki] with types [ti]. *) 109 | let rec tsubst s = function 110 | | (TInt | TBool | TFloat | TString | TUnit | TSome | TJblob | TException ) as t -> t 111 | | TParam k -> (try List.assoc k s with Not_found -> TParam k) 112 | | TArrow t_list -> let u_list = List.map (fun t -> tsubst s t) t_list 113 | in TArrow u_list 114 | | TSomeList t -> TSomeList (tsubst s t) 115 | -------------------------------------------------------------------------------- /src/preprocessor.mll: -------------------------------------------------------------------------------- 1 | { 2 | 3 | type token = EOF 4 | | String of string (* "sss" *) 5 | | Fparen of string (* foo(a) *) 6 | | Fdecl of string (* fn(a b) a + b;; def foo(a) a + 1 *) 7 | | Word of string (* other text in program *) 8 | | Comment (* comments are /* C-style */ *) 9 | | StdFn of string (* if a 10 | b 11 | c *) 12 | | LineBreak (* \n *) 13 | 14 | (* Store the indentation of added left parens using a stack *) 15 | let curIndent = Stack.create();; 16 | Stack.push (-1) curIndent;; (* mark bottom of stack with -1 *) 17 | 18 | (* Counts continuous whitespace in string s, starting at the given index and count *) 19 | let rec countSp s count index = 20 | let len = (String.length s - 1) in 21 | if index > len then count 22 | else if String.get s index = ' ' then countSp s (count+1)(index+1) 23 | else if String.get s index = '\t' then countSp s (count+8)(index+1) 24 | else count 25 | 26 | (* At the end of each expression (after seeing a newline): 27 | Add one right paren for each element popped off the given stack, 28 | until the stop of stack is -1; Adding to the end of given string s *) 29 | let rec closeExpression s stack = 30 | let top = Stack.top stack in 31 | if (top == -1) then (s ^ ";;\n") (* keep -1 as bottom-of-stack marker *) 32 | else (ignore (Stack.pop stack); closeExpression (")" ^ s) stack) 33 | } 34 | let fn_name = ['a'-'z' 'A'-'Z']['a'-'z' 'A'-'Z' '0'-'9' '_']* 35 | let binop = "+" | "-" | "*" | "/" | "+." | "-." | "*." | "/." 36 | | "and" | "or" | "is" | "isnt" | ">" | "<" | ">=" | "<=" | "=" | "++" 37 | 38 | rule token = parse 39 | eof { EOF } 40 | 41 | (* Newline marks end of expression; Add R-parens & ";;"*) 42 | | "\n" { let parens = 43 | if (Stack.top curIndent == -2) then "\n" 44 | else (closeExpression "" curIndent) 45 | in Word(parens) } 46 | 47 | | "/*" { comment lexbuf } 48 | 49 | | '\n'[' ' '\t']*("if" | "do" | "eval" ) as lxm (* Standard library functions *) 50 | { let spaces = countSp lxm 0 1 in 51 | ignore(Stack.push spaces curIndent); 52 | StdFn(lxm) } 53 | | '\n'[' ' '\t']* as ws { (* Indentation: whitespace at the beginning of a line *) 54 | let spaces = countSp ws 0 1 in 55 | if(spaces > Stack.top curIndent) then ( Word(ws)) 56 | else ( 57 | (* Same or less indentation than previously added lparen: 58 | pop stack until current indentation = top of stack *) 59 | let parens = 60 | let rec closeParens s stack = 61 | let top = Stack.top curIndent in 62 | if (top == -1) then (s ^ ";;\n") 63 | else if (top >= spaces) 64 | then (ignore(Stack.pop stack); closeParens (")" ^ s) stack) 65 | else (* top > spaces *) s 66 | in closeParens ws curIndent 67 | in Word(parens) 68 | ) } 69 | 70 | | "fn" ' '* '(' as lxm { let spaces = countSp lxm 0 1 in (* Anonymous function declaration: "fn (" *) 71 | ignore(Stack.push spaces curIndent); Fdecl(lxm) } 72 | 73 | | (fn_name | binop)' '* '(' as lxm { Fparen(lxm) } (* Function call as "f(args)" *) 74 | 75 | | '\"'[^'\"']*'\"' as lxm { String(lxm) } (* Quoted strings: quoted function calls scan as strings, 76 | not evaluated as fn calls *) 77 | 78 | | _ as lxm { Word(String.make 1 lxm) } (* All characters other than the above *) 79 | 80 | and comment = parse 81 | "*/" { token lexbuf } (* Return to normal scanning *) 82 | | _ { comment lexbuf } (* Ignore other characters *) 83 | { 84 | let () = 85 | let infile = Sys.argv.(1) in 86 | let outfile = 87 | let endname = try (String.index infile '.') 88 | with Not_found -> (String.length infile - 1) in 89 | String.sub infile 0 endname ^ ".ss" 90 | in 91 | let oc = open_out outfile in 92 | 93 | let load_file f = 94 | let ic = open_in f in 95 | let n = in_channel_length ic in 96 | let s = Bytes.create n in 97 | really_input ic s 0 n; 98 | close_in ic; 99 | (s) 100 | in 101 | let lexbuf = Lexing.from_string ("\n\n" ^ (load_file infile)) in 102 | 103 | let wordlist = 104 | let rec next l = match token lexbuf with 105 | EOF -> l 106 | | String(s) -> next(s::l) 107 | | Comment -> next(l) 108 | | LineBreak -> next("\n" :: l) 109 | | Word(s) -> next(s::l) 110 | | Fdecl(s) -> next( ("\n(" ^ s) :: l) 111 | | StdFn(s) -> next( ("\n(" ^ s) :: l) 112 | | Fparen(s) -> 113 | let args = String.index s '(' + 1 in 114 | let s = "(" ^ (String.sub s 0 (args - 1)) ^ " " in 115 | next(s::l) 116 | in next [] 117 | in let program = String.concat "" (List.rev wordlist) 118 | in let lines = Str.split (Str.regexp "\n") program 119 | 120 | in ignore(List.iter (fun a -> if a <> ";;" then print_endline(a)) lines); 121 | (List.iter (fun a -> if a <> ";;" then (Printf.fprintf oc "%s\n" a)) lines); 122 | close_out oc; 123 | } 124 | 125 | -------------------------------------------------------------------------------- /src/parser.mly: -------------------------------------------------------------------------------- 1 | %{ 2 | open Ast 3 | open Lexing 4 | open Parsing 5 | 6 | let num_errors = ref 0 7 | 8 | let parse_error msg = (* called by parser function on error *) 9 | let start = symbol_start_pos() in 10 | let final = symbol_end_pos() in 11 | Printf.fprintf stdout "Line:%d char:%d..%d: %s\n" 12 | (start.pos_lnum) (start.pos_cnum - start.pos_bol) (final.pos_cnum - final.pos_bol) msg; 13 | incr num_errors; 14 | flush stdout 15 | 16 | %} 17 | 18 | %token PLUS MINUS TIMES DIVIDE PLUSF MINUSF TIMESF DIVIDEF EOF 19 | %token ASSIGN QUOTE AND OR NOT EQ NEQ LT LEQ GT GEQ CONCAT 20 | %token SEMI LPAREN RPAREN LBRACE RBRACE 21 | %token INT 22 | %token FUNC IF DO EVAL 23 | %token ID 24 | %token STRING 25 | %token FLOAT 26 | %token BOOL 27 | %token NIL 28 | 29 | %right ASSIGN 30 | %left OR 31 | %left AND 32 | %left EQ NEQ 33 | %left LT GT LEQ GEQ 34 | %left PLUS MINUS PLUSF MINUSF 35 | %left TIMES DIVIDE TIMESF DIVIDEF 36 | %left CONCAT 37 | 38 | %start program 39 | %type program 40 | 41 | %% 42 | 43 | program: 44 | expr_list EOF { if(!num_errors == 0) then (List.rev $1) 45 | else (exit (-1)) } 46 | 47 | expr_list: 48 | /* nothing */ { [] } 49 | | expr_list expr SEMI { $2 :: $1 } 50 | | expr_list expr { (parse_error ("Syntax error. Did you forget to terminate the expression with ;; " ^ 51 | "or forget a right paren?")); $1 } 52 | 53 | sexpr: 54 | | IF expr expr expr { If($2, $3, $4) } 55 | | FUNC LPAREN formals_opt RPAREN expr { Fdecl(List.rev $3, $5) } 56 | | call { $1 } 57 | 58 | expr: 59 | atom { $1 } 60 | | list { $1 } 61 | | LBRACE infix_expr RBRACE { $2 } 62 | | unquoted_list { $1 } 63 | 64 | list: 65 | QUOTE LPAREN args_opt RPAREN { List(List.rev $3) } 66 | 67 | unquoted_list: 68 | LPAREN sexpr RPAREN { $2 } 69 | | LPAREN sexpr SEMI { (parse_error "Syntax error. Left paren is unmatched by right paren."); $2 } 70 | 71 | formals_opt: 72 | /* nothing */ { [] } 73 | | formal_list { $1 } 74 | 75 | formal_list: 76 | ID { [$1] } 77 | | formal_list ID { $2 :: $1 } 78 | 79 | atom: 80 | constant { $1 } 81 | | ID { Id($1) } 82 | | NIL { Nil } 83 | | operator { Id($1) } 84 | | two_args_operators { Id($1) } 85 | 86 | operator: 87 | | PLUS { "__add" } 88 | | MINUS { "__sub" } 89 | | TIMES { "__mult" } 90 | | DIVIDE { "__div" } 91 | | PLUSF { "__addf" } 92 | | MINUSF { "__subf" } 93 | | DIVIDEF { "__divf" } 94 | | TIMESF { "__multf" } 95 | | AND { "__and" } 96 | | OR { "__or" } 97 | | NOT { "__not" } 98 | | CONCAT { "__concat" } 99 | | DO { "exec" } 100 | | EVAL { "evaluate" } 101 | 102 | two_args_operators: 103 | | EQ { "__equal" } 104 | | NEQ { "__neq" } 105 | | LT { "__less" } 106 | | LEQ { "__leq" } 107 | | GT { "__greater" } 108 | | GEQ { "__geq" } 109 | 110 | constant: 111 | INT { Int($1) } 112 | | FLOAT { Float($1) } 113 | | BOOL { Boolean($1) } 114 | | STRING { String($1) } 115 | 116 | call: 117 | ID args_opt { Eval(Id($1), List.rev $2) } 118 | | unquoted_list args_opt { Eval($1, List.rev $2) } 119 | | operator args_opt { Eval(Id($1), List.rev $2) } 120 | | two_args_operators two_args { Eval(Id($1), List.rev $2)} 121 | | ASSIGN assign_args { Assign($2) } 122 | | constant args_opt { (parse_error "Syntax error. Function call on inappropriate object."); $1 } 123 | ; 124 | 125 | args_opt: 126 | /* nothing */ { [] } 127 | | args { $1 } 128 | 129 | two_args: 130 | expr expr { [$2; $1] } 131 | 132 | args: 133 | expr { [$1] } 134 | | args expr { $2 :: $1 } 135 | 136 | assign_args: 137 | ID expr { [Id($1); $2] } 138 | | ID expr assign_args { Id($1) :: $2 :: $3 } 139 | | error { (parse_error "Syntax error. Assign usage is (= id1 e1 id2 e2...idn en)"); [] } 140 | 141 | infix_expr: 142 | constant { $1 } 143 | | LPAREN ID args_opt RPAREN { Eval(Id($2), List.rev $3) } 144 | | ID { Id($1) } 145 | | MINUS INT { Int(-1 * $2) } 146 | | MINUS FLOAT { Float(-1.0 *. $2) } 147 | | LBRACE infix_expr RBRACE { $2 } 148 | | ID ASSIGN infix_expr { Assign([Id($1); $3]) } 149 | | infix_expr CONCAT infix_expr { Eval(Id("concat"), [$1; $3]) } 150 | | infix_expr PLUS infix_expr { Eval(Id("__add"), [$1; $3]) } 151 | | infix_expr MINUS infix_expr { Eval(Id("__sub"), [$1; $3]) } 152 | | infix_expr TIMES infix_expr { Eval(Id("__mult"), [$1; $3]) } 153 | | infix_expr DIVIDE infix_expr { Eval(Id("__div"), [$1; $3]) } 154 | | infix_expr PLUSF infix_expr { Eval(Id("__addf"), [$1; $3]) } 155 | | infix_expr MINUSF infix_expr { Eval(Id("__subf"), [$1; $3]) } 156 | | infix_expr TIMESF infix_expr { Eval(Id("__multf"), [$1; $3]) } 157 | | infix_expr DIVIDEF infix_expr { Eval(Id("__divf"), [$1; $3]) } 158 | | infix_expr EQ infix_expr { Eval(Id("__equal"), [$1; $3]) } 159 | | infix_expr NEQ infix_expr { Eval(Id("__neq"), [$1; $3]) } 160 | | infix_expr LT infix_expr { Eval(Id("__less"), [$1; $3]) } 161 | | infix_expr LEQ infix_expr { Eval(Id("__leq"), [$1; $3]) } 162 | | infix_expr GT infix_expr { Eval(Id("__greater"), [$1; $3]) } 163 | | infix_expr GEQ infix_expr { Eval(Id("__geq"), [$1; $3]) } 164 | | infix_expr AND infix_expr { Eval(Id("__and"), [$1; $3]) } 165 | | infix_expr OR infix_expr { Eval(Id("__or"), [$1; $3]) } 166 | -------------------------------------------------------------------------------- /src/executor.ml: -------------------------------------------------------------------------------- 1 | open Ast;; 2 | open Type_infer;; 3 | open Generator;; 4 | open Scanner;; 5 | open Unix;; 6 | open Message;; 7 | open Printf;; 8 | open Array;; 9 | 10 | exception Fatal_error of string 11 | let fatal_error msg = raise (Fatal_error msg) 12 | 13 | (** [exec_cmd ctx cmd] executes the toplevel command [cmd] in 14 | the given context [ctx]. It returns the new context. *) 15 | let rec exec_cmd ctx = function 16 | | Assign(el) -> 17 | let rec gen_pairs l = 18 | match l with 19 | | [] -> [] 20 | | h1::h2::tl -> (h1, h2)::(gen_pairs tl) 21 | | _::[] -> raise(Fatal_error("=operator used on odd numbered list!")) 22 | in 23 | let defs = (gen_pairs el) in 24 | let rec addCtx ctx = function 25 | | [] -> ctx 26 | | (x,e)::tl -> 27 | (* convert x from Ast.htype into the actual identifier string *) 28 | let x = match x with 29 | | Id(s) -> s 30 | | _ -> raise(Fatal_error("first operand of assignment must be an identifier!")) 31 | 32 | in let ty = 33 | (* type check [e], and store it unevaluated! *) 34 | try (Ast.rename (Type_infer.type_of ctx e)) 35 | 36 | with 37 | (* Error: RHS of assignment contained an undeclared variable *) 38 | | Type_infer.Unknown_variable (msg, id) -> ( 39 | 40 | (* Case: unknown var != LHS of assignment --> immediately reject *) 41 | if (String.compare x id) != 0 then 42 | (Type_infer.unknown_var_error("Unknown variable " ^ id) id) 43 | 44 | (* Case: unknown var on RHS == LHS of assignment --> allow if RHS is a recursive fdecl *) 45 | else 46 | ( 47 | 48 | (* Assume RHS is recursive fn definition: 49 | store (x, TParam _) into the context to avoid unknown var errors *) 50 | 51 | let tparam = Type_infer.fresh() in 52 | let ctx = (x,tparam)::ctx in 53 | let recfun = Ast.rename(Type_infer.type_of ctx e) in 54 | 55 | (* Check that type of RHS was indeed a function definition *) 56 | 57 | let ty = match recfun with 58 | | TArrow _ -> recfun 59 | | _ -> Type_infer.unknown_var_error("Unknown variable " ^ x) x 60 | in 61 | ty 62 | ) 63 | ) 64 | in 65 | print_endline ("val " ^ x ^ " : " ^ string_of_type ty); 66 | (x,ty)::(addCtx ctx tl) 67 | in 68 | (addCtx ctx defs) 69 | | _ as e -> 70 | (* type check [e], evaluate, and print result *) 71 | let ty = 72 | try Ast.rename (Type_infer.type_of ctx e) with 73 | Type_infer.Unknown_variable (msg, id) -> raise (Failure (msg)) 74 | 75 | in 76 | print_string ("- : " ^ string_of_type ty) ; 77 | print_newline (); 78 | ctx 79 | ;; 80 | 81 | (** [exec_cmds ctx cmds] executes the list of 82 | expressions [cmds] in the given context [ctx]. 83 | It returns the new context. *) 84 | let exec_cmds ctx cmds = 85 | try 86 | List.fold_left (exec_cmd) ctx cmds 87 | with 88 | | Type_infer.Invalid_args msg -> raise (Failure (msg)) 89 | | Type_infer.Type_error msg -> raise (Failure (msg)) 90 | ;; 91 | 92 | (** [load_file f] loads the file [f] and returns the contents as a string. *) 93 | let load_file f = 94 | let ic = open_in f in 95 | let n = in_channel_length ic in 96 | let s = Bytes.create n in 97 | really_input ic s 0 n; 98 | close_in ic; 99 | (s) ;; 100 | 101 | let rec funct foo = 102 | try 103 | let l = input_line foo in 104 | match l with 105 | | _ -> l::(funct foo) 106 | with End_of_file -> [] ;; 107 | 108 | let write stuff = 109 | let oc = open_out "a.js" in 110 | output_string oc stuff; 111 | close_out oc; 112 | ;; 113 | 114 | (** [exec_file ctx fn] executes the contents of file [fn] in 115 | the given context [ctx]. It returns the new context. *) 116 | let exec_file ctx (sysargs) = 117 | let filename = sysargs.(1) in 118 | let filecontents = 119 | if filename = "-s" then 120 | if Array.length sysargs != 3 121 | then 122 | raise(Failure "Usage: ./geb [file] or ./geb -s [input] ") 123 | else 124 | sysargs.(2) 125 | else 126 | if Array.length sysargs != 2 127 | then 128 | raise(Failure "Usage: ./geb [file] or ./geb -s [input] ") 129 | else 130 | load_file filename 131 | in 132 | let lexbuf = Message.lexer_from_string 133 | (let stdlib = load_file "stdlib.ss" in 134 | stdlib ^ filecontents) in 135 | let program = 136 | try 137 | Parser.program Scanner.token lexbuf 138 | with 139 | | Failure("lexing: empty token") -> print_position lexbuf "Lexing: empty token"; exit (-1) 140 | | LexingErr msg -> print_position lexbuf msg; exit (-1) 141 | | Parsing.Parse_error -> print_position lexbuf "Syntax error occurs before"; exit (-1) 142 | 143 | in 144 | (* Perform type checking, by executing exec_cmds. Print all identifiers & types *) 145 | ignore(exec_cmds ( 146 | (* Add types for built-in functions to the context *) 147 | List.map (fun x -> (x, Generator.arrow_of(x))) 148 | (Generator.get_generatable_fnames program)) 149 | program); 150 | 151 | let prog = Generator.generate_prog program in 152 | write prog; 153 | print_endline (String.concat "\n" (funct (Unix.open_process_in "node a.js"))) 154 | 155 | (** The main program. *) 156 | let main = 157 | if(Array.length Sys.argv < 2) then 158 | raise(Failure "Usage: ./geb [file] or ./geb -s [input] ") 159 | else 160 | exec_file [] (Sys.argv) 161 | -------------------------------------------------------------------------------- /src/stdlib.ss: -------------------------------------------------------------------------------- 1 | /* 2 | ** *~*~ Superscript Standard Library ~*~* 3 | ** ______ ______ 4 | ** / ___// ___/ 5 | ** \__ \ \__ \ 6 | ** ___/ /___/ / 7 | ** /_____//_____/ 8 | */ 9 | 10 | 11 | /* 12 | * identity takes an expression e and returns it. 13 | */ 14 | (= identity (fn (e) e));; 15 | 16 | /* * * * * * * * * * * * * * * * * * * * * * * 17 | ** 18 | ** ~*~* List Manipulation Functions *~*~ 19 | ** 20 | ** * * * * * * * * * * * * * * * * * * * * * */ 21 | 22 | /* 23 | * length takes a list l and returns its length. 24 | */ 25 | (= length (fn (l) 26 | (if (is l '()) 0 27 | {1 + (length (tail l))})));; 28 | 29 | /* 30 | * nth takes an int n and a list l and returns the nth element of the list. 31 | */ 32 | (= nth (fn (n l) 33 | (if (or (is l '()) {n < 0}) (exception "nth: index out of bounds.") 34 | (if (is n 0) (head l) 35 | (nth {n - 1} (tail l))))));; 36 | 37 | /* 38 | * first takes a list l and returns the first element. 39 | */ 40 | (= first (fn (l) (nth 0 l)));; 41 | 42 | /* 43 | * second takes a list l and returns the second element. 44 | */ 45 | (= second (fn (l) (nth 1 l)));; 46 | 47 | /* 48 | * third takes a list l and returns the third element. 49 | */ 50 | (= third (fn (l) (nth 2 l)));; 51 | 52 | /* 53 | * fourth takes a list l and returns the fourth element. 54 | */ 55 | (= fourth (fn (l) (nth 3 l)));; 56 | 57 | /* 58 | * fifth takes a list [l] and returns the fifth element. 59 | */ 60 | (= fifth (fn (l) (nth 4 l)));; 61 | 62 | /* 63 | * sixth takes a list l and returns the sixth element. 64 | */ 65 | (= sixth (fn (l) (nth 5 l)));; 66 | 67 | /* 68 | * seventh takes a list and returns the seventh element. 69 | */ 70 | (= seventh (fn (l) (nth 6 l)));; 71 | 72 | /* 73 | * eighth takes a list and returns the eighth element. 74 | */ 75 | (= eighth (fn (l) (nth 7 l)));; 76 | 77 | /* 78 | * ninth takes a list and returns the ninth element. 79 | */ 80 | (= ninth (fn (l) (nth 8 l)));; 81 | 82 | /* 83 | * tenth takes a list and returns the tenth element. 84 | */ 85 | (= tenth (fn (l) (nth 9 l)));; 86 | 87 | /* 88 | * last takes a list and returns the last element. 89 | */ 90 | (= last (fn (l) (nth (- (length l) 1) l)));; 91 | 92 | /* 93 | * map takes a function f and a HOMOGENEOUS list l. It evaluates f 94 | * on each element of the list, and returns a list of the results. 95 | */ 96 | (= map (fn (f l) 97 | (if (is l '()) '() 98 | (cons (f (head l)) (map f (tail l))))));; 99 | 100 | /* 101 | * fold_left takes a function f, accumulator a, and HOMOGENEOUS list l. 102 | * It evaluates f on each element of list l, starting from the left, 103 | * and stores the results in the accumulator a. It returns a. 104 | */ 105 | (= fold_left (fn (f a l) 106 | (if (is l '()) a 107 | (fold_left f (eval '(f a (head l))) (tail l)))));; 108 | 109 | /* 110 | * fold_right takes a function f, HOMOGENEOUS list l, and accumlator a. 111 | * It evaluates f on each element of list l, starting from the right, 112 | * and stores the results in the accumulator a. It returns a. 113 | */ 114 | (= fold_right (fn (f l a) 115 | (if (is l '()) (eval '(identity a)) 116 | (eval '(f (head l) (fold_right f (tail l) a))))));; 117 | 118 | /* 119 | * filter takes a function p and HOMOGENOUS list l. The function must 120 | * take 1 argument and return a BOOLEAN. Filter returns a list of 121 | * those elements of l, on which the predicate evaluates to true. 122 | */ 123 | (= filter (fn (p l) 124 | (list (fold_right (fn (x y) (if (p x) (cons x y) y)) l '()))));; 125 | 126 | /* 127 | * append takes a list a, and list b. It returns a list 128 | * where the list a is appended onto the front of the list b. 129 | */ 130 | (= append (fn (a b) 131 | (if (is a '()) 132 | b 133 | (cons (head a) (append (tail a) b)))));; 134 | 135 | /* 136 | * reverse takes a list l. It returns the list reversed. 137 | */ 138 | (= reverse (fn (l) 139 | (if (is l '()) 140 | l 141 | (append (reverse (tail l)) (cons (head l) '())))));; 142 | 143 | /* 144 | * drop takes an int i and list l. It drops the first i elements 145 | * from the front of the list, and returns the resulting list. 146 | */ 147 | (= drop (fn (i l) 148 | (if (< i 1) 149 | l 150 | (drop (- i 1) (tail l)))));; 151 | 152 | /* 153 | * take takes an int i and list l. It returns a list containing 154 | * the first i elements of the list. 155 | */ 156 | (= take (fn (i l) 157 | (if (or (not (> i 0)) (is l '())) 158 | '() 159 | (cons (head l) (take (- i 1) (tail l))))));; 160 | 161 | /* 162 | * intersperse takes an expression e and list l. It inserts the 163 | * expression between each pair of elements in the list, 164 | * and returns the resulting list. 165 | */ 166 | (= intersperse (fn (e l) 167 | (if (or (is l '()) (is (tail l) '())) 168 | l 169 | (cons (head l) (cons e (intersperse e (tail l)))))));; 170 | 171 | /* 172 | * member takes an expression e and list l. It returns true if 173 | * e is an element of l, or false if e is not an element of l. 174 | */ 175 | (= member 176 | (fn (e l) 177 | (if (is l '()) 178 | false 179 | (if (boolean (eval '(is (head l) e))) 180 | true 181 | (member e (tail l)) 182 | ) 183 | ) 184 | ) 185 | );; 186 | 187 | /* 188 | * zipwith takes function f, list a, and list b. The function should 189 | * take 2 arguments. zipwith returns a list where each element is the 190 | * result of evaluating (f a b). 191 | */ 192 | (= zipwith (fn (f a b) 193 | (if (or (is a '()) (is b '())) 194 | '() 195 | (cons (f (head a) (head b)) (zipwith f (tail a) (tail b))))));; 196 | 197 | /* 198 | * zipwith3 takes a function f, list a, list b, and list c. The function 199 | * should take 3 arguments. zipwith3 returns a list where each element 200 | * is the result of evaluating (f a b c). 201 | */ 202 | (= zipwith3 (fn (f a b c) 203 | (if (or (or (is a '()) (is b '())) (is c '())) 204 | '() 205 | (cons (f (head a) (head b) (head c)) 206 | (zipwith3 f (tail a) (tail b) (tail c))))));; 207 | 208 | /* 209 | * zip takes list a and list b. It iterates through both lists and 210 | * returns a new list of 'pairs' (2-element lists) 211 | * where each pair has 1 element from a, and 1 from b. 212 | * Example: (zip '(1 2 3) '(a b c)) ---> '( '(1 a) '(2 b) '(3 c) ) 213 | */ 214 | (= zip (fn (a b) 215 | (zipwith 216 | (fn (x y) (cons x (cons y '()))) 217 | a b)));; 218 | 219 | /* 220 | * unzip takes list l, which should be a list of pairs (2-element lists). 221 | * It returns a list of 2 lists, where the first sublist contains all the 222 | * first elements, and the second sublist contains all of the 223 | * second elements, from each pair of the input list l. 224 | * Example: (unzip '( '(1 a) '(2 b) '(3 c) '(4 d) )) 225 | * --> '( '(1 2 3 4) '(a b c d) ) 226 | */ 227 | (= unzip (fn (l) 228 | (fold_right 229 | (fn (x y) '((append (first x) (cons (first y) '())) (append (second x) (cons(second y) '())))) 230 | l 231 | '( '() '() ))));; 232 | 233 | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * 234 | ** 235 | ** 236 | ** *~*~ Printing / Stringify Functions ~*~* 237 | ** 238 | ** 239 | ** USAGE NOTE: stringify_list and print_list take as an argument 240 | ** a function that, when mapped onto a homogeneous list, stringifies 241 | ** the elements of that list. 242 | ** 243 | ** For ease of use, several formatting functions are provided below: 244 | ** 245 | ** format_[t] will stringify a list of atoms of type t. 246 | ** format_[t]2d will stringify a list of lists of type t. 247 | ** 248 | ** These formatting functions may be passed as argument to 249 | ** stringify_list or print_list. 250 | ** 251 | ** Example: (print_list format_int '(1 2 3 4));; 252 | ** >>>>>> prints [1,2,3,4] 253 | ** 254 | ** * * * * * * * * * * * * * * * * * * * * * * * * * * * / 255 | 256 | /* 257 | * format_boolean returns a function which stringifies a boolean value. 258 | */ 259 | (= format_boolean (fn (x) (string_of_boolean (boolean x))));; 260 | 261 | /* 262 | * format_int returns a function which stringifies an int value. 263 | */ 264 | (= format_int (fn (x) (string_of_int (int x))));; 265 | 266 | /* 267 | * format_string returns a function which takes a string and returns it. 268 | */ 269 | (= format_string (fn (x) (string x)));; 270 | 271 | /* 272 | * format_float returns a function which stringifies a float. 273 | */ 274 | (= format_float (fn (x) (string_of_float (float x))));; 275 | 276 | /* 277 | * stringify_list takes a function f and list l. The function f 278 | * should return a function that can transform each element of the 279 | * list into a string. The stringified elements are concatenated, 280 | * with "," as delimiter, and returned altogether as a string. 281 | */ 282 | (= stringify_list (fn (f l) 283 | (++ 284 | "[" 285 | (fold_left ++ "" (intersperse "," (map f l))) 286 | "]")));; 287 | 288 | /* 289 | * format_boolean2d returns a function that takes a HOMOGENEOUS list 290 | * of BOOLEANS and stringifies it. 291 | */ 292 | (= format_boolean2d (fn (x) (stringify_list format_boolean x)));; 293 | 294 | /* 295 | * format_int2d returns a function that takes a HOMOGENEOUS list 296 | * of INTS and stringifies it. 297 | */ 298 | (= format_int2d (fn (x) (stringify_list format_int x)));; 299 | 300 | /* 301 | * format_float2d returns a function that takes a HOMOGENEOUS list 302 | * of FLOATS and stringifies it. 303 | */ 304 | (= format_float2d (fn (x) (stringify_list format_float x)));; 305 | 306 | /* 307 | * format_string2d returns a function that takes a HOMOGENEOUS list 308 | * of STRINGS and stringifies it. 309 | */ 310 | (= format_string2d (fn (x) (stringify_list format_string x)));; 311 | 312 | /* 313 | * print_list takes a function f and list l. The function f should return 314 | * a function that can transform each element of the list into a string. 315 | * The stringified list is printed to console. 316 | */ 317 | (= print_list (fn (f l) 318 | (prn (stringify_list f l))));; 319 | 320 | ###ENDSTDLIB### 321 | -------------------------------------------------------------------------------- /src/finaltest.ml: -------------------------------------------------------------------------------- 1 | open Ast;; 2 | open Generator;; 3 | open Scanner;; 4 | open Unix;; 5 | 6 | let load_file f = 7 | let ic = open_in f in 8 | let n = in_channel_length ic in 9 | let s = Bytes.create n in 10 | really_input ic s 0 n; 11 | close_in ic; 12 | (s) ;; 13 | 14 | let rec funct foo = 15 | try 16 | let l = input_line foo in 17 | match l with 18 | | _ -> l::(funct foo) 19 | with End_of_file -> [] ;; 20 | 21 | 22 | let write stuff = 23 | let oc = open_out "a.js" in 24 | output_string oc stuff; 25 | close_out oc; 26 | ;; 27 | 28 | let tests = [ 29 | ("prn function should log to stdout", "(prn \"Hello World!\");;", [], "Hello World!") ; 30 | ("string_of_int function should make string from int", "(prn (string_of_int 10));;", [], "10") ; 31 | ("string_of_boolean function should make string from boolean", "(pr (string_of_boolean true));;(pr (string_of_boolean false));;", [], "truefalse") ; 32 | ("type function should return type of string", "(prn (type \"Hello\"));;", [], "string") ; 33 | ("type function should return type of int", "(prn (type 10));;", [], "int") ; 34 | ("type function should return type of float", "(prn (type 2.2));;", [], "float") ; 35 | ("type function should return type of boolean", "(prn (type true));;", [], "boolean") ; 36 | ("type function should return type of list", "(prn (type '(10 20)));;", [], "list") ; 37 | ("type function should return type of function", "(prn (type (fn (x) (prn x))));;", [], "function") ; 38 | ("assignment operator", "(= foo \"Hello\");;(prn foo);;", [], "Hello") ; 39 | ("user defined functions", "(= foo (fn (x) (prn x)));;(foo \"Bar\");;", [], "Bar") ; 40 | ("curly infix arithmetic expression", "(prn (string_of_int {5 + 3}));;", [], "8") ; 41 | ("+ operator with no args should return 0", "(prn (string_of_int (+)));;", [], "0") ; 42 | ("* operator with no args should return 1", "(prn (string_of_int (*)));;", [], "1") ; 43 | ("prefix integer add", "(prn (string_of_int (+ 1 2 3 4)));;", [], "10") ; 44 | ("prefix integer sub", "(prn (string_of_int (- 10 2 3)));;", [], "5") ; 45 | ("prefix integer mult", "(prn (string_of_int (* 1 2 3 4)));;", [], "24") ; 46 | ("prefix integer div", "(prn (string_of_int (/ 10 2 (- 5))));;", [], "-1") ; 47 | ("prefix float add", "(prn (string_of_float (+. .1 .2 .3 .4)));;", [], "1") ; 48 | ("prefix float sub", "(prn (string_of_float (-. 5.0 .2 .3)));;", [], "4.5") ; 49 | ("prefix float mult", "(prn (string_of_float (*. 1. 2. 3. 4.)));;", [], "24") ; 50 | ("prefix float div", "(prn (string_of_float (/. 10. 2. (-.5.))));;", [], "-1") ; 51 | ("comparing ints with is func", "(pr (string_of_boolean (is 1 1)));;(pr (string_of_boolean (is 1 2)));;", [], "truefalse") ; 52 | ("comparing floats with is func", "(pr (string_of_boolean (is 1.0 1.)));;(pr (string_of_boolean (is .1 .2)));;", [], "truefalse") ; 53 | ("comparing bools with is func", "(pr (string_of_boolean (is true true)));;(pr (string_of_boolean (is false true)));;", [], "truefalse") ; 54 | ("comparing strings with is func", "(pr (string_of_boolean (is \"hello\" \"world\")));;(pr (string_of_boolean (is \"world\" \"world\")));;", [], "falsetrue") ; 55 | ("empty list should be nil", "(prn (string_of_boolean (is '() nil)));;", [], "true") ; 56 | ("head function should return head of list", "(prn (head '(\"foo\" \"bar\")));;", [], "foo") ; 57 | ("tail function should return tail of list", "(prn (head (tail '(\"foo\" \"bar\"))));;", [], "bar") ; 58 | ("++ operator concatenates strings", "(prn (++ \"foo\" \"bar\" \"orange\"));;", [], "foobarorange") ; 59 | ("< operator should compare ints", "(pr (string_of_boolean (< 9 10)));;(pr (string_of_boolean (< 11 10)));;", [], "truefalse") ; 60 | ("if statements", "(if true (pr \"foo\") (pr \"bar\"));;(if false (pr \"foos\") (pr \"bars\"));;", [], "foobars") ; 61 | ("get first element (int) of list", "(prn (string_of_int (head \'(1 2 3 4 5 6 7 8 9 10))));;", [], "1"); 62 | ("multiple expressions", "( prn \"hello\" );; ( prn \"world\" );; ( prn \"people\");;", [], "hello\nworld\npeople"); 63 | ("set add equal to anon func then call it", "(= add (fn (x y) (+ x y) )) ;;(prn (string_of_int (add 1 3)));; ", [], "4"); 64 | ("print the 5 mod 6", "(prn (string_of_int (mod 5 6)));;", [], "5"); 65 | ("logical AND of true and false","(prn (string_of_boolean (and true false)));;", [], "false"); 66 | ("setting and testing inequality", "(= a \"a\");; (prn (string_of_boolean (is \"a\" a)));;", [], "true"); 67 | ("testing relational comparison operators", "(prn (string_of_boolean (> 2 4)));;", [], "false"); 68 | ("testing string concatenation", "(prn (++ \"hello\" \" \" \"world\" ));;", [], "hello world"); 69 | ("testing cons function", "(prn (head (cons \"a\" \'(\"b\" \"c\"))));;", [], "a"); 70 | ("testing if function", "(prn (if false \"b\" \"c\"));;", [], "c"); 71 | ("print out float with string_of_float", "(prn (string_of_float 3.5));;", [], "3.5"); 72 | ("print out result of infix expr","(prn (string_of_int {3+ 5}));;", [], "8"); 73 | ("print out int with string_of_int","(prn (string_of_int 3));;", [], "3"); 74 | ("print out sum of list ","(prn (string_of_int (+ 3 4 2 5 3 2 5)));;", [], "24"); 75 | ("print out list using print_list","(print_list string '(\"a\" \"b\" \"c\" \"d\"));;", [], "[a,b,c,d]"); 76 | ("should print 'letter a'", "(= a \"letter a\");; (prn a);;", [], "letter a"); 77 | ("using curly infix expressions", "(prn (string_of_int {3 + 5}));;", [], "8"); 78 | ("handle printing negative return value","(prn (string_of_int {7 - 9}));;", [], "-2"); 79 | ("converting int returned from function to string", "(= square (fn (x) (* x x)));; (prn (string_of_int (square 5) ));;", [], "25"); 80 | ("print function's return value, using infix", "(= square (fn (x) {x * x}));; (prn (string_of_int (square 5) ));;", [], "25"); 81 | ("printing return of assignment (int)", "(prn (string_of_int (= x 3)));;", [], "3"); 82 | ("printing return of assignment (float)", "(prn (string_of_float {x = 3.5}));;", [], "3.5"); 83 | ("use string_of_boolean to print", "(pr (string_of_boolean true));;(pr (string_of_boolean false));;", [], "truefalse"); 84 | ("use string_of_boolean with prn", "(prn (string_of_boolean true));;(prn (string_of_boolean false));;", [], "true\nfalse"); (************************) 85 | ("print the type 'string'", "(prn (type {x = \"a string\"}));;", [], "string"); 86 | ("print the type of return value of assignment", "(prn (type {x = 50}));;", [], "int"); 87 | ("print type of an list", "(prn (type '() ));;", [], "list"); 88 | ("print type of var after assingment", "(= a 2);; (prn (type a));;", [], "int"); 89 | ("print type of float", "(prn (type 3.5));;", [], "float"); 90 | ("print type of function", "(prn (type (fn (x y) (/(+ x y) 2)) ));;", [], "function"); 91 | ("use head and tail, basic case", "(= foo '(1 0));; (if true (prn (string_of_int (head foo))) (prn (string_of_int (head (tail foo)))));;", [], "1"); 92 | ("assing var to result of sum, then print", "(= foo (+ 1 2 3 4 5));; (prn (string_of_int foo));;", [], "15"); 93 | ("print boolean", "(= foo true);; (prn (string_of_boolean foo));;", [], "true"); 94 | ("print second element using head and tail","(= foo '(\"a\" \"b\" \"c\"));; (prn (string(head (tail foo))));;", [], "b"); 95 | ("define fibonacci function", "(= fib (fn (x) (if (is x 0) 0 (if (is x 1) 1 {(fib {x - 1}) + (fib {x -2} )}))));; (prn (string_of_int (fib 5)));;", [], "5"); 96 | ("print infix mixed operations", "(prn (string_of_int {5 + 3 + 6 * 7 - 4 / 2}));;", [], "48"); 97 | ("print mixed infix and prefix", "(prn (string_of_int (+ {5 + 3 + 6 * 7 - 4 / 2} (/ 100 5 20) (* {1 - 3} 3))));;", [], "43"); 98 | ("mixed operations", "(= foo '(\"a\" \"b\"));; (prn (++ (string_of_int {5 + 3 + 6 * 7 - 4 / 2}) (string (head foo)) (string_of_int (* {1 - 3} 3))));;", [], "48a-6"); 99 | ("print result of infix sum", "(prn (string_of_int {1 + 2 + 3 + 4}));;", [], "10"); 100 | ("print result of infix subtraction", "(prn (string_of_int {10 - 2 - 3}));;", [], "5"); 101 | ("print result of infix multiplication", "(prn (string_of_int {1 * 2 * 3 * 4}));;", [], "24"); 102 | ("print result of infix float summation", "(prn (string_of_float {.1 +. .2 +. .3 +. .4 }));;", [], "1"); 103 | ("print float summation", "(prn (string_of_float {5.0 -. .2 -. .3 }));;", [], "4.5"); 104 | ("print result of infix float multiplication", "(prn (string_of_float { 1. *. 2. *. 3. *. 4.}));;", [], "24"); 105 | ("using if", "(if true (prn \"a\") (prn \"b\"));;", [], "a"); 106 | ("assing var to list and print", "(= a '(1 2 3 4));; (prn (string_of_boolean (is a a)));;", [], "true"); 107 | ("check for empty list equality", "(= x '(1));; (prn (string_of_boolean (is (tail x) '())));;", [], "true"); 108 | ("appending object to head of list", "(= x '( \"1\"));; (prn (string (head (cons (head x) '(\"a\" \"b\")))));;", [], "1"); 109 | ("def roundabout concat function, use in roundabout way", "(= concat (fn (x y) (if (is x '()) y (if (is (concat (tail x) y) y) (cons (head x) y) (cons (head x) (concat (tail x) y))))));; (prn (string (head (tail (tail (tail (tail(concat '(\"1\" \"2\" \"3\") '(\"1\" \"LAST\")))))))));;", [], "LAST") ; 110 | 111 | (***************************************STANDARD LIBRARY TESTS **********************************************************************************************) 112 | 113 | ("Testing stdlib function: identity", "(= x '(1 2 3 4 ));; (prn (string_of_boolean (is x (identity x))));;", [], "true") ; 114 | ("Testing stdlib function: length", "(= x '(1 2 3 4 ));; (prn (string_of_int (length x )));;", [], "4") ; 115 | ("Testing stdlib function: nth", "(= x '(1 2 3 4 5 6 7 8 9 10));; (prn (string_of_int (nth 5 x)));;", [], "6") ; 116 | ("Testing stdlib function: first", "(= x '(1 2 3 4 5 6 7 8 9 10));; (prn (string_of_int (first x)));;", [], "1") ; 117 | ("Testing stdlib function: second", "(= x '(1 2 3 4 5 6 7 8 9 10));; (prn (string_of_int (second x)));;", [], "2") ; 118 | ("Testing stdlib function: third", "(= x '(1 2 3 4 5 6 7 8 9 10));; (prn (string_of_int (third x)));;", [], "3") ; 119 | ("Testing stdlib function: fourth", "(= x '(1 2 3 4 5 6 7 8 9 10));; (prn (string_of_int (fourth x)));;", [], "4") ; 120 | ("Testing stdlib function: fifth", "(= x '(1 2 3 4 5 6 7 8 9 10));; (prn (string_of_int (fifth x)));;", [], "5") ; 121 | ("Testing stdlib function: sixth", "(= x '(1 2 3 4 5 6 7 8 9 10));; (prn (string_of_int (sixth x)));;", [], "6") ; 122 | ("Testing stdlib function: seventh", "(= x '(1 2 3 4 5 6 7 8 9 10));; (prn (string_of_int (seventh x)));;", [], "7") ; 123 | ("Testing stdlib function: eigth", "(= x '(1 2 3 4 5 6 7 8 9 10));; (prn (string_of_int (eighth x)));;", [], "8") ; 124 | ("Testing stdlib function: ninth", "(= x '(1 2 3 4 5 6 7 8 9 10));; (prn (string_of_int (ninth x)));;", [], "9") ; 125 | ("Testing stdlib function: tenth", "(= x '(1 2 3 4 5 6 7 8 9 10));; (prn (string_of_int (tenth x)));;", [], "10") ; 126 | ("Testing stdlib function: map", "(= newprn (fn (x) (prn (string_of_int (int x)))));; (= x '(1 2 3 4 5 6 7 8 9 10));; (map newprn x);;", [], "1\n2\n3\n4\n5\n6\n7\n8\n9\n10") ; 127 | ("Testing stdlib function: fold_left", "(= x '(1 2 3 4 5 6 7 8 9 10));; (prn (string_of_int (int (fold_left + 0 x))));;", [], "55") ; 128 | ("Testing stdlib function: fold_right", "(= x '(1 2 3 4 5 6 7 8 9 10));; (prn (string_of_int (int (fold_right + x 0 ))));;", [], "55") ; 129 | ("Testing stdlib function: filter", "(= fx (fn (x) (> x 3)));; (= x '(1 2 3 4 5 6 7 8 9 10));; (prn (string_of_int (int (head (filter fx x)))));;", [], "4") ; 130 | ("Testing stdlib function: append", "(= x '(1 2 3 4 5 6 7 8 9 10));; (prn (string (head (tail (tail (tail (tail(append '(\"1\" \"2\" \"3\") '(\"1\" \"LAST\")))))))));;", [], "LAST") ; 131 | ("Testing stdlib function: take", "(= x '(1 2 3 4 5 6 7 8 9 10));; (print_list format_int (list (take 5 x)));; ", [], "[1,2,3,4,5]") ; 132 | ("Testing stdlib function: drop", "(= x '(1 2 3 4 5 6 7 8 9 10));; (print_list format_int (list (drop 5 x)));;", [], "[6,7,8,9,10]") ; 133 | ("Testing stdlib function: zipwith", "(print_list format_int (zipwith (fn (x y) (+ x y)) '(1 2 3 4) '(5 6 7 8)));;", [], "[6,8,10,12]") ; 134 | ("Testing stdlib function: zipwith3", "(print_list format_int (zipwith3 (fn (x y z) (+ x y z)) '(1 2 3 4) '(5 6 7 8) '(10 11 12 13)));;", [], "[16,19,22,25]") ; 135 | ("Testing stdlib function: reverse", "(= x '(1 2 3 4 5 6 7 8 9 10));; (print_list format_int (reverse x));;", [], "[10,9,8,7,6,5,4,3,2,1]") ; 136 | ("Testing stdlib function: member", "(= x '(1 2 3 4 5 6 7 8 9 10));; (prn (string_of_boolean (member 10 x)));; ", [], "true") ; 137 | ("Testing stdlib function: intersperse", "(= x '(1 2 3 4 5 6 7 8 9 10));; (print_list format_int (intersperse 0 x));;", [], "[1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9,0,10]") ; 138 | ("Testing stdlib function: stringify_list", "(= x '(1 2 3 4 5 6 7 8 9 10));; (prn (stringify_list format_int x));;", [], "[1,2,3,4,5,6,7,8,9,10]") 139 | 140 | ] ;; 141 | 142 | let unsuccess = ref 0 ;; 143 | 144 | 145 | List.iter (fun (desc, input, ast, expout) -> 146 | let stdlib = load_file "stdlib.ss" in 147 | let lexbuf = Lexing.from_string (stdlib ^ input) in 148 | try 149 | let expression = Parser.program Scanner.token lexbuf in 150 | if (ast = expression || ast = []) then 151 | let prog = Generator.generate_prog expression in 152 | write prog; 153 | let actout = String.concat "\n" (funct (Unix.open_process_in "node a.js")) in 154 | if expout = actout then print_string "" else 155 | print_endline (String.concat "" ["\027[38;5;1m"; desc; ": "; input; "... UNSUCCESSFUL Compilation....\ninput: "; input; "\nexpected out: "; expout; "\nActual out: "; actout; "\027[0m"]); 156 | else (print_endline (String.concat "" ["\027[38;5;1m"; desc; ": "; input; "\027[0m"]) ; unsuccess := !unsuccess+1 ) ; 157 | with 158 | | _ -> print_endline (String.concat "" ["**START REPORT**\n" ; "Parse Error:\ninput:";input ;"\n**END REPORT**"]) ; unsuccess := !unsuccess+1) tests ;; 159 | 160 | 161 | if !unsuccess = 0 then print_endline "ALL SUCCESSFUL" else exit 1 ;; -------------------------------------------------------------------------------- /src/type_infer.ml: -------------------------------------------------------------------------------- 1 | (* Type inference *) 2 | 3 | open Ast;; 4 | 5 | exception Type_error of string 6 | exception Invalid_args of string 7 | exception Unknown_variable of string * string 8 | 9 | (** [type_error msg] reports a type error by raising [Type_error msg]. *) 10 | let type_error msg = raise (Type_error msg) 11 | 12 | (** [invalid_args_error msg] reports invalid argument exceptions by raising [Invalid_args msg]. *) 13 | let invalid_args_error msg = raise (Invalid_args msg) 14 | 15 | (** [unknown_var_error msg] reports unknown variable exceptions by raising [Unknown_variable msg]. *) 16 | let unknown_var_error msg var = raise (Unknown_variable (msg, var)) 17 | 18 | let remove_underscores input = 19 | let uscore = Str.regexp_string "_" in 20 | Str.global_replace uscore "" input 21 | 22 | (** [fresh ()] returns an unused type parameter. *) 23 | let fresh = 24 | let k = ref 0 in 25 | fun () -> incr k; TParam !k 26 | 27 | (** [refresh t] replaces all parameters appearing in [t] with unused ones. *) 28 | let refresh ty = 29 | let rec refresh s = function 30 | | TInt -> TInt, s 31 | | TFloat -> TFloat, s 32 | | TBool -> TBool, s 33 | | TString -> TString, s 34 | | TUnit -> TUnit, s 35 | | TSome -> TSome, s 36 | | TJblob -> TJblob, s 37 | | TException -> TException, s 38 | | TParam k -> 39 | (try 40 | List.assoc k s, s 41 | with Not_found -> let t = fresh () in t, (k,t)::s) 42 | | TArrow t_list -> 43 | let rec tarrow_refresh ts us s' = 44 | match ts with 45 | | [] -> us, s' 46 | | hd::tl -> let u,s'' = refresh s' hd in 47 | tarrow_refresh tl (us@[u]) s'' in 48 | let u_list, s = tarrow_refresh t_list [] s in 49 | TArrow u_list, s 50 | | TSomeList t -> 51 | let u, s' = refresh s t in 52 | TSomeList u, s' 53 | in 54 | fst (refresh [] ty) 55 | 56 | (** [occurs k t] returns [true] if parameter [TParam k] appears in type [t]. *) 57 | let rec occurs k = function 58 | | TInt -> false 59 | | TFloat -> false 60 | | TString -> false 61 | | TBool -> false 62 | | TUnit -> false 63 | | TSome -> false 64 | | TJblob -> false 65 | | TException -> false 66 | | TParam j -> k = j 67 | | TArrow t_list -> 68 | let rec tarrow_occurs ts o = 69 | match ts with 70 | | [] -> o 71 | | hd::tl -> (tarrow_occurs tl (o||occurs k hd)) in 72 | tarrow_occurs t_list false 73 | | TSomeList t1 -> occurs k t1 74 | 75 | (* [get_name_of_functions fname] takes the intermediate function name inside of 76 | compiler and returns the actual function name users use. *) 77 | let get_name_of_functions = function 78 | | "exec" -> "do" 79 | | "__add" -> "+" 80 | | "__sub" -> "-" 81 | | "__mult" -> "*" 82 | | "__div" -> "/" 83 | | "__addf" -> "+." 84 | | "__subf" -> "-." 85 | | "__multf" -> "*." 86 | | "__divf" -> "/." 87 | | "__equal" -> "is" 88 | | "__neq" -> "isnt" 89 | | "__less" -> "<" 90 | | "__leq" -> "<=" 91 | | "__greater" -> ">" 92 | | "__geq" -> ">=" 93 | | "__and" -> "and" 94 | | "__or" -> "or" 95 | | "__not" -> "not" 96 | | "__concat" -> "++" 97 | | "__evaluate" -> "eval" 98 | | _ as s -> s 99 | 100 | (** [solve [(t1,u1); ...; (tn,un)] solves the system of equations 101 | [t1=u1], ..., [tn=un]. The solution is represented by a list of 102 | pairs [(k,t)], meaning that [TParam k] equals [t]. A type error is 103 | raised if there is no solution. The solution found is the most general 104 | one. 105 | *) 106 | let solve eq = 107 | let rec solve eq sbst = 108 | match eq with 109 | | [] -> sbst 110 | 111 | | (t1, t2 , f) :: eq when t1 = t2 -> solve eq sbst 112 | 113 | | ((TParam k, t, f) :: eq | (t, TParam k, f) :: eq) when (not (occurs k t)) -> 114 | let ts = Ast.tsubst [(k,t)] in 115 | solve 116 | (List.map (fun (ty1,ty2,fn) -> (ts ty1, ts ty2, fn)) eq) 117 | ((k,t)::(List.map (fun (n, u) -> (n, ts u)) sbst)) 118 | 119 | | (TException, _, f) :: eq | (_, TException, f) :: eq -> solve eq sbst 120 | | (TArrow ty1, TArrow ty2, f) :: eq when (List.length ty1) = (List.length ty2) -> 121 | let rec get_eq l1 l2 eq = 122 | match l1 with 123 | | [] -> eq 124 | | hd::tl -> get_eq tl (List.tl l2) ((hd, (List.hd) l2, f)::eq) in 125 | solve (get_eq ty1 ty2 eq) sbst 126 | 127 | | (TSomeList t1, TSomeList t2, f) :: eq -> 128 | solve ((t1,t2,f) :: eq) sbst 129 | | (t1,t2,f)::_ -> 130 | let u1, u2 = rename2 t1 t2 in 131 | type_error ("Type Incompatible Error: The types " ^ string_of_type u1 ^ " and " ^ 132 | string_of_type u2 ^ " are incompatible in " ^ (get_name_of_functions f) ^ "." ) 133 | 134 | in 135 | solve eq [] 136 | 137 | (** [constraints_of gctx e] infers the type of expression [e] and a set 138 | of constraints, where [gctx] is global context of values that [e] 139 | may refer to. *) 140 | let rec constraints_of gctx = 141 | let rec cnstr ctx = function 142 | | Id x -> ( 143 | (try 144 | List.assoc x ctx, [] 145 | with Not_found -> 146 | (try 147 | (* we call [refresh] here to get let-polymorphism *) 148 | refresh (List.assoc x gctx), [] 149 | with Not_found -> 150 | unknown_var_error ("Unknown Variable Error: variable " ^x^ " is unknown.") x 151 | ) 152 | )) 153 | | Int _ -> TInt, [] 154 | | Float _ -> TFloat, [] 155 | | String _ -> TString, [] 156 | | Boolean _ -> TBool, [] 157 | | Nil -> TSomeList (fresh ()), [] 158 | | List thelist -> let rec addcnstr = function 159 | | [] -> [] 160 | | hd::tl -> let ty1, eq1 = cnstr ctx hd in 161 | eq1 @ addcnstr tl 162 | in TSomeList(TSome), addcnstr thelist 163 | 164 | | If (e1, e2, e3) -> 165 | let ty1, eq1 = cnstr ctx e1 in 166 | let ty2, eq2 = cnstr ctx e2 in 167 | let ty3, eq3 = cnstr ctx e3 in 168 | let ty2 = match ty2 with 169 | | TException -> ty3 170 | | _ -> ty2 171 | 172 | in let ty3 = 173 | match ty3 with 174 | | TException -> ty2 175 | | _ -> ty3 176 | 177 | in 178 | ty2, ((ty1, TBool, "if")::(ty2, ty3, "if")::eq1@eq2@eq3) 179 | 180 | | Fdecl(x, e) -> 181 | let eqs = List.rev (List.map (fun v -> (v, fresh ())) x)in 182 | let ty1, eq = cnstr (eqs@ctx) e in 183 | (match eqs with 184 | |[] -> TArrow [TUnit;ty1], eq 185 | | _ -> let func_types = List.map (fun (a,b) -> b) eqs in 186 | TArrow (func_types@[ty1]), eq 187 | ) 188 | 189 | | Assign(e) -> (* all ids/types were already added to ctx in the executor. just return the type of the last assignment *) 190 | let last = List.hd (List.rev e) in 191 | let ty, eq = cnstr ctx last in 192 | ty, eq 193 | | Eval(e1, e2) -> ( 194 | match e1 with 195 | | If(a,b,c)-> ( 196 | let ty1, eq1 = cnstr ctx e1 in 197 | match ty1 with 198 | | TArrow t_list -> ( 199 | let ty2 = fresh() in 200 | match e2 with 201 | | [] -> ty2, (ty1, TArrow [TUnit; ty2], "function call")::eq1 202 | | _ -> let tys = List.map (fun v -> let (ty,eq) = cnstr ctx v in ty) (List.rev e2) in 203 | let rec get_eqs exp_list eq_list = ( 204 | match exp_list with 205 | | [] -> eq_list 206 | | hd::tl -> let (ty, eq) = cnstr ctx hd in 207 | get_eqs tl (eq_list@eq) 208 | ) in 209 | ty2, (ty1, TArrow (tys@[ty2]), "function call")::eq1@(get_eqs e2 []) 210 | ) 211 | | _ -> invalid_args_error ("Invalid Arguments Error: In function call expression 212 | the first argument has type "^(string_of_type ty1)^", but an expression was expected of type function") 213 | ) 214 | | Fdecl(a,b) as e -> ( 215 | let ty1, eq1 = cnstr ctx e in 216 | let ty2 = fresh () in 217 | match e2 with 218 | | [] -> ty2, (ty1, TArrow [TUnit; ty2], "function call")::eq1 219 | | _ -> let tys = List.map (fun v -> let (ty,eq) = cnstr ctx v in ty) (List.rev e2) in 220 | let rec get_eqs exp_list eq_list = ( 221 | match exp_list with 222 | | [] -> eq_list 223 | | hd::tl -> let (ty, eq) = cnstr ctx hd in 224 | get_eqs tl (eq_list@eq) 225 | ) in 226 | ty2, eq1@[(ty1, TArrow (tys@[ty2]), "function call")]@(get_eqs e2 []) 227 | ) 228 | | Eval(a, b) -> ( 229 | let ty1, eq1 = cnstr ctx e1 in 230 | let ty2 = fresh() in 231 | match e2 with 232 | | [] -> ty2, (ty1, TArrow [TUnit; ty2], "function call")::eq1 233 | | _ -> let tys = List.map (fun v -> let (ty,eq) = cnstr ctx v in ty) (List.rev e2) in 234 | let rec get_eqs exp_list eq_list = ( 235 | match exp_list with 236 | | [] -> eq_list 237 | | hd::tl -> let (ty, eq) = cnstr ctx hd in 238 | get_eqs tl (eq_list@eq) 239 | ) in 240 | ty2, eq1@[(ty1, TArrow (tys@[ty2]), "function call")]@(get_eqs e2 []) 241 | ) 242 | | Id(e1) -> 243 | ( 244 | match e1 with 245 | 246 | | "__add" | "__sub" | "__mult"| "__div" 247 | | "__addf" | "__subf" | "__multf" | "__divf" 248 | | "__concat" -> ( 249 | let tarrow = Generator.arrow_of(e1) in 250 | match tarrow with 251 | | TArrow(x) -> (let a = List.hd x in 252 | let b = List.nth x 1 in 253 | let c = List.nth x 2 in 254 | match e2 with 255 | | [] -> c, [] 256 | | hd::tl -> let ty1, eq1 = cnstr ctx hd in 257 | let ty2, eq2 = cnstr ctx (Eval(Id(e1), tl)) in 258 | c, (ty1,a,e1) :: (ty2,b,e1) :: eq1 @ eq2) 259 | | _ -> raise(Failure "Error: Generation of typing for built-in function failed. ") 260 | ) 261 | | "call" -> TJblob, [] (* (let len = List.length e2 in 262 | match len with 263 | | 1 -> let ty1, eq1 = cnstr ctx (List.hd e2) in 264 | TJblob, (ty1, TJblob, e1) :: eq1 265 | | 2 -> let ty1, eq1 = cnstr ctx (List.hd e2) in 266 | let ty2, eq2 = cnstr ctx (List.nth e2 1) in 267 | TJblob, (ty1, TJblob, e1) :: (ty2, TString, e1) :: eq1 @ eq2 268 | | 3 -> let ty1, eq1 = cnstr ctx (List.hd e2) in 269 | let ty2, eq2 = cnstr ctx (List.nth e2 1) in 270 | let ty3, eq3 = cnstr ctx (List.nth e2 2) in 271 | TJblob, (ty1, TJblob, e1) :: (ty2, TString, e1) :: (ty3, TSomeList(TSome), e1) :: eq1 @ eq2 @ eq3 272 | | _ -> invalid_args_error ("Invalid arguments error: call takes at most 3 arguments. ") 273 | ) *) 274 | | "dot" -> TJblob, [] (* if (List.length e2 != 2) then (invalid_args_error("Invalid arguments error: " ^ 275 | "dot takes 1 JBlob and 1 list as arguments. ")) 276 | else ( 277 | let jblob = List.hd e2 in 278 | let ty1, eq1 = cnstr ctx jblob in 279 | let ty2, eq2 = cnstr ctx (List.nth e2 1) in 280 | TJblob, (ty1, TJblob, e1) :: (ty2, TSomeList(TSome), e1) :: eq1 @ eq2 281 | ) *) 282 | | "module" -> 283 | if (List.length e2 != 1) then (invalid_args_error ("Invalid arguments error: " ^ 284 | "module takes 1 String as argument. ")) 285 | else ( 286 | let ty, eq = cnstr ctx (List.hd e2) in 287 | TJblob, (ty, TString, e1) :: eq 288 | ) 289 | | "exception" -> 290 | let e = List.hd e2 in 291 | let ty, eq = cnstr ctx e in 292 | TException, (ty, TString, e1) :: eq 293 | 294 | | "mod" | "__and" | "__or" -> if (List.length e2 != 2) then 295 | (invalid_args_error("Invalid arguments error: the (" 296 | ^ (remove_underscores e1) ^ ") operation takes 2 arguments. ")) 297 | else ( 298 | let expected = match e1 with 299 | | "mod" -> TInt 300 | | _ -> TBool 301 | in 302 | let hd = List.hd e2 in 303 | let tl = List.nth e2 1 in 304 | let ty1, eq1 = cnstr ctx hd in 305 | let ty2, eq2 = cnstr ctx tl in 306 | expected, (ty1, expected, e1) :: (ty2, expected, e1) :: eq1 @ eq2 307 | ) 308 | 309 | | "__not" -> if (List.length e2 != 1) then (invalid_args_error("Invalid Arguments Error: " ^ 310 | "not takes 1 boolean expression as argument. ")) 311 | else ( 312 | let hd = List.hd e2 in 313 | let ty, eq = cnstr ctx hd in 314 | TBool, (ty, TBool, e1) :: eq 315 | ) 316 | | "__equal" | "__neq" | "__less" | "__leq" 317 | | "__greater" | "__geq" -> 318 | if (List.length e2 != 2) then 319 | (invalid_args_error("Invalid arguments error: the (" ^ 320 | (remove_underscores e1) ^ ") comparison takes 2 arguments. ")) 321 | else ( 322 | let ty1, eq1 = cnstr ctx (List.hd e2) in 323 | let ty2, eq2 = cnstr ctx (List.nth e2 1) in 324 | TBool, (ty1, ty2, e1) :: eq1 @ eq2 325 | ) 326 | 327 | | "cons" -> ( 328 | if List.length e2 != 2 then (invalid_args_error("Invalid Arguments Error: " ^ "cons takes 2 arguments. ")) 329 | else ( 330 | let newhd = List.hd e2 331 | and thelist = List.hd (List.rev e2) in 332 | let ty1, eq1 = cnstr ctx newhd in (* ty1 can be anything *) 333 | let ty2, eq2 = cnstr ctx thelist in 334 | TSomeList(TSome), (ty2,TSomeList(TSome), e1) :: eq1 @ eq2 335 | ) 336 | ) 337 | 338 | (* check that every arg to print is of type TString, and every arg to exec is TSomeList(TSome) *) 339 | | "pr" | "prn" | "exec" -> ( 340 | let tarrow = Generator.arrow_of e1 in 341 | match tarrow with 342 | | TArrow(x) -> let a = List.hd(x) in 343 | let b = List.nth x 1 in 344 | let rec addcnstr = function 345 | | [] -> [] 346 | | hd::tl -> let ty1, eq1 = cnstr ctx hd in 347 | (ty1,a,e1) :: eq1 @ addcnstr tl 348 | in b, addcnstr e2 349 | | _ -> raise(Failure "Error: Generation of typing for built-in function failed. ") 350 | ) 351 | 352 | | "int_of_string" 353 | | "string_of_float" 354 | | "float_of_string" 355 | | "string_of_boolean" 356 | | "boolean_of_string" 357 | | "string_of_int" -> 358 | ( 359 | if List.length e2 != 1 then (invalid_args_error("Invalid Arguments Error: " ^ 360 | e1 ^ " takes 1 argument. ")) 361 | else ( 362 | let arg = List.hd e2 in 363 | let ty, eq = cnstr ctx arg in 364 | let tarrow = (Generator.arrow_of e1) in 365 | match tarrow with 366 | | TArrow(x) -> (let a = List.hd(x) in 367 | let b = List.hd(List.tl x) in 368 | b, (ty, a, e1) :: eq) 369 | | _ -> raise(Failure "Error: Generation of typing for built-in function failed. ") 370 | ) 371 | ) 372 | 373 | | "tail" 374 | | "head" 375 | | "evaluate" -> 376 | if List.length e2 != 1 then ( 377 | let fname = 378 | if (String.compare e1 "evaluate") == 0 then "eval" 379 | else e1 380 | in 381 | invalid_args_error("Invalid Arguments Error: " ^ fname ^ " takes 1 list as argument. ")) 382 | else ( 383 | let thelist = (List.hd e2) in 384 | let ty, eq = cnstr ctx thelist in 385 | let tarrow = (Generator.arrow_of e1) in 386 | match tarrow with 387 | | TArrow(x) -> (let a = List.hd(x) in 388 | let b = List.hd(List.tl x) in 389 | b, (ty, a, e1) :: eq) 390 | | _ -> raise(Failure "Error: Generation of typing for built-in function failed. ") 391 | ) 392 | 393 | | "int" | "float" | "boolean" | "string" | "list" 394 | | "type" -> 395 | ( 396 | if List.length e2 != 1 then 397 | (invalid_args_error("Invalid Arguments Error: " ^ e1 ^ " takes 1 argument." )) 398 | else ( 399 | let x = List.hd e2 in 400 | let ty1, eq1 = cnstr ctx x in 401 | let tarrow = (Generator.arrow_of e1) in 402 | match tarrow with 403 | | TArrow(x) -> List.hd(List.rev x), eq1 404 | | _ -> raise(Failure "Error: Generation of typing for built-in function failed. ") 405 | ) 406 | ) 407 | | _ -> ( let ty1, eq1 = cnstr ctx (Id e1) in 408 | let ty2 = fresh () in 409 | match e2 with 410 | | [] -> ty2, (ty1, TArrow [TUnit; ty2], e1)::eq1 411 | | _ -> let tys = List.map (fun v -> let (ty,eq) = cnstr ctx v in ty) (List.rev e2) in 412 | let rec get_eqs exp_list eq_list = ( 413 | match exp_list with 414 | | [] -> eq_list 415 | | hd::tl -> let (ty, eq) = cnstr ctx hd in 416 | get_eqs tl (eq_list@eq) 417 | ) in 418 | ty2, eq1@[(ty1, TArrow (tys@[ty2]),e1)]@(get_eqs e2 []) 419 | ) 420 | ) (* end pattern matching for Id *) 421 | 422 | | _ -> invalid_args_error ("Invalid Arguments Error: In function call expression the first argument is invalid.") 423 | 424 | ) (* end pattern matching for Eval *) 425 | in 426 | cnstr [] 427 | 428 | (** [type_of ctx e] computes the principal type of expression [e] in 429 | context [ctx]. *) 430 | let type_of ctx e = 431 | let ty, eq = constraints_of ctx e in 432 | let ans = solve eq in 433 | let rec printType = function 434 | | TInt -> "TInt" 435 | | TBool -> "TBool" 436 | | TParam k -> "TypeVar" ^ (string_of_int k) 437 | | TSome -> "SomeType" 438 | | TSomeList _ -> "List of sometype" 439 | | TString -> "TString" 440 | | TUnit -> "TUnit" 441 | | TFloat -> "TFloat" 442 | | TArrow t_list -> ( 443 | let rec print_types_list types str = 444 | ( match types with 445 | |[] -> str 446 | | hd::tl when (List.length tl) = 0 -> str^(printType hd) 447 | | hd::tl when (List.length tl > 0) -> str^(printType hd)^" -> " 448 | | _ -> raise(Failure "Exception: List.length is -1") 449 | ) in 450 | print_types_list t_list "" 451 | ) 452 | | _ -> "other case" 453 | in let printpairs p = 454 | ignore(printType (snd p));() 455 | in List.iter (printpairs) ans; 456 | tsubst (ans) ty 457 | -------------------------------------------------------------------------------- /src/generator.ml: -------------------------------------------------------------------------------- 1 | open Ast;; 2 | open Printf;; 3 | 4 | let sprintf = Printf.sprintf;; 5 | 6 | let cc l = String.concat "" l;; 7 | let box t v = sprintf "({ __t: '%s', __v: %s })" t v;; 8 | 9 | let generate_js_func fname = 10 | let helper fname = 11 | match fname with 12 | "prn" -> 13 | ("'function() {\ 14 | for(var i=0; i < arguments.length; i++) {\ 15 | __assert_type(\\'string\\', arguments[i], \\'prn\\', (i+1) + \\'\\');\ 16 | console.log(__unbox(arguments[i]));\ 17 | }\ 18 | return __box(\\'unit\\', 0);\ 19 | }'", [TString], TUnit, []) 20 | 21 | | "exec" -> 22 | ("'function() {\ 23 | var res;\ 24 | for(var i = 0; i < arguments.length; i++) { \ 25 | __assert_type(\\'list\\', arguments[i], \\'do\\', (i+1) + \\'\\'); \ 26 | var str = JSON.stringify(__unbox(arguments[i]).slice(1)); \ 27 | res = eval(\\'(\\' + __unbox(__unbox(arguments[i])[0]) + \\').apply(null, \\' + str + \\')\\'); \ 28 | } \ 29 | return res; \ 30 | }'", [TSomeList(TSome)], TSome, ["evaluate"]) 31 | 32 | | "pr" -> 33 | ("'function(s) { \ 34 | for(var i=0; i < arguments.length; i++) {\ 35 | __assert_type(\\'string\\', arguments[i], \\'pr\\', (i+1) + \\'\\'); \ 36 | process.stdout.write(__unbox(arguments[i]));\ 37 | } \ 38 | return __box(\\'unit\\', 0); \ 39 | }'", [TString], TUnit, []) 40 | 41 | | "type" -> 42 | ("'function(o) { \ 43 | __assert_arguments_num(arguments.length, 1, \\'type\\'); \ 44 | return __box(\\'string\\', o.__t); \ 45 | }'", [TSome], TString, []) 46 | 47 | | "head" -> 48 | ("'function(l) { \ 49 | __assert_arguments_num(arguments.length, 1, \\'head\\'); \ 50 | __assert_type(\\'list\\', l, \\'head\\', \\'1\\'); \ 51 | return __clone(__unbox(l)[0]); \ 52 | }'", [TSomeList(TSome)], TSome, []) 53 | 54 | | "tail" -> 55 | ("'function(l) { \ 56 | __assert_arguments_num(arguments.length, 1, \\'tail\\'); \ 57 | __assert_type(\\'list\\', l, \\'tail\\', \\'1\\'); \ 58 | return __box(\\'list\\', __unbox(l).slice(1)); \ 59 | }'", [TSomeList(TSome)], TSomeList(TSome), []) 60 | 61 | | "cons" -> 62 | ("'function(i, l) { \ 63 | __assert_arguments_num(arguments.length, 2, \\'cons\\'); \ 64 | __assert_type(\\'list\\', l, \\'cons\\', \\'2\\'); \ 65 | var __temp = __unbox(l); \ 66 | __temp.unshift(__clone(i)); \ 67 | return __box(\\'list\\', __temp); \ 68 | }'", [TSome; TSomeList(TSome)], TSomeList(TSome), []) 69 | 70 | | "__add" -> 71 | ("'function() { \ 72 | for(var i=0; i < arguments.length; i++) { \ 73 | __assert_type(\\'int\\', arguments[i], \\'+\\', (i+1) + \\'\\');\ 74 | } \ 75 | return __box(\\'int\\', arguments.length === 0 ? 0 : \ 76 | Array.prototype.slice.call(arguments).map(__unbox).reduce(function(a,b){return a+b;}));\ 77 | }'", [TInt; TInt], TInt, []) 78 | 79 | | "__sub" -> 80 | ("'function(a1) { \ 81 | for(var i=0; i < arguments.length; i++) { \ 82 | __assert_type(\\'int\\', arguments[i], \\'-\\', (i+1) + \\'\\');\ 83 | } \ 84 | return __box(\\'int\\', arguments.length === 0 ? 0 : arguments.length === 1 ? -1 * __unbox(a1) : \ 85 | Array.prototype.slice.call(arguments).map(__unbox).reduce(function(a,b){return a-b;}));\ 86 | }'", [TInt; TInt], TInt, []) 87 | 88 | | "__mult" -> 89 | ("'function() { \ 90 | for(var i=0; i < arguments.length; i++) { \ 91 | __assert_type(\\'int\\', arguments[i], \\'*\\', (i+1) + \\'\\');\ 92 | } \ 93 | return __box(\\'int\\', arguments.length === 0 ? 1 : \ 94 | Array.prototype.slice.call(arguments).map(__unbox).reduce(function(a,b){return a*b;})); \ 95 | }'", [TInt; TInt], TInt, []) 96 | 97 | | "__div" -> 98 | ("'function() { \ 99 | for(var i=0; i < arguments.length; i++) { \ 100 | __assert_type(\\'int\\', arguments[i], \\'/\\', (i+1) + \\'\\');\ 101 | } \ 102 | return __box(\\'int\\', \ 103 | Math.floor(Array.prototype.slice.call(arguments).map(__unbox).reduce(function(a,b){return a/b;}))); \ 104 | }'", [TInt; TInt], TInt, []) 105 | 106 | | "mod" -> 107 | ("'function(a1, a2) { \ 108 | for(var i=0; i < arguments.length; i++) { \ 109 | __assert_arguments_num(arguments.length, 2, \\'mod\\'); \ 110 | __assert_type(\\'int\\', arguments[i], \\'mod\\', (i+1) + \\'\\');\ 111 | } \ 112 | return __box(\\'int\\', __unbox(a1) % __unbox(a2)); \ 113 | }'", [TInt; TInt], TInt, []) 114 | 115 | | "__addf" -> 116 | ("'function(a1) { \ 117 | for(var i=0; i < arguments.length; i++) { \ 118 | __assert_type(\\'float\\', arguments[i], \\'+.\\', (i+1) + \\'\\');\ 119 | } \ 120 | return __box(\\'float\\', arguments.length === 0 ? 0 : \ 121 | Array.prototype.slice.call(arguments).map(__unbox).reduce(function(a,b){return a+b;})); \ 122 | }'", [TFloat; TFloat], TFloat, []) 123 | 124 | | "__subf" -> 125 | ("'function(a1) { \ 126 | for(var i=0; i < arguments.length; i++) { \ 127 | __assert_type(\\'float\\', arguments[i], \\'-.\\', (i+1) + \\'\\');\ 128 | } \ 129 | return __box(\\'float\\', arguments.length === 0 ? 0 : arguments.length === 1 ? -1 * __unbox(a1) : \ 130 | Array.prototype.slice.call(arguments).map(__unbox).reduce(function(a,b){return a-b;})); \ 131 | }'", [TFloat; TFloat], TFloat, []) 132 | 133 | | "__multf" -> 134 | ("'function(a1) { \ 135 | for(var i=0; i < arguments.length; i++) { \ 136 | __assert_type(\\'float\\', arguments[i], \\'*.\\', (i+1) + \\'\\');\ 137 | } \ 138 | return __box(\\'float\\', Array.prototype.slice.call(arguments).map(__unbox).reduce(function(a,b){return a*b;})); \ 139 | }'", [TFloat; TFloat], TFloat, []) 140 | 141 | | "__divf" -> 142 | ("'function(a1, a2) { \ 143 | for(var i=0; i < arguments.length; i++) { \ 144 | __assert_type(\\'float\\', arguments[i], \\'/.\\', (i+1) + \\'\\');\ 145 | } \ 146 | return __box(\\'float\\', Array.prototype.slice.call(arguments).map(__unbox).reduce(function(a,b){return a/b;})); \ 147 | }'", [TFloat; TFloat], TFloat, []) 148 | 149 | | "__equal" -> 150 | ("'function(a1, a2) { \ 151 | __assert_arguments_num(arguments.length, 2, \\'is\\'); \ 152 | return __box(\\'boolean\\', JSON.stringify(__unbox(a1)) === JSON.stringify(__unbox(a2))); \ 153 | }'", [TParam 1; TParam 1], TBool, []) 154 | 155 | | "__neq" -> 156 | ("'function(a1, a2) { \ 157 | __assert_arguments_num(arguments.length, 2, \\'isnt\\'); \ 158 | if (a1.__t !== a2.__t) { \ 159 | throw new TypeError(\\'expected arguments of function isnt to be the same, \ 160 | but found \\' + a1.__t + \\' and \\' + a2.__t +\\'.\\'); \ 161 | } \ 162 | return __box(\\'boolean\\', __unbox(a1) !== __unbox(a2)); \ 163 | }'", [TParam 1; TParam 1], TBool, []) 164 | 165 | | "__less" -> 166 | ("'function(a1, a2) { \ 167 | __assert_arguments_num(arguments.length, 2, \\'<\\'); \ 168 | if (a1.__t !== a2.__t) { \ 169 | throw new TypeError(\\'expected arguments of function < to be the same, \ 170 | but found \\' + a1.__t + \\' and \\' + a2.__t +\\'.\\'); \ 171 | } \ 172 | return __box(\\'boolean\\', __unbox(a1) < __unbox(a2)); \ 173 | }'", [TParam 1; TParam 1], TBool, []) 174 | 175 | | "__leq" -> 176 | ("'function(a1, a2) { \ 177 | __assert_arguments_num(arguments.length, 2, \\'<=\\'); \ 178 | if (a1.__t !== a2.__t) { \ 179 | throw new TypeError(\\'expected arguments of function <= to be the same, \ 180 | but found \\' + a1.__t + \\' and \\' + a2.__t +\\'.\\'); \ 181 | } \ 182 | return __box(\\'boolean\\', __unbox(a1) <= __unbox(a2)); \ 183 | }'",[TParam 1; TParam 1], TBool, []) 184 | 185 | | "__greater" -> 186 | ("'function(a1, a2) { \ 187 | __assert_arguments_num(arguments.length, 2, \\'>\\'); \ 188 | return __box(\\'boolean\\', __unbox(a1) > __unbox(a2)); \ 189 | }'", [TParam 1; TParam 1], TBool, []) 190 | 191 | | "__geq" -> 192 | ("'function(a1, a2) { \ 193 | __assert_arguments_num(arguments.length, 2, \\'<=\\'); \ 194 | if (a1.__t !== a2.__t) { \ 195 | throw new TypeError(\\'expected arguments of function >= to be the same, \ 196 | but found \\' + a1.__t + \\' and \\' + a2.__t +\\'.\\'); \ 197 | } \ 198 | return __box(\\'boolean\\', __unbox(a1) >= __unbox(a2)); \ 199 | }'", [TParam 1; TParam 1], TBool, []) 200 | 201 | | "__and" -> 202 | ("'function(a1, a2) { \ 203 | __assert_arguments_num(arguments.length, 2, \\'and\\'); \ 204 | __assert_type(\\'boolean\\', a1, \\'and\\', \\'1\\'); \ 205 | __assert_type(\\'boolean\\', a2, \\'and\\', \\'2\\'); \ 206 | return __box(\\'boolean\\', __unbox(a1) && __unbox(a2)); \ 207 | }'", [TBool; TBool], TBool, []) 208 | 209 | | "__or" -> 210 | ("'function(a1, a2) { \ 211 | __assert_arguments_num(arguments.length, 2, \\'or\\'); \ 212 | __assert_type(\\'boolean\\', a1, \\'or\\', \\'1\\'); \ 213 | __assert_type(\\'boolean\\', a2, \\'or\\', \\'2\\'); \ 214 | return __box(\\'boolean\\', __unbox(a1) || __unbox(a2)); \ 215 | }'", [TBool; TBool], TBool, []) 216 | 217 | | "__not" -> 218 | ("'function(a) { \ 219 | __assert_arguments_num(arguments.length, 1, \\'not\\'); \ 220 | __assert_type(\\'boolean\\', a, \\'not\\', \\'1\\'); \ 221 | return __box(\\'boolean\\', !__unbox(a)); \ 222 | }'", [TBool], TBool, []) 223 | 224 | | "string_of_int" -> 225 | ("'function(i) { \ 226 | __assert_arguments_num(arguments.length, 1, \\'string_of_int\\'); \ 227 | __assert_type(\\'int\\', i, \\'string_of_int\\', \\'1\\'); \ 228 | return __box(\\'string\\', \\'\\' + __unbox(i)); \ 229 | }'", [TInt], TString, []) 230 | 231 | | "int_of_string" -> 232 | ("'function(s) { \ 233 | __assert_arguments_num(arguments.length, 1, \\'int_of_string\\'); \ 234 | __assert_type(\\'string\\', s, \\'int_of_string\\', \\'1\\'); \ 235 | return __box(\\'int\\', parseInt(__unbox(s))); \ 236 | }'", [TString], TInt, []) 237 | 238 | | "string_of_float" -> 239 | ("'function(f) { \ 240 | __assert_arguments_num(arguments.length, 1, \\'string_of_float\\'); \ 241 | __assert_type(\\'float\\', f, \\'string_of_float\\', \\' 1\\'); \ 242 | return __box(\\'string\\', \\'\\' + __unbox(f)); \ 243 | }'", [TFloat], TString, []) 244 | 245 | | "float_of_string" -> 246 | ("'function(s) { \ 247 | __assert_arguments_num(arguments.length, 1, \\'float_of_string\\'); \ 248 | __assert_type(\\'string\\', s, \\'float_of_string\\', \\'1\\'); \ 249 | return __box(\\'float\\', parseFloat(__unbox(s))); \ 250 | }'", [TString], TFloat, []) 251 | 252 | | "string_of_boolean" -> 253 | ("'function(b) { \ 254 | __assert_arguments_num(arguments.length, 1, \\'string_of_boolean\\'); \ 255 | __assert_type(\\'boolean\\', b, \\'string_of_boolean\\', \\'1\\'); \ 256 | return __box(\\'string\\', \\'\\' + __unbox(b)); \ 257 | }'", [TBool], TString, []) 258 | 259 | | "__concat" -> 260 | ("'function() { \ 261 | for(var i=0; i < arguments.length; i++) { \ 262 | __assert_type(\\'string\\', arguments[i], \\'++\\', (i+1) + \\'\\');\ 263 | } \ 264 | return __box(\\'string\\', arguments.length === 0 ? \\'\\' : \ 265 | Array.prototype.slice.call(arguments).map(__unbox).reduce(function(a,b){return a+b;})); \ 266 | }'", [TString; TString], TString, []) 267 | 268 | | "evaluate" -> 269 | ("'function(l) { \ 270 | __assert_arguments_num(arguments.length, 1, \\'eval\\'); \ 271 | __assert_type(\\'list\\', l, \\'eval\\', \\'1\\');\ 272 | return eval(\\'(\\' + __unbox(__unbox(l)[0]) + \\').apply(null, \\' + JSON.stringify(__unbox(l).slice(1)) + \\')\\'); \ 273 | }'", [TSomeList(TSome)], TSome, []) 274 | 275 | | "module" -> 276 | ("'function(n) { \ 277 | __assert_arguments_num(arguments.length, 1, \\'module\\'); \ 278 | __assert_type(\\'string\\', n, \\'module\\', \\'1\\'); \ 279 | var __t = require(__unbox(n));\ 280 | return __box(\\'module\\', __t, __t); \ 281 | }'", [TString], TJblob, []) 282 | 283 | | "list" -> 284 | ("'function(i) { \ 285 | __assert_arguments_num(arguments.length, 1, \\'list\\'); \ 286 | if (__assert_type(\\'list\\', i, \\'list\\')) { \ 287 | return i; \ 288 | }\ 289 | }'", [TSome], TSomeList(TSome), ["type"]) 290 | 291 | | "int" -> 292 | ("'function(i) { \ 293 | __assert_arguments_num(arguments.length, 1, \\'int\\'); \ 294 | if (__assert_type(\\'int\\', i, \\'int\\')) { \ 295 | return i;\ 296 | }\ 297 | }'", [TSome], TInt, ["type"]) 298 | 299 | | "string" -> 300 | ("'function(i) { \ 301 | __assert_arguments_num(arguments.length, 1, \\'string\\'); \ 302 | if (__assert_type(\\'string\\', i, \\'string\\')) { \ 303 | return i; \ 304 | } \ 305 | }'", [TSome], TString, ["type"]) 306 | 307 | | "float" -> 308 | ("'function(i) { \ 309 | __assert_arguments_num(arguments.length, 1, \\'float\\'); \ 310 | if (__assert_type(\\'float\\', i, \\'float\\')) { \ 311 | return i; \ 312 | } \ 313 | }'", [TSome], TFloat, ["type"]) 314 | 315 | | "boolean" -> 316 | ("'function(i) { \ 317 | __assert_arguments_num(arguments.length, 1, \\'boolean\\'); \ 318 | if (__assert_type(\\'boolean\\', i, \\'boolean\\')) { \ 319 | return i; \ 320 | } \ 321 | }'", [TSome], TBool, ["type"]) 322 | 323 | | "exception" -> 324 | ("'function(i) { \ 325 | __assert_arguments_num(arguments.length, 1, \\'exception\\'); \ 326 | __assert_type(\\'string\\', i, \\'exception\\', \\'1\\'); \ 327 | throw new Error(i); \ 328 | }'", [TString], TUnit, []) 329 | 330 | | _ -> ("", [], TSome, []) 331 | in 332 | let (fstr, arg_types, ret_type, deps) = helper fname in 333 | (box "function" fstr, arg_types, ret_type, deps) 334 | 335 | let is_generatable fname = 336 | let (_, argtypes, _, _) = generate_js_func fname in 337 | argtypes != [] 338 | 339 | let get_generatable_fnames prog = 340 | let rec get_deps fname = 341 | let (_, _, _, deps) = generate_js_func fname in 342 | deps @ (List.flatten (List.map get_deps deps)) in 343 | let rec get_fnames e = match e with 344 | Eval(f, el) -> (match f with 345 | Id(x) -> [x] 346 | | Fdecl(x, y) -> get_fnames y 347 | | Eval(x, y) -> get_fnames (Eval(x, y)) 348 | | If(c, t, e) -> get_fnames (If(c, t, e)) 349 | | _ -> []) @ (get_fnames (List(el))) 350 | | Id(s) -> [s] 351 | | Assign(el) -> get_fnames (List(el)) 352 | | List(el) -> List.flatten (List.map get_fnames el) 353 | | Fdecl(argl, exp) -> get_fnames exp 354 | | If(cond, thenb, elseb) -> (get_fnames cond) @ (get_fnames thenb) @ (get_fnames elseb) 355 | | _ -> [] in 356 | let generatable = (List.filter is_generatable (List.flatten (List.map get_fnames prog))) in 357 | let dependencies = List.map get_deps generatable in 358 | List.sort_uniq compare (generatable @ (List.flatten dependencies)) 359 | 360 | let arrow_of fname = 361 | let (_, arg_types, ret_type, _) = generate_js_func fname in 362 | match arg_types, ret_type with 363 | | [t1], t2 -> TArrow([t1; t2]) 364 | | [t1; t2], t3 -> TArrow([t1; t2; t3]) 365 | | _ -> raise(Failure ("Unknown identifier: '" ^ fname ^ "' ")) 366 | 367 | let generate_prog p = 368 | let escape_quotes s = 369 | Str.global_replace (Str.regexp "\\([^\\\\]?\\)'") "\\1\\'" (Str.global_replace (Str.regexp "\\([\\\\]+\\)'") "\\1\\1'" s) in 370 | let rec generate e = 371 | match e with 372 | Nil -> box "list" "[]" 373 | | List(el) -> box "list" (sprintf "[%s]" (String.concat ", " (List.map generate el))) 374 | | Int(i) -> box "int" (string_of_int (i)) 375 | | Float(f) -> box "float" (string_of_float (f)) 376 | | Boolean(b) -> box "boolean" (if b = true then "true" else "false") 377 | | String(s) -> box "string" (sprintf "'%s'" s) 378 | | Id(s) -> sprintf "eval('%s')" s 379 | 380 | | Assign(el) -> let rec gen_pairs l = 381 | match l with 382 | [] -> [] 383 | | h1::h2::tl -> (h1, h2)::(gen_pairs tl) 384 | | _::[] -> raise (Failure("= operator used on odd numbered list!")) 385 | in 386 | sprintf "eval('%s')" (cc (List.map 387 | (function 388 | | (Id(s), e) -> sprintf "var %s = %s; %s;" s (escape_quotes (generate e)) s 389 | | _ -> raise (Failure "can only assign to identifier")) 390 | (gen_pairs el))) 391 | 392 | | Eval(first, el) -> 393 | let argl = generate (List(el)) in 394 | (match first with 395 | Id(x) -> (match x with 396 | "dot" -> sprintf "__dot(%s)" argl 397 | | "call" -> sprintf "__call(%s)" argl 398 | | _ -> sprintf "(function(_i, _a) { \ 399 | return _i.__t === 'module' ? __box('module', __unbox(_i).apply(null, __unbox(_a).map(__unbox))) : \ 400 | eval('(' + __unbox(_i) + ').apply(null, ' + JSON.stringify(__unbox(_a)) + ')'); \ 401 | })\ 402 | (eval('%s'), %s)" x argl) 403 | 404 | | x -> sprintf 405 | "eval('(' + __unbox(%s) + ').apply(null, ' + JSON.stringify(__unbox(%s)) + ')')" 406 | (match x with 407 | Fdecl(a, e) -> generate (Fdecl(a, e)) 408 | | Eval(f, e) -> generate (Eval(f, e)) 409 | | If(c, t, e) -> generate (If(c, t, e)) 410 | | _ -> raise (Failure "foo")) 411 | argl) 412 | 413 | | Fdecl(argl, exp) -> box "function" 414 | (sprintf 415 | "(function(%s) { return %s; }).toString()" 416 | (String.concat ", " argl) 417 | (generate exp)) 418 | 419 | | If(cond, thenb, elseb) -> 420 | sprintf 421 | "(function() { var __c = __unbox(%s); return !(Array.isArray(__c) && __c.length === 0) && __c ? %s : %s; })()" 422 | (generate cond) 423 | (generate thenb) 424 | (generate elseb) 425 | 426 | in 427 | let generate_head p = 428 | let get_def fname = 429 | let (body, _, _, _) = generate_js_func fname in 430 | cc ["var "; fname; "="; body] in 431 | String.concat ";\n" (List.map get_def (get_generatable_fnames p)) in 432 | let wrap_exp e = cc [generate e; ";"] in 433 | cc ( 434 | " 435 | try { 436 | function getOwnPropertyDescriptors(object) {\ 437 | var keys = Object.getOwnPropertyNames(object), returnObj = {}; \ 438 | keys.forEach(getPropertyDescriptor); \ 439 | return returnObj; \ 440 | function getPropertyDescriptor(key) { \ 441 | var pd = Object.getOwnPropertyDescriptor(object, key); \ 442 | returnObj[key] = pd; \ 443 | } }":: 444 | 445 | "Object.getOwnPropertyDescriptors = getOwnPropertyDescriptors;":: 446 | 447 | "function __dup(o) { \ 448 | return Object.create(Object.getPrototypeOf(o), Object.getOwnPropertyDescriptors(o)); \ 449 | }":: 450 | 451 | "function __flatten(o) { \ 452 | var result = Object.create(o); \ 453 | for(var key in result) { result[key] = result[key]; } \ 454 | return result; \ 455 | }":: 456 | 457 | "function __box(t,v,c){ \ 458 | return ({ __t: t, __v: (t === 'module') ? v : __clone(v), _ctxt: c }); \ 459 | };":: 460 | 461 | "function __clone(o){\ 462 | return JSON.parse(JSON.stringify(o));\ 463 | };":: 464 | 465 | "function __unbox(o){ \ 466 | return (o.__t === 'module') ? o.__v : __clone(o.__v); \ 467 | };":: 468 | 469 | "function __assert_type(t, o, f, nth) { \ 470 | if (o.__t !== t && o.__t !== 'json') { \ 471 | throw new TypeError('expected type of argument ' + nth + ' of function ' + f + \ 472 | ' to be ' + t + ' but found ' + o.__t); \ 473 | } else { \ 474 | return true; \ 475 | }\ 476 | }":: 477 | 478 | "function __assert_arguments_num(actual, expected, f) { \ 479 | if (actual !== expected) { \ 480 | throw new TypeError('expected ' + expected + ' arguments to function ' + f + \ 481 | ' but found ' + actual + ' arguments. '); \ 482 | } else { \ 483 | return true; \ 484 | } \ 485 | };":: 486 | 487 | "function __tojs(o) { \ 488 | if (o.__t === 'function') { \ 489 | return function() { \ 490 | var __temp = Array.prototype.slice.call(arguments); \ 491 | return eval('(' + o.__v + ').apply(null, __temp)'); \ 492 | }; \ 493 | } else { \ 494 | return __unbox(o); \ 495 | } \ 496 | };":: 497 | 498 | "function __call(args) { if(args.__v.length === 1) { return __box('module', args.__v[0].__v(), args.__v[0].__v()); }; var __temp = !args.__v[0].__t ? args.__v[0] : __unbox(args.__v[0]); __temp[__unbox(args.__v[1])].apply(__temp, args.__v.slice(2).map(__tojs)); };":: 499 | 500 | "function __dot(args) { var __temp = args.__v; var res; for(var i = 1; i < __temp.length; i++) { res = (i === 1 ? __temp[0] : res)[__unbox(__temp[i])]; } return __box('json', res); };":: 501 | 502 | (generate_head p)::";\n"::(List.map wrap_exp p)@["}\ 503 | catch (e) {\ 504 | console.log('Runtime Error: ' + e.message);\ 505 | };"]) 506 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Superscript 2 | 3 | ![Build 4 | Passing](https://circleci.com/gh/udaysinghcode/superscript.svg?style=shield&circle-token=c4a7fd27027a5be7c2f8d8295c088c97a8946692) 5 | ![Build 6 | Passing](https://circleci.com/gh/udaysinghcode/superscript.svg?circle-token=c4a7fd27027a5be7c2f8d8295c088c97a8946692) 7 | 8 | ## 1. Introduction 9 | 10 | ### 1.1 Welcome to Superscript 11 | 12 | Superscript is a type-inferred Lisp with syntax, focused on rapid development, that compiles into Javascript. Superscript is a compiled language with static type inference, using the Lisp core, that allows the user to write robust, yet concise programs. It is heavily influenced by both Arc and Clojure, two new languages introduced to the Lisp community, and OCaml. 13 | 14 | Unlike Javascript, the functional-first nature of Superscript encourages users to think more before they code. Using static type inference based on the Hindley-Milner algorithm, our compiler tells users when their functions break due to type inconsistency. Similar to OCaml, it discourages users from thinking in terms of objects, and encourages clean data transformations through the use of S-expressions, which may be written using either Lisp-like, or imperative syntax (refer to Section 8, for Syntax Modifications to the Lisp core). This, combined with the flexibility of the Lisp family of languages, where functions and data are equivalent, gives users of Superscript a level of power unavailable in languages like Javascript. 15 | 16 | Superscript enables sharp programmers to think and express clear functional ideas in a language that is slowly becoming the backbone of the web. 17 | 18 | ### 1.2 Program Structure 19 | 20 | Superscript programs are built with expressions, and a program can be viewed as a single expression or a list of expressions executed in sequence. In Superscript, functions are data and data are functions. 21 | 22 | In the following examples, the indicated result is what the expression would evaluate to, in the executable JavaScript produced by the Superscript compiler. 23 | 24 | ```clojure 25 | ; Function call that prints Hello, world! 26 | > (prn “Hello, world!”);; 27 | Hello, world! 28 | 29 | ; Addition function applied to all integers from 1 to 10 30 | > (+ 1 2 3 4 5 6 7 8 9 10);; 31 | 32 | ; Function call, applying the ‘head’ function to a list 33 | ; that consists of ‘+’ and the integers 1 through 10. 34 | > (head ‘(+ 1 2 3 4 5 6 7 8 9 10));; 35 | ``` 36 | 37 | The idea that both functions and data are one and the same allows for rapid expression of ideas in Superscript that would otherwise be more difficult to express in Javascript. The above examples show not only how functions are executed, but how comments work (using the semicolon), and the power of code and data being one. 38 | 39 | ### 1.3 Related Work and Inspiration 40 | 41 | There are actually a number of related works to Superscript, a lot of which we noticed when we were hunting for names - SLisp, LispyScript, Parenscript, and more. We did not actually consult any of them when designing Superscript, except Clojurescript. Clojurescript, however, is focused on covering many of the syntax ideas of Clojure in a Lisp which compiles to Javascript. Clojure involves many syntactic differences that Superscript does not have such as the notation for sets, maps, and vectors. 42 | 43 | Our work is inspired by a Lisp called Arc developed by Paul Graham prior to Clojure as a response to the lack of Lisp development since the 1980s. We focused on Arc’s obsession of brevity (as in shortening the required amount of tokens to write a program, thus effectively decreasing the number of bugs). We tried not to fall into the Perl trap of requiring too few characters, but reducing the number of tokens so that programs remain transparent and short. We included an alternate syntax which preserves the semantics of Lisp, yet is very approachable for those who might be alarmed by the number of parentheses. Caramel can be preprocessed into Superscript which is then run by GEB (our compiler named after Hofstadter’s seminal work Gödel, Escher, Bach). Caramel allows Superscript to be more appealing to a more mainstream audience, switching out parentheses for indentation, as well as a few more syntactic features. Superscript still allows s-expressions as much like how John McCarthy worked on designing a syntax structure for Lisp, programmers preferred the untouched s-expressions. 44 | 45 | We looked at Poly and Haskell for type inference to prevent classic type errors that plague Lisp, utilizing Hindley Milner’s Algorithm W. We strayed away from Arc’s function overloading as this would break Algorithm W and instead focused on implementing the best of the safety that comes from type inference with a mix between terse Lisp code which is readable and short that can be picked up easily by beginners to Lisp and safe enough to prevent many of the classic bugs that hurt Javascript. 46 | 47 | We also utilized Node.js to evaluate Javascript on a cross-platform runtime environment so that Superscript could be extremely powerful for developing server-side web applications. 48 | 49 | All in all, Superscript could not have developed without the open source community, and for that we are indebted. 50 | 51 | ## 2. Tutorial 52 | 53 | This is a tutorial on Superscript that is for all users. Our Language Reference Manual is also designed like a tutorial, but this is more of a conversational attempt to get you into using Superscript. You do not have to know Lisp to walk through our tutorial. We will use the following syntax to cover code. When you see text in this typeface, it is in reference to command line functions. 54 | 55 | Let’s start by introducing the three characters important to understanding our tutorial. The % character is used to symbolize your Unix shell input. Make sure you have Node.js installed, if not, it can be downloaded from the Node.js site. In order to get started and print 56 | 57 | ```bash 58 | % ./make 59 | % ./geb -s "(prn \"Hello, world!\");;" 60 | ``` 61 | 62 | This allows you to run individual lines of Superscript. Remember when using quotes to escape them in the command line, and to include the double semicolon for concluding statements. 63 | 64 | ``` bash 65 | % vim hello.ss 66 | /* Type (prn "Hello, world!");; */ 67 | % ./geb hello.ss 68 | ``` 69 | 70 | If you want to run a program, you can use this method of compiling the file using geb, and you will see the output. We also used a `/* */` to symbolize a comment. This is how you comment as well in Superscript files. We will sometimes use the comment notation to provide extra information for the user. 71 | 72 | Our second to last symbol we will introduce is the > which is short for any line of Superscript which can be run. Rather than writing for either compiling files, or running individual lines, we will use this character to display lines of Superscript code. Feel free to provide appropriate spacing for writing Superscript files or bringing everything into one line to run with the ./geb -s command. 73 | 74 | ```clojure 75 | > (prn "Hello, world!");; 76 | "Hello, world!" 77 | ``` 78 | 79 | Our last symbol is >> which stands for the return value of the expression. This will not be explicitly printed, but is useful to show for certain expressions. We will usually show the printed output below the returned value. 80 | 81 | ```clojure 82 | > (prn "Hello, world!");; 83 | >> unit 84 | "Hello, world!" 85 | ``` 86 | 87 | So let’s start with the classic “Hello, World!” program. Wait, we’ve actually done that before and we had no build up to it. Instead, we will try something different. 88 | 89 | So here we will try it again, but instead do it with Devanagari script in Hindi. Let’s say hello, or better yet, “namaste” much like you do before a Yoga class. 90 | 91 | ```clojure 92 | > (prn "नमस्ते") 93 | ``` 94 | 95 | So that was terribly easy, and you’ll note that Superscript can print all Unicode characters allowed by Javascript. Essentially when you run when hello.ss has the line above in it: 96 | 97 | ```bash 98 | % ./geb hello.ss 99 | ``` 100 | 101 | This creates a file called a.js which is then run by the Node.js runtime. If Javascript can do it, we can do it too. You can run the file for the same output by running: 102 | 103 | ```bash 104 | % node a.js 105 | ``` 106 | 107 | You will notice a number of functions and respective types printed above the output, this is Superscript showing you the types of all available functions as it is run. You can see what functions are available when and their types, and the process of Algorithm W; this is by design to assist with debugging. 108 | 109 | Superscript programs are built out of expressions such as integers, floats, strings, and booleans. 110 | 111 | ```clojure 112 | > 25;; 113 | >> 25 114 | 115 | > "foo";; 116 | >> "foo" 117 | 118 | > 24.4;; 119 | >> 24.4 120 | 121 | > true;; 122 | >> true 123 | ``` 124 | 125 | Most expressions enclosed within multiple parentheses are also an expression. Many expressions together within parentheses are also known as an expression or actually, an s-expression, we also call these lists. 126 | 127 | ```clojure 128 | > (+ 2 3);; 129 | 130 | >> 5 131 | ``` 132 | 133 | There are two types of lists. Quoted and unquoted lists. We understand this doesn’t mean much right now, but all will be clear very soon. 134 | 135 | ```clojure 136 | /* Unquoted lists */ 137 | (+ 2 3) 138 | 139 | /* Quoted lists */ 140 | '(+ 2 3) 141 | ``` 142 | 143 | The list above, or the unquoted list, is technically a function or is evaluated from left to right with the values of the tail being passed as arguments to the values of the head. The first, unquoted list returns 5. The second quoted list is a list with a +, a 2, and a 3 in it. In other words, lists with quotes are not evaluated, lists with quotes are evaluated as function calls. All s-expressions will return something. So what does this return? 144 | 145 | ```clojure 146 | > (+ (* 1 3) (+ 3 (+ 4 5)));; 147 | ``` 148 | 149 | If you said, 15, you would be correct, but as you are probably noticing, Superscript is not printing your values. So let’s see what’s happening behind the madness. 150 | 151 | In order to print something, you have to use the prn function, however, prn requires a string for it to produce a string. This is an intentional strength of Superscript as the static type inference of Superscript requires functions to have the appropriate types for it to run a successful type check of the expression. The prn function requires a string and outputs a string. In order to do this we can use one of our many cast functions. 152 | 153 | ```clojure 154 | > (string_of_int (+ (* 1 3) (+ 3 (+ 4 5))));; 155 | >> "15" 156 | > (prn (string_of_int (+ (* 1 3) (+ 3 (+ 4 5)))));; 157 | >> "15" 158 | 15 159 | ``` 160 | 161 | All casts are listed in the Language Reference Manual and will be used below. The format is pretty straight forward, string_of_int, string_of_float, string_of_boolean, and more. 162 | 163 | So to go back to the expression, we notice that prefix notation, or putting the + before the elements in the unquoted list may seem a little odd compared to standard infix notation (if you want standard infix notation, we offer that. See the Infix Expression section in the Language Reference Manual or just put the operation within curly brackets. Prefix notation, however, has its benefits as we can keep adding arguments to the function. 164 | 165 | ```clojure 166 | > (+);; 167 | >> 0 168 | 169 | > (+ 1);; 170 | >> 1 171 | 172 | > (+ 1 1);; 173 | >> 2 174 | 175 | > (+ 1 1 1);; 176 | >> 3 177 | ``` 178 | 179 | If we want to assign to foo the value of 42, the entire assignment expression will return 42 when evaluated. 180 | 181 | ```clojure 182 | > (= foo 42);; 183 | >> 42 184 | 185 | > (prn (string_of_int 42));; 186 | >> 42 187 | 42 188 | ``` 189 | 190 | Although most operators evaluate from left to right, this is an exception which stores the value of 42 into foo. Now let’s add 42 to an unquoted list. 191 | 192 | ```clojure 193 | > (cons 4 '(8 15 16 23 42));; 194 | >> ‘(4 8 15 16 23 42) 195 | ``` 196 | 197 | The cons function appends the first argument to the list in the second argument. You’ll note that we are using a quoted list as a data structure inside, and an unquoted list as a function expression. This allows Superscript to be a homoiconic language and allows the user to very clearly note the applicative order of Superscript and even compute Superscript expressions by hand similar to lambda calculus. 198 | 199 | Similarly to cons, we have have two functions to take lists apart: head and tail. Although more traditional Lisps use the terms car and cdr respectively. We found that head and tail made more sense to new users as “Contents of the Address part of Register number” did not have the same ring as “head”. To use these functions try this: 200 | 201 | ```clojure 202 | > (head '(4 8 15 16 23 42));; 203 | >> 4 204 | 205 | > (prn (string_of_int (int (head '(4 8 15 16 23 42)))));; 206 | 4 207 | 208 | > (tail ‘(4 8 15 16 23 42));; 209 | >> '(8 15 16 23 42) 210 | 211 | 212 | > (print_list format_int (tail '(4 8 15 16 23 42))));; 213 | [8,15,16,23,42] 214 | ``` 215 | 216 | You’ll note that the standard Lisp formatting gives us 4 right parentheses at the end of this list may seem cumbersome. How is this dealt with in Lisp? As Paul Graham says, “we don’t.” Lisp programmers don’t count parentheses and let their editors do the work for them. As for readability, we use indentation. If you write in Caramel, our preprocessor allows you to skip parentheses for indentation. Use the print_list function with format_int (or format_string or format_float, you get the idea), to print a list. 217 | 218 | ```clojure 219 | > (= x ‘(4 8 15 16 23 42));; 220 | > (= y (tail x));; 221 | > (= z y);; 222 | > (print_list format_int (tail z));; 223 | [15,16,23,42] 224 | ``` 225 | 226 | By allowing heterogeneous lists, Superscript allows exploratory programming with the strength of static type inference. All lists are lists of type SomeList of SomeType. In order to use the head of a list (or any individual element) in another computation, the result of calling head on the list must be annotated with a specific type (or dynamic cast) in order for type inference to work. In the below example, the result of head must be annotated to be an “int” in order to be passed to string_of_int, and to print the resulting string. 227 | 228 | ```clojure 229 | > (prn (string_of_int (int (head '(4 8 15 16 23 42)))));; 230 | 4 231 | ``` 232 | 233 | So the last few things we will teach you how to go through before we send you off to the language reference manual are booleans and lists. 234 | 235 | So let’s try a simple if statement. 236 | 237 | ```clojure 238 | > (if (is 0 0) 1 2);; 239 | >> 1 240 | 241 | > (if (isnt 0 0) 1 2);; 242 | >> 2 243 | ``` 244 | 245 | We can use is and isnt for returning a boolean value which is fed into the if statement, we can also use standard comparable functions as well (<, >, <=, >=). These equality and comparison operators take 2 arguments which must be of the same type, such as int and int, or string and string. We also have logical operators such as and, or & not. 246 | 247 | Now before we send you off into the language reference manual, we want to cover the last thing. Throughout this tutorial, we have been introducing you to the function and the very simple syntax behind Superscript. Most of the elements you see in Superscript are functions, and as such are easy to create yourself. To create a function, much like Javascript, all you have to do is assign an anonymous function to an identifier, and then you can call the identifier to run the function. 248 | 249 | ```clojure 250 | > (= function_name (fn (arg1 arg2 … argn) (function_body));; 251 | ``` 252 | 253 | ```clojure 254 | > /* Note the use of infix below */ 255 | > (= fib (fn (x) (if (is x 0) 0 (if (is x 1) 1 (+ (fib {x - 1}) (fib {x -2} ))))));; 256 | > (prn (string_of_int (fib 8)));; 257 | 21 258 | ``` 259 | 260 | And there you have it, you can now define and create your own functions in Superscript and run them like the way you learned. We have all sorts of more cute tricks and goodies inside the Language Reference Manual, but don’t want to inundate you now, and instead would love to see you start writing programs. The LRM is also written as a semi-tutorial, so don’t hesitate to just go through it section by section. 261 | 262 | Happy hacking! (John McCarthy is probably smiling) 263 | 264 | ## 3. Language Reference Manual 265 | 266 | ### 3.1 Introduction 267 | 268 | This is a language reference manual updated to reflect the current state of Superscript at the first release plus the geb compiler. 269 | 270 | ### 3.2 Lexical Convention 271 | 272 | #### 3.2.1 Reserved Keywords 273 | 274 | Superscript has a set of reserved keywords, which cannot be used as identifiers. Superscript also comes with built-in functions which generate specific Javascript code when invoked. It also has a standard library, written in Superscript, which is automatically imported (concatenated into the beginning of any user-defined code). 275 | 276 | 277 | 278 | | Reserved Keywords | Built-in functions | Standard Library Functions | 279 | | ------------- |:-------------:| -----:| 280 | | true, false, fn, if, eval, do | +, -, *, /, +., -., *., /., mod, is, isnt, <, <=, >, >=, and, or, not, ++, do, eval, call, dot, module, cons, head, tail, pr, prn, int_of_string, string_of_float, float_of_string, string_of_boolean, boolean_of_string, string_of_int, int, float, boolean, string, list, type | identity, length, nth, first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, last, map, fold_left, fold_right, filter, append, reverse, drop, take, intersperse, member, zipwith, zipwith3, zip, unzip, format_boolean, format_int, format_string, format_float, stringify_list, format_boolean2d, format_int2d, format_float2d, format_string2d, print_list | 281 | 282 | #### 3.2.2 Punctuation 283 | 284 | ##### 3.2.2.1 Comments 285 | Comments in Superscript are C-style: 286 | 287 | ```clojure 288 | >/* this is a comment */ 289 | ``` 290 | 291 | ##### 3.2.2.2 Double semicolon 292 | A program in Superscript is a list of expressions, and the expressions are separated by double semicolons: 293 | ```clojure 294 | > ( prn "hello" );; ( prn "world" );; ( prn "people");; 295 | hello 296 | world 297 | people 298 | ``` 299 | 300 | ##### 3.2.2.3 Parentheses 301 | 302 | Parentheses must enclose the representation of a list, which must be quoted if it is not intended to be a function call: 303 | 304 | ```clojure 305 | > '( 1 2 3 );; 306 | >> ‘(1 2 3) 307 | ``` 308 | 309 | Parentheses must be used to wrap a function definition, to wrap its arguments, and to wrap the function body. We used the Scheme lambda construction but removed the keyword lambda and replaced it with fn similar to Arc to encourage constant use of lambda functions, similar to Javascript function assignment: 310 | 311 | ```clojure 312 | > (fn (x y) (+ x y));; 313 | ``` 314 | 315 | Parentheses must be used to wrap any function call, including a standard library function call or built-in operation. 316 | 317 | ```clojure 318 | > (average 2 4);; /*average is a function that returns the average value of its parameters*/ 319 | 3 320 | 321 | > (if true 1 2);; 322 | 1 323 | ``` 324 | 325 | All unquoted lists are interpreted as function calls. Hence, parentheses cannot be used to wrap an unquoted list that is not a function call. The following is a syntax error, and cannot be evaluated as you are trying to evaluate the operator 1 on the arguments 2 and 3: 326 | 327 | ```clojure 328 | > (1 2 3);; 329 | Line:1 char:1..6: Syntax error. Function call on inappropriate object. 330 | ``` 331 | 332 | ##### 3.2.2.4 Curly Braces 333 | 334 | Braces can be used to wrap an infix expression and to explicitly indicate the order of operations and associativity. See Section 3.8 for more information about syntactic sugar and Syntax Modifications that allow a more imperative programming syntax. Infix expressions can be used in both Superscript and Caramel syntax. See the section on Infix Expressions below. 335 | 336 | ```clojure 337 | > {1 + 2};; 338 | >> 3 339 | ``` 340 | 341 | ### 3.3 Data Types 342 | 343 | #### 3.3.1 Type Inference 344 | 345 | Superscript uses static type inference, based on the Hindley-Milner algorithm[12], to evaluate the type and value of any legal expression and to check that expressions satisfy the proper data type in all function calls. Our compiler will flag any inconsistent data type in function calls as a type incompatibility error. Based on this type inference, the Superscript compiler implements error handling and prints the appropriate error messages to the user. 346 | 347 | Superscript’s standard library provides a set of functions to let user convert between different data types. 348 | 349 | #### 3.3.2 Atomic Data Types 350 | 351 | The following are atomic (non-list) data types in Superscript. 352 | 353 | ##### 3.3.2.1 Numerical types 354 | 355 | We use type inference to avoid NaN errors common in Javascript, since non-numerical values cannot be used in arithmetic functions. 356 | 357 | ###### Integers 358 | Superscript allows integers, which may be manipulated by integer arithmetic using the standard +, -, /, * operators. Integers are sequences of digits containing no decimals. Integers are considered accurate up to 15 digits. 359 | 360 | ```clojure 361 | > 42;; 362 | >> 42 363 | 364 | > (type 42);; 365 | >> ‘int’ 366 | ``` 367 | 368 | ###### Floating Points 369 | Superscript allows floating point values and requires the use of floating point specific operators to perform floating point arithmetic. These operators are the int operators followed by ‘.’ (+., -., /., *.). Floating points must include at least one digit and a decimal, satisfying the regular expression: ['0'-'9']*'.'['0'-'9']+ | ['0'-'9']+'.'['0'-'9']* 370 | 371 | ```clojure 372 | > 42.0;; 373 | 42.0 374 | 375 | > (type 42.0);; 376 | ‘float’ 377 | ``` 378 | 379 | ##### 3.3.2.2 Strings 380 | 381 | Superscript supports UTF-8 strings as a way to represent textual data. Like Javascript, a single character is treated as a single character String. There is no type for chars. Print always prints to console and returns the unit datatype. 382 | 383 | ```clojure 384 | > “Hello, world!”;; 385 | >> “Hello, world!” 386 | 387 | > (type “Hello, world!”);; 388 | >> ‘string’ 389 | ``` 390 | 391 | 392 | ##### 3.3.2.3 Symbols 393 | 394 | Symbols, or identifiers, represent programmer-defined objects. They are containers for storing data values, and they return the value assigned to them. An identifier name must start with a letter, followed by any number of letters, digits, or underscores, and is defined by the regular expression: ['a'-'z' 'A'-'Z']['a'-'z' 'A'-'Z' '0'-'9' '_' ]* 395 | 396 | ```clojure 397 | > (= a 42);; 398 | 42 399 | 400 | > a;; 401 | 42 402 | ``` 403 | 404 | 3.3.2.4 True/False/Nil 405 | 406 | Superscript has a boolean true and false value. 407 | 408 | ```clojure 409 | > (type true);; 410 | ‘boolean’ 411 | 412 | > (type false);; 413 | ‘boolean’ 414 | ``` 415 | 416 | Superscript also has a nil value which is the null datatype. It is equivalent to the empty list. 417 | 418 | ```clojure 419 | > nil;; 420 | nil 421 | 422 | > ‘();; 423 | nil 424 | ``` 425 | 426 | #### 3.3.3 Non-atomic Data Types 427 | 428 | ##### 3.3.3.1 Lists 429 | 430 | Multiple atoms enclosed parentheses are also called lists. An unquoted list is a function call, where the first element is the function name, and the other values are the parameters (See 3.3.2). For instance, `(a b c d e)` calls the function a with the arguments b, c, d, and e. It is a syntax error to write an expression that is an unquoted list, such as `(5 4 8)`, where the first element is not a function name. 431 | 432 | In order to use `(a b c d e)` as a list, rather than function call, you must quote the list: `‘(a b c d e)` is a list of the elements a, b, c, d, and e. 433 | 434 | ```clojure 435 | > ‘(1 2 3);; 436 | ‘(1 2 3) 437 | 438 | > (type ‘(1 2 3));; 439 | ‘(sometype) list ’ 440 | ``` 441 | 442 | ##### 3.3.3.2 Functions 443 | 444 | Call a function using an unquoted list, where the first argument is the function name, the following arguments are the parameters passed into the function call, and all the parameters are passed in by value, in the format of `( function_name arg1 arg2 arg3…)`: 445 | 446 | ```clojure 447 | > (+ 1 2 3 4);; 448 | 10 449 | ``` 450 | 451 | Define an anonymous function in the following way, using the ‘fn’ keyword: `(fn (optional_args) expression)`, where optional_args is 0 or more formal arguments separated by spaces, and enclosed by parentheses; the body of the function is a single expression enclosed by parentheses; and the entire expression is surrounded by parentheses. A function definition returns a function data type. In Superscript, functions are a data type much like lists and atoms. 452 | 453 | ```clojure 454 | > (fn (x y) (/(+ x y) 2));; 455 | - : int -> int -> int 456 | ``` 457 | 458 | We can bind an anonymous function declaration to a name using the `=` function, which evaluates right-to-left. Don’t be scared by the prefix notation, as the same may be expressed using infix notation, covered in Section 8, Syntax Modifications. 459 | 460 | Anonymous function declaration, which is then bound to the name `average`: 461 | 462 | ```clojure 463 | > (= average (fn (x y) (/ (+ x y) 2)));; 464 | val average : int -> int -> int 465 | ``` 466 | Function call: 467 | 468 | ```clojure 469 | > (average 20 10);; 470 | 15 471 | ``` 472 | 473 | ### 3.4. Operators and Built-in Functions 474 | 475 | #### 3.4.1. Basic Assignment 476 | 477 | The ‘=’ operator takes an even number of arguments, and assigns to the first of each pair the value of the second of each pair. This is a basic assignment that sets the value of a to 5, c to 6, and d to 7: 478 | 479 | ```clojure 480 | > (= a 5 c 6 d 7);; 481 | val a : int 482 | val c : int 483 | val d : int 484 | 485 | > (= x 5);; 486 | val x : int 487 | ``` 488 | 489 | Basic assignment is applicable to all datatypes. 490 | 491 | #### 3.4.2. Arithmetic Operators 492 | 493 | Before we go into arithmetic operators, note that we will be using prefix notation here. Superscript allows infix notation as well under the Infix Expression section. 494 | 495 | Superscript offers several Standard Library arithmetic functions. These include both integral and floating addition, subtraction, multiplication, division; as well as the modulo of two ints. These functions are used as follows. 496 | 497 | ###### Addition, Subtraction, Multiplication, Division 498 | 499 | You can add at least 2 arguments, a to b, or add an unlimited amount of arguments together. The following examples show function calls to arithmetic operations. 500 | 501 | ```clojure 502 | (+ a b) 503 | 504 | (+. a b c d e f g h i j k l m n o p …) 505 | ``` 506 | 507 | Both of the above expressions are unquoted lists where the first element is a function call to the addition function, done on the other elements in the list. The first example uses the integer operator (+), and the second, the floating operator (+.). Addition, Subtraction, Multiplication, and Division can be applied to two or more arguments. 508 | 509 | All arguments to arithmetic functions must be numerical. They will be evaluated left to right. 510 | 511 | ###### Modulo 512 | 513 | You can call a modulus function between TWO integers a and b, this will return the remainder of a / b. 514 | 515 | ```clojure 516 | > (mod 5 6) 517 | 5 518 | ``` 519 | 520 | #### 3.4.3. Boolean Operators 521 | 522 | Superscript’s Standard Library contains logical functions to evaluate boolean expressions. 523 | 524 | ##### 3.4.3.1. Logical NOT Function 525 | 526 | ‘not’ is a Standard-Library function that takes one boolean expression as its argument, and negates the value of that expression. 527 | 528 | ```clojure 529 | > (not true);; 530 | false 531 | 532 | > (not false);; 533 | true 534 | ``` 535 | 536 | ##### 3.4.3.2 Logical AND / OR 537 | 538 | Superscript’s Standard Library supports logical AND/OR functions, using ‘and’ and ‘or’ keywords. AND/OR must be used with two boolean expressions as arguments. 539 | 540 | ```clojure 541 | > (and true false);; 542 | false 543 | 544 | (or true true);; 545 | > true 546 | ``` 547 | 548 | ##### 3.4.3.3 Equality and Inequality 549 | 550 | The ‘is’ function is an equality comparison that may be applied on atomic constants: ints, floats, and strings. The ‘isnt’ function compares two ints, floats, or strings for inequality. The arguments must be of the same type, for instance, string and string, or int and int. 551 | 552 | ```clojure 553 | > (is “a” “b”);; 554 | false 555 | 556 | > (is 1 1);; 557 | true 558 | 559 | > (is 1 2);; 560 | false 561 | 562 | > (isnt “a” “b”);; 563 | true 564 | ``` 565 | 566 | #### 3.4.4 Relational Comparison operators 567 | 568 | These relational comparison operators can be used for ints, floats, and strings. They take two expressions, which must be of the same type, as arguments: 569 | 570 | Examples: 571 | ```clojure 572 | (> a b);; 573 | (< a b);; 574 | (>= a b);; 575 | (<= a b);; 576 | ``` 577 | 578 | Try it out: 579 | ```clojure 580 | > (> 5 4);; 581 | true 582 | ``` 583 | 584 | #### 3.4.5 String concatenation 585 | 586 | String concatenation is done using the “++”’ function. It operates on a list of strings and concatenates them all from left to right. 587 | 588 | ```clojure 589 | > (++ “hello” “ ” “world” “ superscript” “ is” “ here”);; 590 | “hello world superscript is here” 591 | ``` 592 | 593 | #### 3.4.6 prn/pr Function 594 | 595 | Print always prints to console. Its type is string -> unit. Hence you must pass it one or more strings as argument. 596 | 597 | ```clojure 598 | > (prn “Hello, world” “!”);; 599 | Hello, world! 600 | 601 | > (prn (string_of_int 5));; 602 | 5 603 | 604 | > (type (prn 5));; 605 | - : string -> unit 606 | ``` 607 | 608 | #### 3.4.7 Infix Expressions 609 | 610 | Infix expressions may be used in Superscript if you enclose them in curly braces: {expression};; Example usage is below: 611 | 612 | 613 | 1. Basic arithmetic in infix expressions will be evaluated in the standard order of operations. To parenthesize within infix expressions, use curly braces: 614 | ```clojure 615 | { 1 * {2 - 4} / 4 };; 616 | ``` 617 | 618 | 2. To call a function with an infix expression as argument, use parentheses around the entire function call, as per standard Superscript function calling syntax: 619 | ```clojure 620 | ( foo {1 + 3 + 3 * 4} );; 621 | ``` 622 | 623 | 3. To call functions from within an infix expression and manipulate its return values, call the functions as you would normally and remember to enclose all infix expression in curly braces. 624 | ```clojure 625 | { 1 + 2 + (foo 3) + ( baz {3 + 4} ) };; 626 | ``` 627 | 628 | ### Footnotes 629 | 630 | [0]: http://www.hanselman.com/blog/JavaScriptIsAssemblyLanguageForTheWebPart2MadnessOrJustInsanity.aspx 631 | [1]: http://rauchg.com/2014/7-principles-of-rich-web-applications 632 | [2]: https://www.destroyallsoftware.com/talks/wat 633 | [3]: http://languagelog.ldc.upenn.edu/myl/ldc/llog/jmc.pdf 634 | [4]: ttp://www.paulgraham.com/arc.html 635 | [5]: http://cs.princeton.edu/courses/archive/spr11/cos333/lectures/17paradigms/sort.lisp 636 | [6]: http://www.braveclojure.com/ 637 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------