Merge branch 'master' into feature/lambda-list-keyword

Conflicts:
	hy/compiler.py
	hy/lex/states.py
	hy/util.py
	tests/compilers/test_ast.py
	tests/lex/test_lex.py
This commit is contained in:
James King 2013-04-18 15:17:30 -04:00
commit 18ed72136f
71 changed files with 953 additions and 7883 deletions

View File

@ -16,6 +16,10 @@ notifications:
channels:
- "irc.freenode.net#woo-city-commits"
- "irc.freenode.net#hy"
on_success: always
on_failure: always
use_notice: true
on_success: change
on_failure: change
use_notice: false
# blacklist
branches:
except:
- debian

View File

@ -7,3 +7,5 @@
* Julien Danjou <julien@danjou.info>
* Nicolas Dandrimont <nicolas.dandrimont@crans.org>
* Gergely Nagy <algernon@madhouse-project.org>
* Konrad Hinsen <konrad.hinsen@fastmail.net>
* Vladimir Gorbunov <vsg@suburban.me>

View File

@ -4,7 +4,6 @@ all:
@echo " Other targets:"
@echo ""
@echo " - docs"
@echo " - site"
@echo " - full"
@echo ""
@echo " - dev (test & flake)"
@ -16,16 +15,13 @@ all:
@echo " - r"
@echo ""
site:
make -C site
docs:
make -C docs html
upload: r
python setup.py sdist upload
full: d tox site docs
full: d tox docs
venv:
ifeq (,$(findstring hy,$(VIRTUAL_ENV)))
@ -45,7 +41,6 @@ tox: venv
flake:
flake8 hy
flake8 site
clear:
clear
@ -58,4 +53,4 @@ diff:
r: d tox diff
.PHONY: site docs
.PHONY: docs

View File

@ -1,11 +1,11 @@
Hy
==
![](https://raw.github.com/paultag/hy/master/site/imgs/xkcd.png)
![](https://raw.github.com/hylang/shyte/master/imgs/xkcd.png)
Lisp and Python should love each other. Let's make it happen.
[![Build Status](https://travis-ci.org/paultag/hy.png?branch=master)](https://travis-ci.org/paultag/hy)
[![Build Status](https://travis-ci.org/hylang/hy.png?branch=master)](https://travis-ci.org/paultag/hy)
Hylarious Hacks
@ -34,8 +34,8 @@ Oh, and lisps are neat.
Project
-------
* Code: https://github.com/paultag/hy
* Code: https://github.com/hylang/hy
* Docs: http://hy.rtfd.org/
* Quickstart: http://hy.rtfd.org/en/latest/quickstart.html
* Bug reports: We have no bugs! Your bugs are your own! (https://github.com/paultag/hy/issues)
* Bug reports: We have no bugs! Your bugs are your own! (https://github.com/hylang/hy/issues)
* License: MIT (Expat)

10
bin/hy
View File

@ -21,6 +21,7 @@ from hy.lex.states import Idle, LexException
from hy.lex.machine import Machine
from hy.compiler import hy_compile
from hy.core import process
from hy.importer import compile_
import hy.completer
@ -48,12 +49,17 @@ class HyREPL(code.InteractiveConsole):
_machine = Machine(Idle, 1, 0)
return True
tokens = process(_machine.nodes)
try:
tokens = process(_machine.nodes)
except Exception:
_machine = Machine(Idle, 1, 0)
self.showtraceback()
return False
_machine = Machine(Idle, 1, 0)
try:
_ast = hy_compile(tokens, root=ast.Interactive)
code = compile(_ast, filename, symbol)
code = compile_(_ast, filename, symbol)
except Exception:
self.showtraceback()
return False

View File

@ -11,7 +11,10 @@
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os, hy
import sys, os
sys.path.append(os.path.abspath(".."))
import hy
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the

View File

@ -23,5 +23,16 @@ __appname__ = "hy"
__version__ = "0.9.5"
from hy.models.expression import HyExpression # NOQA
from hy.models.integer import HyInteger # NOQA
from hy.models.keyword import HyKeyword # NOQA
from hy.models.complex import HyComplex # NOQA
from hy.models.string import HyString # NOQA
from hy.models.symbol import HySymbol # NOQA
from hy.models.float import HyFloat # NOQA
from hy.models.dict import HyDict # NOQA
from hy.models.list import HyList # NOQA
import hy.importer # NOQA
# we import for side-effects.

View File

@ -26,36 +26,50 @@ from hy.errors import HyError
from hy.models.expression import HyExpression
from hy.models.integer import HyInteger
from hy.models.lambdalist import HyLambdaListKeyword
from hy.models.float import HyFloat
from hy.models.complex import HyComplex
from hy.models.string import HyString
from hy.models.symbol import HySymbol
from hy.models.list import HyList
from hy.models.dict import HyDict
from hy.models.keyword import HyKeyword
from hy.util import flatten_literal_list
from hy.util import flatten_literal_list, str_type
from collections import defaultdict
import codecs
import ast
import sys
import traceback
class HyCompileError(HyError):
def __init__(self, exception,
start_line=0, start_column=0):
def __init__(self, exception, traceback=None):
self.exception = exception
self.start_line = start_line
self.start_column = start_column
self.traceback = traceback
def __str__(self):
if self.start_line == 0:
return("Internal Compiler Bug\n%s: %s"
% (self.exception.__class__.__name__,
self.exception))
return ("Compilation error at line %d, column %d\n%s: %s"
% (self.start_line, self.start_column,
self.exception.__class__.__name__,
self.exception))
if isinstance(self.exception, HyTypeError):
return str(self.exception)
if self.traceback:
tb = "".join(traceback.format_tb(self.traceback)).strip()
else:
tb = "No traceback available. 😟"
return("Internal Compiler Bug 😱\n%s: %s\nCompilation traceback:\n%s"
% (self.exception.__class__.__name__,
self.exception, tb))
class HyTypeError(TypeError):
def __init__(self, expression, message):
super(HyTypeError, self).__init__(message)
self.expression = expression
def __str__(self):
return (self.message + " (line %s, column %d)"
% (self.expression.start_line,
self.expression.start_column))
_compile_table = {}
@ -84,20 +98,17 @@ def builds(_type):
def _raise_wrong_args_number(expression, error):
err = TypeError(error % (expression.pop(0),
len(expression)))
err.start_line = expression.start_line
err.start_column = expression.start_column
raise err
raise HyTypeError(expression,
error % (expression.pop(0),
len(expression)))
def checkargs(exact=None, min=None, max=None):
def _dec(fn):
def checker(self, expression):
if exact is not None and (len(expression) - 1) != exact:
_raise_wrong_args_number(expression,
"`%%s' needs %d arguments, got %%d" %
exact)
_raise_wrong_args_number(
expression, "`%%s' needs %d arguments, got %%d" % exact)
if min is not None and (len(expression) - 1) < min:
_raise_wrong_args_number(
@ -120,6 +131,7 @@ class HyASTCompiler(object):
def __init__(self):
self.returnable = False
self.anon_fn_count = 0
self.imports = defaultdict(list)
def compile(self, tree):
try:
@ -132,21 +144,22 @@ class HyASTCompiler(object):
# another HyCompileError!
raise
except Exception as e:
raise HyCompileError(exception=e,
start_line=getattr(e, "start_line", 0),
start_column=getattr(e, "start_column", 0))
raise HyCompileError(e, sys.exc_info()[2])
raise HyCompileError("Unknown type - `%s'" % (str(type(tree))))
raise HyCompileError(
Exception("Unknown type: `%s'" % (str(type(tree)))))
def _mangle_branch(self, tree, start_line, start_column):
tree = list(flatten_literal_list(tree))
tree = list(filter(bool, tree)) # Remove empty statements
# If tree is empty, just return a pass statement
if tree == []:
return [ast.Pass(lineno=start_line,
col_offset=start_column)]
return [ast.Pass(lineno=start_line, col_offset=start_column)]
tree.reverse()
ret = []
tree = list(flatten_literal_list(tree))
tree.reverse()
if self.returnable and len(tree) > 0:
el = tree[0]
@ -167,9 +180,10 @@ class HyASTCompiler(object):
ret.append(el)
continue
ret.append(ast.Expr(value=el,
lineno=el.lineno,
col_offset=el.col_offset))
ret.append(ast.Expr(
value=el,
lineno=el.lineno,
col_offset=el.col_offset))
ret.reverse()
return ret
@ -225,6 +239,34 @@ class HyASTCompiler(object):
def compile_raw_list(self, entries):
return [self.compile(x) for x in entries]
def _render_quoted_form(self, form):
name = form.__class__.__name__
self.imports["hy"].append((name, form))
if isinstance(form, HyList):
return HyExpression(
[HySymbol(name),
HyList([self._render_quoted_form(x) for x in form])]
).replace(form)
elif isinstance(form, HySymbol):
return HyExpression([HySymbol(name), HyString(form)]).replace(form)
return HyExpression([HySymbol(name), form]).replace(form)
@builds("quote")
@checkargs(exact=1)
def compile_quote(self, entries):
return self.compile(self._render_quoted_form(entries[1]))
@builds("eval")
@checkargs(exact=1)
def compile_eval(self, expr):
expr.pop(0)
self.imports["hy.importer"].append(("hy_eval", expr))
return self.compile(HyExpression([
HySymbol("hy_eval")] + expr + [
HyExpression([HySymbol("locals")])]).replace(expr))
@builds("do")
@builds("progn")
def compile_do_expression(self, expr):
@ -248,12 +290,6 @@ class HyASTCompiler(object):
def compile_try_expression(self, expr):
expr.pop(0) # try
if sys.version_info[0] >= 3 and sys.version_info[1] >= 3:
# Python 3.3 features a rename of TryExcept to Try.
Try = ast.Try
else:
Try = ast.TryExcept
try:
body = expr.pop(0)
except IndexError:
@ -265,8 +301,45 @@ class HyASTCompiler(object):
expr.start_column)
orelse = []
if len(expr) == 0:
# (try) or (try body)
finalbody = []
handlers = []
for e in expr:
if not len(e):
raise HyTypeError(e, "Empty list not allowed in `try'")
if e[0] in (HySymbol("except"), HySymbol("catch")):
handlers.append(self.compile(e))
elif e[0] == HySymbol("else"):
if orelse:
raise HyTypeError(
e,
"`try' cannot have more than one `else'")
else:
orelse = self._code_branch(self.compile(e[1:]),
e.start_line,
e.start_column)
elif e[0] == HySymbol("finally"):
if finalbody:
raise HyTypeError(
e,
"`try' cannot have more than one `finally'")
else:
finalbody = self._code_branch(self.compile(e[1:]),
e.start_line,
e.start_column)
else:
raise HyTypeError(e, "Unknown expression in `try'")
# Using (else) without (except) is verboten!
if orelse and not handlers:
raise HyTypeError(
e,
"`try' cannot have `else' without `except'")
# (try) or (try BODY)
# Generate a default handler for Python >= 3.3 and pypy
if not handlers and not finalbody and not orelse:
handlers = [ast.ExceptHandler(
lineno=expr.start_line,
col_offset=expr.start_column,
@ -274,35 +347,41 @@ class HyASTCompiler(object):
name=None,
body=[ast.Pass(lineno=expr.start_line,
col_offset=expr.start_column)])]
else:
handlers = []
for e in expr:
if not len(e):
raise TypeError("Empty list not allowed in `try'")
if e[0] in (HySymbol("except"), HySymbol("catch")):
handlers.append(self.compile(e))
elif e[0] == HySymbol("else"):
if orelse:
raise TypeError(
"`try' cannot have more than one `else'")
else:
orelse = self._code_branch(self.compile(e[1:]),
e.start_line,
e.start_column)
else:
raise TypeError("Unknown expression in `try'")
if sys.version_info[0] >= 3 and sys.version_info[1] >= 3:
# Python 3.3 features a merge of TryExcept+TryFinally into Try.
return ast.Try(
lineno=expr.start_line,
col_offset=expr.start_column,
body=body,
handlers=handlers,
orelse=orelse,
finalbody=finalbody)
if handlers == []:
raise TypeError(
"`try' must have at least `except' or `finally'")
if finalbody:
if handlers:
return ast.TryFinally(
lineno=expr.start_line,
col_offset=expr.start_column,
body=[ast.TryExcept(
lineno=expr.start_line,
col_offset=expr.start_column,
handlers=handlers,
body=body,
orelse=orelse)],
finalbody=finalbody)
return Try(
return ast.TryFinally(
lineno=expr.start_line,
col_offset=expr.start_column,
body=body,
finalbody=finalbody)
return ast.TryExcept(
lineno=expr.start_line,
col_offset=expr.start_column,
body=body,
handlers=handlers,
finalbody=[],
body=body,
orelse=orelse)
@builds("catch")
@ -325,9 +404,11 @@ class HyASTCompiler(object):
# or
# []
if not isinstance(exceptions, HyList):
raise TypeError("`%s' exceptions list is not a list" % catch)
raise HyTypeError(exceptions,
"`%s' exceptions list is not a list" % catch)
if len(exceptions) > 2:
raise TypeError("`%s' exceptions list is too long" % catch)
raise HyTypeError(exceptions,
"`%s' exceptions list is too long" % catch)
# [variable [list of exceptions]]
# let's pop variable and use it as name
@ -365,7 +446,8 @@ class HyASTCompiler(object):
elif isinstance(exceptions_list, HySymbol):
_type = self.compile(exceptions_list)
else:
raise TypeError("`%s' needs a valid exception list" % catch)
raise HyTypeError(exceptions,
"`%s' needs a valid exception list" % catch)
body = self._code_branch([self.compile(x) for x in expr],
expr.start_line,
@ -460,27 +542,83 @@ class HyASTCompiler(object):
kw_defaults=[]),
body=self.compile(body))
@builds("pass")
@checkargs(0)
def compile_pass_expression(self, expr):
return ast.Pass(lineno=expr.start_line, col_offset=expr.start_column)
@builds("yield")
@checkargs(1)
@checkargs(max=1)
def compile_yield_expression(self, expr):
expr.pop(0)
value = None
if expr != []:
value = self.compile(expr.pop(0))
return ast.Yield(
value=self.compile(expr.pop(0)),
value=value,
lineno=expr.start_line,
col_offset=expr.start_column)
@builds("import")
def compile_import_expression(self, expr):
def _compile_import(expr, module, names=None, importer=ast.Import):
return [
importer(
lineno=expr.start_line,
col_offset=expr.start_column,
module=ast_str(module),
names=names or [
ast.alias(name=ast_str(module), asname=None)
],
level=0)
]
expr.pop(0) # index
return ast.Import(
lineno=expr.start_line,
col_offset=expr.start_column,
names=[ast.alias(name=ast_str(x), asname=None) for x in expr])
rimports = []
while len(expr) > 0:
iexpr = expr.pop(0)
if isinstance(iexpr, HySymbol):
rimports += _compile_import(expr, iexpr)
continue
if isinstance(iexpr, HyList) and len(iexpr) == 1:
rimports += _compile_import(expr, iexpr.pop(0))
continue
if isinstance(iexpr, HyList) and iexpr:
module = iexpr.pop(0)
entry = iexpr[0]
if isinstance(entry, HyKeyword) and entry == HyKeyword(":as"):
assert len(iexpr) == 2, "garbage after aliased import"
iexpr.pop(0) # :as
alias = iexpr.pop(0)
rimports += _compile_import(
expr,
ast_str(module),
[
ast.alias(name=ast_str(module),
asname=ast_str(alias))
]
)
continue
if isinstance(entry, HyList):
names = []
while entry:
sym = entry.pop(0)
if entry and isinstance(entry[0], HyKeyword):
entry.pop(0)
alias = ast_str(entry.pop(0))
else:
alias = None
names += [
ast.alias(name=ast_str(sym),
asname=alias)
]
rimports += _compile_import(expr, module,
names, ast.ImportFrom)
continue
raise TypeError("Unknown entry (`%s`) in the HyList" % (entry))
return rimports
@builds("import_as")
def compile_import_as_expression(self, expr):
@ -568,7 +706,7 @@ class HyASTCompiler(object):
expr.pop(0) # decorate-with
fn = self.compile(expr.pop(-1))
if type(fn) != ast.FunctionDef:
raise TypeError("Decorated a non-function")
raise HyTypeError(expr, "Decorated a non-function")
fn.decorator_list = [self.compile(x) for x in expr]
return fn
@ -579,7 +717,7 @@ class HyASTCompiler(object):
args = expr.pop(0)
if len(args) > 2 or len(args) < 1:
raise TypeError("with needs [arg (expr)] or [(expr)]")
raise HyTypeError(expr, "with needs [arg (expr)] or [(expr)]")
args.reverse()
ctx = self.compile(args.pop(0))
@ -653,7 +791,10 @@ class HyASTCompiler(object):
kwargs = expr.pop(0)
if type(call) != ast.Call:
raise TypeError("kwapplying a non-call")
raise HyTypeError(expr, "kwapplying a non-call")
if type(kwargs) != HyDict:
raise TypeError("kwapplying with a non-dict")
call.keywords = [ast.keyword(arg=ast_str(x),
value=self.compile(kwargs[x])) for x in kwargs]
@ -721,18 +862,28 @@ class HyASTCompiler(object):
@builds("%")
@builds("-")
@builds("/")
@builds("//")
@builds("*")
@builds("**")
@builds("<<")
@builds(">>")
@builds("|")
@builds("^")
@builds("&")
@checkargs(min=2)
def compile_maths_expression(self, expression):
# operator = Mod | Pow | LShift | RShift | BitOr |
# BitXor | BitAnd | FloorDiv
# (to implement list) XXX
ops = {"+": ast.Add,
"/": ast.Div,
"//": ast.FloorDiv,
"*": ast.Mult,
"-": ast.Sub,
"%": ast.Mod}
"%": ast.Mod,
"**": ast.Pow,
"<<": ast.LShift,
">>": ast.RShift,
"|": ast.BitOr,
"^": ast.BitXor,
"&": ast.BitAnd}
inv = expression.pop(0)
op = ops[inv]
@ -748,6 +899,45 @@ class HyASTCompiler(object):
left = calc
return calc
@builds("+=")
@builds("/=")
@builds("//=")
@builds("*=")
@builds("_=")
@builds("%=")
@builds("**=")
@builds("<<=")
@builds(">>=")
@builds("|=")
@builds("^=")
@builds("&=")
@checkargs(2)
def compile_augassign_expression(self, expression):
ops = {"+=": ast.Add,
"/=": ast.Div,
"//=": ast.FloorDiv,
"*=": ast.Mult,
"_=": ast.Sub,
"%=": ast.Mod,
"**=": ast.Pow,
"<<=": ast.LShift,
">>=": ast.RShift,
"|=": ast.BitOr,
"^=": ast.BitXor,
"&=": ast.BitAnd}
op = ops[expression[0]]
target = self._storeize(self.compile(expression[1]))
value = self.compile(expression[2])
return ast.AugAssign(
target=target,
value=value,
op=op(),
lineno=expression.start_line,
col_offset=expression.start_column)
def compile_dotted_expression(self, expr):
ofn = expr.pop(0) # .join
@ -779,6 +969,11 @@ class HyASTCompiler(object):
if expression[0].startswith("."):
return self.compile_dotted_expression(expression)
if isinstance(fn, HyKeyword):
new_expr = HyExpression(["get", expression[1], fn])
new_expr.start_line = expression.start_line
new_expr.start_column = expression.start_column
return self.compile_index_expression(new_expr)
return ast.Call(func=self.compile(fn),
args=[self.compile(x) for x in expression[1:]],
@ -822,6 +1017,19 @@ class HyASTCompiler(object):
name, iterable = expression.pop(0)
target = self._storeize(self.compile_symbol(name))
orelse = []
# (foreach [] body (else …))
if expression and expression[-1][0] == HySymbol("else"):
else_expr = expression.pop()
if len(else_expr) > 2:
# XXX use HyTypeError as soon as it lands
raise TypeError("`else' statement in `foreach' is too long")
elif len(else_expr) == 2:
orelse = self._code_branch(
self.compile(else_expr[1]),
else_expr[1].start_line,
else_expr[1].start_column)
ret = ast.For(lineno=expression.start_line,
col_offset=expression.start_column,
target=target,
@ -830,7 +1038,7 @@ class HyASTCompiler(object):
[self.compile(x) for x in expression],
expression.start_line,
expression.start_column),
orelse=[])
orelse=orelse)
self.returnable = ret_status
return ret
@ -909,8 +1117,20 @@ class HyASTCompiler(object):
return ret
@builds(HyInteger)
def compile_number(self, number):
return ast.Num(n=int(number), # See HyInteger above.
def compile_integer(self, number):
return ast.Num(n=int(number),
lineno=number.start_line,
col_offset=number.start_column)
@builds(HyFloat)
def compile_float(self, number):
return ast.Num(n=float(number),
lineno=number.start_line,
col_offset=number.start_column)
@builds(HyComplex)
def compile_complex(self, number):
return ast.Num(n=complex(number),
lineno=number.start_line,
col_offset=number.start_column)
@ -937,9 +1157,14 @@ class HyASTCompiler(object):
@builds(HyString)
def compile_string(self, string):
return ast.Str(s=ast_str(string), lineno=string.start_line,
return ast.Str(s=str_type(string), lineno=string.start_line,
col_offset=string.start_column)
@builds(HyKeyword)
def compile_keyword(self, keyword):
return ast.Str(s=str_type(keyword), lineno=keyword.start_line,
col_offset=keyword.start_column)
@builds(HyDict)
def compile_dict(self, m):
keys = []
@ -961,5 +1186,39 @@ def hy_compile(tree, root=None):
tlo = root
if root is None:
tlo = ast.Module
ret = tlo(body=compiler._mangle_branch(compiler.compile(tree), 0, 0))
_ast = compiler.compile(tree)
if type(_ast) == list:
_ast = compiler._mangle_branch(_ast, 0, 0)
if hasattr(sys, "subversion"):
implementation = sys.subversion[0].lower()
elif hasattr(sys, "implementation"):
implementation = sys.implementation.name.lower()
imports = []
for package in compiler.imports:
imported = set()
syms = compiler.imports[package]
for entry, form in syms:
if entry in imported:
continue
replace = form
if implementation != "cpython":
# using form causes pypy to blow up; let's conditionally
# add this for cpython, since it won't go through and make
# sure the AST makes sense. Muhahaha. - PRT
replace = tree[0]
imported.add(entry)
imports.append(HyExpression([
HySymbol("import_from"),
HySymbol(package),
HySymbol(entry)
]).replace(replace))
_ast = compiler.compile(imports) + _ast
ret = tlo(body=_ast)
return ret

View File

@ -41,7 +41,7 @@ class HoistableMangle(hy.mangle.Mangle):
class FunctionMangle(HoistableMangle):
hoistable = ["fn"]
ignore = ["def", "decorate_with", "setf", "setv"]
ignore = ["def", "decorate_with", "setf", "setv", "foreach", "do"]
def __init__(self):
self.series = 0
@ -65,7 +65,7 @@ class FunctionMangle(HoistableMangle):
class IfMangle(HoistableMangle):
ignore = []
ignore = ["foreach", "do"]
def __init__(self):
self.series = 0

View File

@ -18,8 +18,9 @@
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from hy.compiler import hy_compile
from py_compile import wr_long, MAGIC
from hy.compiler import hy_compile
from hy.models import HyObject
from hy.core import process
from hy.lex import tokenize
@ -28,13 +29,21 @@ from io import open
import marshal
import imp
import sys
import ast
import os
import __future__
if sys.version_info[0] >= 3:
from io import StringIO
long_type = int
else:
from StringIO import StringIO # NOQA
import __builtin__
long_type = long # NOQA
def compile_(ast, filename, mode):
return compile(ast, filename, mode, __future__.CO_FUTURE_DIVISION)
def import_buffer_to_hst(fd):
@ -49,38 +58,60 @@ def import_file_to_hst(fpath):
def import_file_to_ast(fpath):
tree = import_file_to_hst(fpath)
ast = hy_compile(tree)
return ast
_ast = hy_compile(tree)
return _ast
def import_string_to_ast(buff):
tree = import_buffer_to_hst(StringIO(buff))
ast = hy_compile(tree)
return ast
_ast = hy_compile(tree)
return _ast
def import_file_to_module(name, fpath):
ast = import_file_to_ast(fpath)
_ast = import_file_to_ast(fpath)
mod = imp.new_module(name)
mod.__file__ = fpath
eval(compile(ast, fpath, "exec"), mod.__dict__)
eval(compile_(_ast, fpath, "exec"), mod.__dict__)
return mod
def hy_eval(hytree, namespace):
foo = HyObject()
foo.start_line = 0
foo.end_line = 0
foo.start_column = 0
foo.end_column = 0
hytree.replace(foo)
_ast = hy_compile(hytree, root=ast.Expression)
return eval(compile_(_ast, "<eval>", "eval"), namespace)
def write_hy_as_pyc(fname):
with open(fname, 'U') as f:
try:
timestamp = long(os.fstat(f.fileno()).st_mtime)
st = os.fstat(f.fileno())
except AttributeError:
timestamp = long(os.stat(fname).st_mtime)
st = os.stat(fname)
timestamp = long_type(st.st_mtime)
_ast = import_file_to_ast(fname)
code = compile(_ast, fname, "exec")
code = compile_(_ast, fname, "exec")
cfile = "%s.pyc" % fname[:-len(".hy")]
with open(cfile, 'wb') as fc:
fc.write('\0\0\0\0')
if sys.version_info[0] >= 3:
open_ = open
else:
open_ = __builtin__.open
with open_(cfile, 'wb') as fc:
if sys.version_info[0] >= 3:
fc.write(b'\0\0\0\0')
else:
fc.write('\0\0\0\0')
wr_long(fc, timestamp)
if (sys.version_info[0] >= 3 and sys.version_info[1] >= 3):
wr_long(fc, st.st_size)
marshal.dump(code, fc)
fc.flush()
fc.seek(0, 0)

View File

@ -21,8 +21,11 @@
from hy.models.expression import HyExpression
from hy.models.integer import HyInteger
from hy.models.lambdalist import HyLambdaListKeyword
from hy.models.float import HyFloat
from hy.models.complex import HyComplex
from hy.models.symbol import HySymbol
from hy.models.string import HyString
from hy.models.keyword import HyKeyword
from hy.models.dict import HyDict
from hy.models.list import HyList
@ -47,6 +50,8 @@ def _resolve_atom(obj):
- Integer
- LambdaListKeyword
- Float
- Complex
- Symbol
"""
try:
@ -57,6 +62,16 @@ def _resolve_atom(obj):
if obj.startswith("&"):
return HyLambdaListKeyword(obj)
try:
return HyFloat(obj)
except ValueError:
pass
try:
return HyComplex(obj)
except ValueError:
pass
table = {
"true": "True",
"false": "False",
@ -66,7 +81,10 @@ def _resolve_atom(obj):
if obj in table:
return HySymbol(table[obj])
if obj.startswith("*") and obj.endswith("*") and obj != "*":
if obj.startswith(":"):
return HyKeyword(obj)
if obj.startswith("*") and obj.endswith("*") and obj not in ("*", "**"):
obj = obj[1:-1].upper()
if "-" in obj and obj != "-":
@ -260,6 +278,46 @@ class String(State):
self.nodes.append(char)
class Atom(State):
"""
This state parses integer constants, boolean constants, and symbols
"""
def __init__(self, machine):
State.__init__(self, machine)
self.initial_buf = ''
def enter(self):
self.buf = self.initial_buf
def exit(self):
self.result = _resolve_atom(self.buf)
def process(self, char):
"""
State transitions:
- WHITESPACE - Idle
- ; - Comment
"""
if char in WHITESPACE:
return Idle
if char == ";":
return Comment
self.buf += char
def AtomStartingWith(initial_char):
def AtomFactory(machine):
state = Atom(machine)
state.initial_buf = initial_char
return state
return AtomFactory
class Idle(State):
"""
Idle state. This is the first (and last) thing that we should
@ -271,7 +329,12 @@ class Idle(State):
State transitions:
- ( - Expression
- (default) - Error
- [ - List
- { - Dict
- \" - String
- ; - Comment
- # - Hash
- (default) - Atom
"""
if char == "(":
@ -283,6 +346,9 @@ class Idle(State):
if char == "{":
return Dict
if char == "\"":
return String
if char == ";":
return Comment
@ -292,7 +358,7 @@ class Idle(State):
if char in WHITESPACE:
return
raise LexException("Unknown char (Idle state): `{0}`".format(char))
return AtomStartingWith(char)
class Comment(State):

View File

@ -34,3 +34,5 @@ class HyObject(object):
setattr(self, attr, getattr(other, attr))
else:
raise TypeError("Can't replace a non Hy object with a Hy object")
return self

32
hy/models/complex.py Normal file
View File

@ -0,0 +1,32 @@
# Copyright (c) 2013 Paul Tagliamonte <paultag@debian.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from hy.models import HyObject
class HyComplex(HyObject, complex):
"""
Internal represntation of a Hy Complex. May raise a ValueError as if
complex(foo) was called, given HyComplex(foo).
"""
def __new__(cls, number, *args, **kwargs):
number = complex(number)
return super(HyComplex, cls).__new__(cls, number)

32
hy/models/float.py Normal file
View File

@ -0,0 +1,32 @@
# Copyright (c) 2013 Paul Tagliamonte <paultag@debian.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from hy.models import HyObject
class HyFloat(HyObject, float):
"""
Internal represntation of a Hy Float. May raise a ValueError as if
float(foo) was called, given HyFloat(foo).
"""
def __new__(cls, number, *args, **kwargs):
number = float(number)
return super(HyFloat, cls).__new__(cls, number)

33
hy/models/keyword.py Normal file
View File

@ -0,0 +1,33 @@
# Copyright (c) 2013 Gergely Nagy <algernon@madhouse-project.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from __future__ import unicode_literals
from hy.models import HyObject
from hy.util import str_type
class HyKeyword(HyObject, str_type):
"""Generic Hy Keyword object. It's either a ``str`` or a ``unicode``,
depending on the Python version.
"""
def __new__(cls, value):
obj = str_type.__new__(cls, "\uFDD0" + value)
return obj

View File

@ -31,6 +31,7 @@ class HyList(HyObject, list):
x.replace(other)
HyObject.replace(self, other)
return self
def __repr__(self):
return "[%s]" % (" ".join([str(x) for x in self]))

View File

@ -19,13 +19,7 @@
# DEALINGS IN THE SOFTWARE.
from hy.models import HyObject
import sys
if sys.version_info[0] >= 3:
str_type = str
else:
str_type = unicode
from hy.util import str_type
class HyString(HyObject, str_type):

View File

@ -19,6 +19,13 @@
# DEALINGS IN THE SOFTWARE.
import ast
import sys
if sys.version_info[0] >= 3:
str_type = str
else:
str_type = unicode
def flatten_literal_list(entry):

View File

@ -1,9 +0,0 @@
#!/bin/bash
metatron() {
ssh metatron.pault.ag $@
}
metatron "cd /srv/www/uwsgi/app/hy; git pull"
metatron "cd /srv/www/uwsgi/app/hy/site; make"
metatron -l www "kill-apps; start-apps"

15
maintainer-scripts/update.sh Executable file
View File

@ -0,0 +1,15 @@
#!/bin/bash
function metatron {
ssh metatron.pault.ag $@
}
function www {
metatron -l www $@
}
metatron "cd /opt/hylang/hy; git pull"
metatron "cd /srv/www/uwsgi/app/shyte; git pull; make"
www "kill-apps"
www "start-apps"

View File

@ -1,4 +0,0 @@
flask
astor
pygments
autopep8

1
site/.gitignore vendored
View File

@ -1 +0,0 @@
static/

View File

@ -1,48 +0,0 @@
STATIC = static
STATIC_CSS = $(STATIC)/css
STATIC_JS = $(STATIC)/js
all: hello deps build
hello:
@cowsay 'Welcome to Hy!'
build: clean css js
css: less
cp -rv css/* $(STATIC_CSS)
js: coffee
cp -rv js/* $(STATIC_JS)
less:
make -C less
mv -v less/*css $(STATIC_CSS)
coffee:
make -C coffee
mv -v coffee/*js $(STATIC_JS)
clean:
rm -fr $(STATIC_CSS) $(STATIC_JS)
mkdir -p $(STATIC_CSS) $(STATIC_JS)
devel:
@./devel.sh
deps:
set -e; for x in $(shell cat dependencies); do \
echo "Checking for dependency: $$x"; \
dpkg-query -s $$x >/dev/null 2>&1; \
done;
.PHONY: build clean less coffee devel

View File

@ -1,33 +0,0 @@
; Copyright (c) Paul R. Tagliamonte <tag@pault.ag>, 2013 under the terms of
; hy.
(import-from flask
Flask render-template request make-response)
(import-from hy.errors HyError)
(import-from hy.lex LexException)
(import-from hy.importer import-string-to-ast)
(import astor.codegen)
(import autopep8)
(setv app (Flask "__main__")) ; long story, needed hack
(defn hy-to-py [hython]
(.fix-string autopep8
(.to_source astor.codegen (import-string-to-ast hython))))
(defn err [msg] (make-response msg 500))
; view routes
(route index "/" [] (render-template "repl.html"))
(post-route hy2py "/hy2py" []
(try
(hy-to-py (get request.form "code"))
(catch [e LexException] (err "Incomplete Code."))
(catch [e HyError] (err "Generic error during processing."))
(catch [e Exception] (err "Erm, you broke something."))))

View File

@ -1,18 +0,0 @@
.SUFFIXES:
.SUFFIXES: .coffee .js
COFFEE_SCRIPTS = main.js
all: build
build: $(COFFEE_SCRIPTS)
.coffee.js:
coffee -c $<
uglifyjs --no-copyright --overwrite $@
.PHONY: build

View File

@ -1,73 +0,0 @@
# Copyright (c) 2012 Paul Tagliamonte <paultag@debian.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
theme = "elegant"
HyCodeMirror = CodeMirror.fromTextArea($('#hython-target')[0], {
mode: "clojure",
theme: theme,
autofocus: true,
})
PyCodeMirror = CodeMirror($('#python-repl')[0], {
mode: "python",
theme: theme,
readOnly: true,
})
PyCodeMirror.setSize("100%", "100%")
HyCodeMirror.setSize("100%", "100%")
reload = ->
input = HyCodeMirror.getValue()
format = "h:mm:ss"
$.ajax({
url: "/hy2py",
type: "POST",
data: {'code': input},
success: (result) ->
PyCodeMirror.setValue(result)
now = Date.parse("now").toString(format)
$("#build-msgs").prepend(now + " updated.<br />")
$("#repl-root").removeClass("error")
$("#repl-root").addClass("ok")
statusCode: {
500: (response) ->
now = Date.parse("now").toString(format)
$("#build-msgs").prepend(now + " " + response.responseText + "<br />")
$("#repl-root").removeClass("ok")
$("#repl-root").addClass("error")
}
})
$(document).ready(->
count = 0
HyCodeMirror.on("change", (instance, cob) ->
count += 1
curcount = count
window.setTimeout(->
if curcount == count
reload()
, 500)
)
reload()
)

View File

@ -1,240 +0,0 @@
/* BASICS */
.CodeMirror {
/* Set height, width, borders, and global font properties here */
font-family: monospace;
height: 300px;
}
.CodeMirror-scroll {
/* Set scrolling behaviour here */
overflow: auto;
}
/* PADDING */
.CodeMirror-lines {
padding: 4px 0; /* Vertical padding around content */
}
.CodeMirror pre {
padding: 0 4px; /* Horizontal padding of content */
}
.CodeMirror-scrollbar-filler {
background-color: white; /* The little square between H and V scrollbars */
}
/* GUTTER */
.CodeMirror-gutters {
border-right: 1px solid #ddd;
background-color: #f7f7f7;
}
.CodeMirror-linenumbers {}
.CodeMirror-linenumber {
padding: 0 3px 0 5px;
min-width: 20px;
text-align: right;
color: #999;
}
/* CURSOR */
.CodeMirror div.CodeMirror-cursor {
border-left: 1px solid black;
z-index: 3;
}
/* Shown when moving in bi-directional text */
.CodeMirror div.CodeMirror-secondarycursor {
border-left: 1px solid silver;
}
.CodeMirror.cm-keymap-fat-cursor div.CodeMirror-cursor {
width: auto;
border: 0;
background: #7e7;
z-index: 1;
}
/* Can style cursor different in overwrite (non-insert) mode */
.CodeMirror div.CodeMirror-cursor.CodeMirror-overwrite {}
/* DEFAULT THEME */
.cm-s-default .cm-keyword {color: #708;}
.cm-s-default .cm-atom {color: #219;}
.cm-s-default .cm-number {color: #164;}
.cm-s-default .cm-def {color: #00f;}
.cm-s-default .cm-variable {color: black;}
.cm-s-default .cm-variable-2 {color: #05a;}
.cm-s-default .cm-variable-3 {color: #085;}
.cm-s-default .cm-property {color: black;}
.cm-s-default .cm-operator {color: black;}
.cm-s-default .cm-comment {color: #a50;}
.cm-s-default .cm-string {color: #a11;}
.cm-s-default .cm-string-2 {color: #f50;}
.cm-s-default .cm-meta {color: #555;}
.cm-s-default .cm-error {color: #f00;}
.cm-s-default .cm-qualifier {color: #555;}
.cm-s-default .cm-builtin {color: #30a;}
.cm-s-default .cm-bracket {color: #997;}
.cm-s-default .cm-tag {color: #170;}
.cm-s-default .cm-attribute {color: #00c;}
.cm-s-default .cm-header {color: blue;}
.cm-s-default .cm-quote {color: #090;}
.cm-s-default .cm-hr {color: #999;}
.cm-s-default .cm-link {color: #00c;}
.cm-negative {color: #d44;}
.cm-positive {color: #292;}
.cm-header, .cm-strong {font-weight: bold;}
.cm-em {font-style: italic;}
.cm-link {text-decoration: underline;}
.cm-invalidchar {color: #f00;}
div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
/* STOP */
/* The rest of this file contains styles related to the mechanics of
the editor. You probably shouldn't touch them. */
.CodeMirror {
line-height: 1;
position: relative;
overflow: hidden;
}
.CodeMirror-scroll {
/* 30px is the magic margin used to hide the element's real scrollbars */
/* See overflow: hidden in .CodeMirror, and the paddings in .CodeMirror-sizer */
margin-bottom: -30px; margin-right: -30px;
padding-bottom: 30px; padding-right: 30px;
height: 100%;
outline: none; /* Prevent dragging from highlighting the element */
position: relative;
}
.CodeMirror-sizer {
position: relative;
}
/* The fake, visible scrollbars. Used to force redraw during scrolling
before actuall scrolling happens, thus preventing shaking and
flickering artifacts. */
.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler {
position: absolute;
z-index: 6;
display: none;
}
.CodeMirror-vscrollbar {
right: 0; top: 0;
overflow-x: hidden;
overflow-y: scroll;
}
.CodeMirror-hscrollbar {
bottom: 0; left: 0;
overflow-y: hidden;
overflow-x: scroll;
}
.CodeMirror-scrollbar-filler {
right: 0; bottom: 0;
z-index: 6;
}
.CodeMirror-gutters {
position: absolute; left: 0; top: 0;
height: 100%;
padding-bottom: 30px;
z-index: 3;
}
.CodeMirror-gutter {
height: 100%;
display: inline-block;
/* Hack to make IE7 behave */
*zoom:1;
*display:inline;
}
.CodeMirror-gutter-elt {
position: absolute;
cursor: default;
z-index: 4;
}
.CodeMirror-lines {
cursor: text;
}
.CodeMirror pre {
/* Reset some styles that the rest of the page might have set */
-moz-border-radius: 0; -webkit-border-radius: 0; -o-border-radius: 0; border-radius: 0;
border-width: 0;
background: transparent;
font-family: inherit;
font-size: inherit;
margin: 0;
white-space: pre;
word-wrap: normal;
line-height: inherit;
color: inherit;
z-index: 2;
position: relative;
overflow: visible;
}
.CodeMirror-wrap pre {
word-wrap: break-word;
white-space: pre-wrap;
word-break: normal;
}
.CodeMirror-linebackground {
position: absolute;
left: 0; right: 0; top: 0; bottom: 0;
z-index: 0;
}
.CodeMirror-linewidget {
position: relative;
z-index: 2;
overflow: auto;
}
.CodeMirror-widget {
display: inline-block;
}
.CodeMirror-wrap .CodeMirror-scroll {
overflow-x: hidden;
}
.CodeMirror-measure {
position: absolute;
width: 100%; height: 0px;
overflow: hidden;
visibility: hidden;
}
.CodeMirror-measure pre { position: static; }
.CodeMirror div.CodeMirror-cursor {
position: absolute;
visibility: hidden;
border-right: none;
width: 0;
}
.CodeMirror-focused div.CodeMirror-cursor {
visibility: visible;
}
.CodeMirror-selected { background: #d9d9d9; }
.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
.cm-searching {
background: #ffa;
background: rgba(255, 255, 0, .4);
}
/* IE7 hack to prevent it from returning funny offsetTops on the spans */
.CodeMirror span { *vertical-align: text-bottom; }
@media print {
/* Hide the cursor when printing */
.CodeMirror div.CodeMirror-cursor {
visibility: hidden;
}
}

View File

@ -1,61 +0,0 @@
.hll { background-color: #ffffcc }
.c { color: #408080; font-style: italic } /* Comment */
.err { border: 1px solid #FF0000 } /* Error */
.k { color: #008000; font-weight: bold } /* Keyword */
.o { color: #666666 } /* Operator */
.cm { color: #408080; font-style: italic } /* Comment.Multiline */
.cp { color: #BC7A00 } /* Comment.Preproc */
.c1 { color: #408080; font-style: italic } /* Comment.Single */
.cs { color: #408080; font-style: italic } /* Comment.Special */
.gd { color: #A00000 } /* Generic.Deleted */
.ge { font-style: italic } /* Generic.Emph */
.gr { color: #FF0000 } /* Generic.Error */
.gh { color: #000080; font-weight: bold } /* Generic.Heading */
.gi { color: #00A000 } /* Generic.Inserted */
.go { color: #808080 } /* Generic.Output */
.gp { color: #000080; font-weight: bold } /* Generic.Prompt */
.gs { font-weight: bold } /* Generic.Strong */
.gu { color: #800080; font-weight: bold } /* Generic.Subheading */
.gt { color: #0040D0 } /* Generic.Traceback */
.kc { color: #008000; font-weight: bold } /* Keyword.Constant */
.kd { color: #008000; font-weight: bold } /* Keyword.Declaration */
.kn { color: #008000; font-weight: bold } /* Keyword.Namespace */
.kp { color: #008000 } /* Keyword.Pseudo */
.kr { color: #008000; font-weight: bold } /* Keyword.Reserved */
.kt { color: #B00040 } /* Keyword.Type */
.m { color: #666666 } /* Literal.Number */
.s { color: #BA2121 } /* Literal.String */
.na { color: #7D9029 } /* Name.Attribute */
.nb { color: #008000 } /* Name.Builtin */
.nc { color: #0000FF; font-weight: bold } /* Name.Class */
.no { color: #880000 } /* Name.Constant */
.nd { color: #AA22FF } /* Name.Decorator */
.ni { color: #999999; font-weight: bold } /* Name.Entity */
.ne { color: #D2413A; font-weight: bold } /* Name.Exception */
.nf { color: #0000FF } /* Name.Function */
.nl { color: #A0A000 } /* Name.Label */
.nn { color: #0000FF; font-weight: bold } /* Name.Namespace */
.nt { color: #008000; font-weight: bold } /* Name.Tag */
.nv { color: #19177C } /* Name.Variable */
.ow { color: #AA22FF; font-weight: bold } /* Operator.Word */
.w { color: #bbbbbb } /* Text.Whitespace */
.mf { color: #666666 } /* Literal.Number.Float */
.mh { color: #666666 } /* Literal.Number.Hex */
.mi { color: #666666 } /* Literal.Number.Integer */
.mo { color: #666666 } /* Literal.Number.Oct */
.sb { color: #BA2121 } /* Literal.String.Backtick */
.sc { color: #BA2121 } /* Literal.String.Char */
.sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */
.s2 { color: #BA2121 } /* Literal.String.Double */
.se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */
.sh { color: #BA2121 } /* Literal.String.Heredoc */
.si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */
.sx { color: #008000 } /* Literal.String.Other */
.sr { color: #BB6688 } /* Literal.String.Regex */
.s1 { color: #BA2121 } /* Literal.String.Single */
.ss { color: #19177C } /* Literal.String.Symbol */
.bp { color: #008000 } /* Name.Builtin.Pseudo */
.vc { color: #19177C } /* Name.Variable.Class */
.vg { color: #19177C } /* Name.Variable.Global */
.vi { color: #19177C } /* Name.Variable.Instance */
.il { color: #666666 } /* Literal.Number.Integer.Long */

View File

@ -1,6 +0,0 @@
.cm-s-ambiance.CodeMirror {
-webkit-box-shadow: none;
-moz-box-shadow: none;
-o-box-shadow: none;
box-shadow: none;
}

File diff suppressed because one or more lines are too long

View File

@ -1,25 +0,0 @@
/* Port of TextMate's Blackboard theme */
.cm-s-blackboard.CodeMirror { background: #0C1021; color: #F8F8F8; }
.cm-s-blackboard .CodeMirror-selected { background: #253B76 !important; }
.cm-s-blackboard .CodeMirror-gutters { background: #0C1021; border-right: 0; }
.cm-s-blackboard .CodeMirror-linenumber { color: #888; }
.cm-s-blackboard .CodeMirror-cursor { border-left: 1px solid #A7A7A7 !important; }
.cm-s-blackboard .cm-keyword { color: #FBDE2D; }
.cm-s-blackboard .cm-atom { color: #D8FA3C; }
.cm-s-blackboard .cm-number { color: #D8FA3C; }
.cm-s-blackboard .cm-def { color: #8DA6CE; }
.cm-s-blackboard .cm-variable { color: #FF6400; }
.cm-s-blackboard .cm-operator { color: #FBDE2D;}
.cm-s-blackboard .cm-comment { color: #AEAEAE; }
.cm-s-blackboard .cm-string { color: #61CE3C; }
.cm-s-blackboard .cm-string-2 { color: #61CE3C; }
.cm-s-blackboard .cm-meta { color: #D8FA3C; }
.cm-s-blackboard .cm-error { background: #9D1E15; color: #F8F8F8; }
.cm-s-blackboard .cm-builtin { color: #8DA6CE; }
.cm-s-blackboard .cm-tag { color: #8DA6CE; }
.cm-s-blackboard .cm-attribute { color: #8DA6CE; }
.cm-s-blackboard .cm-header { color: #FF6400; }
.cm-s-blackboard .cm-hr { color: #AEAEAE; }
.cm-s-blackboard .cm-link { color: #8DA6CE; }

View File

@ -1,18 +0,0 @@
.cm-s-cobalt.CodeMirror { background: #002240; color: white; }
.cm-s-cobalt div.CodeMirror-selected { background: #b36539 !important; }
.cm-s-cobalt .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; }
.cm-s-cobalt .CodeMirror-linenumber { color: #d0d0d0; }
.cm-s-cobalt .CodeMirror-cursor { border-left: 1px solid white !important; }
.cm-s-cobalt span.cm-comment { color: #08f; }
.cm-s-cobalt span.cm-atom { color: #845dc4; }
.cm-s-cobalt span.cm-number, .cm-s-cobalt span.cm-attribute { color: #ff80e1; }
.cm-s-cobalt span.cm-keyword { color: #ffee80; }
.cm-s-cobalt span.cm-string { color: #3ad900; }
.cm-s-cobalt span.cm-meta { color: #ff9d00; }
.cm-s-cobalt span.cm-variable-2, .cm-s-cobalt span.cm-tag { color: #9effff; }
.cm-s-cobalt span.cm-variable-3, .cm-s-cobalt span.cm-def { color: white; }
.cm-s-cobalt span.cm-error { color: #9d1e15; }
.cm-s-cobalt span.cm-bracket { color: #d8d8d8; }
.cm-s-cobalt span.cm-builtin, .cm-s-cobalt span.cm-special { color: #ff9e59; }
.cm-s-cobalt span.cm-link { color: #845dc4; }

View File

@ -1,25 +0,0 @@
.cm-s-eclipse span.cm-meta {color: #FF1717;}
.cm-s-eclipse span.cm-keyword { line-height: 1em; font-weight: bold; color: #7F0055; }
.cm-s-eclipse span.cm-atom {color: #219;}
.cm-s-eclipse span.cm-number {color: #164;}
.cm-s-eclipse span.cm-def {color: #00f;}
.cm-s-eclipse span.cm-variable {color: black;}
.cm-s-eclipse span.cm-variable-2 {color: #0000C0;}
.cm-s-eclipse span.cm-variable-3 {color: #0000C0;}
.cm-s-eclipse span.cm-property {color: black;}
.cm-s-eclipse span.cm-operator {color: black;}
.cm-s-eclipse span.cm-comment {color: #3F7F5F;}
.cm-s-eclipse span.cm-string {color: #2A00FF;}
.cm-s-eclipse span.cm-string-2 {color: #f50;}
.cm-s-eclipse span.cm-error {color: #f00;}
.cm-s-eclipse span.cm-qualifier {color: #555;}
.cm-s-eclipse span.cm-builtin {color: #30a;}
.cm-s-eclipse span.cm-bracket {color: #cc7;}
.cm-s-eclipse span.cm-tag {color: #170;}
.cm-s-eclipse span.cm-attribute {color: #00c;}
.cm-s-eclipse span.cm-link {color: #219;}
.cm-s-eclipse .CodeMirror-matchingbracket {
outline:1px solid grey;
color:black !important;;
}

View File

@ -1,10 +0,0 @@
.cm-s-elegant span.cm-number, .cm-s-elegant span.cm-string, .cm-s-elegant span.cm-atom {color: #762;}
.cm-s-elegant span.cm-comment {color: #262; font-style: italic; line-height: 1em;}
.cm-s-elegant span.cm-meta {color: #555; font-style: italic; line-height: 1em;}
.cm-s-elegant span.cm-variable {color: black;}
.cm-s-elegant span.cm-variable-2 {color: #b11;}
.cm-s-elegant span.cm-qualifier {color: #555;}
.cm-s-elegant span.cm-keyword {color: #730;}
.cm-s-elegant span.cm-builtin {color: #30a;}
.cm-s-elegant span.cm-error {background-color: #fdd;}
.cm-s-elegant span.cm-link {color: #762;}

View File

@ -1,21 +0,0 @@
.cm-s-erlang-dark.CodeMirror { background: #002240; color: white; }
.cm-s-erlang-dark div.CodeMirror-selected { background: #b36539 !important; }
.cm-s-erlang-dark .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; }
.cm-s-erlang-dark .CodeMirror-linenumber { color: #d0d0d0; }
.cm-s-erlang-dark .CodeMirror-cursor { border-left: 1px solid white !important; }
.cm-s-erlang-dark span.cm-atom { color: #845dc4; }
.cm-s-erlang-dark span.cm-attribute { color: #ff80e1; }
.cm-s-erlang-dark span.cm-bracket { color: #ff9d00; }
.cm-s-erlang-dark span.cm-builtin { color: #eeaaaa; }
.cm-s-erlang-dark span.cm-comment { color: #7777ff; }
.cm-s-erlang-dark span.cm-def { color: #ee77aa; }
.cm-s-erlang-dark span.cm-error { color: #9d1e15; }
.cm-s-erlang-dark span.cm-keyword { color: #ffee80; }
.cm-s-erlang-dark span.cm-meta { color: #50fefe; }
.cm-s-erlang-dark span.cm-number { color: #ffd0d0; }
.cm-s-erlang-dark span.cm-operator { color: #dd1111; }
.cm-s-erlang-dark span.cm-string { color: #3ad900; }
.cm-s-erlang-dark span.cm-tag { color: #9effff; }
.cm-s-erlang-dark span.cm-variable { color: #50fe50; }
.cm-s-erlang-dark span.cm-variable-2 { color: #ee00ee; }

View File

@ -1,44 +0,0 @@
/*
http://lesscss.org/ dark theme
Ported to CodeMirror by Peter Kroon
*/
.cm-s-lesser-dark {
line-height: 1.3em;
}
.cm-s-lesser-dark {
font-family: 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', 'Monaco', Courier, monospace !important;
}
.cm-s-lesser-dark.CodeMirror { background: #262626; color: #EBEFE7; text-shadow: 0 -1px 1px #262626; }
.cm-s-lesser-dark div.CodeMirror-selected {background: #45443B !important;} /* 33322B*/
.cm-s-lesser-dark .CodeMirror-cursor { border-left: 1px solid white !important; }
.cm-s-lesser-dark pre { padding: 0 8px; }/*editable code holder*/
div.CodeMirror span.CodeMirror-matchingbracket { color: #7EFC7E; }/*65FC65*/
.cm-s-lesser-dark .CodeMirror-gutters { background: #262626; border-right:1px solid #aaa; }
.cm-s-lesser-dark .CodeMirror-linenumber { color: #777; }
.cm-s-lesser-dark span.cm-keyword { color: #599eff; }
.cm-s-lesser-dark span.cm-atom { color: #C2B470; }
.cm-s-lesser-dark span.cm-number { color: #B35E4D; }
.cm-s-lesser-dark span.cm-def {color: white;}
.cm-s-lesser-dark span.cm-variable { color:#D9BF8C; }
.cm-s-lesser-dark span.cm-variable-2 { color: #669199; }
.cm-s-lesser-dark span.cm-variable-3 { color: white; }
.cm-s-lesser-dark span.cm-property {color: #92A75C;}
.cm-s-lesser-dark span.cm-operator {color: #92A75C;}
.cm-s-lesser-dark span.cm-comment { color: #666; }
.cm-s-lesser-dark span.cm-string { color: #BCD279; }
.cm-s-lesser-dark span.cm-string-2 {color: #f50;}
.cm-s-lesser-dark span.cm-meta { color: #738C73; }
.cm-s-lesser-dark span.cm-error { color: #9d1e15; }
.cm-s-lesser-dark span.cm-qualifier {color: #555;}
.cm-s-lesser-dark span.cm-builtin { color: #ff9e59; }
.cm-s-lesser-dark span.cm-bracket { color: #EBEFE7; }
.cm-s-lesser-dark span.cm-tag { color: #669199; }
.cm-s-lesser-dark span.cm-attribute {color: #00c;}
.cm-s-lesser-dark span.cm-header {color: #a0a;}
.cm-s-lesser-dark span.cm-quote {color: #090;}
.cm-s-lesser-dark span.cm-hr {color: #999;}
.cm-s-lesser-dark span.cm-link {color: #00c;}

View File

@ -1,28 +0,0 @@
/* Based on Sublime Text's Monokai theme */
.cm-s-monokai.CodeMirror {background: #272822; color: #f8f8f2;}
.cm-s-monokai div.CodeMirror-selected {background: #49483E !important;}
.cm-s-monokai .CodeMirror-gutters {background: #272822; border-right: 0px;}
.cm-s-monokai .CodeMirror-linenumber {color: #d0d0d0;}
.cm-s-monokai .CodeMirror-cursor {border-left: 1px solid #f8f8f0 !important;}
.cm-s-monokai span.cm-comment {color: #75715e;}
.cm-s-monokai span.cm-atom {color: #ae81ff;}
.cm-s-monokai span.cm-number {color: #ae81ff;}
.cm-s-monokai span.cm-property, .cm-s-monokai span.cm-attribute {color: #a6e22e;}
.cm-s-monokai span.cm-keyword {color: #f92672;}
.cm-s-monokai span.cm-string {color: #e6db74;}
.cm-s-monokai span.cm-variable {color: #a6e22e;}
.cm-s-monokai span.cm-variable-2 {color: #9effff;}
.cm-s-monokai span.cm-def {color: #fd971f;}
.cm-s-monokai span.cm-error {background: #f92672; color: #f8f8f0;}
.cm-s-monokai span.cm-bracket {color: #f8f8f2;}
.cm-s-monokai span.cm-tag {color: #f92672;}
.cm-s-monokai span.cm-link {color: #ae81ff;}
.cm-s-monokai .CodeMirror-matchingbracket {
text-decoration: underline;
color: white !important;
}

View File

@ -1,9 +0,0 @@
.cm-s-neat span.cm-comment { color: #a86; }
.cm-s-neat span.cm-keyword { line-height: 1em; font-weight: bold; color: blue; }
.cm-s-neat span.cm-string { color: #a22; }
.cm-s-neat span.cm-builtin { line-height: 1em; font-weight: bold; color: #077; }
.cm-s-neat span.cm-special { line-height: 1em; font-weight: bold; color: #0aa; }
.cm-s-neat span.cm-variable { color: black; }
.cm-s-neat span.cm-number, .cm-s-neat span.cm-atom { color: #3a3; }
.cm-s-neat span.cm-meta {color: #555;}
.cm-s-neat span.cm-link { color: #3a3; }

View File

@ -1,21 +0,0 @@
/* Loosely based on the Midnight Textmate theme */
.cm-s-night.CodeMirror { background: #0a001f; color: #f8f8f8; }
.cm-s-night div.CodeMirror-selected { background: #447 !important; }
.cm-s-night .CodeMirror-gutters { background: #0a001f; border-right: 1px solid #aaa; }
.cm-s-night .CodeMirror-linenumber { color: #f8f8f8; }
.cm-s-night .CodeMirror-cursor { border-left: 1px solid white !important; }
.cm-s-night span.cm-comment { color: #6900a1; }
.cm-s-night span.cm-atom { color: #845dc4; }
.cm-s-night span.cm-number, .cm-s-night span.cm-attribute { color: #ffd500; }
.cm-s-night span.cm-keyword { color: #599eff; }
.cm-s-night span.cm-string { color: #37f14a; }
.cm-s-night span.cm-meta { color: #7678e2; }
.cm-s-night span.cm-variable-2, .cm-s-night span.cm-tag { color: #99b2ff; }
.cm-s-night span.cm-variable-3, .cm-s-night span.cm-def { color: white; }
.cm-s-night span.cm-error { color: #9d1e15; }
.cm-s-night span.cm-bracket { color: #8da6ce; }
.cm-s-night span.cm-comment { color: #6900a1; }
.cm-s-night span.cm-builtin, .cm-s-night span.cm-special { color: #ff9e59; }
.cm-s-night span.cm-link { color: #845dc4; }

View File

@ -1,21 +0,0 @@
.cm-s-rubyblue { font:13px/1.4em Trebuchet, Verdana, sans-serif; } /* - customized editor font - */
.cm-s-rubyblue.CodeMirror { background: #112435; color: white; }
.cm-s-rubyblue div.CodeMirror-selected { background: #38566F !important; }
.cm-s-rubyblue .CodeMirror-gutters { background: #1F4661; border-right: 7px solid #3E7087; }
.cm-s-rubyblue .CodeMirror-linenumber { color: white; }
.cm-s-rubyblue .CodeMirror-cursor { border-left: 1px solid white !important; }
.cm-s-rubyblue span.cm-comment { color: #999; font-style:italic; line-height: 1em; }
.cm-s-rubyblue span.cm-atom { color: #F4C20B; }
.cm-s-rubyblue span.cm-number, .cm-s-rubyblue span.cm-attribute { color: #82C6E0; }
.cm-s-rubyblue span.cm-keyword { color: #F0F; }
.cm-s-rubyblue span.cm-string { color: #F08047; }
.cm-s-rubyblue span.cm-meta { color: #F0F; }
.cm-s-rubyblue span.cm-variable-2, .cm-s-rubyblue span.cm-tag { color: #7BD827; }
.cm-s-rubyblue span.cm-variable-3, .cm-s-rubyblue span.cm-def { color: white; }
.cm-s-rubyblue span.cm-error { color: #AF2018; }
.cm-s-rubyblue span.cm-bracket { color: #F0F; }
.cm-s-rubyblue span.cm-link { color: #F4C20B; }
.cm-s-rubyblue span.CodeMirror-matchingbracket { color:#F0F !important; }
.cm-s-rubyblue span.cm-builtin, .cm-s-rubyblue span.cm-special { color: #FF9D00; }

File diff suppressed because one or more lines are too long

View File

@ -1,26 +0,0 @@
.cm-s-twilight.CodeMirror { background: #141414; color: #f7f7f7; } /**/
.cm-s-twilight .CodeMirror-selected { background: #323232 !important; } /**/
.cm-s-twilight .CodeMirror-gutters { background: #222; border-right: 1px solid #aaa; }
.cm-s-twilight .CodeMirror-linenumber { color: #aaa; }
.cm-s-twilight .CodeMirror-cursor { border-left: 1px solid white !important; }
.cm-s-twilight .cm-keyword { color: #f9ee98; } /**/
.cm-s-twilight .cm-atom { color: #FC0; }
.cm-s-twilight .cm-number { color: #ca7841; } /**/
.cm-s-twilight .cm-def { color: #8DA6CE; }
.cm-s-twilight span.cm-variable-2, .cm-s-twilight span.cm-tag { color: #607392; } /**/
.cm-s-twilight span.cm-variable-3, .cm-s-twilight span.cm-def { color: #607392; } /**/
.cm-s-twilight .cm-operator { color: #cda869; } /**/
.cm-s-twilight .cm-comment { color:#777; font-style:italic; font-weight:normal; } /**/
.cm-s-twilight .cm-string { color:#8f9d6a; font-style:italic; } /**/
.cm-s-twilight .cm-string-2 { color:#bd6b18 } /*?*/
.cm-s-twilight .cm-meta { background-color:#141414; color:#f7f7f7; } /*?*/
.cm-s-twilight .cm-error { border-bottom: 1px solid red; }
.cm-s-twilight .cm-builtin { color: #cda869; } /*?*/
.cm-s-twilight .cm-tag { color: #997643; } /**/
.cm-s-twilight .cm-attribute { color: #d6bb6d; } /*?*/
.cm-s-twilight .cm-header { color: #FF6400; }
.cm-s-twilight .cm-hr { color: #AEAEAE; }
.cm-s-twilight .cm-link { color:#ad9361; font-style:italic; text-decoration:none; } /**/

View File

@ -1,27 +0,0 @@
/* Taken from the popular Visual Studio Vibrant Ink Schema */
.cm-s-vibrant-ink.CodeMirror { background: black; color: white; }
.cm-s-vibrant-ink .CodeMirror-selected { background: #35493c !important; }
.cm-s-vibrant-ink .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; }
.cm-s-vibrant-ink .CodeMirror-linenumber { color: #d0d0d0; }
.cm-s-vibrant-ink .CodeMirror-cursor { border-left: 1px solid white !important; }
.cm-s-vibrant-ink .cm-keyword { color: #CC7832; }
.cm-s-vibrant-ink .cm-atom { color: #FC0; }
.cm-s-vibrant-ink .cm-number { color: #FFEE98; }
.cm-s-vibrant-ink .cm-def { color: #8DA6CE; }
.cm-s-vibrant-ink span.cm-variable-2, .cm-s-cobalt span.cm-tag { color: #FFC66D }
.cm-s-vibrant-ink span.cm-variable-3, .cm-s-cobalt span.cm-def { color: #FFC66D }
.cm-s-vibrant-ink .cm-operator { color: #888; }
.cm-s-vibrant-ink .cm-comment { color: gray; font-weight: bold; }
.cm-s-vibrant-ink .cm-string { color: #A5C25C }
.cm-s-vibrant-ink .cm-string-2 { color: red }
.cm-s-vibrant-ink .cm-meta { color: #D8FA3C; }
.cm-s-vibrant-ink .cm-error { border-bottom: 1px solid red; }
.cm-s-vibrant-ink .cm-builtin { color: #8DA6CE; }
.cm-s-vibrant-ink .cm-tag { color: #8DA6CE; }
.cm-s-vibrant-ink .cm-attribute { color: #8DA6CE; }
.cm-s-vibrant-ink .cm-header { color: #FF6400; }
.cm-s-vibrant-ink .cm-hr { color: #AEAEAE; }
.cm-s-vibrant-ink .cm-link { color: blue; }

View File

@ -1,46 +0,0 @@
/*
Copyright (C) 2011 by MarkLogic Corporation
Author: Mike Brevoort <mike@brevoort.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
.cm-s-xq-dark.CodeMirror { background: #0a001f; color: #f8f8f8; }
.cm-s-xq-dark span.CodeMirror-selected { background: #a8f !important; }
.cm-s-xq-dark .CodeMirror-gutters { background: #0a001f; border-right: 1px solid #aaa; }
.cm-s-xq-dark .CodeMirror-linenumber { color: #f8f8f8; }
.cm-s-xq-dark .CodeMirror-cursor { border-left: 1px solid white !important; }
.cm-s-xq-dark span.cm-keyword {color: #FFBD40;}
.cm-s-xq-dark span.cm-atom {color: #6C8CD5;}
.cm-s-xq-dark span.cm-number {color: #164;}
.cm-s-xq-dark span.cm-def {color: #FFF; text-decoration:underline;}
.cm-s-xq-dark span.cm-variable {color: #FFF;}
.cm-s-xq-dark span.cm-variable-2 {color: #EEE;}
.cm-s-xq-dark span.cm-variable-3 {color: #DDD;}
.cm-s-xq-dark span.cm-property {}
.cm-s-xq-dark span.cm-operator {}
.cm-s-xq-dark span.cm-comment {color: gray;}
.cm-s-xq-dark span.cm-string {color: #9FEE00;}
.cm-s-xq-dark span.cm-meta {color: yellow;}
.cm-s-xq-dark span.cm-error {color: #f00;}
.cm-s-xq-dark span.cm-qualifier {color: #FFF700;}
.cm-s-xq-dark span.cm-builtin {color: #30a;}
.cm-s-xq-dark span.cm-bracket {color: #cc7;}
.cm-s-xq-dark span.cm-tag {color: #FFBD40;}
.cm-s-xq-dark span.cm-attribute {color: #FFF700;}

View File

@ -1,4 +0,0 @@
coffeescript
node-uglify
node-less
cowsay

View File

@ -1,13 +0,0 @@
#!/bin/bash
shopt -s extglob
last=""
while [ true ]; do
now=$(find coffee less -type f -printf "%T@ %Tx %TX %p\n" | sort -n -r | head -1)
if [ "$last" != "$now" ]; then
make >/dev/null
echo "Updated."
fi
last=$now
sleep 1
done

Binary file not shown.

Before

Width:  |  Height:  |  Size: 258 KiB

File diff suppressed because it is too large Load Diff

View File

@ -1,104 +0,0 @@
/**
* Version: 1.0 Alpha-1
* Build Date: 13-Nov-2007
* Copyright (c) 2006-2007, Coolite Inc. (http://www.coolite.com/). All rights reserved.
* License: Licensed under The MIT License. See license.txt and http://www.datejs.com/license/.
* Website: http://www.datejs.com/ or http://www.coolite.com/datejs/
*/
Date.CultureInfo={name:"en-US",englishName:"English (United States)",nativeName:"English (United States)",dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],abbreviatedDayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],shortestDayNames:["Su","Mo","Tu","We","Th","Fr","Sa"],firstLetterDayNames:["S","M","T","W","T","F","S"],monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],abbreviatedMonthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],amDesignator:"AM",pmDesignator:"PM",firstDayOfWeek:0,twoDigitYearMax:2029,dateElementOrder:"mdy",formatPatterns:{shortDate:"M/d/yyyy",longDate:"dddd, MMMM dd, yyyy",shortTime:"h:mm tt",longTime:"h:mm:ss tt",fullDateTime:"dddd, MMMM dd, yyyy h:mm:ss tt",sortableDateTime:"yyyy-MM-ddTHH:mm:ss",universalSortableDateTime:"yyyy-MM-dd HH:mm:ssZ",rfc1123:"ddd, dd MMM yyyy HH:mm:ss GMT",monthDay:"MMMM dd",yearMonth:"MMMM, yyyy"},regexPatterns:{jan:/^jan(uary)?/i,feb:/^feb(ruary)?/i,mar:/^mar(ch)?/i,apr:/^apr(il)?/i,may:/^may/i,jun:/^jun(e)?/i,jul:/^jul(y)?/i,aug:/^aug(ust)?/i,sep:/^sep(t(ember)?)?/i,oct:/^oct(ober)?/i,nov:/^nov(ember)?/i,dec:/^dec(ember)?/i,sun:/^su(n(day)?)?/i,mon:/^mo(n(day)?)?/i,tue:/^tu(e(s(day)?)?)?/i,wed:/^we(d(nesday)?)?/i,thu:/^th(u(r(s(day)?)?)?)?/i,fri:/^fr(i(day)?)?/i,sat:/^sa(t(urday)?)?/i,future:/^next/i,past:/^last|past|prev(ious)?/i,add:/^(\+|after|from)/i,subtract:/^(\-|before|ago)/i,yesterday:/^yesterday/i,today:/^t(oday)?/i,tomorrow:/^tomorrow/i,now:/^n(ow)?/i,millisecond:/^ms|milli(second)?s?/i,second:/^sec(ond)?s?/i,minute:/^min(ute)?s?/i,hour:/^h(ou)?rs?/i,week:/^w(ee)?k/i,month:/^m(o(nth)?s?)?/i,day:/^d(ays?)?/i,year:/^y((ea)?rs?)?/i,shortMeridian:/^(a|p)/i,longMeridian:/^(a\.?m?\.?|p\.?m?\.?)/i,timezone:/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt)/i,ordinalSuffix:/^\s*(st|nd|rd|th)/i,timeContext:/^\s*(\:|a|p)/i},abbreviatedTimeZoneStandard:{GMT:"-000",EST:"-0400",CST:"-0500",MST:"-0600",PST:"-0700"},abbreviatedTimeZoneDST:{GMT:"-000",EDT:"-0500",CDT:"-0600",MDT:"-0700",PDT:"-0800"}};
Date.getMonthNumberFromName=function(name){var n=Date.CultureInfo.monthNames,m=Date.CultureInfo.abbreviatedMonthNames,s=name.toLowerCase();for(var i=0;i<n.length;i++){if(n[i].toLowerCase()==s||m[i].toLowerCase()==s){return i;}}
return-1;};Date.getDayNumberFromName=function(name){var n=Date.CultureInfo.dayNames,m=Date.CultureInfo.abbreviatedDayNames,o=Date.CultureInfo.shortestDayNames,s=name.toLowerCase();for(var i=0;i<n.length;i++){if(n[i].toLowerCase()==s||m[i].toLowerCase()==s){return i;}}
return-1;};Date.isLeapYear=function(year){return(((year%4===0)&&(year%100!==0))||(year%400===0));};Date.getDaysInMonth=function(year,month){return[31,(Date.isLeapYear(year)?29:28),31,30,31,30,31,31,30,31,30,31][month];};Date.getTimezoneOffset=function(s,dst){return(dst||false)?Date.CultureInfo.abbreviatedTimeZoneDST[s.toUpperCase()]:Date.CultureInfo.abbreviatedTimeZoneStandard[s.toUpperCase()];};Date.getTimezoneAbbreviation=function(offset,dst){var n=(dst||false)?Date.CultureInfo.abbreviatedTimeZoneDST:Date.CultureInfo.abbreviatedTimeZoneStandard,p;for(p in n){if(n[p]===offset){return p;}}
return null;};Date.prototype.clone=function(){return new Date(this.getTime());};Date.prototype.compareTo=function(date){if(isNaN(this)){throw new Error(this);}
if(date instanceof Date&&!isNaN(date)){return(this>date)?1:(this<date)?-1:0;}else{throw new TypeError(date);}};Date.prototype.equals=function(date){return(this.compareTo(date)===0);};Date.prototype.between=function(start,end){var t=this.getTime();return t>=start.getTime()&&t<=end.getTime();};Date.prototype.addMilliseconds=function(value){this.setMilliseconds(this.getMilliseconds()+value);return this;};Date.prototype.addSeconds=function(value){return this.addMilliseconds(value*1000);};Date.prototype.addMinutes=function(value){return this.addMilliseconds(value*60000);};Date.prototype.addHours=function(value){return this.addMilliseconds(value*3600000);};Date.prototype.addDays=function(value){return this.addMilliseconds(value*86400000);};Date.prototype.addWeeks=function(value){return this.addMilliseconds(value*604800000);};Date.prototype.addMonths=function(value){var n=this.getDate();this.setDate(1);this.setMonth(this.getMonth()+value);this.setDate(Math.min(n,this.getDaysInMonth()));return this;};Date.prototype.addYears=function(value){return this.addMonths(value*12);};Date.prototype.add=function(config){if(typeof config=="number"){this._orient=config;return this;}
var x=config;if(x.millisecond||x.milliseconds){this.addMilliseconds(x.millisecond||x.milliseconds);}
if(x.second||x.seconds){this.addSeconds(x.second||x.seconds);}
if(x.minute||x.minutes){this.addMinutes(x.minute||x.minutes);}
if(x.hour||x.hours){this.addHours(x.hour||x.hours);}
if(x.month||x.months){this.addMonths(x.month||x.months);}
if(x.year||x.years){this.addYears(x.year||x.years);}
if(x.day||x.days){this.addDays(x.day||x.days);}
return this;};Date._validate=function(value,min,max,name){if(typeof value!="number"){throw new TypeError(value+" is not a Number.");}else if(value<min||value>max){throw new RangeError(value+" is not a valid value for "+name+".");}
return true;};Date.validateMillisecond=function(n){return Date._validate(n,0,999,"milliseconds");};Date.validateSecond=function(n){return Date._validate(n,0,59,"seconds");};Date.validateMinute=function(n){return Date._validate(n,0,59,"minutes");};Date.validateHour=function(n){return Date._validate(n,0,23,"hours");};Date.validateDay=function(n,year,month){return Date._validate(n,1,Date.getDaysInMonth(year,month),"days");};Date.validateMonth=function(n){return Date._validate(n,0,11,"months");};Date.validateYear=function(n){return Date._validate(n,1,9999,"seconds");};Date.prototype.set=function(config){var x=config;if(!x.millisecond&&x.millisecond!==0){x.millisecond=-1;}
if(!x.second&&x.second!==0){x.second=-1;}
if(!x.minute&&x.minute!==0){x.minute=-1;}
if(!x.hour&&x.hour!==0){x.hour=-1;}
if(!x.day&&x.day!==0){x.day=-1;}
if(!x.month&&x.month!==0){x.month=-1;}
if(!x.year&&x.year!==0){x.year=-1;}
if(x.millisecond!=-1&&Date.validateMillisecond(x.millisecond)){this.addMilliseconds(x.millisecond-this.getMilliseconds());}
if(x.second!=-1&&Date.validateSecond(x.second)){this.addSeconds(x.second-this.getSeconds());}
if(x.minute!=-1&&Date.validateMinute(x.minute)){this.addMinutes(x.minute-this.getMinutes());}
if(x.hour!=-1&&Date.validateHour(x.hour)){this.addHours(x.hour-this.getHours());}
if(x.month!==-1&&Date.validateMonth(x.month)){this.addMonths(x.month-this.getMonth());}
if(x.year!=-1&&Date.validateYear(x.year)){this.addYears(x.year-this.getFullYear());}
if(x.day!=-1&&Date.validateDay(x.day,this.getFullYear(),this.getMonth())){this.addDays(x.day-this.getDate());}
if(x.timezone){this.setTimezone(x.timezone);}
if(x.timezoneOffset){this.setTimezoneOffset(x.timezoneOffset);}
return this;};Date.prototype.clearTime=function(){this.setHours(0);this.setMinutes(0);this.setSeconds(0);this.setMilliseconds(0);return this;};Date.prototype.isLeapYear=function(){var y=this.getFullYear();return(((y%4===0)&&(y%100!==0))||(y%400===0));};Date.prototype.isWeekday=function(){return!(this.is().sat()||this.is().sun());};Date.prototype.getDaysInMonth=function(){return Date.getDaysInMonth(this.getFullYear(),this.getMonth());};Date.prototype.moveToFirstDayOfMonth=function(){return this.set({day:1});};Date.prototype.moveToLastDayOfMonth=function(){return this.set({day:this.getDaysInMonth()});};Date.prototype.moveToDayOfWeek=function(day,orient){var diff=(day-this.getDay()+7*(orient||+1))%7;return this.addDays((diff===0)?diff+=7*(orient||+1):diff);};Date.prototype.moveToMonth=function(month,orient){var diff=(month-this.getMonth()+12*(orient||+1))%12;return this.addMonths((diff===0)?diff+=12*(orient||+1):diff);};Date.prototype.getDayOfYear=function(){return Math.floor((this-new Date(this.getFullYear(),0,1))/86400000);};Date.prototype.getWeekOfYear=function(firstDayOfWeek){var y=this.getFullYear(),m=this.getMonth(),d=this.getDate();var dow=firstDayOfWeek||Date.CultureInfo.firstDayOfWeek;var offset=7+1-new Date(y,0,1).getDay();if(offset==8){offset=1;}
var daynum=((Date.UTC(y,m,d,0,0,0)-Date.UTC(y,0,1,0,0,0))/86400000)+1;var w=Math.floor((daynum-offset+7)/7);if(w===dow){y--;var prevOffset=7+1-new Date(y,0,1).getDay();if(prevOffset==2||prevOffset==8){w=53;}else{w=52;}}
return w;};Date.prototype.isDST=function(){console.log('isDST');return this.toString().match(/(E|C|M|P)(S|D)T/)[2]=="D";};Date.prototype.getTimezone=function(){return Date.getTimezoneAbbreviation(this.getUTCOffset,this.isDST());};Date.prototype.setTimezoneOffset=function(s){var here=this.getTimezoneOffset(),there=Number(s)*-6/10;this.addMinutes(there-here);return this;};Date.prototype.setTimezone=function(s){return this.setTimezoneOffset(Date.getTimezoneOffset(s));};Date.prototype.getUTCOffset=function(){var n=this.getTimezoneOffset()*-10/6,r;if(n<0){r=(n-10000).toString();return r[0]+r.substr(2);}else{r=(n+10000).toString();return"+"+r.substr(1);}};Date.prototype.getDayName=function(abbrev){return abbrev?Date.CultureInfo.abbreviatedDayNames[this.getDay()]:Date.CultureInfo.dayNames[this.getDay()];};Date.prototype.getMonthName=function(abbrev){return abbrev?Date.CultureInfo.abbreviatedMonthNames[this.getMonth()]:Date.CultureInfo.monthNames[this.getMonth()];};Date.prototype._toString=Date.prototype.toString;Date.prototype.toString=function(format){var self=this;var p=function p(s){return(s.toString().length==1)?"0"+s:s;};return format?format.replace(/dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?/g,function(format){switch(format){case"hh":return p(self.getHours()<13?self.getHours():(self.getHours()-12));case"h":return self.getHours()<13?self.getHours():(self.getHours()-12);case"HH":return p(self.getHours());case"H":return self.getHours();case"mm":return p(self.getMinutes());case"m":return self.getMinutes();case"ss":return p(self.getSeconds());case"s":return self.getSeconds();case"yyyy":return self.getFullYear();case"yy":return self.getFullYear().toString().substring(2,4);case"dddd":return self.getDayName();case"ddd":return self.getDayName(true);case"dd":return p(self.getDate());case"d":return self.getDate().toString();case"MMMM":return self.getMonthName();case"MMM":return self.getMonthName(true);case"MM":return p((self.getMonth()+1));case"M":return self.getMonth()+1;case"t":return self.getHours()<12?Date.CultureInfo.amDesignator.substring(0,1):Date.CultureInfo.pmDesignator.substring(0,1);case"tt":return self.getHours()<12?Date.CultureInfo.amDesignator:Date.CultureInfo.pmDesignator;case"zzz":case"zz":case"z":return"";}}):this._toString();};
Date.now=function(){return new Date();};Date.today=function(){return Date.now().clearTime();};Date.prototype._orient=+1;Date.prototype.next=function(){this._orient=+1;return this;};Date.prototype.last=Date.prototype.prev=Date.prototype.previous=function(){this._orient=-1;return this;};Date.prototype._is=false;Date.prototype.is=function(){this._is=true;return this;};Number.prototype._dateElement="day";Number.prototype.fromNow=function(){var c={};c[this._dateElement]=this;return Date.now().add(c);};Number.prototype.ago=function(){var c={};c[this._dateElement]=this*-1;return Date.now().add(c);};(function(){var $D=Date.prototype,$N=Number.prototype;var dx=("sunday monday tuesday wednesday thursday friday saturday").split(/\s/),mx=("january february march april may june july august september october november december").split(/\s/),px=("Millisecond Second Minute Hour Day Week Month Year").split(/\s/),de;var df=function(n){return function(){if(this._is){this._is=false;return this.getDay()==n;}
return this.moveToDayOfWeek(n,this._orient);};};for(var i=0;i<dx.length;i++){$D[dx[i]]=$D[dx[i].substring(0,3)]=df(i);}
var mf=function(n){return function(){if(this._is){this._is=false;return this.getMonth()===n;}
return this.moveToMonth(n,this._orient);};};for(var j=0;j<mx.length;j++){$D[mx[j]]=$D[mx[j].substring(0,3)]=mf(j);}
var ef=function(j){return function(){if(j.substring(j.length-1)!="s"){j+="s";}
return this["add"+j](this._orient);};};var nf=function(n){return function(){this._dateElement=n;return this;};};for(var k=0;k<px.length;k++){de=px[k].toLowerCase();$D[de]=$D[de+"s"]=ef(px[k]);$N[de]=$N[de+"s"]=nf(de);}}());Date.prototype.toJSONString=function(){return this.toString("yyyy-MM-ddThh:mm:ssZ");};Date.prototype.toShortDateString=function(){return this.toString(Date.CultureInfo.formatPatterns.shortDatePattern);};Date.prototype.toLongDateString=function(){return this.toString(Date.CultureInfo.formatPatterns.longDatePattern);};Date.prototype.toShortTimeString=function(){return this.toString(Date.CultureInfo.formatPatterns.shortTimePattern);};Date.prototype.toLongTimeString=function(){return this.toString(Date.CultureInfo.formatPatterns.longTimePattern);};Date.prototype.getOrdinal=function(){switch(this.getDate()){case 1:case 21:case 31:return"st";case 2:case 22:return"nd";case 3:case 23:return"rd";default:return"th";}};
(function(){Date.Parsing={Exception:function(s){this.message="Parse error at '"+s.substring(0,10)+" ...'";}};var $P=Date.Parsing;var _=$P.Operators={rtoken:function(r){return function(s){var mx=s.match(r);if(mx){return([mx[0],s.substring(mx[0].length)]);}else{throw new $P.Exception(s);}};},token:function(s){return function(s){return _.rtoken(new RegExp("^\s*"+s+"\s*"))(s);};},stoken:function(s){return _.rtoken(new RegExp("^"+s));},until:function(p){return function(s){var qx=[],rx=null;while(s.length){try{rx=p.call(this,s);}catch(e){qx.push(rx[0]);s=rx[1];continue;}
break;}
return[qx,s];};},many:function(p){return function(s){var rx=[],r=null;while(s.length){try{r=p.call(this,s);}catch(e){return[rx,s];}
rx.push(r[0]);s=r[1];}
return[rx,s];};},optional:function(p){return function(s){var r=null;try{r=p.call(this,s);}catch(e){return[null,s];}
return[r[0],r[1]];};},not:function(p){return function(s){try{p.call(this,s);}catch(e){return[null,s];}
throw new $P.Exception(s);};},ignore:function(p){return p?function(s){var r=null;r=p.call(this,s);return[null,r[1]];}:null;},product:function(){var px=arguments[0],qx=Array.prototype.slice.call(arguments,1),rx=[];for(var i=0;i<px.length;i++){rx.push(_.each(px[i],qx));}
return rx;},cache:function(rule){var cache={},r=null;return function(s){try{r=cache[s]=(cache[s]||rule.call(this,s));}catch(e){r=cache[s]=e;}
if(r instanceof $P.Exception){throw r;}else{return r;}};},any:function(){var px=arguments;return function(s){var r=null;for(var i=0;i<px.length;i++){if(px[i]==null){continue;}
try{r=(px[i].call(this,s));}catch(e){r=null;}
if(r){return r;}}
throw new $P.Exception(s);};},each:function(){var px=arguments;return function(s){var rx=[],r=null;for(var i=0;i<px.length;i++){if(px[i]==null){continue;}
try{r=(px[i].call(this,s));}catch(e){throw new $P.Exception(s);}
rx.push(r[0]);s=r[1];}
return[rx,s];};},all:function(){var px=arguments,_=_;return _.each(_.optional(px));},sequence:function(px,d,c){d=d||_.rtoken(/^\s*/);c=c||null;if(px.length==1){return px[0];}
return function(s){var r=null,q=null;var rx=[];for(var i=0;i<px.length;i++){try{r=px[i].call(this,s);}catch(e){break;}
rx.push(r[0]);try{q=d.call(this,r[1]);}catch(ex){q=null;break;}
s=q[1];}
if(!r){throw new $P.Exception(s);}
if(q){throw new $P.Exception(q[1]);}
if(c){try{r=c.call(this,r[1]);}catch(ey){throw new $P.Exception(r[1]);}}
return[rx,(r?r[1]:s)];};},between:function(d1,p,d2){d2=d2||d1;var _fn=_.each(_.ignore(d1),p,_.ignore(d2));return function(s){var rx=_fn.call(this,s);return[[rx[0][0],r[0][2]],rx[1]];};},list:function(p,d,c){d=d||_.rtoken(/^\s*/);c=c||null;return(p instanceof Array?_.each(_.product(p.slice(0,-1),_.ignore(d)),p.slice(-1),_.ignore(c)):_.each(_.many(_.each(p,_.ignore(d))),px,_.ignore(c)));},set:function(px,d,c){d=d||_.rtoken(/^\s*/);c=c||null;return function(s){var r=null,p=null,q=null,rx=null,best=[[],s],last=false;for(var i=0;i<px.length;i++){q=null;p=null;r=null;last=(px.length==1);try{r=px[i].call(this,s);}catch(e){continue;}
rx=[[r[0]],r[1]];if(r[1].length>0&&!last){try{q=d.call(this,r[1]);}catch(ex){last=true;}}else{last=true;}
if(!last&&q[1].length===0){last=true;}
if(!last){var qx=[];for(var j=0;j<px.length;j++){if(i!=j){qx.push(px[j]);}}
p=_.set(qx,d).call(this,q[1]);if(p[0].length>0){rx[0]=rx[0].concat(p[0]);rx[1]=p[1];}}
if(rx[1].length<best[1].length){best=rx;}
if(best[1].length===0){break;}}
if(best[0].length===0){return best;}
if(c){try{q=c.call(this,best[1]);}catch(ey){throw new $P.Exception(best[1]);}
best[1]=q[1];}
return best;};},forward:function(gr,fname){return function(s){return gr[fname].call(this,s);};},replace:function(rule,repl){return function(s){var r=rule.call(this,s);return[repl,r[1]];};},process:function(rule,fn){return function(s){var r=rule.call(this,s);return[fn.call(this,r[0]),r[1]];};},min:function(min,rule){return function(s){var rx=rule.call(this,s);if(rx[0].length<min){throw new $P.Exception(s);}
return rx;};}};var _generator=function(op){return function(){var args=null,rx=[];if(arguments.length>1){args=Array.prototype.slice.call(arguments);}else if(arguments[0]instanceof Array){args=arguments[0];}
if(args){for(var i=0,px=args.shift();i<px.length;i++){args.unshift(px[i]);rx.push(op.apply(null,args));args.shift();return rx;}}else{return op.apply(null,arguments);}};};var gx="optional not ignore cache".split(/\s/);for(var i=0;i<gx.length;i++){_[gx[i]]=_generator(_[gx[i]]);}
var _vector=function(op){return function(){if(arguments[0]instanceof Array){return op.apply(null,arguments[0]);}else{return op.apply(null,arguments);}};};var vx="each any all".split(/\s/);for(var j=0;j<vx.length;j++){_[vx[j]]=_vector(_[vx[j]]);}}());(function(){var flattenAndCompact=function(ax){var rx=[];for(var i=0;i<ax.length;i++){if(ax[i]instanceof Array){rx=rx.concat(flattenAndCompact(ax[i]));}else{if(ax[i]){rx.push(ax[i]);}}}
return rx;};Date.Grammar={};Date.Translator={hour:function(s){return function(){this.hour=Number(s);};},minute:function(s){return function(){this.minute=Number(s);};},second:function(s){return function(){this.second=Number(s);};},meridian:function(s){return function(){this.meridian=s.slice(0,1).toLowerCase();};},timezone:function(s){return function(){var n=s.replace(/[^\d\+\-]/g,"");if(n.length){this.timezoneOffset=Number(n);}else{this.timezone=s.toLowerCase();}};},day:function(x){var s=x[0];return function(){this.day=Number(s.match(/\d+/)[0]);};},month:function(s){return function(){this.month=((s.length==3)?Date.getMonthNumberFromName(s):(Number(s)-1));};},year:function(s){return function(){var n=Number(s);this.year=((s.length>2)?n:(n+(((n+2000)<Date.CultureInfo.twoDigitYearMax)?2000:1900)));};},rday:function(s){return function(){switch(s){case"yesterday":this.days=-1;break;case"tomorrow":this.days=1;break;case"today":this.days=0;break;case"now":this.days=0;this.now=true;break;}};},finishExact:function(x){x=(x instanceof Array)?x:[x];var now=new Date();this.year=now.getFullYear();this.month=now.getMonth();this.day=1;this.hour=0;this.minute=0;this.second=0;for(var i=0;i<x.length;i++){if(x[i]){x[i].call(this);}}
this.hour=(this.meridian=="p"&&this.hour<13)?this.hour+12:this.hour;if(this.day>Date.getDaysInMonth(this.year,this.month)){throw new RangeError(this.day+" is not a valid value for days.");}
var r=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second);if(this.timezone){r.set({timezone:this.timezone});}else if(this.timezoneOffset){r.set({timezoneOffset:this.timezoneOffset});}
return r;},finish:function(x){x=(x instanceof Array)?flattenAndCompact(x):[x];if(x.length===0){return null;}
for(var i=0;i<x.length;i++){if(typeof x[i]=="function"){x[i].call(this);}}
if(this.now){return new Date();}
var today=Date.today();var method=null;var expression=!!(this.days!=null||this.orient||this.operator);if(expression){var gap,mod,orient;orient=((this.orient=="past"||this.operator=="subtract")?-1:1);if(this.weekday){this.unit="day";gap=(Date.getDayNumberFromName(this.weekday)-today.getDay());mod=7;this.days=gap?((gap+(orient*mod))%mod):(orient*mod);}
if(this.month){this.unit="month";gap=(this.month-today.getMonth());mod=12;this.months=gap?((gap+(orient*mod))%mod):(orient*mod);this.month=null;}
if(!this.unit){this.unit="day";}
if(this[this.unit+"s"]==null||this.operator!=null){if(!this.value){this.value=1;}
if(this.unit=="week"){this.unit="day";this.value=this.value*7;}
this[this.unit+"s"]=this.value*orient;}
return today.add(this);}else{if(this.meridian&&this.hour){this.hour=(this.hour<13&&this.meridian=="p")?this.hour+12:this.hour;}
if(this.weekday&&!this.day){this.day=(today.addDays((Date.getDayNumberFromName(this.weekday)-today.getDay()))).getDate();}
if(this.month&&!this.day){this.day=1;}
return today.set(this);}}};var _=Date.Parsing.Operators,g=Date.Grammar,t=Date.Translator,_fn;g.datePartDelimiter=_.rtoken(/^([\s\-\.\,\/\x27]+)/);g.timePartDelimiter=_.stoken(":");g.whiteSpace=_.rtoken(/^\s*/);g.generalDelimiter=_.rtoken(/^(([\s\,]|at|on)+)/);var _C={};g.ctoken=function(keys){var fn=_C[keys];if(!fn){var c=Date.CultureInfo.regexPatterns;var kx=keys.split(/\s+/),px=[];for(var i=0;i<kx.length;i++){px.push(_.replace(_.rtoken(c[kx[i]]),kx[i]));}
fn=_C[keys]=_.any.apply(null,px);}
return fn;};g.ctoken2=function(key){return _.rtoken(Date.CultureInfo.regexPatterns[key]);};g.h=_.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2]|[1-9])/),t.hour));g.hh=_.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2])/),t.hour));g.H=_.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3]|[0-9])/),t.hour));g.HH=_.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3])/),t.hour));g.m=_.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/),t.minute));g.mm=_.cache(_.process(_.rtoken(/^[0-5][0-9]/),t.minute));g.s=_.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/),t.second));g.ss=_.cache(_.process(_.rtoken(/^[0-5][0-9]/),t.second));g.hms=_.cache(_.sequence([g.H,g.mm,g.ss],g.timePartDelimiter));g.t=_.cache(_.process(g.ctoken2("shortMeridian"),t.meridian));g.tt=_.cache(_.process(g.ctoken2("longMeridian"),t.meridian));g.z=_.cache(_.process(_.rtoken(/^(\+|\-)?\s*\d\d\d\d?/),t.timezone));g.zz=_.cache(_.process(_.rtoken(/^(\+|\-)\s*\d\d\d\d/),t.timezone));g.zzz=_.cache(_.process(g.ctoken2("timezone"),t.timezone));g.timeSuffix=_.each(_.ignore(g.whiteSpace),_.set([g.tt,g.zzz]));g.time=_.each(_.optional(_.ignore(_.stoken("T"))),g.hms,g.timeSuffix);g.d=_.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1]|\d)/),_.optional(g.ctoken2("ordinalSuffix"))),t.day));g.dd=_.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1])/),_.optional(g.ctoken2("ordinalSuffix"))),t.day));g.ddd=g.dddd=_.cache(_.process(g.ctoken("sun mon tue wed thu fri sat"),function(s){return function(){this.weekday=s;};}));g.M=_.cache(_.process(_.rtoken(/^(1[0-2]|0\d|\d)/),t.month));g.MM=_.cache(_.process(_.rtoken(/^(1[0-2]|0\d)/),t.month));g.MMM=g.MMMM=_.cache(_.process(g.ctoken("jan feb mar apr may jun jul aug sep oct nov dec"),t.month));g.y=_.cache(_.process(_.rtoken(/^(\d\d?)/),t.year));g.yy=_.cache(_.process(_.rtoken(/^(\d\d)/),t.year));g.yyy=_.cache(_.process(_.rtoken(/^(\d\d?\d?\d?)/),t.year));g.yyyy=_.cache(_.process(_.rtoken(/^(\d\d\d\d)/),t.year));_fn=function(){return _.each(_.any.apply(null,arguments),_.not(g.ctoken2("timeContext")));};g.day=_fn(g.d,g.dd);g.month=_fn(g.M,g.MMM);g.year=_fn(g.yyyy,g.yy);g.orientation=_.process(g.ctoken("past future"),function(s){return function(){this.orient=s;};});g.operator=_.process(g.ctoken("add subtract"),function(s){return function(){this.operator=s;};});g.rday=_.process(g.ctoken("yesterday tomorrow today now"),t.rday);g.unit=_.process(g.ctoken("minute hour day week month year"),function(s){return function(){this.unit=s;};});g.value=_.process(_.rtoken(/^\d\d?(st|nd|rd|th)?/),function(s){return function(){this.value=s.replace(/\D/g,"");};});g.expression=_.set([g.rday,g.operator,g.value,g.unit,g.orientation,g.ddd,g.MMM]);_fn=function(){return _.set(arguments,g.datePartDelimiter);};g.mdy=_fn(g.ddd,g.month,g.day,g.year);g.ymd=_fn(g.ddd,g.year,g.month,g.day);g.dmy=_fn(g.ddd,g.day,g.month,g.year);g.date=function(s){return((g[Date.CultureInfo.dateElementOrder]||g.mdy).call(this,s));};g.format=_.process(_.many(_.any(_.process(_.rtoken(/^(dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?)/),function(fmt){if(g[fmt]){return g[fmt];}else{throw Date.Parsing.Exception(fmt);}}),_.process(_.rtoken(/^[^dMyhHmstz]+/),function(s){return _.ignore(_.stoken(s));}))),function(rules){return _.process(_.each.apply(null,rules),t.finishExact);});var _F={};var _get=function(f){return _F[f]=(_F[f]||g.format(f)[0]);};g.formats=function(fx){if(fx instanceof Array){var rx=[];for(var i=0;i<fx.length;i++){rx.push(_get(fx[i]));}
return _.any.apply(null,rx);}else{return _get(fx);}};g._formats=g.formats(["yyyy-MM-ddTHH:mm:ss","ddd, MMM dd, yyyy H:mm:ss tt","ddd MMM d yyyy HH:mm:ss zzz","d"]);g._start=_.process(_.set([g.date,g.time,g.expression],g.generalDelimiter,g.whiteSpace),t.finish);g.start=function(s){try{var r=g._formats.call({},s);if(r[1].length===0){return r;}}catch(e){}
return g._start.call({},s);};}());Date._parse=Date.parse;Date.parse=function(s){var r=null;if(!s){return null;}
try{r=Date.Grammar.start.call({},s);}catch(e){return null;}
return((r[1].length===0)?r[0]:null);};Date.getParseFunction=function(fx){var fn=Date.Grammar.formats(fx);return function(s){var r=null;try{r=fn.call({},s);}catch(e){return null;}
return((r[1].length===0)?r[0]:null);};};Date.parseExact=function(s,fx){return Date.getParseFunction(fx)(s);};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,67 +0,0 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Clojure mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="clojure.js"></script>
<style>.CodeMirror {background: #f8f8f8;}</style>
<link rel="stylesheet" href="../../doc/docs.css">
</head>
<body>
<h1>CodeMirror: Clojure mode</h1>
<form><textarea id="code" name="code">
; Conway's Game of Life, based on the work of:
;; Laurent Petit https://gist.github.com/1200343
;; Christophe Grand http://clj-me.cgrand.net/2011/08/19/conways-game-of-life
(ns ^{:doc "Conway's Game of Life."}
game-of-life)
;; Core game of life's algorithm functions
(defn neighbours
"Given a cell's coordinates, returns the coordinates of its neighbours."
[[x y]]
(for [dx [-1 0 1] dy (if (zero? dx) [-1 1] [-1 0 1])]
[(+ dx x) (+ dy y)]))
(defn step
"Given a set of living cells, computes the new set of living cells."
[cells]
(set (for [[cell n] (frequencies (mapcat neighbours cells))
:when (or (= n 3) (and (= n 2) (cells cell)))]
cell)))
;; Utility methods for displaying game on a text terminal
(defn print-board
"Prints a board on *out*, representing a step in the game."
[board w h]
(doseq [x (range (inc w)) y (range (inc h))]
(if (= y 0) (print "\n"))
(print (if (board [x y]) "[X]" " . "))))
(defn display-grids
"Prints a squence of boards on *out*, representing several steps."
[grids w h]
(doseq [board grids]
(print-board board w h)
(print "\n")))
;; Launches an example board
(def
^{:doc "board represents the initial set of living cells"}
board #{[2 1] [2 2] [2 3]})
(display-grids (take 3 (iterate step board)) 5 5) </textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-clojure</code>.</p>
</body>
</html>

View File

@ -1,21 +0,0 @@
The MIT License
Copyright (c) 2010 Timothy Farrell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -1,135 +0,0 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Python mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="../../addon/edit/matchbrackets.js"></script>
<script src="python.js"></script>
<link rel="stylesheet" href="../../doc/docs.css">
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
</head>
<body>
<h1>CodeMirror: Python mode</h1>
<div><textarea id="code" name="code">
# Literals
1234
0.0e101
.123
0b01010011100
0o01234567
0x0987654321abcdef
7
2147483647
3L
79228162514264337593543950336L
0x100000000L
79228162514264337593543950336
0xdeadbeef
3.14j
10.j
10j
.001j
1e100j
3.14e-10j
# String Literals
'For\''
"God\""
"""so loved
the world"""
'''that he gave
his only begotten\' '''
'that whosoever believeth \
in him'
''
# Identifiers
__a__
a.b
a.b.c
# Operators
+ - * / % & | ^ ~ < >
== != <= >= <> << >> // **
and or not in is
# Delimiters
() [] {} , : ` = ; @ . # Note that @ and . require the proper context.
+= -= *= /= %= &= |= ^=
//= >>= <<= **=
# Keywords
as assert break class continue def del elif else except
finally for from global if import lambda pass raise
return try while with yield
# Python 2 Keywords (otherwise Identifiers)
exec print
# Python 3 Keywords (otherwise Identifiers)
nonlocal
# Types
bool classmethod complex dict enumerate float frozenset int list object
property reversed set slice staticmethod str super tuple type
# Python 2 Types (otherwise Identifiers)
basestring buffer file long unicode xrange
# Python 3 Types (otherwise Identifiers)
bytearray bytes filter map memoryview open range zip
# Some Example code
import os
from package import ParentClass
@nonsenseDecorator
def doesNothing():
pass
class ExampleClass(ParentClass):
@staticmethod
def example(inputStr):
a = list(inputStr)
a.reverse()
return ''.join(a)
def __init__(self, mixin = 'Hello'):
self.mixin = mixin
</textarea></div>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: {name: "python",
version: 2,
singleLineStringErrors: false},
lineNumbers: true,
indentUnit: 4,
tabMode: "shift",
matchBrackets: true
});
</script>
<h2>Configuration Options:</h2>
<ul>
<li>version - 2/3 - The version of Python to recognize. Default is 2.</li>
<li>singleLineStringErrors - true/false - If you have a single-line string that is not terminated at the end of the line, this will show subsequent lines as errors if true, otherwise it will consider the newline as the end of the string. Default is false.</li>
</ul>
<h2>Advanced Configuration Options:</h2>
<p>Usefull for superset of python syntax like Enthought enaml, IPython magics and questionmark help</p>
<ul>
<li>singleOperators - RegEx - Regular Expression for single operator matching, default : <pre>^[\\+\\-\\*/%&amp;|\\^~&lt;&gt;!]</pre></li>
<li>singleDelimiters - RegEx - Regular Expression for single delimiter matching, default : <pre>^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]</pre></li>
<li>doubleOperators - RegEx - Regular Expression for double operators matching, default : <pre>^((==)|(!=)|(&lt;=)|(&gt;=)|(&lt;&gt;)|(&lt;&lt;)|(&gt;&gt;)|(//)|(\\*\\*))</pre></li>
<li>doubleDelimiters - RegEx - Regular Expressoin for double delimiters matching, default : <pre>^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&amp;=)|(\\|=)|(\\^=))</pre></li>
<li>tripleDelimiters - RegEx - Regular Expression for triple delimiters matching, default : <pre>^((//=)|(&gt;&gt;=)|(&lt;&lt;=)|(\\*\\*=))</pre></li>
<li>identifiers - RegEx - Regular Expression for identifier, default : <pre>^[_A-Za-z][_A-Za-z0-9]*</pre></li>
</ul>
<p><strong>MIME types defined:</strong> <code>text/x-python</code>.</p>
</body>
</html>

View File

@ -1,340 +0,0 @@
CodeMirror.defineMode("python", function(conf, parserConf) {
var ERRORCLASS = 'error';
function wordRegexp(words) {
return new RegExp("^((" + words.join(")|(") + "))\\b");
}
var singleOperators = parserConf.singleOperators || new RegExp("^[\\+\\-\\*/%&|\\^~<>!]");
var singleDelimiters = parserConf.singleDelimiters || new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]');
var doubleOperators = parserConf.doubleOperators || new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
var doubleDelimiters = parserConf.doubleDelimiters || new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
var tripleDelimiters = parserConf.tripleDelimiters || new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
var identifiers = parserConf.identifiers|| new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
var wordOperators = wordRegexp(['and', 'or', 'not', 'is', 'in']);
var commonkeywords = ['as', 'assert', 'break', 'class', 'continue',
'def', 'del', 'elif', 'else', 'except', 'finally',
'for', 'from', 'global', 'if', 'import',
'lambda', 'pass', 'raise', 'return',
'try', 'while', 'with', 'yield'];
var commonBuiltins = ['abs', 'all', 'any', 'bin', 'bool', 'bytearray', 'callable', 'chr',
'classmethod', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod',
'enumerate', 'eval', 'filter', 'float', 'format', 'frozenset',
'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id',
'input', 'int', 'isinstance', 'issubclass', 'iter', 'len',
'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next',
'object', 'oct', 'open', 'ord', 'pow', 'property', 'range',
'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple',
'type', 'vars', 'zip', '__import__', 'NotImplemented',
'Ellipsis', '__debug__'];
var py2 = {'builtins': ['apply', 'basestring', 'buffer', 'cmp', 'coerce', 'execfile',
'file', 'intern', 'long', 'raw_input', 'reduce', 'reload',
'unichr', 'unicode', 'xrange', 'False', 'True', 'None'],
'keywords': ['exec', 'print']};
var py3 = {'builtins': ['ascii', 'bytes', 'exec', 'print'],
'keywords': ['nonlocal', 'False', 'True', 'None']};
if (!!parserConf.version && parseInt(parserConf.version, 10) === 3) {
commonkeywords = commonkeywords.concat(py3.keywords);
commonBuiltins = commonBuiltins.concat(py3.builtins);
var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");
} else {
commonkeywords = commonkeywords.concat(py2.keywords);
commonBuiltins = commonBuiltins.concat(py2.builtins);
var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
}
var keywords = wordRegexp(commonkeywords);
var builtins = wordRegexp(commonBuiltins);
var indentInfo = null;
// tokenizers
function tokenBase(stream, state) {
// Handle scope changes
if (stream.sol()) {
var scopeOffset = state.scopes[0].offset;
if (stream.eatSpace()) {
var lineOffset = stream.indentation();
if (lineOffset > scopeOffset) {
indentInfo = 'indent';
} else if (lineOffset < scopeOffset) {
indentInfo = 'dedent';
}
return null;
} else {
if (scopeOffset > 0) {
dedent(stream, state);
}
}
}
if (stream.eatSpace()) {
return null;
}
var ch = stream.peek();
// Handle Comments
if (ch === '#') {
stream.skipToEnd();
return 'comment';
}
// Handle Number Literals
if (stream.match(/^[0-9\.]/, false)) {
var floatLiteral = false;
// Floats
if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
if (stream.match(/^\.\d+/)) { floatLiteral = true; }
if (floatLiteral) {
// Float literals may be "imaginary"
stream.eat(/J/i);
return 'number';
}
// Integers
var intLiteral = false;
// Hex
if (stream.match(/^0x[0-9a-f]+/i)) { intLiteral = true; }
// Binary
if (stream.match(/^0b[01]+/i)) { intLiteral = true; }
// Octal
if (stream.match(/^0o[0-7]+/i)) { intLiteral = true; }
// Decimal
if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
// Decimal literals may be "imaginary"
stream.eat(/J/i);
// TODO - Can you have imaginary longs?
intLiteral = true;
}
// Zero by itself with no other piece of number.
if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; }
if (intLiteral) {
// Integer literals may be "long"
stream.eat(/L/i);
return 'number';
}
}
// Handle Strings
if (stream.match(stringPrefixes)) {
state.tokenize = tokenStringFactory(stream.current());
return state.tokenize(stream, state);
}
// Handle operators and Delimiters
if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
return null;
}
if (stream.match(doubleOperators)
|| stream.match(singleOperators)
|| stream.match(wordOperators)) {
return 'operator';
}
if (stream.match(singleDelimiters)) {
return null;
}
if (stream.match(keywords)) {
return 'keyword';
}
if (stream.match(builtins)) {
return 'builtin';
}
if (stream.match(identifiers)) {
return 'variable';
}
// Handle non-detected items
stream.next();
return ERRORCLASS;
}
function tokenStringFactory(delimiter) {
while ('rub'.indexOf(delimiter.charAt(0).toLowerCase()) >= 0) {
delimiter = delimiter.substr(1);
}
var singleline = delimiter.length == 1;
var OUTCLASS = 'string';
function tokenString(stream, state) {
while (!stream.eol()) {
stream.eatWhile(/[^'"\\]/);
if (stream.eat('\\')) {
stream.next();
if (singleline && stream.eol()) {
return OUTCLASS;
}
} else if (stream.match(delimiter)) {
state.tokenize = tokenBase;
return OUTCLASS;
} else {
stream.eat(/['"]/);
}
}
if (singleline) {
if (parserConf.singleLineStringErrors) {
return ERRORCLASS;
} else {
state.tokenize = tokenBase;
}
}
return OUTCLASS;
}
tokenString.isString = true;
return tokenString;
}
function indent(stream, state, type) {
type = type || 'py';
var indentUnit = 0;
if (type === 'py') {
if (state.scopes[0].type !== 'py') {
state.scopes[0].offset = stream.indentation();
return;
}
for (var i = 0; i < state.scopes.length; ++i) {
if (state.scopes[i].type === 'py') {
indentUnit = state.scopes[i].offset + conf.indentUnit;
break;
}
}
} else {
indentUnit = stream.column() + stream.current().length;
}
state.scopes.unshift({
offset: indentUnit,
type: type
});
}
function dedent(stream, state, type) {
type = type || 'py';
if (state.scopes.length == 1) return;
if (state.scopes[0].type === 'py') {
var _indent = stream.indentation();
var _indent_index = -1;
for (var i = 0; i < state.scopes.length; ++i) {
if (_indent === state.scopes[i].offset) {
_indent_index = i;
break;
}
}
if (_indent_index === -1) {
return true;
}
while (state.scopes[0].offset !== _indent) {
state.scopes.shift();
}
return false;
} else {
if (type === 'py') {
state.scopes[0].offset = stream.indentation();
return false;
} else {
if (state.scopes[0].type != type) {
return true;
}
state.scopes.shift();
return false;
}
}
}
function tokenLexer(stream, state) {
indentInfo = null;
var style = state.tokenize(stream, state);
var current = stream.current();
// Handle '.' connected identifiers
if (current === '.') {
style = stream.match(identifiers, false) ? null : ERRORCLASS;
if (style === null && state.lastToken === 'meta') {
// Apply 'meta' style to '.' connected identifiers when
// appropriate.
style = 'meta';
}
return style;
}
// Handle decorators
if (current === '@') {
return stream.match(identifiers, false) ? 'meta' : ERRORCLASS;
}
if ((style === 'variable' || style === 'builtin')
&& state.lastToken === 'meta') {
style = 'meta';
}
// Handle scope changes.
if (current === 'pass' || current === 'return') {
state.dedent += 1;
}
if (current === 'lambda') state.lambda = true;
if ((current === ':' && !state.lambda && state.scopes[0].type == 'py')
|| indentInfo === 'indent') {
indent(stream, state);
}
var delimiter_index = '[({'.indexOf(current);
if (delimiter_index !== -1) {
indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
}
if (indentInfo === 'dedent') {
if (dedent(stream, state)) {
return ERRORCLASS;
}
}
delimiter_index = '])}'.indexOf(current);
if (delimiter_index !== -1) {
if (dedent(stream, state, current)) {
return ERRORCLASS;
}
}
if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'py') {
if (state.scopes.length > 1) state.scopes.shift();
state.dedent -= 1;
}
return style;
}
var external = {
startState: function(basecolumn) {
return {
tokenize: tokenBase,
scopes: [{offset:basecolumn || 0, type:'py'}],
lastToken: null,
lambda: false,
dedent: 0
};
},
token: function(stream, state) {
var style = tokenLexer(stream, state);
state.lastToken = style;
if (stream.eol() && stream.lambda) {
state.lambda = false;
}
return style;
},
indent: function(state) {
if (state.tokenize != tokenBase) {
return state.tokenize.isString ? CodeMirror.Pass : 0;
}
return state.scopes[0].offset;
}
};
return external;
});
CodeMirror.defineMIME("text/x-python", "python");

View File

@ -1,21 +0,0 @@
LESS_SCRIPTS = hy.css
LESSC = lessc
LESSCFLAGS = -x
STATIC = static
.SUFFIXES:
.SUFFIXES: .less .css
all: build
build: $(LESS_SCRIPTS)
.less.css:
$(LESSC) $(LESSCFLAGS) $< > $@
.PHONY: build

View File

@ -1,53 +0,0 @@
@gh-text-color: #FFFFFF;
@gh-background: #ef7600;
@gh-border: #ef9f4c;
@gh-text-shadow: #522600;
@gh-text-color: #FFFFFF;
@gh-background: #356c96;
@gh-border: #5083A9;
@gh-text-shadow: #52a8ec;
#github {
display: block;
position: absolute;
z-index: 1001;
top: 40px;
right: -70px;
width: 250px;
padding: 3px 0;
border-top: 2px solid @gh-border;
border-bottom: 2px solid @gh-border;
background: @gh-background;
color: @gh-text-color;
text-align: center;
text-decoration: none;
font-size: 13px;
font-weight: bold;
line-height: 19px;
letter-spacing: -1px;
text-shadow: 0 0 10px @gh-text-shadow;
pointer-events: auto;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);
-webkit-box-shadow: rgba(0,0,0,0.5) 1px 1px 10px,rgba(0,0,0,0.07) 0 0 3px 1px inset;
-moz-box-shadow: rgba(0,0,0,0.5) 1px 1px 10px,rgba(0,0,0,0.07) 0 0 3px 1px inset;
box-shadow: rgba(0,0,0,0.5) 1px 1px 10px,rgba(0,0,0,0.07) 0 0 3px 1px inset;
}
#github-wrapper {
.sans-serif;
position: absolute;
z-index: 1001;
top: 0px;
right: 0px;
width: 135px;
height: 135px;
overflow: hidden;
pointer-events: none;
}

View File

@ -1,5 +0,0 @@
/* Copyright (c) Paul Tagliamonte <paultag@debian.org> 2013 under the
* terms and conditions of Hy it's self. */
@import "layout.less";
@import "github.less";

View File

@ -1,85 +0,0 @@
/* Copyright (c) Paul Tagliamonte <paultag@debian.org> 2013 under the
* terms and conditions of Hy it's self. */
.sans-serif {
font-family: cantarell, tahoma, sans-serif;
}
.reset {
padding: 0px;
margin: 0px;
}
body, html {
height: 100%;
color: #000000;
font-family: monospace;
.reset;
}
a {
color: #DCDCDC;
}
h1 {
text-align: center;
.reset;
}
.repl {
width: 49.9%;
height: 90%;
.reset;
}
.border {
outline: 0;
outline: thin dotted \9;
}
.ok {
border-color: rgba(82, 168, 236, 0.8);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
.border;
}
.error {
border-color: rgba(236, 103, 82, 0.8);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(236, 103, 82, 0.6);
.border;
}
.repl-root {
margin-top: 2%;
width: 90%;
height: 90%;
margin-left: auto;
margin-right: auto;
}
#python-repl {
.repl;
float: right;
}
#hython-repl {
.repl;
float: left;
border-right: 1px solid rgba(82, 168, 236, 0.2);
}
#hython-target {
display: none;
}
.clear {
clear: both;
}
#build-msgs {
border-top: 1px solid rgba(82, 168, 236, 0.2);
height: 8%;
padding: 5px;
color: #777777;
overflow: hidden;
}

View File

@ -1,7 +0,0 @@
import hy # NOQA
import hy.contrib.meth # NOQA
from app import app
if __name__ == '__main__':
app.run(debug=True)

View File

@ -1,21 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="{{ url_for("static", filename="css/pygments.css") }}" ></link>
<link rel="stylesheet" href="{{ url_for("static", filename="css/hy.css") }}" ></link>
<script src="{{ url_for("static", filename="js/jquery-1.9.1.min.js") }}" type="text/javascript" ></script>
<script src="{{ url_for("static", filename="js/date.js") }}" type="text/javascript" ></script>
<script src="{{ url_for("static", filename="js/main.js") }}" type="text/javascript" ></script>
{% block head %}{% endblock %}
</head>
<body>
<div id='github-wrapper'>
<a href='http://git.io/hy' id='github'>Fork me on GitHub</a>
</div>
{% block content %}
{% endblock %}
{% block tail %}
{% endblock %}
</body>
</html>

View File

@ -1,25 +0,0 @@
{% extends "base.html" %}
{% block title %}Welcome!{% endblock %}
{% block head %}
{% endblock %}
{% block content %}
<h1>Hi, Welcome to Hy!</h1>
<p>
Hy is a special Lisp langage. It compiles into a Python AST, and allows for
some pretty awesome stuff (like writing Flask or Django apps in Lisp).
</p>
<p>
It's got an extremely simple Macro system, which will hopefully become
a bit more advanced as the language develops.
</p>
<p>
<a href="https://hy.readthedocs.org/en/latest/" title="Hy Documentation">Read the docs</a> to learn more.
</p>
<p>
Want to try it out? Flip on JavaScript and try out the <a href="/repl" >REPL</a>
</p>
{% endblock %}

View File

@ -1,51 +0,0 @@
{% extends "base.html" %}
{% block title %}Welcome!{% endblock %}
{% block head %}
<script src="{{url_for("static", filename="js/codemirror.js")}}"></script>
<link rel="stylesheet" href="{{url_for("static", filename="css/codemirror.css")}}">
<link rel="stylesheet" href="{{url_for("static", filename="css/themes/elegant.css")}}">
<script src="{{url_for("static", filename="js/mode/clojure/clojure.js")}}"></script>
<script src="{{url_for("static", filename="js/mode/python/python.js")}}"></script>
{% endblock %}
{% block tail %}
<script src="{{url_for("static", filename="js/main.js")}}"></script>
{% endblock %}
{% block content %}
<div id='repl-root' class='repl-root' >
<div class='repl' id='hython-repl'>
<textarea id="hython-target">
;;;; This is Hy. Hy is a Lisp variant that
;;;; "compiles" to Python ASTs.
;;;;
;;;; This pane is the Hy lisp variant,
;;;; and the right side is what the output
;;;; AST looks like using the `codegen` module.
;;;;
;;;; star the repo @ http://git.io/hy
;;;;
(defn square [x]
"This function will square a number"
(* x x))
(print (square 2))
(defn add-two-numbers [x y]
(+ x y))
;; (dashes turn to underscores)
(print (add-two-numbers 1 2))
</textarea>
</div>
<div class='repl' id='python-repl'></div>
<div class='clear'></div>
<div class='msgs' id='build-msgs'></div>
</div>
{% endblock %}

View File

View File

@ -0,0 +1,10 @@
;;;
;;;
(import-from hy HyExpression HySymbol HyString)
(defn test-basic-quoting []
(assert (= (type (quote (foo bar))) HyExpression))
(assert (= (type (quote foo)) HySymbol))
(assert (= (type (quote "string")) HyString)))

View File

@ -19,6 +19,9 @@
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from __future__ import unicode_literals
from hy import HyString
from hy.compiler import hy_compile, HyCompileError
from hy.lex import tokenize
from hy.util import dump
@ -121,6 +124,11 @@ def test_ast_good_try():
hy_compile(tokenize("(try 1)"))
hy_compile(tokenize("(try 1 (except) (else 1))"))
hy_compile(tokenize("(try 1 (else 1) (except))"))
hy_compile(tokenize("(try 1 (finally 1) (except))"))
hy_compile(tokenize("(try 1 (finally 1))"))
hy_compile(tokenize("(try 1 (except) (finally 1))"))
hy_compile(tokenize("(try 1 (except) (finally 1) (else 1))"))
hy_compile(tokenize("(try 1 (except) (else 1) (finally 1))"))
def test_ast_bad_try():
@ -190,17 +198,6 @@ def test_ast_bad_lambda():
cant_compile("(lambda [])")
def test_ast_good_pass():
"Make sure AST can compile valid pass"
hy_compile(tokenize("(pass)"))
def test_ast_bad_pass():
"Make sure AST can't compile invalid pass"
cant_compile("(pass 1)")
cant_compile("(pass 1 2)")
def test_ast_good_yield():
"Make sure AST can compile valid yield"
hy_compile(tokenize("(yield 1)"))
@ -208,7 +205,6 @@ def test_ast_good_yield():
def test_ast_bad_yield():
"Make sure AST can't compile invalid yield"
cant_compile("(yield)")
cant_compile("(yield 1 2)")
@ -272,6 +268,16 @@ def test_ast_valid_while():
hy_compile(tokenize("(while foo bar)"))
def test_ast_valid_foreach():
"Make sure AST can compile valid foreach"
hy_compile(tokenize("(foreach [a 2])"))
def test_ast_invalid_foreach():
"Make sure AST can't compile invalid foreach"
cant_compile("(foreach [a 1] (else 1 2))")
def test_ast_expression_basics():
""" Ensure basic AST expression conversion works. """
code = hy_compile(tokenize("(foo bar)")).body[0]
@ -332,3 +338,20 @@ def test_lambda_list_keywords():
""" Ensure we can compile functions with lambda list keywords."""
hy_compile(tokenize("(fn (x &rest xs) (print xs))"))
cant_compile("(fn (x &rest xs &rest ys) (print xs))")
def test_ast_unicode_strings():
"""Ensure we handle unicode strings correctly"""
def _compile_string(s):
hy_s = HyString(s)
hy_s.start_line = hy_s.end_line = 0
hy_s.start_column = hy_s.end_column = 0
code = hy_compile([hy_s])
# code == ast.Module(body=[ast.Expr(value=ast.Str(s=xxx))])
return code.body[0].value.s
assert _compile_string("test") == "test"
assert _compile_string("\u03b1\u03b2") == "\u03b1\u03b2"
assert _compile_string("\xc3\xa9") == "\xc3\xa9"

View File

@ -0,0 +1 @@
from .native.quoting import * # NOQA

View File

@ -0,0 +1,20 @@
import os
import imp
import tempfile
from hy.importer import write_hy_as_pyc
def test_pyc():
"""Test pyc compilation."""
f = tempfile.NamedTemporaryFile(suffix='.hy', delete=False)
f.write(b'(defn pyctest [s] s)')
f.close()
write_hy_as_pyc(f.name)
os.unlink(f.name)
cfile = "%s.pyc" % f.name[:-len(".hy")]
mod = imp.load_compiled('pyc', cfile)
os.unlink(cfile)
assert mod.pyctest('Foo') == 'Foo'

View File

@ -21,6 +21,8 @@
from hy.models.expression import HyExpression
from hy.models.integer import HyInteger
from hy.models.lambdalist import HyLambdaListKeyword
from hy.models.float import HyFloat
from hy.models.complex import HyComplex
from hy.models.symbol import HySymbol
from hy.models.string import HyString
from hy.models.dict import HyDict
@ -85,6 +87,43 @@ def test_lex_lambda_list_keyword():
HyLambdaListKeyword("&rest"),
HySymbol("xs")])]
def test_lex_symbols():
""" Make sure that symbols are valid expressions"""
objs = tokenize("foo ")
assert objs == [HySymbol("foo")]
def test_lex_strings():
""" Make sure that strings are valid expressions"""
objs = tokenize("\"foo\" ")
assert objs == [HyString("foo")]
def test_lex_integers():
""" Make sure that integers are valid expressions"""
objs = tokenize("42 ")
assert objs == [HyInteger(42)]
def test_lex_expression_float():
""" Make sure expressions can produce floats """
objs = tokenize("(foo 2.)")
assert objs == [HyExpression([HySymbol("foo"), HyFloat(2.)])]
objs = tokenize("(foo -0.5)")
assert objs == [HyExpression([HySymbol("foo"), HyFloat(-0.5)])]
objs = tokenize("(foo 1.e7)")
assert objs == [HyExpression([HySymbol("foo"), HyFloat(1.e7)])]
def test_lex_expression_complex():
""" Make sure expressions can produce complex """
objs = tokenize("(foo 2.j)")
assert objs == [HyExpression([HySymbol("foo"), HyComplex(2.j)])]
objs = tokenize("(foo -0.5j)")
assert objs == [HyExpression([HySymbol("foo"), HyComplex(-0.5j)])]
objs = tokenize("(foo 1.e7j)")
assert objs == [HyExpression([HySymbol("foo"), HyComplex(1.e7j)])]
def test_lex_line_counting():
""" Make sure we can count lines / columns """

View File

@ -172,11 +172,11 @@
(try (do))
(try (pass))
(try (do))
(try (pass) (except))
(try (do) (except))
(try (pass) (except [IOError]) (except))
(try (do) (except [IOError]) (except))
;; Test correct (raise)
(let [[passed false]]
@ -198,6 +198,34 @@
(setv passed true)))
(assert passed))
;; Test (finally)
(let [[passed false]]
(try
(do)
(finally (setv passed true)))
(assert passed))
;; Test (finally) + (raise)
(let [[passed false]]
(try
(raise Exception)
(except)
(finally (setv passed true)))
(assert passed))
;; Test (finally) + (raise) + (else)
(let [[passed false]
[not-elsed true]]
(try
(raise Exception)
(except)
(else (setv not-elsed false))
(finally (setv passed true)))
(assert passed)
(assert not-elsed))
(try
(raise (KeyError))
(catch [[IOError]] (assert false))
@ -208,16 +236,15 @@
(except [[IOError]] (assert false))
(catch [e [KeyError]] (assert e)))
(try
(get [1] 3)
(catch [IndexError] (assert true))
(except [IndexError] (pass)))
(except [IndexError] (do)))
(try
(print foobar42ofthebaz)
(catch [IndexError] (assert false))
(except [NameError] (pass)))
(except [NameError] (do)))
(try
(get [1] 3)
@ -233,11 +260,11 @@
(try
(print foobar42)
(catch [[IndexError NameError]] (pass)))
(catch [[IndexError NameError]] (do)))
(try
(get [1] 3)
(catch [[IndexError NameError]] (pass)))
(catch [[IndexError NameError]] (do)))
(try
(print foobar42ofthebaz)
@ -249,7 +276,7 @@
(try
(print foobar42ofthebaz)
(except [] (pass)))
(except [] (do)))
(try
(print foobar42ofthebaz)
@ -259,7 +286,7 @@
(let [[passed false]]
(try
(try (pass) (except) (else (bla)))
(try (do) (except) (else (bla)))
(except [NameError] (setv passed true)))
(assert passed))
@ -324,7 +351,7 @@
(defn test-pass []
"NATIVE: Test pass worksish"
(if true (pass) (pass))
(if true (do) (do))
(assert (= 1 1)))
@ -362,7 +389,7 @@
(defn test-context []
"NATIVE: test with"
(with [fd (open "README.md" "r")] (assert fd))
(with [(open "README.md" "r")] (pass)))
(with [(open "README.md" "r")] (do)))
(defn test-for-doodle []
@ -375,6 +402,21 @@
(assert (= y x 2)))
(defn test-foreach-else []
"NATIVE: test foreach else"
(let [[x 0]]
(foreach [a [1 2]]
(setv x (+ x a))
(else (setv x (+ x 50))))
(assert (= x 53)))
(let [[x 0]]
(foreach [a [1 2]]
(setv x (+ x a))
(else))
(assert (= x 3))))
(defn test-comprehensions []
"NATIVE: test list comprehensions"
(assert (= (list-comp (* x 2) (x (range 2))) [0 2]))
@ -506,20 +548,71 @@
2)
1)))
(assert (= 1 (let [[x 1] [y 2]]
(pass)
(pass)
(do)
(do)
((fn [] 1))))))
(defn test-keyword []
"NATIVE: test if keywords are recognised"
; FEATURE: native hy-eval
;
; - related to bug #64
; - https://github.com/paultag/hy/issues/64
; - https://github.com/paultag/hy/pull/62
;
; (defn test-eval []
; "NATIVE: test eval"
; (assert (= 1 (eval 1)))
; (assert (= "foobar" (eval "foobar")))
; (setv x 42)
; (assert (= x (eval x))))
(assert (= :foo :foo))
(assert (= (get {:foo "bar"} :foo) "bar"))
(assert (= (get {:bar "quux"} (get {:foo :bar} :foo)) "quux")))
(defn test-keyword-clash []
"NATIVE: test that keywords do not clash with normal strings"
(assert (= (get {:foo "bar" ":foo" "quux"} :foo) "bar"))
(assert (= (get {:foo "bar" ":foo" "quux"} ":foo") "quux")))
(defn test-nested-if []
"NATIVE: test nested if"
(for [x (range 10)]
(if (in "foo" "foobar")
(do
(if true true true))
(do
(if false false false)))))
(defn test-eval []
"NATIVE: test eval"
(assert (= 2 (eval (quote (+ 1 1)))))
(setf x 2)
(assert (= 4 (eval (quote (+ x 2)))))
(setf test-payload (quote (+ x 2)))
(setf x 4)
(assert (= 6 (eval test-payload)))
(assert (= 6 (eval (quote ((fn [] (+ 3 3)))))))
(assert (= 1 (eval (quote 1))))
(assert (= "foobar" (eval (quote "foobar"))))
(setv x (quote 42))
(assert (= x (eval x))))
(defn test-import-syntax []
"NATIVE: test the import syntax."
; Simple import
(import sys os)
; from os.path import basename
(import [os.path [basename]])
(assert (= (basename "/some/path") "path"))
; import os.path as p
(import [os.path :as p])
(assert (= p.basename basename))
; from os.path import basename as bn
(import [os.path [basename :as bn]])
(assert (= bn basename))
(import [sys])
;; Multiple stuff to import
(import sys [os.path [dirname]]
[os.path :as op]
[os.path [dirname :as dn]])
(assert (= (dirname "/some/path") "/some"))
(assert (= op.dirname dirname))
(assert (= dn dirname)))

View File

@ -27,8 +27,111 @@
(setv test_div (fn []
"NATIVE: Test division"
(assert (= 25 (/ 100 2 2)))))
(assert (= 25 (/ 100 2 2)))
; Commented out until float constants get implemented
; (assert (= 0.5 (/ 1 2)))
(assert (= 1 (* 2 (/ 1 2))))))
(setv test_int_div (fn []
"NATIVE: Test integer division"
(assert (= 25 (// 101 2 2)))))
(defn test-modulo []
"NATIVE: test mod"
(assert (= (% 10 2) 0)))
(defn test-pow []
"NATIVE: test pow"
(assert (= (** 10 2) 100)))
(defn test-lshift []
"NATIVE: test lshift"
(assert (= (<< 1 2) 4)))
(defn test-rshift []
"NATIVE: test lshift"
(assert (= (>> 8 1) 4)))
(defn test-bitor []
"NATIVE: test lshift"
(assert (= (| 1 2) 3)))
(defn test-bitxor []
"NATIVE: test xor"
(assert (= (^ 1 2) 3)))
(defn test-bitand []
"NATIVE: test lshift"
(assert (= (& 1 2) 0)))
(defn test-augassign-add []
"NATIVE: test augassign add"
(let [[x 1]]
(+= x 41)
(assert (= x 42))))
(defn test-augassign-sub []
"NATIVE: test augassign sub"
(let [[x 1]]
(-= x 41)
(assert (= x -40))))
(defn test-augassign-mult []
"NATIVE: test augassign mult"
(let [[x 1]]
(*= x 41)
(assert (= x 41))))
(defn test-augassign-div []
"NATIVE: test augassign div"
(let [[x 42]]
(/= x 2)
(assert (= x 21))))
(defn test-augassign-floordiv []
"NATIVE: test augassign floordiv"
(let [[x 42]]
(//= x 2)
(assert (= x 21))))
(defn test-augassign-mod []
"NATIVE: test augassign mod"
(let [[x 42]]
(%= x 2)
(assert (= x 0))))
(defn test-augassign-pow []
"NATIVE: test augassign pow"
(let [[x 2]]
(**= x 3)
(assert (= x 8))))
(defn test-augassign-lshift []
"NATIVE: test augassign lshift"
(let [[x 2]]
(<<= x 2)
(assert (= x 8))))
(defn test-augassign-rshift []
"NATIVE: test augassign rshift"
(let [[x 8]]
(>>= x 1)
(assert (= x 4))))
(defn test-augassign-bitand []
"NATIVE: test augassign bitand"
(let [[x 8]]
(&= x 1)
(assert (= x 0))))
(defn test-augassign-bitor []
"NATIVE: test augassign bitand"
(let [[x 0]]
(|= x 2)
(assert (= x 2))))
(defn test-augassign-bitxor []
"NATIVE: test augassign bitand"
(let [[x 1]]
(^= x 1)
(assert (= x 0))))