From 11799d3a9cbe9530ad8a04a379115b95b34bd097 Mon Sep 17 00:00:00 2001 From: Danny Yoo Date: Thu, 8 Sep 2011 17:10:16 -0400 Subject: [PATCH 01/27] renaming RUNTIME references to RT to see if that shortens code. --- js-assembler/assemble-expression.rkt | 4 +- js-assembler/assemble-helpers.rkt | 48 ++++++++++----------- js-assembler/assemble-open-coded.rkt | 20 ++++----- js-assembler/assemble-perform-statement.rkt | 16 +++---- js-assembler/assemble.rkt | 12 +++--- tests/test-assemble.rkt | 4 +- 6 files changed, 52 insertions(+), 52 deletions(-) diff --git a/js-assembler/assemble-expression.rkt b/js-assembler/assemble-expression.rkt index 16b32f7..dfa0369 100644 --- a/js-assembler/assemble-expression.rkt +++ b/js-assembler/assemble-expression.rkt @@ -17,7 +17,7 @@ "MACHINE.proc.label"] [(MakeCompiledProcedure? op) - (format "new RUNTIME.Closure(~a, ~a, [~a], ~a)" + (format "new RT.Closure(~a, ~a, [~a], ~a)" (assemble-label (make-Label (MakeCompiledProcedure-label op))) (assemble-arity (MakeCompiledProcedure-arity op)) (string-join (map @@ -31,7 +31,7 @@ (assemble-display-name (MakeCompiledProcedure-display-name op)))] [(MakeCompiledProcedureShell? op) - (format "new RUNTIME.Closure(~a, ~a, undefined, ~a)" + (format "new RT.Closure(~a, ~a, undefined, ~a)" (assemble-label (make-Label (MakeCompiledProcedureShell-label op))) (assemble-arity (MakeCompiledProcedureShell-arity op)) (assemble-display-name (MakeCompiledProcedureShell-display-name op)))] diff --git a/js-assembler/assemble-helpers.rkt b/js-assembler/assemble-helpers.rkt index c79e098..35dffd0 100644 --- a/js-assembler/assemble-helpers.rkt +++ b/js-assembler/assemble-helpers.rkt @@ -74,7 +74,7 @@ (cond [(PrimitivesReference? target) (lambda: ([rhs : String]) - (format "RUNTIME.Primitives[~s]=RUNTIME.Primitives[~s]||~a;" + (format "RT.Primitives[~s]=RT.Primitives[~s]||~a;" (symbol->string (PrimitivesReference-name target)) (symbol->string (PrimitivesReference-name target)) rhs))] @@ -111,38 +111,38 @@ (define (assemble-const stmt) (let: loop : String ([val : const-value (Const-const stmt)]) (cond [(symbol? val) - (format "RUNTIME.makeSymbol(~s)" (symbol->string val))] + (format "RT.makeSymbol(~s)" (symbol->string val))] [(pair? val) - (format "RUNTIME.makePair(~a,~a)" + (format "RT.makePair(~a,~a)" (loop (car val)) (loop (cdr val)))] [(boolean? val) (if val "true" "false")] [(void? val) - "RUNTIME.VOID"] + "RT.VOID"] [(empty? val) - (format "RUNTIME.NULL")] + (format "RT.NULL")] [(number? val) (assemble-numeric-constant val)] [(string? val) (format "~s" val)] [(char? val) - (format "RUNTIME.makeChar(~s)" (string val))] + (format "RT.makeChar(~s)" (string val))] [(bytes? val) - (format "RUNTIME.makeBytes(~a)" + (format "RT.makeBytes(~a)" (string-join (for/list ([a-byte val]) (number->string a-byte)) ","))] [(path? val) - (format "RUNTIME.makePath(~s)" + (format "RT.makePath(~s)" (path->string val))] [(vector? val) - (format "RUNTIME.makeVector(~a)" + (format "RT.makeVector(~a)" (string-join (for/list ([elt (vector->list val)]) (loop elt)) ","))] [(box? val) - (format "RUNTIME.makeBox(~s)" + (format "RT.makeBox(~s)" (loop (unbox val)))]))) @@ -152,9 +152,9 @@ (let loop ([vals vals]) (cond [(empty? vals) - "RUNTIME.NULL"] + "RT.NULL"] [else - (format "RUNTIME.makePair(~a,~a)" (first vals) (loop (rest vals)))]))) + (format "RT.makePair(~a,~a)" (first vals) (loop (rest vals)))]))) @@ -171,15 +171,15 @@ (define (floating-number->js a-num) (cond [(eqv? a-num -0.0) - "RUNTIME.NEGATIVE_ZERO"] + "RT.NEGATIVE_ZERO"] [(eqv? a-num +inf.0) - "RUNTIME.INF"] + "RT.INF"] [(eqv? a-num -inf.0) - "RUNTIME.NEGATIVE_INF"] + "RT.NEGATIVE_INF"] [(eqv? a-num +nan.0) - "RUNTIME.NAN"] + "RT.NAN"] [else - (string-append "RUNTIME.makeFloat(" (number->string a-num) ")")])) + (string-append "RT.makeFloat(" (number->string a-num) ")")])) ;; FIXME: fix the type signature when typed-racket isn't breaking on ;; (define-predicate ExactRational? (U Exact-Rational)) @@ -188,7 +188,7 @@ (cond [(= (denominator a-num) 1) (string-append (integer->js (ensure-integer (numerator a-num))))] [else - (string-append "RUNTIME.makeRational(" + (string-append "RT.makeRational(" (integer->js (ensure-integer (numerator a-num))) "," (integer->js (ensure-integer (denominator a-num))) @@ -211,7 +211,7 @@ (number->string an-int)] ;; overflow case [else - (string-append "RUNTIME.makeBignum(" + (string-append "RT.makeBignum(" (format "~s" (number->string an-int)) ")")])) @@ -223,7 +223,7 @@ (floating-number->js a-num)] [(complex? a-num) - (string-append "RUNTIME.makeComplex(" + (string-append "RT.makeComplex(" (assemble-numeric-constant (real-part a-num)) "," (assemble-numeric-constant (imag-part a-num)) @@ -328,7 +328,7 @@ (: assemble-default-continuation-prompt-tag (-> String)) (define (assemble-default-continuation-prompt-tag) - "RUNTIME.DEFAULT_CONTINUATION_PROMPT_TAG") + "RT.DEFAULT_CONTINUATION_PROMPT_TAG") @@ -350,7 +350,7 @@ [(natural? an-arity) (number->string an-arity)] [(ArityAtLeast? an-arity) - (format "(RUNTIME.makeArityAtLeast(~a))" + (format "(RT.makeArityAtLeast(~a))" (ArityAtLeast-value an-arity))] [(listof-atomic-arity? an-arity) (assemble-listof-assembled-values @@ -360,7 +360,7 @@ [(natural? atomic-arity) (number->string atomic-arity)] [(ArityAtLeast? atomic-arity) - (format "(RUNTIME.makeArityAtLeast(~a))" + (format "(RT.makeArityAtLeast(~a))" (ArityAtLeast-value atomic-arity))])) an-arity))])) @@ -425,6 +425,6 @@ (: assemble-variable-reference (VariableReference -> String)) (define (assemble-variable-reference varref) (let ([t (VariableReference-toplevel varref)]) - (format "(new RUNTIME.VariableReference(MACHINE.env[MACHINE.env.length-~a],~a))" + (format "(new RT.VariableReference(MACHINE.env[MACHINE.env.length-~a],~a))" (add1 (ToplevelRef-depth t)) (ToplevelRef-pos t)))) \ No newline at end of file diff --git a/js-assembler/assemble-open-coded.rkt b/js-assembler/assemble-open-coded.rkt index 1d4b789..542eaf1 100644 --- a/js-assembler/assemble-open-coded.rkt +++ b/js-assembler/assemble-open-coded.rkt @@ -70,7 +70,7 @@ (assemble-boolean-chain "plt.baselib.numbers.greaterThanOrEqual" checked-operands)] [(cons) - (format "RUNTIME.makePair(~a, ~a)" + (format "RT.makePair(~a, ~a)" (first checked-operands) (second checked-operands))] @@ -85,15 +85,15 @@ (assemble-listof-assembled-values checked-operands))] [(list?) - (format "RUNTIME.isList(~a)" + (format "RT.isList(~a)" (first checked-operands))] [(pair?) - (format "RUNTIME.isPair(~a)" + (format "RT.isPair(~a)" (first checked-operands))] [(null?) - (format "(~a === RUNTIME.NULL)" (first checked-operands))] + (format "(~a === RT.NULL)" (first checked-operands))] [(not) (format "(~a === false)" (first checked-operands))] @@ -154,16 +154,16 @@ (let: ([predicate : String (case domain [(number) - (format "RUNTIME.isNumber")] + (format "RT.isNumber")] [(string) - (format "RUNTIME.isString")] + (format "RT.isString")] [(list) - (format "RUNTIME.isList")] + (format "RT.isList")] [(pair) - (format "RUNTIME.isPair")] + (format "RT.isPair")] [(box) - (format "RUNTIME.isBox")])]) - (format "RUNTIME.testArgument(MACHINE, ~s, ~a, ~a, ~a, ~s)" + (format "RT.isBox")])]) + (format "RT.testArgument(MACHINE, ~s, ~a, ~a, ~a, ~s)" (symbol->string domain) predicate operand-string diff --git a/js-assembler/assemble-perform-statement.rkt b/js-assembler/assemble-perform-statement.rkt index 82ad504..dbf4e46 100644 --- a/js-assembler/assemble-perform-statement.rkt +++ b/js-assembler/assemble-perform-statement.rkt @@ -14,7 +14,7 @@ (cond [(CheckToplevelBound!? op) - (format "if (MACHINE.env[MACHINE.env.length - 1 - ~a][~a] === undefined) { RUNTIME.raiseUnboundToplevelError(MACHINE.env[MACHINE.env.length - 1 - ~a].names[~a]); }" + (format "if (MACHINE.env[MACHINE.env.length - 1 - ~a][~a] === undefined) { RT.raiseUnboundToplevelError(MACHINE.env[MACHINE.env.length - 1 - ~a].names[~a]); }" (CheckToplevelBound!-depth op) (CheckToplevelBound!-pos op) (CheckToplevelBound!-depth op) @@ -22,13 +22,13 @@ [(CheckClosureArity!? op) - (format "if(!(MACHINE.proc instanceof RUNTIME.Closure)){RUNTIME.raiseOperatorIsNotClosure(MACHINE,MACHINE.proc);}if(!RUNTIME.isArityMatching(MACHINE.proc.racketArity,~a)){RUNTIME.raiseArityMismatchError(MACHINE, MACHINE.proc,~a);}" + (format "if(!(MACHINE.proc instanceof RT.Closure)){RT.raiseOperatorIsNotClosure(MACHINE,MACHINE.proc);}if(!RT.isArityMatching(MACHINE.proc.racketArity,~a)){RT.raiseArityMismatchError(MACHINE, MACHINE.proc,~a);}" (assemble-oparg (CheckClosureArity!-num-args op)) (assemble-oparg (CheckClosureArity!-num-args op)))] [(CheckPrimitiveArity!? op) - (format "if(!RUNTIME.isArityMatching(MACHINE.proc.racketArity,~a)){RUNTIME.raiseArityMismatchError(MACHINE,MACHINE.proc,~a);}" + (format "if(!RT.isArityMatching(MACHINE.proc.racketArity,~a)){RT.raiseArityMismatchError(MACHINE,MACHINE.proc,~a);}" (assemble-oparg (CheckPrimitiveArity!-num-args op)) (assemble-oparg (CheckPrimitiveArity!-num-args op)))] @@ -125,28 +125,28 @@ "MACHINE.val);")] [(RaiseContextExpectedValuesError!? op) - (format "RUNTIME.raiseContextExpectedValuesError(MACHINE,~a);" + (format "RT.raiseContextExpectedValuesError(MACHINE,~a);" (RaiseContextExpectedValuesError!-expected op))] [(RaiseArityMismatchError!? op) - (format "RUNTIME.raiseArityMismatchError(MACHINE,~a,~a);" + (format "RT.raiseArityMismatchError(MACHINE,~a,~a);" (assemble-oparg (RaiseArityMismatchError!-proc op)) (assemble-oparg (RaiseArityMismatchError!-received op)))] [(RaiseOperatorApplicationError!? op) - (format "RUNTIME.raiseOperatorApplicationError(MACHINE,~a);" + (format "RT.raiseOperatorApplicationError(MACHINE,~a);" (assemble-oparg (RaiseOperatorApplicationError!-operator op)))] [(RaiseUnimplementedPrimitiveError!? op) - (format "RUNTIME.raiseUnimplementedPrimitiveError(MACHINE,~s);" + (format "RT.raiseUnimplementedPrimitiveError(MACHINE,~s);" (symbol->string (RaiseUnimplementedPrimitiveError!-name op)))] [(InstallModuleEntry!? op) - (format "MACHINE.modules[~s]=new RUNTIME.ModuleRecord(~s,~a);" + (format "MACHINE.modules[~s]=new RT.ModuleRecord(~s,~a);" (symbol->string (ModuleLocator-name (InstallModuleEntry!-path op))) (symbol->string (InstallModuleEntry!-name op)) (assemble-label (make-Label (InstallModuleEntry!-entry-point op))))] diff --git a/js-assembler/assemble.rkt b/js-assembler/assemble.rkt index 9ff2735..3526860 100644 --- a/js-assembler/assemble.rkt +++ b/js-assembler/assemble.rkt @@ -41,7 +41,7 @@ (define (assemble/write-invoke stmts op) (display "(function(MACHINE, success, fail, params) {\n" op) (display "var param;\n" op) - (display "var RUNTIME = plt.runtime;\n" op) + (display "var RT = plt.runtime;\n" op) (define-values (basic-blocks entry-points) (fracture stmts)) @@ -241,7 +241,7 @@ EOF (assemble-oparg (TestPrimitiveProcedure-operand test)))] [(TestClosureArityMismatch? test) - (format "if(!RUNTIME.isArityMatching((~a).racketArity,~a))" + (format "if(!RT.isArityMatching((~a).racketArity,~a))" (assemble-oparg (TestClosureArityMismatch-closure test)) (assemble-oparg (TestClosureArityMismatch-n test)))])) (display test-code op) @@ -440,7 +440,7 @@ EOF (assemble-oparg (TestPrimitiveProcedure-operand test)) jump)] [(TestClosureArityMismatch? test) - (format "if(!RUNTIME.isArityMatching((~a).racketArity,~a)){~a}" + (format "if(!RT.isArityMatching((~a).racketArity,~a)){~a}" (assemble-oparg (TestClosureArityMismatch-closure test)) (assemble-oparg (TestClosureArityMismatch-n test)) jump)]) @@ -450,10 +450,10 @@ EOF (assemble-jump (GotoStatement-target stmt))] [(PushControlFrame/Generic? stmt) - "MACHINE.control.push(new RUNTIME.Frame());"] + "MACHINE.control.push(new RT.Frame());"] [(PushControlFrame/Call? stmt) - (format "MACHINE.control.push(new RUNTIME.CallFrame(~a,MACHINE.proc));" + (format "MACHINE.control.push(new RT.CallFrame(~a,MACHINE.proc));" (let: ([label : (U Symbol LinkedLabel) (PushControlFrame/Call-label stmt)]) (cond [(symbol? label) @@ -463,7 +463,7 @@ EOF [(PushControlFrame/Prompt? stmt) ;; fixme: use a different frame structure - (format "MACHINE.control.push(new RUNTIME.PromptFrame(~a,~a));" + (format "MACHINE.control.push(new RT.PromptFrame(~a,~a));" (let: ([label : (U Symbol LinkedLabel) (PushControlFrame/Prompt-label stmt)]) (cond [(symbol? label) diff --git a/tests/test-assemble.rkt b/tests/test-assemble.rkt index a9551ed..a6f8e8f 100644 --- a/tests/test-assemble.rkt +++ b/tests/test-assemble.rkt @@ -46,7 +46,7 @@ "(function() { " runtime - "var RUNTIME = plt.runtime;" + "var RT = plt.runtime;" "var MACHINE = new plt.runtime.Machine();\n" "return function(success, fail, params){" @@ -65,7 +65,7 @@ [inspector (cdr a-statement+inspector)]) (display runtime op) - "var RUNTIME = plt.runtime;" + "var RT = plt.runtime;" (display "var MACHINE = new plt.runtime.Machine();\n" op) (display "(function() { " op) (display "var myInvoke = " op) From 9f978f5592c9d47e29564a7cab753b09a8678f72 Mon Sep 17 00:00:00 2001 From: Danny Yoo Date: Thu, 8 Sep 2011 17:18:15 -0400 Subject: [PATCH 02/27] reducing code size by renaming MACHINE to M, RUNTIME to RT --- js-assembler/assemble-expression.rkt | 10 ++-- js-assembler/assemble-helpers.rkt | 38 ++++++------ js-assembler/assemble-open-coded.rkt | 2 +- js-assembler/assemble-perform-statement.rkt | 52 ++++++++-------- js-assembler/assemble.rkt | 30 +++++----- js-assembler/package.rkt | 50 ++++++++-------- tests/test-assemble.rkt | 66 ++++++++++----------- 7 files changed, 124 insertions(+), 124 deletions(-) diff --git a/js-assembler/assemble-expression.rkt b/js-assembler/assemble-expression.rkt index dfa0369..651da60 100644 --- a/js-assembler/assemble-expression.rkt +++ b/js-assembler/assemble-expression.rkt @@ -14,7 +14,7 @@ (define (assemble-op-expression op) (cond [(GetCompiledProcedureEntry? op) - "MACHINE.proc.label"] + "M.proc.label"] [(MakeCompiledProcedure? op) (format "new RT.Closure(~a, ~a, [~a], ~a)" @@ -37,14 +37,14 @@ (assemble-display-name (MakeCompiledProcedureShell-display-name op)))] [(ApplyPrimitiveProcedure? op) - (format "MACHINE.proc(MACHINE)")] + (format "M.proc(M)")] [(CaptureEnvironment? op) - (format "MACHINE.env.slice(0, MACHINE.env.length - ~a)" + (format "M.env.slice(0, M.env.length - ~a)" (CaptureEnvironment-skip op))] [(CaptureControl? op) - (format "MACHINE.captureControl(~a, ~a)" + (format "M.captureControl(~a, ~a)" (CaptureControl-skip op) (let: ([tag : (U DefaultContinuationPromptTag OpArg) (CaptureControl-tag op)]) @@ -55,7 +55,7 @@ [(MakeBoxedEnvironmentValue? op) - (format "[MACHINE.env[MACHINE.env.length - 1 - ~a]]" + (format "[M.env[M.env.length - 1 - ~a]]" (MakeBoxedEnvironmentValue-depth op))] [(CallKernelPrimitiveProcedure? op) diff --git a/js-assembler/assemble-helpers.rkt b/js-assembler/assemble-helpers.rkt index 35dffd0..0e721a9 100644 --- a/js-assembler/assemble-helpers.rkt +++ b/js-assembler/assemble-helpers.rkt @@ -83,11 +83,11 @@ (format "~a=~a;" (cond [(eq? target 'proc) - "MACHINE.proc"] + "M.proc"] [(eq? target 'val) - "MACHINE.val"] + "M.val"] [(eq? target 'argcount) - "MACHINE.argcount"] + "M.argcount"] [(EnvLexicalReference? target) (assemble-lexical-reference target)] [(EnvPrefixReference? target) @@ -95,7 +95,7 @@ [(ControlFrameTemporary? target) (assemble-control-frame-temporary target)] [(ModulePrefixTarget? target) - (format "MACHINE.modules[~s].prefix" + (format "M.modules[~s].prefix" (symbol->string (ModuleLocator-name (ModulePrefixTarget-path target))))]) rhs))])) @@ -103,7 +103,7 @@ (: assemble-control-frame-temporary (ControlFrameTemporary -> String)) (define (assemble-control-frame-temporary t) - (format "MACHINE.control[MACHINE.control.length-1].~a" + (format "M.control[M.control.length-1].~a" (ControlFrameTemporary-name t))) ;; fixme: use js->string @@ -253,26 +253,26 @@ (: assemble-lexical-reference (EnvLexicalReference -> String)) (define (assemble-lexical-reference a-lex-ref) (if (EnvLexicalReference-unbox? a-lex-ref) - (format "MACHINE.env[MACHINE.env.length-~a][0]" + (format "M.env[M.env.length-~a][0]" (add1 (EnvLexicalReference-depth a-lex-ref))) - (format "MACHINE.env[MACHINE.env.length-~a]" + (format "M.env[M.env.length-~a]" (add1 (EnvLexicalReference-depth a-lex-ref))))) (: assemble-prefix-reference (EnvPrefixReference -> String)) (define (assemble-prefix-reference a-ref) - (format "MACHINE.env[MACHINE.env.length-~a][~a]" + (format "M.env[M.env.length-~a][~a]" (add1 (EnvPrefixReference-depth a-ref)) (EnvPrefixReference-pos a-ref))) (: assemble-whole-prefix-reference (EnvWholePrefixReference -> String)) (define (assemble-whole-prefix-reference a-prefix-ref) - (format "MACHINE.env[MACHINE.env.length-~a]" + (format "M.env[M.env.length-~a]" (add1 (EnvWholePrefixReference-depth a-prefix-ref)))) (: assemble-reg (Reg -> String)) (define (assemble-reg a-reg) - (string-append "MACHINE." (symbol->string (Reg-name a-reg)))) + (string-append "M." (symbol->string (Reg-name a-reg)))) @@ -302,12 +302,12 @@ (: assemble-control-stack-label (ControlStackLabel -> String)) (define (assemble-control-stack-label a-csl) - "MACHINE.control[MACHINE.control.length-1].label") + "M.control[M.control.length-1].label") (: assemble-control-stack-label/multiple-value-return (ControlStackLabel/MultipleValueReturn -> String)) (define (assemble-control-stack-label/multiple-value-return a-csl) - "MACHINE.control[MACHINE.control.length-1].label.multipleValueReturn") + "M.control[M.control.length-1].label.multipleValueReturn") @@ -337,7 +337,7 @@ ;; lexical references: they must remain boxes. So all we need is ;; the depth into the environment. (define (assemble-env-reference/closure-capture depth) - (format "MACHINE.env[MACHINE.env.length - ~a]" + (format "M.env[M.env.length - ~a]" (add1 depth))) @@ -370,7 +370,7 @@ (: assemble-jump (OpArg -> String)) (define (assemble-jump target) - (format "return(~a)(MACHINE);" (assemble-oparg target))) + (format "return(~a)(M);" (assemble-oparg target))) @@ -399,25 +399,25 @@ (: assemble-primitive-kernel-value (PrimitiveKernelValue -> String)) (define (assemble-primitive-kernel-value a-prim) - (format "MACHINE.primitives[~s]" (symbol->string (PrimitiveKernelValue-id a-prim)))) + (format "M.primitives[~s]" (symbol->string (PrimitiveKernelValue-id a-prim)))) (: assemble-module-entry (ModuleEntry -> String)) (define (assemble-module-entry entry) - (format "MACHINE.modules[~s].label" + (format "M.modules[~s].label" (symbol->string (ModuleLocator-name (ModuleEntry-name entry))))) (: assemble-is-module-invoked (IsModuleInvoked -> String)) (define (assemble-is-module-invoked entry) - (format "MACHINE.modules[~s].isInvoked" + (format "M.modules[~s].isInvoked" (symbol->string (ModuleLocator-name (IsModuleInvoked-name entry))))) (: assemble-is-module-linked (IsModuleLinked -> String)) (define (assemble-is-module-linked entry) - (format "(MACHINE.modules[~s]!==undefined)" + (format "(M.modules[~s]!==undefined)" (symbol->string (ModuleLocator-name (IsModuleLinked-name entry))))) @@ -425,6 +425,6 @@ (: assemble-variable-reference (VariableReference -> String)) (define (assemble-variable-reference varref) (let ([t (VariableReference-toplevel varref)]) - (format "(new RT.VariableReference(MACHINE.env[MACHINE.env.length-~a],~a))" + (format "(new RT.VariableReference(M.env[M.env.length-~a],~a))" (add1 (ToplevelRef-depth t)) (ToplevelRef-pos t)))) \ No newline at end of file diff --git a/js-assembler/assemble-open-coded.rkt b/js-assembler/assemble-open-coded.rkt index 542eaf1..57bc7e3 100644 --- a/js-assembler/assemble-open-coded.rkt +++ b/js-assembler/assemble-open-coded.rkt @@ -163,7 +163,7 @@ (format "RT.isPair")] [(box) (format "RT.isBox")])]) - (format "RT.testArgument(MACHINE, ~s, ~a, ~a, ~a, ~s)" + (format "RT.testArgument(M, ~s, ~a, ~a, ~a, ~s)" (symbol->string domain) predicate operand-string diff --git a/js-assembler/assemble-perform-statement.rkt b/js-assembler/assemble-perform-statement.rkt index dbf4e46..956c611 100644 --- a/js-assembler/assemble-perform-statement.rkt +++ b/js-assembler/assemble-perform-statement.rkt @@ -14,7 +14,7 @@ (cond [(CheckToplevelBound!? op) - (format "if (MACHINE.env[MACHINE.env.length - 1 - ~a][~a] === undefined) { RT.raiseUnboundToplevelError(MACHINE.env[MACHINE.env.length - 1 - ~a].names[~a]); }" + (format "if (M.env[M.env.length - 1 - ~a][~a] === undefined) { RT.raiseUnboundToplevelError(M.env[M.env.length - 1 - ~a].names[~a]); }" (CheckToplevelBound!-depth op) (CheckToplevelBound!-pos op) (CheckToplevelBound!-depth op) @@ -22,31 +22,31 @@ [(CheckClosureArity!? op) - (format "if(!(MACHINE.proc instanceof RT.Closure)){RT.raiseOperatorIsNotClosure(MACHINE,MACHINE.proc);}if(!RT.isArityMatching(MACHINE.proc.racketArity,~a)){RT.raiseArityMismatchError(MACHINE, MACHINE.proc,~a);}" + (format "if(!(M.proc instanceof RT.Closure)){RT.raiseOperatorIsNotClosure(M,M.proc);}if(!RT.isArityMatching(M.proc.racketArity,~a)){RT.raiseArityMismatchError(M, M.proc,~a);}" (assemble-oparg (CheckClosureArity!-num-args op)) (assemble-oparg (CheckClosureArity!-num-args op)))] [(CheckPrimitiveArity!? op) - (format "if(!RT.isArityMatching(MACHINE.proc.racketArity,~a)){RT.raiseArityMismatchError(MACHINE,MACHINE.proc,~a);}" + (format "if(!RT.isArityMatching(M.proc.racketArity,~a)){RT.raiseArityMismatchError(M,M.proc,~a);}" (assemble-oparg (CheckPrimitiveArity!-num-args op)) (assemble-oparg (CheckPrimitiveArity!-num-args op)))] [(ExtendEnvironment/Prefix!? op) (let: ([names : (Listof (U Symbol False GlobalBucket ModuleVariable)) (ExtendEnvironment/Prefix!-names op)]) - (format "MACHINE.env.push([~a]);MACHINE.env[MACHINE.env.length-1].names=[~a];" + (format "M.env.push([~a]);M.env[M.env.length-1].names=[~a];" (string-join (map (lambda: ([n : (U Symbol False GlobalBucket ModuleVariable)]) (cond [(symbol? n) - (format "MACHINE.params.currentNamespace[~s] || MACHINE.primitives[~s]" + (format "M.params.currentNamespace[~s] || M.primitives[~s]" (symbol->string n) (symbol->string n))] [(eq? n #f) "false"] [(GlobalBucket? n) ;; FIXME: maybe we should keep a set of global variables here? - (format "MACHINE.primitives[~s]" + (format "M.primitives[~s]" (symbol->string (GlobalBucket-name n)))] ;; FIXME: this should be looking at the module path and getting ;; the value here! It shouldn't be looking into Primitives... @@ -54,10 +54,10 @@ (cond [((current-kernel-module-locator?) (ModuleVariable-module-name n)) - (format "MACHINE.primitives[~s]" + (format "M.primitives[~s]" (symbol->string (ModuleVariable-name n)))] [else - (format "MACHINE.modules[~s].namespace[~s]" + (format "M.modules[~s].namespace[~s]" (symbol->string (ModuleLocator-name (ModuleVariable-module-name n))) @@ -79,13 +79,13 @@ ",")))] [(InstallClosureValues!? op) - "MACHINE.env.splice.apply(MACHINE.env,[MACHINE.env.length, 0].concat(MACHINE.proc.closedVals));"] + "M.env.splice.apply(M.env,[M.env.length, 0].concat(M.proc.closedVals));"] [(RestoreEnvironment!? op) - "MACHINE.env=MACHINE.env[MACHINE.env.length-2].slice(0);"] + "M.env=M.env[M.env.length-2].slice(0);"] [(RestoreControl!? op) - (format "MACHINE.restoreControl(~a);" + (format "M.restoreControl(~a);" (let: ([tag : (U DefaultContinuationPromptTag OpArg) (RestoreControl!-tag op)]) (cond @@ -95,7 +95,7 @@ (assemble-oparg tag)])))] [(FixClosureShellMap!? op) - (format "MACHINE.env[MACHINE.env.length-~a].closedVals=[~a];" + (format "M.env[M.env.length-~a].closedVals=[~a];" (add1 (FixClosureShellMap!-depth op)) (string-join (map assemble-env-reference/closure-capture @@ -107,60 +107,60 @@ ","))] [(SetFrameCallee!? op) - (format "MACHINE.control[MACHINE.control.length-1].proc = ~a;" + (format "M.control[M.control.length-1].proc = ~a;" (assemble-oparg (SetFrameCallee!-proc op)))] [(SpliceListIntoStack!? op) - (format "MACHINE.spliceListIntoStack(~a);" + (format "M.spliceListIntoStack(~a);" (assemble-oparg (SpliceListIntoStack!-depth op)))] [(UnspliceRestFromStack!? op) - (format "MACHINE.unspliceRestFromStack(~a,~a);" + (format "M.unspliceRestFromStack(~a,~a);" (assemble-oparg (UnspliceRestFromStack!-depth op)) (assemble-oparg (UnspliceRestFromStack!-length op)))] [(InstallContinuationMarkEntry!? op) - (string-append "MACHINE.installContinuationMarkEntry(" - "MACHINE.control[MACHINE.control.length-1].pendingContinuationMarkKey," - "MACHINE.val);")] + (string-append "M.installContinuationMarkEntry(" + "M.control[M.control.length-1].pendingContinuationMarkKey," + "M.val);")] [(RaiseContextExpectedValuesError!? op) - (format "RT.raiseContextExpectedValuesError(MACHINE,~a);" + (format "RT.raiseContextExpectedValuesError(M,~a);" (RaiseContextExpectedValuesError!-expected op))] [(RaiseArityMismatchError!? op) - (format "RT.raiseArityMismatchError(MACHINE,~a,~a);" + (format "RT.raiseArityMismatchError(M,~a,~a);" (assemble-oparg (RaiseArityMismatchError!-proc op)) (assemble-oparg (RaiseArityMismatchError!-received op)))] [(RaiseOperatorApplicationError!? op) - (format "RT.raiseOperatorApplicationError(MACHINE,~a);" + (format "RT.raiseOperatorApplicationError(M,~a);" (assemble-oparg (RaiseOperatorApplicationError!-operator op)))] [(RaiseUnimplementedPrimitiveError!? op) - (format "RT.raiseUnimplementedPrimitiveError(MACHINE,~s);" + (format "RT.raiseUnimplementedPrimitiveError(M,~s);" (symbol->string (RaiseUnimplementedPrimitiveError!-name op)))] [(InstallModuleEntry!? op) - (format "MACHINE.modules[~s]=new RT.ModuleRecord(~s,~a);" + (format "M.modules[~s]=new RT.ModuleRecord(~s,~a);" (symbol->string (ModuleLocator-name (InstallModuleEntry!-path op))) (symbol->string (InstallModuleEntry!-name op)) (assemble-label (make-Label (InstallModuleEntry!-entry-point op))))] [(MarkModuleInvoked!? op) - (format "MACHINE.modules[~s].isInvoked=true;" + (format "M.modules[~s].isInvoked=true;" (symbol->string (ModuleLocator-name (MarkModuleInvoked!-path op))))] [(AliasModuleAsMain!? op) - (format "MACHINE.mainModules.push(MACHINE.modules[~s]);" + (format "M.mainModules.push(M.modules[~s]);" (symbol->string (ModuleLocator-name (AliasModuleAsMain!-from op))))] [(FinalizeModuleInvokation!? op) - (format "MACHINE.modules[~s].finalizeModuleInvokation();" + (format "M.modules[~s].finalizeModuleInvokation();" (symbol->string (ModuleLocator-name (FinalizeModuleInvokation!-path op))))])) diff --git a/js-assembler/assemble.rkt b/js-assembler/assemble.rkt index 3526860..096e846 100644 --- a/js-assembler/assemble.rkt +++ b/js-assembler/assemble.rkt @@ -39,7 +39,7 @@ ;; What's emitted is a function expression that, when invoked, runs the ;; statements. (define (assemble/write-invoke stmts op) - (display "(function(MACHINE, success, fail, params) {\n" op) + (display "(function(M, success, fail, params) {\n" op) (display "var param;\n" op) (display "var RT = plt.runtime;\n" op) @@ -49,17 +49,17 @@ (write-linked-label-attributes stmts op) - (display "MACHINE.params.currentErrorHandler = fail;\n" op) - (display "MACHINE.params.currentSuccessHandler = success;\n" op) + (display "M.params.currentErrorHandler = fail;\n" op) + (display "M.params.currentSuccessHandler = success;\n" op) (display #< 'ok)) (define (assemble-basic-block a-basic-block blockht entry-points op) - (fprintf op "var ~a = function(MACHINE) { if(--MACHINE.callsBeforeTrampoline < 0) { throw ~a; }\n" + (fprintf op "var ~a = function(M) { if(--M.callsBeforeTrampoline < 0) { throw ~a; }\n" (assemble-label (make-Label (BasicBlock-name a-basic-block))) (assemble-label (make-Label (BasicBlock-name a-basic-block)))) (assemble-block-statements (BasicBlock-name a-basic-block) @@ -399,7 +399,7 @@ EOF (define assembled (cond [(DebugPrint? stmt) - (format "MACHINE.params.currentOutputPort.writeDomNode(MACHINE, $('').text(~a));" + (format "M.params.currentOutputPort.writeDomNode(M, $('').text(~a));" (assemble-oparg (DebugPrint-value stmt)))] [(AssignImmediateStatement? stmt) (let: ([t : (String -> String) (assemble-target (AssignImmediateStatement-target stmt))] @@ -450,10 +450,10 @@ EOF (assemble-jump (GotoStatement-target stmt))] [(PushControlFrame/Generic? stmt) - "MACHINE.control.push(new RT.Frame());"] + "M.control.push(new RT.Frame());"] [(PushControlFrame/Call? stmt) - (format "MACHINE.control.push(new RT.CallFrame(~a,MACHINE.proc));" + (format "M.control.push(new RT.CallFrame(~a,M.proc));" (let: ([label : (U Symbol LinkedLabel) (PushControlFrame/Call-label stmt)]) (cond [(symbol? label) @@ -463,7 +463,7 @@ EOF [(PushControlFrame/Prompt? stmt) ;; fixme: use a different frame structure - (format "MACHINE.control.push(new RT.PromptFrame(~a,~a));" + (format "M.control.push(new RT.PromptFrame(~a,~a));" (let: ([label : (U Symbol LinkedLabel) (PushControlFrame/Prompt-label stmt)]) (cond [(symbol? label) @@ -480,12 +480,12 @@ EOF (assemble-oparg tag)])))] [(PopControlFrame? stmt) - "MACHINE.control.pop();"] + "M.control.pop();"] [(PushEnvironment? stmt) (if (= (PushEnvironment-n stmt) 0) "" - (format "MACHINE.env.push(~a);" (string-join + (format "M.env.push(~a);" (string-join (build-list (PushEnvironment-n stmt) (lambda: ([i : Natural]) (if (PushEnvironment-unbox? stmt) @@ -496,16 +496,16 @@ EOF (let: ([skip : OpArg (PopEnvironment-skip stmt)]) (cond [(and (Const? skip) (= (ensure-natural (Const-const skip)) 0)) - (format "MACHINE.env.length-=~a;" + (format "M.env.length-=~a;" (assemble-oparg (PopEnvironment-n stmt)))] [else - (format "MACHINE.env.splice(MACHINE.env.length-(~a +~a),~a);" + (format "M.env.splice(M.env.length-(~a +~a),~a);" (assemble-oparg (PopEnvironment-skip stmt)) (assemble-oparg (PopEnvironment-n stmt)) (assemble-oparg (PopEnvironment-n stmt)))]))] [(PushImmediateOntoEnvironment? stmt) - (format "MACHINE.env.push(~a);" + (format "M.env.push(~a);" (let: ([val-string : String (cond [(PushImmediateOntoEnvironment-box? stmt) (format "[~a]" (assemble-oparg (PushImmediateOntoEnvironment-value stmt)))] diff --git a/js-assembler/package.rkt b/js-assembler/package.rkt index a0c9476..3936fc4 100644 --- a/js-assembler/package.rkt +++ b/js-assembler/package.rkt @@ -155,23 +155,23 @@ module-requires)) (let ([module-body-text (format " - if(--MACHINE.callsBeforeTrampoline<0) { throw arguments.callee; } - var modrec = MACHINE.modules[~s]; + if(--M.callsBeforeTrampoline<0) { throw arguments.callee; } + var modrec = M.modules[~s]; var exports = {}; modrec.isInvoked = true; - (function(MACHINE, RUNTIME, EXPORTS){~a})(MACHINE, plt.runtime, exports); + (function(MACHINE, RUNTIME, EXPORTS){~a})(M, plt.runtime, exports); ~a modrec.privateExports = exports; - return MACHINE.control.pop().label(MACHINE);" + return M.control.pop().label(M);" (symbol->string name) text (get-provided-name-code bytecode))]) (make-UninterpretedSource (format " -MACHINE.modules[~s] = +M.modules[~s] = new plt.runtime.ModuleRecord(~s, - function(MACHINE) { + function(M) { ~a }); " @@ -204,10 +204,10 @@ MACHINE.modules[~s] = (let ([name (rewrite-path (path->string path))] [afterName (gensym 'afterName)]) (format "var ~a = function() { ~a }; - if (! MACHINE.modules[~s].isInvoked) { - MACHINE.modules[~s].internalInvoke(MACHINE, + if (! M.modules[~s].isInvoked) { + M.modules[~s].internalInvoke(M, ~a, - MACHINE.params.currentErrorHandler); + M.params.currentErrorHandler); } else { ~a(); }" @@ -229,7 +229,7 @@ MACHINE.modules[~s] = ;; following module paths of a source's dependencies. ;; ;; The generated output defines a function called 'invoke' with -;; four arguments (MACHINE, SUCCESS, FAIL, PARAMS). When called, it will +;; four arguments (M, SUCCESS, FAIL, PARAMS). When called, it will ;; execute the code to either run standalone expressions or ;; load in modules. (define (package source-code @@ -265,7 +265,7 @@ MACHINE.modules[~s] = plt.runtime.setReadyFalse(); (") (assemble/write-invoke stmts op) - (fprintf op ")(MACHINE, + (fprintf op ")(M, function() { if (window.console && window.console.log) { window.console.log('loaded ' + ~s); @@ -308,7 +308,7 @@ MACHINE.modules[~s] = ;; last on-last-src)) - (fprintf op "var invoke = (function(MACHINE, SUCCESS, FAIL, PARAMS) {") + (fprintf op "var invoke = (function(M, SUCCESS, FAIL, PARAMS) {") (fprintf op " plt.runtime.ready(function() {") (fprintf op " plt.runtime.setReadyFalse();") (make (list (make-MainModuleSource source-code)) @@ -347,7 +347,7 @@ MACHINE.modules[~s] = ;; on (lambda (src ast stmts) (assemble/write-invoke stmts op) - (fprintf op "(MACHINE, function() { ")) + (fprintf op "(M, function() { ")) ;; after (lambda (src) @@ -360,7 +360,7 @@ MACHINE.modules[~s] = (display (runtime:get-runtime) op) (newline op) - (fprintf op "(function(MACHINE, SUCCESS, FAIL, PARAMS) {") + (fprintf op "(function(M, SUCCESS, FAIL, PARAMS) {") (make (list only-bootstrapped-code) packaging-configuration) (fprintf op "})(plt.runtime.currentMachine,\nfunction(){ plt.runtime.setReadyTrue(); },\nfunction(){},\n{});\n"))) @@ -465,12 +465,12 @@ EOF (define invoke-main-module-code #<').text(' at ' + context[i].elts[0] + ', line ' + context[i].elts[2] + ', column ' + context[i].elts[3]) @@ -505,8 +505,8 @@ var invokeMainModule = function() { .css('whitespace', 'pre') .css('color', 'red')); } else if (plt.runtime.isProcedure(context[i])) { - MACHINE.params.currentErrorDisplayer( - MACHINE, + M.params.currentErrorDisplayer( + M, $('
').text(' in ' + context[i].displayName) .addClass('stacktrace') .css('margin-left', '10px') diff --git a/tests/test-assemble.rkt b/tests/test-assemble.rkt index a6f8e8f..1a92d79 100644 --- a/tests/test-assemble.rkt +++ b/tests/test-assemble.rkt @@ -47,7 +47,7 @@ runtime "var RT = plt.runtime;" - "var MACHINE = new plt.runtime.Machine();\n" + "var M = new plt.runtime.Machine();\n" "return function(success, fail, params){" snippet @@ -55,7 +55,7 @@ "});")]) (displayln snippet) (display code op)))))) -(define (E-single a-statement (inspector "MACHINE.val")) +(define (E-single a-statement (inspector "M.val")) (evaluated-value ((force -E) (cons a-statement inspector)))) ;; evaluating many expressions[. @@ -66,24 +66,24 @@ (display runtime op) "var RT = plt.runtime;" - (display "var MACHINE = new plt.runtime.Machine();\n" op) + (display "var M = new plt.runtime.Machine();\n" op) (display "(function() { " op) (display "var myInvoke = " op) (assemble/write-invoke a-statement op) (display ";" op) (fprintf op "return function(succ, fail, params) { - var newParams = { currentDisplayer: function(MACHINE, v) { + var newParams = { currentDisplayer: function(M, v) { params.currentDisplayer(v); } }; - myInvoke(MACHINE, + myInvoke(M, function(v) { succ(plt.runtime.toDisplayedString(~a));}, - function(MACHINE, exn) { fail(exn); }, + function(M, exn) { fail(exn); }, newParams); }" inspector) (display "})" op)))))) -(define (E-many stmts (inspector "MACHINE.val")) +(define (E-many stmts (inspector "M.val")) (evaluated-value ((force -E-many) (cons stmts inspector)))) @@ -108,27 +108,27 @@ ;; Assigning to proc means val should still be uninitialized. (test (E-single (make-AssignImmediateStatement 'proc (make-Const "Danny"))) "#") -;; But we should see the assignment if we inspect MACHINE.proc. +;; But we should see the assignment if we inspect M.proc. (test (E-single (make-AssignImmediateStatement 'proc (make-Const "Danny")) - "MACHINE.proc") + "M.proc") "Danny") (test (E-single (make-PushEnvironment 1 #f) - "MACHINE.env.length") + "M.env.length") "1") (test (E-single (make-PushEnvironment 20 #f) - "MACHINE.env.length") + "M.env.length") "20") ;; PopEnvironment (test (E-many (list (make-PushEnvironment 2 #f)) - "MACHINE.env.length") + "M.env.length") "2") (test (E-many (list (make-PushEnvironment 2 #f) (make-PopEnvironment (make-Const 1) (make-Const 0))) - "MACHINE.env.length") + "M.env.length") "1") @@ -137,23 +137,23 @@ (test (E-many (list (make-PushEnvironment 2 #f) (make-AssignImmediateStatement (make-EnvLexicalReference 0 #f) (make-Const 12345))) - "MACHINE.env[1]") + "M.env[1]") "12345") (test (E-many (list (make-PushEnvironment 2 #f) (make-AssignImmediateStatement (make-EnvLexicalReference 0 #f) (make-Const 12345))) - "MACHINE.env[0]") + "M.env[0]") "#") (test (E-many (list (make-PushEnvironment 2 #f) (make-AssignImmediateStatement (make-EnvLexicalReference 1 #f) (make-Const 12345))) - "MACHINE.env[0]") + "M.env[0]") "12345") ;; Toplevel Environment loading (test (E-single (make-PerformStatement (make-ExtendEnvironment/Prefix! '(pi))) - "plt.runtime.toWrittenString(MACHINE.env[0]).slice(0, 5)") + "plt.runtime.toWrittenString(M.env[0]).slice(0, 5)") "3.141") @@ -180,7 +180,7 @@ (make-GotoStatement (make-Label 'afterLambda)) 'afterLambda (make-AssignPrimOpStatement 'val (make-MakeCompiledProcedure 'closureStart 0 '() 'closureStart))) - "MACHINE.val.displayName") + "M.val.displayName") "closureStart") @@ -197,7 +197,7 @@ (make-AssignPrimOpStatement 'val (make-MakeCompiledProcedure 'closureStart 0 (list 0 1) 'closureStart))) - "MACHINE.val.closedVals[1] + ',' + MACHINE.val.closedVals[0]") + "M.val.closedVals[1] + ',' + M.val.closedVals[0]") "hello,world") ;; Let's try to install the closure values. @@ -220,7 +220,7 @@ (make-Const 0)) (make-GotoStatement (make-Label 'closureStart)) 'theEnd) - "plt.runtime.toWrittenString(MACHINE.env.length) + ',' + MACHINE.env[1] + ',' + MACHINE.env[0]") + "plt.runtime.toWrittenString(M.env.length) + ',' + M.env[1] + ',' + M.env[0]") "2,hello,world") @@ -244,7 +244,7 @@ (make-PopEnvironment (make-Const 2) (make-Const 0)) (make-AssignPrimOpStatement 'val (make-GetCompiledProcedureEntry)) 'theEnd) - "typeof(MACHINE.val) + ',' + (MACHINE.val === MACHINE.proc.label)") + "typeof(M.val) + ',' + (M.val === M.proc.label)") "function,true") @@ -364,7 +364,7 @@ (test (E-many `(,(make-PerformStatement (make-ExtendEnvironment/Prefix! '(advisor))) ,(make-AssignImmediateStatement 'val (make-Const "Kathi")) ,(make-AssignImmediateStatement (make-EnvPrefixReference 0 0) (make-Reg 'val))) - "MACHINE.env[0][0]") + "M.env[0][0]") "Kathi") @@ -381,7 +381,7 @@ ,(make-AssignImmediateStatement 'val (make-Const "Shriram")) ,(make-AssignImmediateStatement (make-EnvPrefixReference 0 0) (make-Reg 'val)) ,(make-PerformStatement (make-CheckToplevelBound! 0 0))) - "MACHINE.env[0][0]") + "M.env[0][0]") "Shriram") @@ -391,7 +391,7 @@ (make-Const '(1 2 3))) ,(make-AssignImmediateStatement 'argcount (make-Const 1)) ,(make-PerformStatement (make-SpliceListIntoStack! (make-Const 0)))) - "MACHINE.argcount + ',' + MACHINE.env[0] + ',' + MACHINE.env[1] + ',' + MACHINE.env[2]") + "M.argcount + ',' + M.env[0] + ',' + M.env[1] + ',' + M.env[2]") "3,3,2,1") @@ -404,7 +404,7 @@ (make-Const '(1 2 3))) ,(make-AssignImmediateStatement 'argcount (make-Const 3)) ,(make-PerformStatement (make-SpliceListIntoStack! (make-Const 2)))) - "MACHINE.argcount + ',' + MACHINE.env[0] + ',' + MACHINE.env[1] + ',' + MACHINE.env[2] + ',' + MACHINE.env[3] + ',' + MACHINE.env[4]") + "M.argcount + ',' + M.env[0] + ',' + M.env[1] + ',' + M.env[2] + ',' + M.env[3] + ',' + M.env[4]") "5,3,2,1,world,hello") @@ -420,7 +420,7 @@ ,(make-AssignImmediateStatement 'argcount (make-Const 1)) ,(make-PerformStatement (make-UnspliceRestFromStack! (make-Const 0) (make-Const 1)))) - "MACHINE.argcount + ',' + plt.runtime.isList(MACHINE.env[0])") + "M.argcount + ',' + plt.runtime.isList(M.env[0])") "1,true") @@ -438,7 +438,7 @@ (make-Const 'z)) ,(make-AssignImmediateStatement 'argcount (make-Const 5)) ,(make-PerformStatement (make-UnspliceRestFromStack! (make-Const 2) (make-Const 3)))) - "MACHINE.argcount + ',' + MACHINE.env.length + ',' + plt.runtime.isList(MACHINE.env[0]) + ',' + MACHINE.env[2] + ',' + MACHINE.env[1]") + "M.argcount + ',' + M.env.length + ',' + plt.runtime.isList(M.env[0]) + ',' + M.env[2] + ',' + M.env[1]") "3,3,true,hello,world") @@ -457,7 +457,7 @@ bad ,(make-AssignImmediateStatement 'val (make-Const 'bad)) end) - "MACHINE.val") + "M.val") "ok") @@ -474,7 +474,7 @@ ok ,(make-AssignImmediateStatement 'val (make-Const 'ok)) end) - "MACHINE.val") + "M.val") "ok") (test (E-many `(procedure-entry @@ -490,7 +490,7 @@ ok ,(make-AssignImmediateStatement 'val (make-Const 'ok)) end) - "MACHINE.val") + "M.val") "ok") (test (E-many `(procedure-entry @@ -506,7 +506,7 @@ bad ,(make-AssignImmediateStatement 'val (make-Const 'bad)) end) - "MACHINE.val") + "M.val") "ok") @@ -521,7 +521,7 @@ 'proc (make-MakeCompiledProcedure 'procedure-entry (make-ArityAtLeast 2) (list 0 1) 'procedure-entry)) ,(make-AssignImmediateStatement 'val (make-CompiledProcedureClosureReference (make-Reg 'proc) 0))) - "MACHINE.val") + "M.val") "4") (test (E-many `(,(make-PushImmediateOntoEnvironment (make-Const 3) #f) @@ -532,7 +532,7 @@ 'proc (make-MakeCompiledProcedure 'procedure-entry (make-ArityAtLeast 2) (list 0 1) 'procedure-entry)) ,(make-AssignImmediateStatement 'val (make-CompiledProcedureClosureReference (make-Reg 'proc) 1))) - "MACHINE.val") + "M.val") "3") From 6bc6a0aad9acd34f34f4af9bab0bc738fb24e9e7 Mon Sep 17 00:00:00 2001 From: Danny Yoo Date: Fri, 9 Sep 2011 12:55:01 -0400 Subject: [PATCH 03/27] contining to do things to shrink code space --- js-assembler/package.rkt | 2 +- .../runtime-src/baselib-primitives.js | 997 +++++++++--------- js-assembler/runtime-src/runtime.js | 44 +- 3 files changed, 522 insertions(+), 521 deletions(-) diff --git a/js-assembler/package.rkt b/js-assembler/package.rkt index 3936fc4..cad2582 100644 --- a/js-assembler/package.rkt +++ b/js-assembler/package.rkt @@ -159,7 +159,7 @@ var modrec = M.modules[~s]; var exports = {}; modrec.isInvoked = true; - (function(MACHINE, RUNTIME, EXPORTS){~a})(M, plt.runtime, exports); + (function(MACHINE, EXPORTS){~a})(M, exports); ~a modrec.privateExports = exports; return M.control.pop().label(M);" diff --git a/js-assembler/runtime-src/baselib-primitives.js b/js-assembler/runtime-src/baselib-primitives.js index a9a918f..a2ced70 100644 --- a/js-assembler/runtime-src/baselib-primitives.js +++ b/js-assembler/runtime-src/baselib-primitives.js @@ -137,10 +137,10 @@ installPrimitiveProcedure( 'gensym', makeList(0, 1), - function(MACHINE) { + function(M) { var baseName = "g"; - if (MACHINE.argcount === 1) { - baseName = checkSymbolOrString(MACHINE, 'gensym', 0).toString(); + if (M.argcount === 1) { + baseName = checkSymbolOrString(M, 'gensym', 0).toString(); } gensymCounter++; return new baselib.symbols.Symbol(baseName + gensymCounter); @@ -150,13 +150,13 @@ installPrimitiveProcedure( 'display', makeList(1, 2), - function (MACHINE) { - var firstArg = MACHINE.env[MACHINE.env.length - 1]; - var outputPort = MACHINE.params.currentOutputPort; - if (MACHINE.argcount === 2) { - outputPort = checkOutputPort(MACHINE, 'display', 1); + function (M) { + var firstArg = M.env[M.env.length - 1]; + var outputPort = M.params.currentOutputPort; + if (M.argcount === 2) { + outputPort = checkOutputPort(M, 'display', 1); } - outputPort.writeDomNode(MACHINE, toDomNode(firstArg, 'display')); + outputPort.writeDomNode(M, toDomNode(firstArg, 'display')); return VOID; }); @@ -164,39 +164,39 @@ installPrimitiveProcedure( 'write-byte', makeList(1, 2), - function (MACHINE) { - var firstArg = checkByte(MACHINE, 'write-byte', 0); - var outputPort = MACHINE.params.currentOutputPort; - if (MACHINE.argcount === 2) { - outputPort = checkOutputPort(MACHINE, 'display', 1); + function (M) { + var firstArg = checkByte(M, 'write-byte', 0); + var outputPort = M.params.currentOutputPort; + if (M.argcount === 2) { + outputPort = checkOutputPort(M, 'display', 1); } - outputPort.writeDomNode(MACHINE, toDomNode(String.fromCharCode(firstArg), 'display')); + outputPort.writeDomNode(M, toDomNode(String.fromCharCode(firstArg), 'display')); return VOID; }); installPrimitiveProcedure( 'newline', makeList(0, 1), - function (MACHINE) { - var outputPort = MACHINE.params.currentOutputPort; - if (MACHINE.argcount === 1) { - outputPort = checkOutputPort(MACHINE, 'newline', 1); + function (M) { + var outputPort = M.params.currentOutputPort; + if (M.argcount === 1) { + outputPort = checkOutputPort(M, 'newline', 1); } - outputPort.writeDomNode(MACHINE, toDomNode("\n", 'display')); + outputPort.writeDomNode(M, toDomNode("\n", 'display')); return VOID; }); installPrimitiveProcedure( 'displayln', makeList(1, 2), - function (MACHINE){ - var firstArg = MACHINE.env[MACHINE.env.length-1]; - var outputPort = MACHINE.params.currentOutputPort; - if (MACHINE.argcount === 2) { - outputPort = checkOutputPort(MACHINE, 'displayln', 1); + function (M){ + var firstArg = M.env[M.env.length-1]; + var outputPort = M.params.currentOutputPort; + if (M.argcount === 2) { + outputPort = checkOutputPort(M, 'displayln', 1); } - outputPort.writeDomNode(MACHINE, toDomNode(firstArg, 'display')); - outputPort.writeDomNode(MACHINE, toDomNode("\n", 'display')); + outputPort.writeDomNode(M, toDomNode(firstArg, 'display')); + outputPort.writeDomNode(M, toDomNode("\n", 'display')); return VOID; }); @@ -205,11 +205,11 @@ installPrimitiveProcedure( 'format', baselib.arity.makeArityAtLeast(1), - function (MACHINE) { + function (M) { var args = [], i, formatString; - formatString = checkString(MACHINE, 'format', 0).toString(); - for(i = 1; i < MACHINE.argcount; i++) { - args.push(MACHINE.env[MACHINE.env.length - 1 - i]); + formatString = checkString(M, 'format', 0).toString(); + for(i = 1; i < M.argcount; i++) { + args.push(M.env[M.env.length - 1 - i]); } return baselib.format.format(formatString, args, 'format'); }); @@ -218,15 +218,15 @@ installPrimitiveProcedure( 'printf', baselib.arity.makeArityAtLeast(1), - function (MACHINE) { + function (M) { var args = [], i, formatString, result, outputPort; - formatString = checkString(MACHINE, 'printf', 0).toString(); - for(i = 1; i < MACHINE.argcount; i++) { - args.push(MACHINE.env[MACHINE.env.length - 1 - i]); + formatString = checkString(M, 'printf', 0).toString(); + for(i = 1; i < M.argcount; i++) { + args.push(M.env[M.env.length - 1 - i]); } result = baselib.format.format(formatString, args, 'format'); - outputPort = MACHINE.params.currentOutputPort; - outputPort.writeDomNode(MACHINE, toDomNode(result, 'display')); + outputPort = M.params.currentOutputPort; + outputPort.writeDomNode(M, toDomNode(result, 'display')); return VOID; }); @@ -234,15 +234,15 @@ installPrimitiveProcedure( 'fprintf', baselib.arity.makeArityAtLeast(2), - function (MACHINE) { + function (M) { var args = [], i, formatString, outputPort, result; - outputPort = checkOutputPort(MACHINE, 'fprintf', 0); - formatString = checkString(MACHINE, 'fprintf', 1).toString(); - for(i = 2; i < MACHINE.argcount; i++) { - args.push(MACHINE.env[MACHINE.env.length - 1 - i]); + outputPort = checkOutputPort(M, 'fprintf', 0); + formatString = checkString(M, 'fprintf', 1).toString(); + for(i = 2; i < M.argcount; i++) { + args.push(M.env[M.env.length - 1 - i]); } result = baselib.format.format(formatString, args, 'format'); - outputPort.writeDomNode(MACHINE, toDomNode(result, 'display')); + outputPort.writeDomNode(M, toDomNode(result, 'display')); return VOID; }); @@ -254,13 +254,13 @@ installPrimitiveProcedure( 'current-print', makeList(0, 1), - function (MACHINE) { - if (MACHINE.argcount === 1) { - MACHINE.params['currentPrint'] = - checkProcedure(MACHINE, 'current-print', 0); + function (M) { + if (M.argcount === 1) { + M.params['currentPrint'] = + checkProcedure(M, 'current-print', 0); return VOID; } else { - return MACHINE.params['currentPrint']; + return M.params['currentPrint']; } }); @@ -268,13 +268,13 @@ installPrimitiveProcedure( 'current-output-port', makeList(0, 1), - function (MACHINE) { - if (MACHINE.argcount === 1) { - MACHINE.params['currentOutputPort'] = - checkOutputPort(MACHINE, 'current-output-port', 0); + function (M) { + if (M.argcount === 1) { + M.params['currentOutputPort'] = + checkOutputPort(M, 'current-output-port', 0); return VOID; } else { - return MACHINE.params['currentOutputPort']; + return M.params['currentOutputPort']; } }); @@ -283,13 +283,13 @@ installPrimitiveProcedure( 'current-error-port', makeList(0, 1), - function (MACHINE) { - if (MACHINE.argcount === 1) { - MACHINE.params['currentErrorPort'] = - checkOutputPort(MACHINE, 'current-output-port', 0); + function (M) { + if (M.argcount === 1) { + M.params['currentErrorPort'] = + checkOutputPort(M, 'current-output-port', 0); return VOID; } else { - return MACHINE.params['currentOutputPort']; + return M.params['currentOutputPort']; } }); @@ -302,11 +302,11 @@ installPrimitiveProcedure( '=', baselib.arity.makeArityAtLeast(2), - function (MACHINE) { + function (M) { var i; - var firstArg = checkNumber(MACHINE, '=', 0), secondArg; - for (i = 1; i < MACHINE.argcount; i++) { - secondArg = checkNumber(MACHINE, '=', i); + var firstArg = checkNumber(M, '=', 0), secondArg; + for (i = 1; i < M.argcount; i++) { + secondArg = checkNumber(M, '=', i); if (! (baselib.numbers.equals(firstArg, secondArg))) { return false; } @@ -319,10 +319,10 @@ installPrimitiveProcedure( '=~', 3, - function (MACHINE) { - var x = checkReal(MACHINE, '=~', 0); - var y = checkReal(MACHINE, '=~', 1); - var range = checkNonNegativeReal(MACHINE, '=~', 2); + function (M) { + var x = checkReal(M, '=~', 0); + var y = checkReal(M, '=~', 1); + var range = checkNonNegativeReal(M, '=~', 2); return baselib.numbers.lessThanOrEqual( baselib.numbers.abs(baselib.numbers.subtract(x, y)), range); @@ -331,10 +331,10 @@ var makeChainingBinop = function (predicate, name) { - return function (MACHINE) { - var firstArg = checkNumber(MACHINE, name, 0), secondArg, i; - for (i = 1; i < MACHINE.argcount; i++) { - secondArg = checkNumber(MACHINE, name, i); + return function (M) { + var firstArg = checkNumber(M, name, 0), secondArg, i; + for (i = 1; i < M.argcount; i++) { + secondArg = checkNumber(M, name, i); if (! (predicate(firstArg, secondArg))) { return false; } @@ -371,13 +371,13 @@ installPrimitiveProcedure( '+', baselib.arity.makeArityAtLeast(0), - function (MACHINE) { + function (M) { var result = 0; var i = 0; - for (i = 0; i < MACHINE.argcount; i++) { + for (i = 0; i < M.argcount; i++) { result = baselib.numbers.add( result, - checkNumber(MACHINE, '+', i)); + checkNumber(M, '+', i)); } return result; }); @@ -386,13 +386,13 @@ installPrimitiveProcedure( '*', baselib.arity.makeArityAtLeast(0), - function (MACHINE) { + function (M) { var result = 1; var i = 0; - for (i=0; i < MACHINE.argcount; i++) { + for (i=0; i < M.argcount; i++) { result = baselib.numbers.multiply( result, - checkNumber(MACHINE, '*', i)); + checkNumber(M, '*', i)); } return result; }); @@ -400,17 +400,17 @@ installPrimitiveProcedure( '-', baselib.arity.makeArityAtLeast(1), - function (MACHINE) { - if (MACHINE.argcount === 1) { + function (M) { + if (M.argcount === 1) { return baselib.numbers.subtract( 0, - checkNumber(MACHINE, '-', 0)); + checkNumber(M, '-', 0)); } - var result = checkNumber(MACHINE, '-', 0), i; - for (i = 1; i < MACHINE.argcount; i++) { + var result = checkNumber(M, '-', 0), i; + for (i = 1; i < M.argcount; i++) { result = baselib.numbers.subtract( result, - checkNumber(MACHINE, '-', i)); + checkNumber(M, '-', i)); } return result; }); @@ -418,12 +418,12 @@ installPrimitiveProcedure( '/', baselib.arity.makeArityAtLeast(1), - function (MACHINE) { - var result = checkNumber(MACHINE, '/', 0), i; - for (i = 1; i < MACHINE.argcount; i++) { + function (M) { + var result = checkNumber(M, '/', 0), i; + for (i = 1; i < M.argcount; i++) { result = baselib.numbers.divide( result, - checkNumber(MACHINE, '/', i)); + checkNumber(M, '/', i)); } return result; }); @@ -432,8 +432,8 @@ installPrimitiveProcedure( 'add1', 1, - function (MACHINE) { - var firstArg = checkNumber(MACHINE, 'add1', 0); + function (M) { + var firstArg = checkNumber(M, 'add1', 0); return baselib.numbers.add(firstArg, 1); }); @@ -441,8 +441,8 @@ installPrimitiveProcedure( 'sub1', 1, - function (MACHINE) { - var firstArg = checkNumber(MACHINE, 'sub1', 0); + function (M) { + var firstArg = checkNumber(M, 'sub1', 0); return baselib.numbers.subtract(firstArg, 1); }); @@ -450,8 +450,8 @@ installPrimitiveProcedure( 'zero?', 1, - function (MACHINE) { - var firstArg = MACHINE.env[MACHINE.env.length-1]; + function (M) { + var firstArg = M.env[M.env.length-1]; return baselib.numbers.equals(firstArg, 0); }); @@ -459,9 +459,9 @@ installPrimitiveProcedure( 'cons', 2, - function (MACHINE) { - var firstArg = MACHINE.env[MACHINE.env.length-1]; - var secondArg = MACHINE.env[MACHINE.env.length-2]; + function (M) { + var firstArg = M.env[M.env.length-1]; + var secondArg = M.env[M.env.length-2]; return makePair(firstArg, secondArg); }); @@ -469,10 +469,10 @@ installPrimitiveProcedure( 'list', baselib.arity.makeArityAtLeast(0), - function (MACHINE) { + function (M) { var result = NULL, i; - for (i = 0; i < MACHINE.argcount; i++) { - result = makePair(MACHINE.env[MACHINE.env.length - (MACHINE.argcount - i)], + for (i = 0; i < M.argcount; i++) { + result = makePair(M.env[M.env.length - (M.argcount - i)], result); } return result; @@ -481,10 +481,10 @@ installPrimitiveProcedure( 'list*', baselib.arity.makeArityAtLeast(1), - function (MACHINE) { - var result = checkList(MACHINE, 'list*', MACHINE.argcount - 1), i; - for (i = MACHINE.argcount - 2; i >= 0; i--) { - result = makePair(MACHINE.env[MACHINE.env.length - 1 - i], + function (M) { + var result = checkList(M, 'list*', M.argcount - 1), i; + for (i = M.argcount - 2; i >= 0; i--) { + result = makePair(M.env[M.env.length - 1 - i], result); } return result; @@ -494,9 +494,9 @@ installPrimitiveProcedure( 'list-ref', 2, - function (MACHINE) { - var lst = checkList(MACHINE, 'list-ref', 0); - var index = checkNaturalInRange(MACHINE, 'list-ref', 1, + function (M) { + var lst = checkList(M, 'list-ref', 0); + var index = checkNaturalInRange(M, 'list-ref', 1, 0, baselib.lists.length(lst)); return baselib.lists.listRef(lst, baselib.numbers.toFixnum(index)); }); @@ -507,24 +507,24 @@ installPrimitiveProcedure( 'car', 1, - function (MACHINE) { - var firstArg = checkPair(MACHINE, 'car', 0); + function (M) { + var firstArg = checkPair(M, 'car', 0); return firstArg.first; }); installPrimitiveProcedure( 'cdr', 1, - function (MACHINE) { - var firstArg = checkPair(MACHINE, 'cdr', 0); + function (M) { + var firstArg = checkPair(M, 'cdr', 0); return firstArg.rest; }); installPrimitiveProcedure( 'pair?', 1, - function (MACHINE) { - var firstArg = MACHINE.env[MACHINE.env.length-1]; + function (M) { + var firstArg = M.env[M.env.length-1]; return isPair(firstArg); }); @@ -532,17 +532,17 @@ installPrimitiveProcedure( 'list?', 1, - function (MACHINE) { - return isList(MACHINE.env[MACHINE.env.length -1]); + function (M) { + return isList(M.env[M.env.length -1]); }); installPrimitiveProcedure( 'set-car!', 2, - function (MACHINE) { - var firstArg = checkPair(MACHINE, 'set-car!', 0); - var secondArg = MACHINE.env[MACHINE.env.length-2]; + function (M) { + var firstArg = checkPair(M, 'set-car!', 0); + var secondArg = M.env[M.env.length-2]; firstArg.first = secondArg; return VOID; }); @@ -551,9 +551,9 @@ installPrimitiveProcedure( 'set-cdr!', 2, - function (MACHINE) { - var firstArg = checkPair(MACHINE, 'set-car!', 0); - var secondArg = MACHINE.env[MACHINE.env.length-2]; + function (M) { + var firstArg = checkPair(M, 'set-car!', 0); + var secondArg = M.env[M.env.length-2]; firstArg.rest = secondArg; return VOID; }); @@ -562,8 +562,8 @@ installPrimitiveProcedure( 'not', 1, - function (MACHINE) { - var firstArg = MACHINE.env[MACHINE.env.length-1]; + function (M) { + var firstArg = M.env[M.env.length-1]; return (firstArg === false); }); @@ -571,8 +571,8 @@ installPrimitiveProcedure( 'null?', 1, - function (MACHINE) { - var firstArg = MACHINE.env[MACHINE.env.length-1]; + function (M) { + var firstArg = M.env[M.env.length-1]; return firstArg === NULL; }); @@ -580,11 +580,11 @@ installPrimitiveProcedure( 'vector', baselib.arity.makeArityAtLeast(0), - function (MACHINE) { + function (M) { var i; var result = []; - for (i = 0; i < MACHINE.argcount; i++) { - result.push(MACHINE.env[MACHINE.env.length-1-i]); + for (i = 0; i < M.argcount; i++) { + result.push(M.env[M.env.length-1-i]); } var newVector = makeVector.apply(null, result); return newVector; @@ -594,12 +594,12 @@ installPrimitiveProcedure( 'make-vector', makeList(1, 2), - function (MACHINE) { + function (M) { var value = 0; var length = baselib.numbers.toFixnum( - checkNatural(MACHINE, 'make-vector', 0)); - if (MACHINE.argcount === 2) { - value = MACHINE.env[MACHINE.env.length - 2]; + checkNatural(M, 'make-vector', 0)); + if (M.argcount === 2) { + value = M.env[M.env.length - 2]; } var arr = []; var i; @@ -613,8 +613,8 @@ installPrimitiveProcedure( 'vector->list', 1, - function (MACHINE) { - var elts = checkVector(MACHINE, 'vector->list', 0).elts; + function (M) { + var elts = checkVector(M, 'vector->list', 0).elts; var i; var result = NULL; for (i = 0; i < elts.length; i++) { @@ -627,8 +627,8 @@ installPrimitiveProcedure( 'list->vector', 1, - function (MACHINE) { - var firstArg = checkList(MACHINE, 'list->vector', 0); + function (M) { + var firstArg = checkList(M, 'list->vector', 0); var result = []; while (firstArg !== NULL) { result.push(firstArg.first); @@ -641,9 +641,9 @@ installPrimitiveProcedure( 'vector-ref', 2, - function (MACHINE) { - var elts = checkVector(MACHINE, 'vector-ref', 0).elts; - var index = MACHINE.env[MACHINE.env.length-2]; + function (M) { + var elts = checkVector(M, 'vector-ref', 0).elts; + var index = M.env[M.env.length-2]; return elts[index]; }); @@ -651,13 +651,13 @@ installPrimitiveProcedure( 'vector-set!', 3, - function (MACHINE) { - var elts = checkVector(MACHINE, 'vector-set!', 0).elts; + function (M) { + var elts = checkVector(M, 'vector-set!', 0).elts; // FIXME: check out-of-bounds vector var index = baselib.numbers.toFixnum( - checkNaturalInRange(MACHINE, 'vector-set!', 1, + checkNaturalInRange(M, 'vector-set!', 1, 0, elts.length)); - var val = MACHINE.env[MACHINE.env.length - 1 - 2]; + var val = M.env[M.env.length - 1 - 2]; elts[index] = val; return VOID; }); @@ -666,8 +666,8 @@ installPrimitiveProcedure( 'vector-length', 1, - function (MACHINE) { - return checkVector(MACHINE, 'vector-length', 0).elts.length; + function (M) { + return checkVector(M, 'vector-length', 0).elts.length; }); @@ -675,12 +675,12 @@ installPrimitiveProcedure( 'make-string', makeList(1, 2), - function (MACHINE) { + function (M) { var value = String.fromCharCode(0); var length = baselib.numbers.toFixnum( - checkNatural(MACHINE, 'make-string', 0)); - if (MACHINE.argcount === 2) { - value = checkChar(MACHINE, 'make-string', 1).val; + checkNatural(M, 'make-string', 0)); + if (M.argcount === 2) { + value = checkChar(M, 'make-string', 1).val; } var arr = []; var i; @@ -693,12 +693,12 @@ installPrimitiveProcedure( 'substring', makeList(2, 3), - function(MACHINE) { - var str = String(checkString(MACHINE, 'substring', 0)); - var start = baselib.numbers.toFixnum(checkNatural(MACHINE, 'substring', 1)); + function(M) { + var str = String(checkString(M, 'substring', 0)); + var start = baselib.numbers.toFixnum(checkNatural(M, 'substring', 1)); var end = str.length; - if (MACHINE.argcount === 3) { - end = baselib.numbers.toFixnum(checkNatural(MACHINE, 'substring', 2)); + if (M.argcount === 3) { + end = baselib.numbers.toFixnum(checkNatural(M, 'substring', 2)); } return str.substring(start, end); }); @@ -707,8 +707,8 @@ installPrimitiveProcedure( 'list->string', 1, - function (MACHINE) { - var firstArg = checkListofChars(MACHINE, 'list->string', 0); + function (M) { + var firstArg = checkListofChars(M, 'list->string', 0); var result = []; while (firstArg !== NULL) { result.push(firstArg.first.val); @@ -721,11 +721,11 @@ installPrimitiveProcedure( 'string', baselib.arity.makeArityAtLeast(0), - function (MACHINE) { + function (M) { var i; var chars = []; - for (i = 0; i < MACHINE.argcount; i++) { - chars.push(checkChar(MACHINE, 'string', i).val); + for (i = 0; i < M.argcount; i++) { + chars.push(checkChar(M, 'string', i).val); } return chars.join(''); }); @@ -734,8 +734,8 @@ installPrimitiveProcedure( 'string->list', 1, - function (MACHINE) { - var str = checkString(MACHINE, 'string->list', 0).toString(); + function (M) { + var str = checkString(M, 'string->list', 0).toString(); var i; var result = NULL; for (i = str.length - 1; i >= 0; i--) { @@ -749,10 +749,10 @@ installPrimitiveProcedure( 'string-set!', 3, - function (MACHINE) { - var str = checkMutableString(MACHINE, 'string-set!', 0); - var k = checkNatural(MACHINE, 'string-set!', 1); - var ch = checkChar(MACHINE, 'string-set!', 2); + function (M) { + var str = checkMutableString(M, 'string-set!', 0); + var k = checkNatural(M, 'string-set!', 1); + var ch = checkChar(M, 'string-set!', 2); str.set(baselib.numbers.toFixnum(k), ch.val); return VOID; }); @@ -764,16 +764,16 @@ installPrimitiveProcedure( 'symbol?', 1, - function (MACHINE) { - var firstArg = MACHINE.env[MACHINE.env.length-1]; + function (M) { + var firstArg = M.env[M.env.length-1]; return isSymbol(firstArg); }); installPrimitiveProcedure( 'symbol->string', 1, - function (MACHINE) { - var firstArg = checkSymbol(MACHINE, 'symbol->string', 0); + function (M) { + var firstArg = checkSymbol(M, 'symbol->string', 0); return firstArg.toString(); }); @@ -781,11 +781,11 @@ installPrimitiveProcedure( 'string=?', baselib.arity.makeArityAtLeast(1), - function (MACHINE) { - var s = checkString(MACHINE, 'string=?', 0).toString(); + function (M) { + var s = checkString(M, 'string=?', 0).toString(); var i; - for (i = 1; i < MACHINE.argcount; i++) { - if (s !== checkString(MACHINE, 'string=?', i).toString()) { + for (i = 1; i < M.argcount; i++) { + if (s !== checkString(M, 'string=?', i).toString()) { return false; } } @@ -796,11 +796,11 @@ installPrimitiveProcedure( 'string<=?', baselib.arity.makeArityAtLeast(1), - function (MACHINE) { - var s = checkString(MACHINE, 'string<=?', 0).toString(); + function (M) { + var s = checkString(M, 'string<=?', 0).toString(); var i; - for (i = 1; i < MACHINE.argcount; i++) { - if ((s <= checkString(MACHINE, 'string<=?', i).toString()) === false) { + for (i = 1; i < M.argcount; i++) { + if ((s <= checkString(M, 'string<=?', i).toString()) === false) { return false; } } @@ -810,11 +810,11 @@ installPrimitiveProcedure( 'string=?', baselib.arity.makeArityAtLeast(1), - function (MACHINE) { - var s = checkString(MACHINE, 'string>=?', 0).toString(); + function (M) { + var s = checkString(M, 'string>=?', 0).toString(); var i; - for (i = 1; i < MACHINE.argcount; i++) { - if ((s >= checkString(MACHINE, 'string>=?', i).toString()) === false) { + for (i = 1; i < M.argcount; i++) { + if ((s >= checkString(M, 'string>=?', i).toString()) === false) { return false; } } @@ -838,11 +838,11 @@ installPrimitiveProcedure( 'string>?', baselib.arity.makeArityAtLeast(1), - function (MACHINE) { - var s = checkString(MACHINE, 'string>?', 0).toString(); + function (M) { + var s = checkString(M, 'string>?', 0).toString(); var i; - for (i = 1; i < MACHINE.argcount; i++) { - if ((s > checkString(MACHINE, 'string>?', i).toString()) === false) { + for (i = 1; i < M.argcount; i++) { + if ((s > checkString(M, 'string>?', i).toString()) === false) { return false; } } @@ -869,11 +869,11 @@ installPrimitiveProcedure( 'string-ci=?', baselib.arity.makeArityAtLeast(1), - function (MACHINE) { - var s = checkString(MACHINE, 'string-ci=?', 0).toString().toUpperCase(); + function (M) { + var s = checkString(M, 'string-ci=?', 0).toString().toUpperCase(); var i; - for (i = 1; i < MACHINE.argcount; i++) { - if (s !== checkString(MACHINE, 'string-ci=?', i).toString().toUpperCase()) { + for (i = 1; i < M.argcount; i++) { + if (s !== checkString(M, 'string-ci=?', i).toString().toUpperCase()) { return false; } } @@ -884,11 +884,11 @@ installPrimitiveProcedure( 'string-ci<=?', baselib.arity.makeArityAtLeast(1), - function (MACHINE) { - var s = checkString(MACHINE, 'string-ci<=?', 0).toString().toUpperCase(); + function (M) { + var s = checkString(M, 'string-ci<=?', 0).toString().toUpperCase(); var i; - for (i = 1; i < MACHINE.argcount; i++) { - if ((s <= checkString(MACHINE, 'string-ci<=?', i).toString().toUpperCase()) === false) { + for (i = 1; i < M.argcount; i++) { + if ((s <= checkString(M, 'string-ci<=?', i).toString().toUpperCase()) === false) { return false; } } @@ -898,11 +898,11 @@ installPrimitiveProcedure( 'string-ci=?', baselib.arity.makeArityAtLeast(1), - function (MACHINE) { - var s = checkString(MACHINE, 'string-ci>=?', 0).toString().toUpperCase(); + function (M) { + var s = checkString(M, 'string-ci>=?', 0).toString().toUpperCase(); var i; - for (i = 1; i < MACHINE.argcount; i++) { - if ((s >= checkString(MACHINE, 'string-ci>=?', i).toString().toUpperCase()) === false) { + for (i = 1; i < M.argcount; i++) { + if ((s >= checkString(M, 'string-ci>=?', i).toString().toUpperCase()) === false) { return false; } } @@ -926,11 +926,11 @@ installPrimitiveProcedure( 'string-ci>?', baselib.arity.makeArityAtLeast(1), - function (MACHINE) { - var s = checkString(MACHINE, 'string-ci>?', 0).toString().toUpperCase(); + function (M) { + var s = checkString(M, 'string-ci>?', 0).toString().toUpperCase(); var i; - for (i = 1; i < MACHINE.argcount; i++) { - if ((s > checkString(MACHINE, 'string-ci>?', i).toString().toUpperCase()) === false) { + for (i = 1; i < M.argcount; i++) { + if ((s > checkString(M, 'string-ci>?', i).toString().toUpperCase()) === false) { return false; } } @@ -944,11 +944,11 @@ installPrimitiveProcedure( 'string-append', baselib.arity.makeArityAtLeast(0), - function (MACHINE) { + function (M) { var buffer = []; var i; - for (i = 0; i < MACHINE.argcount; i++) { - buffer.push(checkString(MACHINE, 'string-append', i).toString()); + for (i = 0; i < M.argcount; i++) { + buffer.push(checkString(M, 'string-append', i).toString()); } return buffer.join(''); }); @@ -956,8 +956,8 @@ installPrimitiveProcedure( 'string-length', 1, - function (MACHINE) { - var firstArg = checkString(MACHINE, 'string-length', 0).toString(); + function (M) { + var firstArg = checkString(M, 'string-length', 0).toString(); return firstArg.length; }); @@ -965,10 +965,10 @@ installPrimitiveProcedure( 'string-ref', 2, - function (MACHINE) { - var firstArg = checkString(MACHINE, 'string-ref', 0).toString(); + function (M) { + var firstArg = checkString(M, 'string-ref', 0).toString(); var index = baselib.numbers.toFixnum( - checkNaturalInRange(MACHINE, 'string-ref', 1, + checkNaturalInRange(M, 'string-ref', 1, 0, firstArg.length)); return baselib.chars.makeChar(firstArg[index]); }); @@ -978,41 +978,41 @@ installPrimitiveProcedure( 'string?', 1, - function (MACHINE) { - return isString(MACHINE.env[MACHINE.env.length - 1]); + function (M) { + return isString(M.env[M.env.length - 1]); }); installPrimitiveProcedure( 'number->string', 1, - function (MACHINE) { - return checkNumber(MACHINE, 'number->string', 0).toString(); + function (M) { + return checkNumber(M, 'number->string', 0).toString(); }); installPrimitiveProcedure( 'string->symbol', 1, - function (MACHINE) { - return makeSymbol(checkString(MACHINE, 'string->symbol', 0).toString()); + function (M) { + return makeSymbol(checkString(M, 'string->symbol', 0).toString()); }); installPrimitiveProcedure( 'string->number', 1, - function (MACHINE) { + function (M) { return baselib.numbers.fromString( - checkString(MACHINE, 'string->number', 0).toString()); + checkString(M, 'string->number', 0).toString()); }); installPrimitiveProcedure( 'boolean?', 1, - function(MACHINE) { - var v = MACHINE.env[MACHINE.env.length - 1]; + function(M) { + var v = M.env[M.env.length - 1]; return (v === true || v === false); }); @@ -1020,19 +1020,19 @@ installPrimitiveProcedure( 'char?', 1, - function(MACHINE) { - return baselib.chars.isChar(MACHINE.env[MACHINE.env.length -1 ]); + function(M) { + return baselib.chars.isChar(M.env[M.env.length -1 ]); }); installPrimitiveProcedure( 'char=?', baselib.arity.makeArityAtLeast(2), - function(MACHINE) { - var s = checkChar(MACHINE, 'char=?', 0).val; + function(M) { + var s = checkChar(M, 'char=?', 0).val; var i; - for (i = 1; i < MACHINE.argcount; i++) { - if (checkChar(MACHINE, 'char=?', i).val !== s) { + for (i = 1; i < M.argcount; i++) { + if (checkChar(M, 'char=?', i).val !== s) { return false; } } @@ -1043,16 +1043,16 @@ installPrimitiveProcedure( 'char-upcase', 1, - function(MACHINE) { - var ch = checkChar(MACHINE, 'char=?', 0).val; + function(M) { + var ch = checkChar(M, 'char=?', 0).val; return baselib.chars.makeChar(ch.toUpperCase()); }); installPrimitiveProcedure( 'char-downcase', 1, - function(MACHINE) { - var ch = checkChar(MACHINE, 'char=?', 0).val; + function(M) { + var ch = checkChar(M, 'char=?', 0).val; return baselib.chars.makeChar(ch.toLowerCase()); }); @@ -1063,25 +1063,25 @@ installPrimitiveProcedure( 'box', 1, - function (MACHINE) { - var firstArg = MACHINE.env[MACHINE.env.length-1]; + function (M) { + var firstArg = M.env[M.env.length-1]; return makeBox(firstArg); }); installPrimitiveProcedure( 'unbox', 1, - function (MACHINE) { - var firstArg = checkBox(MACHINE, 'unbox', 0); + function (M) { + var firstArg = checkBox(M, 'unbox', 0); return firstArg.ref(); }); installPrimitiveProcedure( 'set-box!', 2, - function (MACHINE) { - var firstArg = checkMutableBox(MACHINE, 'set-box!', 0); - var secondArg = MACHINE.env[MACHINE.env.length-2]; + function (M) { + var firstArg = checkMutableBox(M, 'set-box!', 0); + var secondArg = M.env[M.env.length-2]; firstArg.set(secondArg); return VOID; }); @@ -1089,7 +1089,7 @@ installPrimitiveProcedure( 'void', baselib.arity.makeArityAtLeast(0), - function (MACHINE) { + function (M) { return VOID; }); @@ -1097,11 +1097,11 @@ installPrimitiveProcedure( 'random', baselib.lists.makeList(0, 1), - function (MACHINE) { - if (MACHINE.argcount === 0) { + function (M) { + if (M.argcount === 0) { return makeFloat(Math.random()); } else { - var n = checkNatural(MACHINE, 'random', 0); + var n = checkNatural(M, 'random', 0); return Math.floor(Math.random() * baselib.numbers.toFixnum(n)); } }); @@ -1110,18 +1110,18 @@ installPrimitiveProcedure( 'eq?', 2, - function (MACHINE) { - var firstArg = MACHINE.env[MACHINE.env.length-1]; - var secondArg = MACHINE.env[MACHINE.env.length-2]; + function (M) { + var firstArg = M.env[M.env.length-1]; + var secondArg = M.env[M.env.length-2]; return firstArg === secondArg; }); installPrimitiveProcedure( 'eqv?', 2, - function (MACHINE) { - var firstArg = MACHINE.env[MACHINE.env.length-1]; - var secondArg = MACHINE.env[MACHINE.env.length-2]; + function (M) { + var firstArg = M.env[M.env.length-1]; + var secondArg = M.env[M.env.length-2]; return baselib.equality.eqv(firstArg, secondArg); }); @@ -1130,9 +1130,9 @@ installPrimitiveProcedure( 'equal?', 2, - function (MACHINE) { - var firstArg = MACHINE.env[MACHINE.env.length-1]; - var secondArg = MACHINE.env[MACHINE.env.length-2]; + function (M) { + var firstArg = M.env[M.env.length-1]; + var secondArg = M.env[M.env.length-2]; return equals(firstArg, secondArg); }); @@ -1140,24 +1140,24 @@ // This definition of apply will take precedence over the // implementation of apply in the boostrapped-primitives.rkt, // since it provides nicer error handling. - var applyImplementation = function (MACHINE) { - if(--MACHINE.callsBeforeTrampoline < 0) { + var applyImplementation = function (M) { + if(--M.callsBeforeTrampoline < 0) { throw applyImplementation; } - var proc = checkProcedure(MACHINE, 'apply', 0); - MACHINE.env.pop(); - MACHINE.argcount--; - checkList(MACHINE, 'apply', MACHINE.argcount - 1); - MACHINE.spliceListIntoStack(MACHINE.argcount - 1); - if (baselib.arity.isArityMatching(proc.racketArity, MACHINE.argcount)) { - MACHINE.proc = proc; + var proc = checkProcedure(M, 'apply', 0); + M.env.pop(); + M.argcount--; + checkList(M, 'apply', M.argcount - 1); + M.spliceListIntoStack(M.argcount - 1); + if (baselib.arity.isArityMatching(proc.racketArity, M.argcount)) { + M.proc = proc; if (baselib.functions.isPrimitiveProcedure(proc)) { - return finalizeClosureCall(MACHINE, proc(MACHINE)); + return finalizeClosureCall(M, proc(M)); } else { - return proc.label(MACHINE); + return proc.label(M); } } else { - raiseArityMismatchError(MACHINE, proc, MACHINE.argcount); + raiseArityMismatchError(M, proc, M.argcount); } }; installPrimitiveClosure( @@ -1177,24 +1177,24 @@ installPrimitiveProcedure( 'procedure?', 1, - function (MACHINE) { - return baselib.functions.isProcedure(MACHINE.env[MACHINE.env.length - 1]); + function (M) { + return baselib.functions.isProcedure(M.env[M.env.length - 1]); }); installPrimitiveProcedure( 'procedure-arity-includes?', 2, - function (MACHINE) { - var proc = checkProcedure(MACHINE, 'procedure-arity-includes?', 0); - var argcount = checkNatural(MACHINE, 'procedure-arity-includes?', 1); + function (M) { + var proc = checkProcedure(M, 'procedure-arity-includes?', 0); + var argcount = checkNatural(M, 'procedure-arity-includes?', 1); return baselib.arity.isArityMatching(proc.racketArity, argcount); }); installPrimitiveProcedure( 'procedure-arity', 1, - function (MACHINE) { - var proc = checkProcedure(MACHINE, 'procedure-arity-includes?', 0); + function (M) { + var proc = checkProcedure(M, 'procedure-arity-includes?', 0); return proc.racketArity; }); @@ -1202,9 +1202,9 @@ installPrimitiveProcedure( 'procedure-rename', 2, - function (MACHINE) { - var proc = checkProcedure(MACHINE, 'procedure-rename', 0); - var name = checkSymbol(MACHINE, 'procedure-rename', 1); + function (M) { + var proc = checkProcedure(M, 'procedure-rename', 0); + var name = checkSymbol(M, 'procedure-rename', 1); return baselib.functions.renameProcedure(proc, name); }); @@ -1213,19 +1213,19 @@ installPrimitiveProcedure( 'member', 2, - function (MACHINE) { - var x = MACHINE.env[MACHINE.env.length-1]; - var lst = MACHINE.env[MACHINE.env.length-2]; + function (M) { + var x = M.env[M.env.length-1]; + var lst = M.env[M.env.length-2]; while (true) { if (lst === NULL) { return false; } if (! isPair(lst)) { - raiseArgumentTypeError(MACHINE, + raiseArgumentTypeError(M, 'member', 'list', 1, - MACHINE.env[MACHINE.env.length - 1 - 1]); + M.env[M.env.length - 1 - 1]); } if (equals(x, (lst.first))) { return lst; @@ -1239,11 +1239,11 @@ installPrimitiveProcedure( 'reverse', 1, - function (MACHINE) { + function (M) { var rev = NULL; - var lst = MACHINE.env[MACHINE.env.length-1]; + var lst = M.env[M.env.length-1]; while(lst !== NULL) { - rev = makePair(testArgument(MACHINE, 'pair', isPair, lst, 0, 'reverse').first, + rev = makePair(testArgument(M, 'pair', isPair, lst, 0, 'reverse').first, rev); lst = lst.rest; } @@ -1256,43 +1256,43 @@ installPrimitiveProcedure( 'number?', 1, - function(MACHINE) { - return isNumber(MACHINE.env[MACHINE.env.length - 1]); + function(M) { + return isNumber(M.env[M.env.length - 1]); }); installPrimitiveProcedure( 'real?', 1, - function(MACHINE) { - return isReal(MACHINE.env[MACHINE.env.length - 1]); + function(M) { + return isReal(M.env[M.env.length - 1]); }); installPrimitiveProcedure( 'complex?', 1, - function(MACHINE) { - return isComplex(MACHINE.env[MACHINE.env.length - 1]); + function(M) { + return isComplex(M.env[M.env.length - 1]); }); installPrimitiveProcedure( 'rational?', 1, - function(MACHINE) { - return isRational(MACHINE.env[MACHINE.env.length - 1]); + function(M) { + return isRational(M.env[M.env.length - 1]); }); installPrimitiveProcedure( 'even?', 1, - function(MACHINE) { - var n = checkInteger(MACHINE, 'even?', 0); + function(M) { + var n = checkInteger(M, 'even?', 0); return baselib.numbers.equals(0, baselib.numbers.modulo(n, 2)); }); installPrimitiveProcedure( 'odd?', 1, - function(MACHINE) { - var n = checkInteger(MACHINE, 'odd?', 0); + function(M) { + var n = checkInteger(M, 'odd?', 0); return baselib.numbers.equals(1, baselib.numbers.modulo(n, 2)); }); @@ -1300,16 +1300,16 @@ installPrimitiveProcedure( 'positive?', 1, - function(MACHINE) { - var n = checkReal(MACHINE, 'positive?', 0); + function(M) { + var n = checkReal(M, 'positive?', 0); return baselib.numbers.greaterThan(n, 0); }); installPrimitiveProcedure( 'negative?', 1, - function(MACHINE) { - var n = checkReal(MACHINE, 'negative?', 0); + function(M) { + var n = checkReal(M, 'negative?', 0); return baselib.numbers.lessThan(n, 0); }); @@ -1321,34 +1321,34 @@ installPrimitiveProcedure( 'abs', 1, - function (MACHINE) { + function (M) { return baselib.numbers.abs( - checkNumber(MACHINE, 'abs', 0)); + checkNumber(M, 'abs', 0)); }); installPrimitiveProcedure( 'acos', 1, - function (MACHINE) { + function (M) { return baselib.numbers.acos( - checkNumber(MACHINE, 'acos', 0)); + checkNumber(M, 'acos', 0)); }); installPrimitiveProcedure( 'asin', 1, - function (MACHINE) { + function (M) { return baselib.numbers.asin( - checkNumber(MACHINE, 'asin', 0)); + checkNumber(M, 'asin', 0)); }); installPrimitiveProcedure( 'sin', 1, - function (MACHINE) { + function (M) { return baselib.numbers.sin( - checkNumber(MACHINE, 'sin', 0)); + checkNumber(M, 'sin', 0)); }); @@ -1356,18 +1356,18 @@ installPrimitiveProcedure( 'sinh', 1, - function (MACHINE) { + function (M) { return baselib.numbers.sinh( - checkNumber(MACHINE, 'sinh', 0)); + checkNumber(M, 'sinh', 0)); }); installPrimitiveProcedure( 'tan', 1, - function (MACHINE) { + function (M) { return baselib.numbers.tan( - checkNumber(MACHINE, 'tan', 0)); + checkNumber(M, 'tan', 0)); }); @@ -1375,15 +1375,15 @@ installPrimitiveProcedure( 'atan', makeList(1, 2), - function (MACHINE) { - if (MACHINE.argcount === 1) { + function (M) { + if (M.argcount === 1) { return baselib.numbers.atan( - checkNumber(MACHINE, 'atan', 0)); + checkNumber(M, 'atan', 0)); } else { return makeFloat( Math.atan2( - baselib.numbers.toFixnum(checkNumber(MACHINE, 'atan', 0)), - baselib.numbers.toFixnum(checkNumber(MACHINE, 'atan', 1)))); + baselib.numbers.toFixnum(checkNumber(M, 'atan', 0)), + baselib.numbers.toFixnum(checkNumber(M, 'atan', 1)))); } }); @@ -1391,25 +1391,25 @@ installPrimitiveProcedure( 'angle', 1, - function (MACHINE) { + function (M) { return baselib.numbers.angle( - checkNumber(MACHINE, 'angle', 0)); + checkNumber(M, 'angle', 0)); }); installPrimitiveProcedure( 'magnitude', 1, - function (MACHINE) { + function (M) { return baselib.numbers.magnitude( - checkNumber(MACHINE, 'magnitude', 0)); + checkNumber(M, 'magnitude', 0)); }); installPrimitiveProcedure( 'conjugate', 1, - function (MACHINE) { + function (M) { return baselib.numbers.conjugate( - checkNumber(MACHINE, 'conjugate', 0)); + checkNumber(M, 'conjugate', 0)); }); @@ -1418,27 +1418,27 @@ installPrimitiveProcedure( 'cos', 1, - function (MACHINE) { + function (M) { return baselib.numbers.cos( - checkNumber(MACHINE, 'cos', 0)); + checkNumber(M, 'cos', 0)); }); installPrimitiveProcedure( 'cosh', 1, - function (MACHINE) { + function (M) { return baselib.numbers.cosh( - checkNumber(MACHINE, 'cosh', 0)); + checkNumber(M, 'cosh', 0)); }); installPrimitiveProcedure( 'gcd', baselib.arity.makeArityAtLeast(1), - function (MACHINE) { + function (M) { var args = [], i, x; - for (i = 0; i < MACHINE.argcount; i++) { - args.push(checkNumber(MACHINE, 'gcd', i)); + for (i = 0; i < M.argcount; i++) { + args.push(checkNumber(M, 'gcd', i)); } x = args.shift(); return baselib.numbers.gcd(x, args); @@ -1447,10 +1447,10 @@ installPrimitiveProcedure( 'lcm', baselib.arity.makeArityAtLeast(1), - function (MACHINE) { + function (M) { var args = [], i, x; - for (i = 0; i < MACHINE.argcount; i++) { - args.push(checkNumber(MACHINE, 'lcm', i)); + for (i = 0; i < M.argcount; i++) { + args.push(checkNumber(M, 'lcm', i)); } x = args.shift(); return baselib.numbers.lcm(x, args); @@ -1462,43 +1462,43 @@ installPrimitiveProcedure( 'exp', 1, - function (MACHINE) { + function (M) { return baselib.numbers.exp( - checkNumber(MACHINE, 'exp', 0)); + checkNumber(M, 'exp', 0)); }); installPrimitiveProcedure( 'expt', 2, - function (MACHINE) { + function (M) { return baselib.numbers.expt( - checkNumber(MACHINE, 'expt', 0), - checkNumber(MACHINE, 'expt', 1)); + checkNumber(M, 'expt', 0), + checkNumber(M, 'expt', 1)); }); installPrimitiveProcedure( 'exact?', 1, - function (MACHINE) { + function (M) { return baselib.numbers.isExact( - checkNumber(MACHINE, 'exact?', 0)); + checkNumber(M, 'exact?', 0)); }); installPrimitiveProcedure( 'integer?', 1, - function (MACHINE) { - return baselib.numbers.isInteger(MACHINE.env[MACHINE.env.length - 1]); + function (M) { + return baselib.numbers.isInteger(M.env[M.env.length - 1]); }); installPrimitiveProcedure( 'exact-nonnegative-integer?', 1, - function (MACHINE) { - return isNatural(MACHINE.env[MACHINE.env.length - 1]); + function (M) { + return isNatural(M.env[M.env.length - 1]); }); @@ -1506,67 +1506,67 @@ installPrimitiveProcedure( 'imag-part', 1, - function (MACHINE) { + function (M) { return baselib.numbers.imaginaryPart( - checkNumber(MACHINE, 'imag-part', 0)); + checkNumber(M, 'imag-part', 0)); }); installPrimitiveProcedure( 'real-part', 1, - function (MACHINE) { + function (M) { return baselib.numbers.realPart( - checkNumber(MACHINE, 'real-part', 0)); + checkNumber(M, 'real-part', 0)); }); installPrimitiveProcedure( 'make-polar', 2, - function (MACHINE) { + function (M) { return makeComplexPolar( - checkReal(MACHINE, 'make-polar', 0), - checkReal(MACHINE, 'make-polar', 1)); + checkReal(M, 'make-polar', 0), + checkReal(M, 'make-polar', 1)); }); installPrimitiveProcedure( 'make-rectangular', 2, - function (MACHINE) { + function (M) { return makeComplex( - checkReal(MACHINE, 'make-rectangular', 0), - checkReal(MACHINE, 'make-rectangular', 1)); + checkReal(M, 'make-rectangular', 0), + checkReal(M, 'make-rectangular', 1)); }); installPrimitiveProcedure( 'modulo', 2, - function (MACHINE) { + function (M) { return baselib.numbers.modulo( - checkInteger(MACHINE, 'modulo', 0), - checkInteger(MACHINE, 'modulo', 1)); + checkInteger(M, 'modulo', 0), + checkInteger(M, 'modulo', 1)); }); installPrimitiveProcedure( 'remainder', 2, - function (MACHINE) { + function (M) { return baselib.numbers.remainder( - checkInteger(MACHINE, 'remainder', 0), - checkInteger(MACHINE, 'remainder', 1)); + checkInteger(M, 'remainder', 0), + checkInteger(M, 'remainder', 1)); }); installPrimitiveProcedure( 'quotient', 2, - function (MACHINE) { + function (M) { return baselib.numbers.quotient( - checkInteger(MACHINE, 'quotient', 0), - checkInteger(MACHINE, 'quotient', 1)); + checkInteger(M, 'quotient', 0), + checkInteger(M, 'quotient', 1)); }); @@ -1574,35 +1574,35 @@ installPrimitiveProcedure( 'floor', 1, - function (MACHINE) { + function (M) { return baselib.numbers.floor( - checkReal(MACHINE, 'floor', 0)); + checkReal(M, 'floor', 0)); }); installPrimitiveProcedure( 'ceiling', 1, - function (MACHINE) { + function (M) { return baselib.numbers.ceiling( - checkReal(MACHINE, 'ceiling', 0)); + checkReal(M, 'ceiling', 0)); }); installPrimitiveProcedure( 'round', 1, - function (MACHINE) { + function (M) { return baselib.numbers.round( - checkReal(MACHINE, 'round', 0)); + checkReal(M, 'round', 0)); }); installPrimitiveProcedure( 'truncate', 1, - function (MACHINE) { - var n = checkReal(MACHINE, 'truncate', 0); + function (M) { + var n = checkReal(M, 'truncate', 0); if (baselib.numbers.lessThan(n, 0)) { return baselib.numbers.ceiling(n); } else { @@ -1614,36 +1614,36 @@ installPrimitiveProcedure( 'numerator', 1, - function (MACHINE) { + function (M) { return baselib.numbers.numerator( - checkRational(MACHINE, 'numerator', 0)); + checkRational(M, 'numerator', 0)); }); installPrimitiveProcedure( 'denominator', 1, - function (MACHINE) { + function (M) { return baselib.numbers.denominator( - checkRational(MACHINE, 'denominator', 0)); + checkRational(M, 'denominator', 0)); }); installPrimitiveProcedure( 'log', 1, - function (MACHINE) { + function (M) { return baselib.numbers.log( - checkNumber(MACHINE, 'log', 0)); + checkNumber(M, 'log', 0)); }); installPrimitiveProcedure( 'sqr', 1, - function (MACHINE) { + function (M) { return baselib.numbers.sqr( - checkNumber(MACHINE, 'sqr', 0)); + checkNumber(M, 'sqr', 0)); }); @@ -1652,9 +1652,9 @@ installPrimitiveProcedure( 'sqrt', 1, - function (MACHINE) { + function (M) { return baselib.numbers.sqrt( - checkNumber(MACHINE, 'sqrt', 0)); + checkNumber(M, 'sqrt', 0)); }); @@ -1662,9 +1662,9 @@ installPrimitiveProcedure( 'integer-sqrt', 1, - function (MACHINE) { + function (M) { return baselib.numbers.integerSqrt( - checkInteger(MACHINE, 'integer-sqrt', 0)); + checkInteger(M, 'integer-sqrt', 0)); }); @@ -1672,21 +1672,21 @@ installPrimitiveProcedure( 'sgn', 1, - function (MACHINE) { + function (M) { return baselib.numbers.sign( - checkInteger(MACHINE, 'sgn', 0)); + checkInteger(M, 'sgn', 0)); }); installPrimitiveProcedure( 'min', baselib.arity.makeArityAtLeast(1), - function(MACHINE) { + function(M) { var i; var next; - var currentMin = checkReal(MACHINE, 'min', 0); - for (i = 1; i < MACHINE.argcount; i++) { - next = checkReal(MACHINE, 'min', i); + var currentMin = checkReal(M, 'min', 0); + for (i = 1; i < M.argcount; i++) { + next = checkReal(M, 'min', i); if (baselib.numbers.lessThan(next, currentMin)) { currentMin = next; } @@ -1697,12 +1697,12 @@ installPrimitiveProcedure( 'max', baselib.arity.makeArityAtLeast(1), - function(MACHINE) { + function(M) { var i; var next; - var currentMax = checkReal(MACHINE, 'min', 0); - for (i = 1; i < MACHINE.argcount; i++) { - next = checkReal(MACHINE, 'min', i); + var currentMax = checkReal(M, 'min', 0); + for (i = 1; i < M.argcount; i++) { + next = checkReal(M, 'min', i); if (baselib.numbers.greaterThan(next, currentMax)) { currentMax = next; } @@ -1718,76 +1718,76 @@ installPrimitiveProcedure( 'error', baselib.arity.makeArityAtLeast(1), - function (MACHINE) { + function (M) { var i; - if (MACHINE.argcount === 1) { - var sym = checkSymbol(MACHINE, 'error', 1); - raise(MACHINE, baselib.exceptions.makeExnFail(String(sym), - MACHINE.captureContinuationMarks())); + if (M.argcount === 1) { + var sym = checkSymbol(M, 'error', 1); + raise(M, baselib.exceptions.makeExnFail(String(sym), + M.captureContinuationMarks())); } - if (isString(MACHINE.env[MACHINE.env.length - 1])) { + if (isString(M.env[M.env.length - 1])) { var vs = []; - for (i = 1; i < MACHINE.argcount; i++) { - vs.push(baselib.format.format("~e", [MACHINE.env[MACHINE.env.length - 1 - i]])); + for (i = 1; i < M.argcount; i++) { + vs.push(baselib.format.format("~e", [M.env[M.env.length - 1 - i]])); } - raise(MACHINE, baselib.exceptions.makeExnFail(String(MACHINE.env[MACHINE.env.length - 1]) + + raise(M, baselib.exceptions.makeExnFail(String(M.env[M.env.length - 1]) + ": " + vs.join(' '), - MACHINE.captureContinuationMarks())); + M.captureContinuationMarks())); } - if (isSymbol(MACHINE.env[MACHINE.env.length - 1])) { - var fmtString = checkString(MACHINE, 'error', 1); - var args = [MACHINE.env[MACHINE.env.length - 1]]; - for (i = 2; i < MACHINE.argcount; i++) { - args.push(MACHINE.env[MACHINE.env.length - 1 - i]); + if (isSymbol(M.env[M.env.length - 1])) { + var fmtString = checkString(M, 'error', 1); + var args = [M.env[M.env.length - 1]]; + for (i = 2; i < M.argcount; i++) { + args.push(M.env[M.env.length - 1 - i]); } - raise(MACHINE, baselib.exceptions.makeExnFail( + raise(M, baselib.exceptions.makeExnFail( baselib.format.format('~s: ' + String(fmtString), args), - MACHINE.captureContinuationMarks())); + M.captureContinuationMarks())); } // Fall-through - raiseArgumentTypeError(MACHINE, 'error', 'symbol or string', 0, MACHINE.env[MACHINE.env.length - 1]); + raiseArgumentTypeError(M, 'error', 'symbol or string', 0, M.env[M.env.length - 1]); }); installPrimitiveProcedure( 'raise-mismatch-error', 3, - function (MACHINE) { - var name = checkSymbol(MACHINE, 'raise-mismatch-error', 0); - var message = checkString(MACHINE, 'raise-mismatch-error', 0); - var val = MACHINE.env[MACHINE.env.length - 1 - 2]; - raise(MACHINE, baselib.exceptions.makeExnFail( + function (M) { + var name = checkSymbol(M, 'raise-mismatch-error', 0); + var message = checkString(M, 'raise-mismatch-error', 0); + var val = M.env[M.env.length - 1 - 2]; + raise(M, baselib.exceptions.makeExnFail( baselib.format.format("~a: ~a~e", [name, message, val]), - MACHINE.captureContinuationMarks())); + M.captureContinuationMarks())); }); installPrimitiveProcedure( 'raise-type-error', baselib.arity.makeArityAtLeast(3), - function (MACHINE) { - var name = checkSymbol(MACHINE, 'raise-type-error', 0); - var expected = checkString(MACHINE, 'raise-type-error', 1); - if (MACHINE.argcount === 3) { - raiseArgumentTypeError(MACHINE, + function (M) { + var name = checkSymbol(M, 'raise-type-error', 0); + var expected = checkString(M, 'raise-type-error', 1); + if (M.argcount === 3) { + raiseArgumentTypeError(M, name, expected, undefined, - MACHINE.env[MACHINE.env.length - 1 - 2]); + M.env[M.env.length - 1 - 2]); } else { - raiseArgumentTypeError(MACHINE, + raiseArgumentTypeError(M, name, expected, - checkNatural(MACHINE, 'raise-type-error', 2), - MACHINE.env[MACHINE.env.length - 1 - 2]); + checkNatural(M, 'raise-type-error', 2), + M.env[M.env.length - 1 - 2]); } }); @@ -1797,9 +1797,9 @@ installPrimitiveClosure( 'make-struct-type', makeList(4, 5, 6, 7, 8, 9, 10, 11), - function (MACHINE) { + function (M) { withArguments( - MACHINE, + M, 4, [false, NULL, @@ -1839,11 +1839,11 @@ makePrimitiveProcedure( constructorName, baselib.numbers.toFixnum(initFieldCount), - function (MACHINE) { + function (M) { var args = []; var i; for(i = 0; i < initFieldCount; i++) { - args.push(MACHINE.env[MACHINE.env.length - 1 - i]); + args.push(M.env[M.env.length - 1 - i]); } return structType.constructor.apply(null, args); }); @@ -1852,18 +1852,18 @@ makePrimitiveProcedure( String(name) + "?", 1, - function (MACHINE) { - return structType.predicate(MACHINE.env[MACHINE.env.length - 1]); + function (M) { + return structType.predicate(M.env[M.env.length - 1]); }); var accessorValue = makePrimitiveProcedure( String(name) + "-accessor", 2, - function (MACHINE) { + function (M) { return structType.accessor( - MACHINE.env[MACHINE.env.length - 1], - baselib.numbers.toFixnum(MACHINE.env[MACHINE.env.length - 2])); + M.env[M.env.length - 1], + baselib.numbers.toFixnum(M.env[M.env.length - 2])); }); accessorValue.structType = structType; @@ -1871,16 +1871,16 @@ makePrimitiveProcedure( String(name) + "-mutator", 3, - function (MACHINE) { + function (M) { return structType.mutator( - MACHINE.env[MACHINE.env.length - 1], - baselib.numbers.toFixnum(MACHINE.env[MACHINE.env.length - 2]), - MACHINE.env[MACHINE.env.length - 3]); + M.env[M.env.length - 1], + baselib.numbers.toFixnum(M.env[M.env.length - 2]), + M.env[M.env.length - 3]); }); mutatorValue.structType = structType; - finalizeClosureCall(MACHINE, + finalizeClosureCall(M, structType, constructorValue, predicateValue, @@ -1893,13 +1893,13 @@ installPrimitiveProcedure( 'current-inspector', makeList(0, 1), - function (MACHINE) { - if (MACHINE.argcount === 1) { - MACHINE.params['currentInspector'] = - checkInspector(MACHINE, 'current-inspector', 0); + function (M) { + if (M.argcount === 1) { + M.params['currentInspector'] = + checkInspector(M, 'current-inspector', 0); return VOID; } else { - return MACHINE.params['currentInspector']; + return M.params['currentInspector']; } } ); @@ -1908,12 +1908,12 @@ installPrimitiveProcedure( 'make-struct-field-accessor', makeList(2, 3), - function (MACHINE){ - var structType = MACHINE.env[MACHINE.env.length - 1].structType; - var index = MACHINE.env[MACHINE.env.length - 2]; + function (M){ + var structType = M.env[M.env.length - 1].structType; + var index = M.env[M.env.length - 2]; var name; - if (MACHINE.argcount === 3) { - name = String(MACHINE.env[MACHINE.env.length - 3]); + if (M.argcount === 3) { + name = String(M.env[M.env.length - 3]); } else { name = 'field' + index; } @@ -1922,8 +1922,8 @@ return makePrimitiveProcedure( name, 1, - function (MACHINE) { - var aStruct = checkStruct(MACHINE, name, 0); + function (M) { + var aStruct = checkStruct(M, name, 0); return structType.accessor( aStruct, baselib.numbers.toFixnum(index)); @@ -1935,12 +1935,12 @@ installPrimitiveProcedure( 'make-struct-field-mutator', makeList(2, 3), - function (MACHINE){ - var structType = MACHINE.env[MACHINE.env.length - 1].structType; - var index = MACHINE.env[MACHINE.env.length - 2]; + function (M){ + var structType = M.env[M.env.length - 1].structType; + var index = M.env[M.env.length - 2]; var name; - if (MACHINE.argcount === 3) { - name = String(MACHINE.env[MACHINE.env.length - 3]); + if (M.argcount === 3) { + name = String(M.env[M.env.length - 3]); } else { name = 'field' + index; } @@ -1949,12 +1949,12 @@ return makePrimitiveProcedure( name, 2, - function (MACHINE) { - var aStruct = checkStruct(MACHINE, name, 0); + function (M) { + var aStruct = checkStruct(M, name, 0); return structType.mutator( aStruct, baselib.numbers.toFixnum(index), - MACHINE.env[MACHINE.env.length - 2]); + M.env[M.env.length - 2]); }); }); @@ -1962,8 +1962,8 @@ installPrimitiveProcedure( 'make-placeholder', 1, - function(MACHINE) { - var v = MACHINE.env[MACHINE.env.length - 1]; + function(M) { + var v = M.env[M.env.length - 1]; return baselib.placeholders.makePlaceholder(v); }); @@ -1971,9 +1971,9 @@ installPrimitiveProcedure( 'placeholder-set!', 2, - function(MACHINE) { - var placeholder = checkPlaceholder(MACHINE, 'placeholder-set!', 0); - var val = MACHINE.env[MACHINE.env.length - 2]; + function(M) { + var placeholder = checkPlaceholder(M, 'placeholder-set!', 0); + var val = M.env[M.env.length - 2]; placeholder.set(val); return VOID; }); @@ -1983,8 +1983,8 @@ installPrimitiveProcedure( 'make-reader-graph', 1, - function(MACHINE) { - var x = MACHINE.env[MACHINE.env.length - 1]; + function(M) { + var x = M.env[M.env.length - 1]; return baselib.readergraph.readerGraph(x, baselib.hashes.makeLowLevelEqHash(), 0); @@ -1996,67 +1996,68 @@ installPrimitiveProcedure( 'srcloc', 5, - function(MACHINE) { - var source = MACHINE.env[MACHINE.env.length - 1]; - var line = checkNatural(MACHINE, 'srcloc', 1); - var column = checkNatural(MACHINE, 'srcloc', 2); - var position = checkNatural(MACHINE, 'srcloc', 3); - var span = checkNatural(MACHINE, 'srcloc', 4); + function(M) { + var source = M.env[M.env.length - 1]; + var line = checkNatural(M, 'srcloc', 1); + var column = checkNatural(M, 'srcloc', 2); + var position = checkNatural(M, 'srcloc', 3); + var span = checkNatural(M, 'srcloc', 4); return baselib.srclocs.makeSrcloc(source, line, column, position, span); }); + installPrimitiveProcedure( 'make-srcloc', 5, - function(MACHINE) { - var source = MACHINE.env[MACHINE.env.length - 1]; - var line = checkNatural(MACHINE, 'make-srcloc', 1); - var column = checkNatural(MACHINE, 'make-srcloc', 2); - var position = checkNatural(MACHINE, 'make-srcloc', 3); - var span = checkNatural(MACHINE, 'make-srcloc', 4); + function(M) { + var source = M.env[M.env.length - 1]; + var line = checkNatural(M, 'make-srcloc', 1); + var column = checkNatural(M, 'make-srcloc', 2); + var position = checkNatural(M, 'make-srcloc', 3); + var span = checkNatural(M, 'make-srcloc', 4); return baselib.srclocs.makeSrcloc(source, line, column, position, span); }); + installPrimitiveProcedure( 'srcloc?', 1, - function(MACHINE) { - return baselib.srclocs.isSrcloc(MACHINE.env[MACHINE.env.length - 1]); + function(M) { + return baselib.srclocs.isSrcloc(M.env[M.env.length - 1]); }); + installPrimitiveProcedure( 'srcloc-source', 1, - function(MACHINE) { - return baselib.srclocs.srclocSource(checkSrcloc(MACHINE, 'srcloc-source', 0)); + function(M) { + return baselib.srclocs.srclocSource(checkSrcloc(M, 'srcloc-source', 0)); }); + installPrimitiveProcedure( 'srcloc-line', 1, - function(MACHINE) { - return baselib.srclocs.srclocLine(checkSrcloc(MACHINE, 'srcloc-line', 0)); + function(M) { + return baselib.srclocs.srclocLine(checkSrcloc(M, 'srcloc-line', 0)); }); + installPrimitiveProcedure( 'srcloc-column', 1, - function(MACHINE) { - return baselib.srclocs.srclocColumn(checkSrcloc(MACHINE, 'srcloc-column', 0)); + function(M) { + return baselib.srclocs.srclocColumn(checkSrcloc(M, 'srcloc-column', 0)); }); + installPrimitiveProcedure( 'srcloc-position', 1, - function(MACHINE) { - return baselib.srclocs.srclocPosition(checkSrcloc(MACHINE, 'srcloc-position', 0)); + function(M) { + return baselib.srclocs.srclocPosition(checkSrcloc(M, 'srcloc-position', 0)); }); + installPrimitiveProcedure( 'srcloc-span', 1, - function(MACHINE) { - return baselib.srclocs.srclocSpan(checkSrcloc(MACHINE, 'srcloc-span', 0)); + function(M) { + return baselib.srclocs.srclocSpan(checkSrcloc(M, 'srcloc-span', 0)); }); - - - - - - exports['Primitives'] = Primitives; exports['installPrimitiveProcedure'] = installPrimitiveProcedure; diff --git a/js-assembler/runtime-src/runtime.js b/js-assembler/runtime-src/runtime.js index fc7d328..38465ba 100644 --- a/js-assembler/runtime-src/runtime.js +++ b/js-assembler/runtime-src/runtime.js @@ -212,11 +212,11 @@ var Machine = function() { this.callsBeforeTrampoline = STACK_LIMIT_ESTIMATE; - this.val = undefined; - this.proc = undefined; - this.argcount = undefined; - this.env = []; - this.control = []; // Arrayof (U Frame CallFrame PromptFrame) + this.val = undefined; // value register + this.proc = undefined; // procedure register + this.argcount = undefined; // argument count + this.env = []; // environment + this.control = []; // control: Arrayof (U Frame CallFrame PromptFrame) this.running = false; this.modules = {}; // String -> ModuleRecord this.mainModules = []; // Arrayof String @@ -444,17 +444,16 @@ Machine.prototype.trampoline = function(initialJump) { - var MACHINE = this; var thunk = initialJump; var startTime = (new Date()).valueOf(); - MACHINE.callsBeforeTrampoline = STACK_LIMIT_ESTIMATE; - MACHINE.params.numBouncesBeforeYield = - MACHINE.params.maxNumBouncesBeforeYield; - MACHINE.running = true; + this.callsBeforeTrampoline = STACK_LIMIT_ESTIMATE; + this.params.numBouncesBeforeYield = + this.params.maxNumBouncesBeforeYield; + this.running = true; while(true) { try { - thunk(MACHINE); + thunk(this); break; } catch (e) { // There are a few kinds of things that can get thrown @@ -479,35 +478,36 @@ // The running flag is set to false. if (typeof(e) === 'function') { thunk = e; - MACHINE.callsBeforeTrampoline = STACK_LIMIT_ESTIMATE; + this.callsBeforeTrampoline = STACK_LIMIT_ESTIMATE; - if (MACHINE.params.numBouncesBeforeYield-- < 0) { + if (this.params.numBouncesBeforeYield-- < 0) { recomputeMaxNumBouncesBeforeYield( - MACHINE, + this, (new Date()).valueOf() - startTime); - scheduleTrampoline(MACHINE, thunk); + scheduleTrampoline(this, thunk); return; } } else if (e instanceof Pause) { - var restart = makeRestartFunction(MACHINE); + var restart = makeRestartFunction(this); e.onPause(restart); return; } else if (e instanceof HaltError) { - MACHINE.running = false; - e.onHalt(MACHINE); + this.running = false; + e.onHalt(this); return; } else { // General error condition: just exit out // of the trampoline and call the current error handler. - MACHINE.running = false; - MACHINE.params.currentErrorHandler(MACHINE, e); + this.running = false; + this.params.currentErrorHandler(this, e); return; } } } - MACHINE.running = false; + this.running = false; + var that = this; setTimeout( - function() { MACHINE.params.currentSuccessHandler(MACHINE); }, + function() { that.params.currentSuccessHandler(that); }, 0); return; }; From b68eca9735bebe983d410d769eb22e8c5ad2d4ff Mon Sep 17 00:00:00 2001 From: Danny Yoo Date: Fri, 9 Sep 2011 13:38:41 -0400 Subject: [PATCH 04/27] replacing for loops with push.apply where appropriate --- js-assembler/assemble-perform-statement.rkt | 2 +- js-assembler/runtime-src/baselib-functions.js | 8 ++------ 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/js-assembler/assemble-perform-statement.rkt b/js-assembler/assemble-perform-statement.rkt index 956c611..61db922 100644 --- a/js-assembler/assemble-perform-statement.rkt +++ b/js-assembler/assemble-perform-statement.rkt @@ -79,7 +79,7 @@ ",")))] [(InstallClosureValues!? op) - "M.env.splice.apply(M.env,[M.env.length, 0].concat(M.proc.closedVals));"] + "M.env.push.apply(M.env,M.proc.closedVals);"] [(RestoreEnvironment!? op) "M.env=M.env[M.env.length-2].slice(0);"] diff --git a/js-assembler/runtime-src/baselib-functions.js b/js-assembler/runtime-src/baselib-functions.js index 9f659cb..0de0ed5 100644 --- a/js-assembler/runtime-src/baselib-functions.js +++ b/js-assembler/runtime-src/baselib-functions.js @@ -65,8 +65,7 @@ var i, returnArgs = [].slice.call(arguments, 1); // clear out stack space - // TODO: replace with a splice. - MACHINE.env.length = MACHINE.env.length - MACHINE.argcount; + MACHINE.env.length -= MACHINE.argcount; if (returnArgs.length === 1) { MACHINE.val = returnArgs[0]; @@ -77,10 +76,7 @@ } else { MACHINE.argcount = returnArgs.length; MACHINE.val = returnArgs.shift(); - // TODO: replace with a splice. - for (i = 0; i < MACHINE.argcount - 1; i++) { - MACHINE.env.push(returnArgs.pop()); - } + MACHINE.env.push.apply(MACHINE.env, returnArgs.reverse()); return MACHINE.control.pop().label.multipleValueReturn(MACHINE); } }; From ad83451030a2e25452e73cd0569a5ad4eeb247bb Mon Sep 17 00:00:00 2001 From: Danny Yoo Date: Fri, 9 Sep 2011 13:46:29 -0400 Subject: [PATCH 05/27] trying to eliminate primitives again and see how it affects code size --- js-assembler/runtime-src/baselib-functions.js | 28 ++++++++++++------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/js-assembler/runtime-src/baselib-functions.js b/js-assembler/runtime-src/baselib-functions.js index 0de0ed5..8529731 100644 --- a/js-assembler/runtime-src/baselib-functions.js +++ b/js-assembler/runtime-src/baselib-functions.js @@ -62,7 +62,7 @@ // extra function call here. var finalizeClosureCall = function (MACHINE) { MACHINE.callsBeforeTrampoline--; - var i, returnArgs = [].slice.call(arguments, 1); + var returnArgs = [].slice.call(arguments, 1); // clear out stack space MACHINE.env.length -= MACHINE.argcount; @@ -307,15 +307,6 @@ - - - - var makePrimitiveProcedure = function (name, arity, f) { - f.racketArity = arity; - f.displayName = name; - return f; - }; - var makeClosure = function (name, arity, f, closureArgs) { if (! closureArgs) { closureArgs = []; } return new Closure(f, @@ -325,6 +316,23 @@ }; + var makePrimitiveProcedure = function (name, arity, f) { + // f.racketArity = arity; + // f.displayName = name; + // return f; + return makeClosure(name, + arity, + function(M) { + --M.callsBeforeTrampoline; + M.val = f(M); + M.env.length -= M.argcount; + return M.control.pop().label(M); + }, + []); + }; + + + From 9e11017b7e305489a7d82341e80066897f2d43fb Mon Sep 17 00:00:00 2001 From: Danny Yoo Date: Fri, 9 Sep 2011 13:56:01 -0400 Subject: [PATCH 06/27] getting rid of primitive procedures --- compiler/compiler.rkt | 34 +++++++++++----------- tests/test-assemble.rkt | 62 ++++++++++++++++++++--------------------- 2 files changed, 48 insertions(+), 48 deletions(-) diff --git a/compiler/compiler.rkt b/compiler/compiler.rkt index 459ba9c..2342c24 100644 --- a/compiler/compiler.rkt +++ b/compiler/compiler.rkt @@ -1417,9 +1417,9 @@ linkage cenv (append-instruction-sequences - (make-TestAndJumpStatement (make-TestPrimitiveProcedure - (make-Reg 'proc)) - primitive-branch) + ;; (make-TestAndJumpStatement (make-TestPrimitiveProcedure + ;; (make-Reg 'proc)) + ;; primitive-branch) ;; Compiled branch @@ -1431,24 +1431,24 @@ compiled-linkage) ;; Primitive branch - primitive-branch - (make-PerformStatement (make-CheckPrimitiveArity! (make-Reg 'argcount))) - (compile-primitive-application cenv target primitive-linkage) + ;; primitive-branch + ;; (make-PerformStatement (make-CheckPrimitiveArity! (make-Reg 'argcount))) + ;; (compile-primitive-application cenv target primitive-linkage) after-call))))) -(: compile-primitive-application (CompileTimeEnvironment Target Linkage -> InstructionSequence)) -(define (compile-primitive-application cenv target linkage) - (let ([singular-context-check (emit-singular-context linkage)]) - (append-instruction-sequences - (make-AssignPrimOpStatement 'val (make-ApplyPrimitiveProcedure)) - (make-PopEnvironment (make-Reg 'argcount) - (make-Const 0)) - (if (eq? target 'val) - empty-instruction-sequence - (make-AssignImmediateStatement target (make-Reg 'val))) - singular-context-check))) +;; (: compile-primitive-application (CompileTimeEnvironment Target Linkage -> InstructionSequence)) +;; (define (compile-primitive-application cenv target linkage) +;; (let ([singular-context-check (emit-singular-context linkage)]) +;; (append-instruction-sequences +;; (make-AssignPrimOpStatement 'val (make-ApplyPrimitiveProcedure)) +;; (make-PopEnvironment (make-Reg 'argcount) +;; (make-Const 0)) +;; (if (eq? target 'val) +;; empty-instruction-sequence +;; (make-AssignImmediateStatement target (make-Reg 'val))) +;; singular-context-check))) diff --git a/tests/test-assemble.rkt b/tests/test-assemble.rkt index 1a92d79..40f6123 100644 --- a/tests/test-assemble.rkt +++ b/tests/test-assemble.rkt @@ -159,17 +159,17 @@ ;; Simple application -(test (E-many (list (make-PerformStatement (make-ExtendEnvironment/Prefix! '(+))) - (make-AssignImmediateStatement 'proc (make-EnvPrefixReference 0 0)) - (make-PushEnvironment 2 #f) - (make-AssignImmediateStatement (make-EnvLexicalReference 0 #f) - (make-Const 3)) - (make-AssignImmediateStatement (make-EnvLexicalReference 1 #f) - (make-Const 4)) - (make-AssignImmediateStatement 'argcount (make-Const 2)) - (make-AssignPrimOpStatement 'val (make-ApplyPrimitiveProcedure)) - 'done)) - "7") +;; (test (E-many (list (make-PerformStatement (make-ExtendEnvironment/Prefix! '(+))) +;; (make-AssignImmediateStatement 'proc (make-EnvPrefixReference 0 0)) +;; (make-PushEnvironment 2 #f) +;; (make-AssignImmediateStatement (make-EnvLexicalReference 0 #f) +;; (make-Const 3)) +;; (make-AssignImmediateStatement (make-EnvLexicalReference 1 #f) +;; (make-Const 4)) +;; (make-AssignImmediateStatement 'argcount (make-Const 2)) +;; (make-AssignPrimOpStatement 'val (make-ApplyPrimitiveProcedure)) +;; 'done)) +;; "7") @@ -325,16 +325,16 @@ end)) "ok") -;; Give a primitive procedure in val -(test (E-many `(,(make-PerformStatement (make-ExtendEnvironment/Prefix! '(+))) - ,(make-AssignImmediateStatement 'val (make-EnvPrefixReference 0 0)) - ,(make-TestAndJumpStatement (make-TestPrimitiveProcedure (make-Reg 'val)) 'onTrue) - ,(make-AssignImmediateStatement 'val (make-Const 'not-ok)) - ,(make-GotoStatement (make-Label 'end)) - onTrue - ,(make-AssignImmediateStatement 'val (make-Const 'ok)) - end)) - "ok") +;; ;; Give a primitive procedure in val +;; (test (E-many `(,(make-PerformStatement (make-ExtendEnvironment/Prefix! '(+))) +;; ,(make-AssignImmediateStatement 'val (make-EnvPrefixReference 0 0)) +;; ,(make-TestAndJumpStatement (make-TestPrimitiveProcedure (make-Reg 'val)) 'onTrue) +;; ,(make-AssignImmediateStatement 'val (make-Const 'not-ok)) +;; ,(make-GotoStatement (make-Label 'end)) +;; onTrue +;; ,(make-AssignImmediateStatement 'val (make-Const 'ok)) +;; end)) +;; "ok") ;; Give a primitive procedure in proc, but test val (test (E-many `(,(make-PerformStatement (make-ExtendEnvironment/Prefix! '(+))) @@ -347,16 +347,16 @@ end)) "not-a-procedure") -;; Give a primitive procedure in proc and test proc -(test (E-many `(,(make-PerformStatement (make-ExtendEnvironment/Prefix! '(+))) - ,(make-AssignImmediateStatement 'proc (make-EnvPrefixReference 0 0)) - ,(make-TestAndJumpStatement (make-TestPrimitiveProcedure (make-Reg 'proc)) 'onTrue) - ,(make-AssignImmediateStatement 'val (make-Const 'not-a-procedure)) - ,(make-GotoStatement (make-Label 'end)) - onTrue - ,(make-AssignImmediateStatement 'val (make-Const 'a-procedure)) - end)) - "a-procedure") +;; ;; Give a primitive procedure in proc and test proc +;; (test (E-many `(,(make-PerformStatement (make-ExtendEnvironment/Prefix! '(+))) +;; ,(make-AssignImmediateStatement 'proc (make-EnvPrefixReference 0 0)) +;; ,(make-TestAndJumpStatement (make-TestPrimitiveProcedure (make-Reg 'proc)) 'onTrue) +;; ,(make-AssignImmediateStatement 'val (make-Const 'not-a-procedure)) +;; ,(make-GotoStatement (make-Label 'end)) +;; onTrue +;; ,(make-AssignImmediateStatement 'val (make-Const 'a-procedure)) +;; end)) +;; "a-procedure") From 0de37fae867f77c4d324c8ae4b91b22205717585 Mon Sep 17 00:00:00 2001 From: Danny Yoo Date: Fri, 9 Sep 2011 14:19:56 -0400 Subject: [PATCH 07/27] continuing to shrink code down. Eliminating the use of simulator in test suite; I don't think we'll need the simulator any more. --- compiler/compiler.rkt | 2 +- compiler/il-structs.rkt | 24 ++---------- compiler/optimize-il.rkt | 2 - js-assembler/assemble-expression.rkt | 3 -- js-assembler/assemble-perform-statement.rkt | 13 ++----- js-assembler/assemble.rkt | 14 +++---- js-assembler/collect-jump-targets.rkt | 10 ++--- simulator/simulator.rkt | 24 ++---------- tests/test-all.rkt | 6 +-- tests/test-assemble.rkt | 42 ++++++++++----------- 10 files changed, 48 insertions(+), 92 deletions(-) diff --git a/compiler/compiler.rkt b/compiler/compiler.rkt index 2342c24..bfe9a99 100644 --- a/compiler/compiler.rkt +++ b/compiler/compiler.rkt @@ -1423,7 +1423,7 @@ ;; Compiled branch - (make-PerformStatement (make-CheckClosureArity! (make-Reg 'argcount))) + (make-PerformStatement (make-CheckClosureAndArity! (make-Reg 'argcount))) (compile-compiled-procedure-application cenv number-of-arguments 'dynamic diff --git a/compiler/il-structs.rkt b/compiler/il-structs.rkt index 33552b2..2783aa5 100644 --- a/compiler/il-structs.rkt +++ b/compiler/il-structs.rkt @@ -280,7 +280,6 @@ (define-type PrimitiveOperator (U GetCompiledProcedureEntry MakeCompiledProcedure MakeCompiledProcedureShell - ApplyPrimitiveProcedure MakeBoxedEnvironmentValue @@ -312,15 +311,6 @@ #:transparent) -;; Applies the primitive procedure that's stored in the proc register, using -;; the argcount number of values that are bound in the environment as arguments -;; to that primitive. -(define-struct: ApplyPrimitiveProcedure () - #:transparent) - - - - @@ -356,14 +346,12 @@ TestTrue TestOne TestZero - TestPrimitiveProcedure TestClosureArityMismatch )) (define-struct: TestFalse ([operand : OpArg]) #:transparent) (define-struct: TestTrue ([operand : OpArg]) #:transparent) (define-struct: TestOne ([operand : OpArg]) #:transparent) (define-struct: TestZero ([operand : OpArg]) #:transparent) -(define-struct: TestPrimitiveProcedure ([operand : OpArg]) #:transparent) (define-struct: TestClosureArityMismatch ([closure : OpArg] [n : OpArg]) #:transparent) @@ -375,13 +363,10 @@ [pos : Natural]) #:transparent) -;; Check the closure procedure value in 'proc and make sure it can accept the -;; # of arguments (stored as a number in the argcount register.). -(define-struct: CheckClosureArity! ([num-args : OpArg]) +;; Check the closure procedure value in 'proc and make sure it's a closure +;; that can accept the right arguments (stored as a number in the argcount register.). +(define-struct: CheckClosureAndArity! ([num-args : OpArg]) #:transparent) -(define-struct: CheckPrimitiveArity! ([num-args : OpArg]) - #:transparent) - ;; Extends the environment with a prefix that holds @@ -481,8 +466,7 @@ (define-type PrimitiveCommand (U CheckToplevelBound! - CheckClosureArity! - CheckPrimitiveArity! + CheckClosureAndArity! ExtendEnvironment/Prefix! InstallClosureValues! diff --git a/compiler/optimize-il.rkt b/compiler/optimize-il.rkt index 4f4b48c..4c8f921 100644 --- a/compiler/optimize-il.rkt +++ b/compiler/optimize-il.rkt @@ -128,8 +128,6 @@ (MakeCompiledProcedureShell-arity op) (MakeCompiledProcedureShell-display-name op))] - [(ApplyPrimitiveProcedure? op) - op] [(MakeBoxedEnvironmentValue? op) op] diff --git a/js-assembler/assemble-expression.rkt b/js-assembler/assemble-expression.rkt index 651da60..47c9708 100644 --- a/js-assembler/assemble-expression.rkt +++ b/js-assembler/assemble-expression.rkt @@ -36,9 +36,6 @@ (assemble-arity (MakeCompiledProcedureShell-arity op)) (assemble-display-name (MakeCompiledProcedureShell-display-name op)))] - [(ApplyPrimitiveProcedure? op) - (format "M.proc(M)")] - [(CaptureEnvironment? op) (format "M.env.slice(0, M.env.length - ~a)" (CaptureEnvironment-skip op))] diff --git a/js-assembler/assemble-perform-statement.rkt b/js-assembler/assemble-perform-statement.rkt index 61db922..5944fc1 100644 --- a/js-assembler/assemble-perform-statement.rkt +++ b/js-assembler/assemble-perform-statement.rkt @@ -21,18 +21,11 @@ (CheckToplevelBound!-pos op))] - [(CheckClosureArity!? op) + [(CheckClosureAndArity!? op) (format "if(!(M.proc instanceof RT.Closure)){RT.raiseOperatorIsNotClosure(M,M.proc);}if(!RT.isArityMatching(M.proc.racketArity,~a)){RT.raiseArityMismatchError(M, M.proc,~a);}" - (assemble-oparg (CheckClosureArity!-num-args op)) - (assemble-oparg (CheckClosureArity!-num-args op)))] + (assemble-oparg (CheckClosureAndArity!-num-args op)) + (assemble-oparg (CheckClosureAndArity!-num-args op)))] - - [(CheckPrimitiveArity!? op) - (format "if(!RT.isArityMatching(M.proc.racketArity,~a)){RT.raiseArityMismatchError(M,M.proc,~a);}" - (assemble-oparg (CheckPrimitiveArity!-num-args op)) - (assemble-oparg (CheckPrimitiveArity!-num-args op)))] - - [(ExtendEnvironment/Prefix!? op) (let: ([names : (Listof (U Symbol False GlobalBucket ModuleVariable)) (ExtendEnvironment/Prefix!-names op)]) (format "M.env.push([~a]);M.env[M.env.length-1].names=[~a];" diff --git a/js-assembler/assemble.rkt b/js-assembler/assemble.rkt index 096e846..951d0b2 100644 --- a/js-assembler/assemble.rkt +++ b/js-assembler/assemble.rkt @@ -236,9 +236,9 @@ EOF (format "if(~a===0)" (assemble-oparg (TestZero-operand test)))] - [(TestPrimitiveProcedure? test) - (format "if(typeof(~a)==='function')" - (assemble-oparg (TestPrimitiveProcedure-operand test)))] + ;; [(TestPrimitiveProcedure? test) + ;; (format "if(typeof(~a)==='function')" + ;; (assemble-oparg (TestPrimitiveProcedure-operand test)))] [(TestClosureArityMismatch? test) (format "if(!RT.isArityMatching((~a).racketArity,~a))" @@ -435,10 +435,10 @@ EOF (format "if(~a===0){~a}" (assemble-oparg (TestZero-operand test)) jump)] - [(TestPrimitiveProcedure? test) - (format "if(typeof(~a)==='function'){~a}" - (assemble-oparg (TestPrimitiveProcedure-operand test)) - jump)] + ;; [(TestPrimitiveProcedure? test) + ;; (format "if(typeof(~a)==='function'){~a}" + ;; (assemble-oparg (TestPrimitiveProcedure-operand test)) + ;; jump)] [(TestClosureArityMismatch? test) (format "if(!RT.isArityMatching((~a).racketArity,~a)){~a}" (assemble-oparg (TestClosureArityMismatch-closure test)) diff --git a/js-assembler/collect-jump-targets.rkt b/js-assembler/collect-jump-targets.rkt index b21c56f..0f334bf 100644 --- a/js-assembler/collect-jump-targets.rkt +++ b/js-assembler/collect-jump-targets.rkt @@ -112,8 +112,8 @@ (list (MakeCompiledProcedure-label op))] [(MakeCompiledProcedureShell? op) (list (MakeCompiledProcedureShell-label op))] - [(ApplyPrimitiveProcedure? op) - empty] + ;; [(ApplyPrimitiveProcedure? op) + ;; empty] [(CaptureEnvironment? op) empty] [(CaptureControl? op) @@ -258,8 +258,8 @@ (list (MakeCompiledProcedure-label op))] [(MakeCompiledProcedureShell? op) (list (MakeCompiledProcedureShell-label op))] - [(ApplyPrimitiveProcedure? op) - empty] + ;; [(ApplyPrimitiveProcedure? op) + ;; empty] [(CaptureEnvironment? op) empty] [(CaptureControl? op) @@ -279,7 +279,7 @@ ;; currently written this way because I'm hitting some bad type-checking behavior. #;([(CheckToplevelBound!? op) empty] - [(CheckClosureArity!? op) + [(CheckClosureAndArity!? op) empty] [(CheckPrimitiveArity!? op) empty] diff --git a/simulator/simulator.rkt b/simulator/simulator.rkt index 8ef658a..36d60bc 100644 --- a/simulator/simulator.rkt +++ b/simulator/simulator.rkt @@ -308,15 +308,15 @@ [else 'ok]))] - [(CheckClosureArity!? op) + [(CheckClosureAndArity!? op) (let: ([clos : SlotValue (machine-proc m)]) (cond [(closure? clos) (if (arity-match? (closure-arity clos) - (ensure-natural (evaluate-oparg m (CheckClosureArity!-num-args op)))) + (ensure-natural (evaluate-oparg m (CheckClosureAndArity!-num-args op)))) 'ok (error 'check-closure-arity "arity mismatch: passed ~s args to ~s" - (ensure-natural (evaluate-oparg m (CheckClosureArity!-num-args op))) + (ensure-natural (evaluate-oparg m (CheckClosureAndArity!-num-args op))) (closure-display-name clos)))] [else (error 'check-closure-arity "not a closure: ~s" clos)]))] @@ -654,23 +654,7 @@ (MakeCompiledProcedureShell-arity op) '() (MakeCompiledProcedureShell-display-name op)))] - - [(ApplyPrimitiveProcedure? op) - (let: ([prim : SlotValue (machine-proc m)] - [args : (Listof PrimitiveValue) - (map ensure-primitive-value (take (machine-env m) - (ensure-natural (machine-argcount m))))]) - (cond - [(primitive-proc? prim) - (target-updater! m (ensure-primitive-value - (parameterize ([current-output-port - (current-simulated-output-port)]) - (apply (primitive-proc-f prim) - m - args))))] - [else - (error 'apply-primitive-procedure)]))] - + [(CaptureEnvironment? op) (target-updater! m (make-CapturedEnvironment (drop (machine-env m) (CaptureEnvironment-skip op))))] diff --git a/tests/test-all.rkt b/tests/test-all.rkt index cb7cfbd..4237463 100644 --- a/tests/test-all.rkt +++ b/tests/test-all.rkt @@ -2,9 +2,9 @@ (require "test-parse.rkt" "test-parse-bytecode.rkt" - "test-simulator.rkt" - "test-compiler.rkt" - "test-compiler-2.rkt" + ;; "test-simulator.rkt" + ;; "test-compiler.rkt" + ;; "test-compiler-2.rkt" "test-assemble.rkt" "test-browser-evaluate.rkt" "test-package.rkt" diff --git a/tests/test-assemble.rkt b/tests/test-assemble.rkt index 40f6123..e92b5d3 100644 --- a/tests/test-assemble.rkt +++ b/tests/test-assemble.rkt @@ -265,7 +265,7 @@ (list 0 1) 'closureStart)) (make-PopEnvironment (make-Const 2) (make-Const 0)) - (make-PerformStatement (make-CheckClosureArity! (make-Const 5))) + (make-PerformStatement (make-CheckClosureAndArity! (make-Const 5))) 'theEnd))) ;; this should fail, since the check is for 1, but the closure expects 5. @@ -288,7 +288,7 @@ (list 0 1) 'closureStart)) (make-PopEnvironment (make-Const 2) (make-Const 0)) - (make-PerformStatement (make-CheckClosureArity! (make-Const 1))) + (make-PerformStatement (make-CheckClosureAndArity! (make-Const 1))) 'theEnd))) (error 'expected-failure)) @@ -315,15 +315,15 @@ end)) "ok") -;; Test for primitive procedure -(test (E-many `(,(make-AssignImmediateStatement 'val (make-Const '+)) - ,(make-TestAndJumpStatement (make-TestPrimitiveProcedure (make-Reg 'val)) 'onTrue) - ,(make-AssignImmediateStatement 'val (make-Const 'ok)) - ,(make-GotoStatement (make-Label 'end)) - onTrue - ,(make-AssignImmediateStatement 'val (make-Const 'not-ok)) - end)) - "ok") +;; ;; Test for primitive procedure +;; (test (E-many `(,(make-AssignImmediateStatement 'val (make-Const '+)) +;; ,(make-TestAndJumpStatement (make-TestPrimitiveProcedure (make-Reg 'val)) 'onTrue) +;; ,(make-AssignImmediateStatement 'val (make-Const 'ok)) +;; ,(make-GotoStatement (make-Label 'end)) +;; onTrue +;; ,(make-AssignImmediateStatement 'val (make-Const 'not-ok)) +;; end)) +;; "ok") ;; ;; Give a primitive procedure in val ;; (test (E-many `(,(make-PerformStatement (make-ExtendEnvironment/Prefix! '(+))) @@ -336,16 +336,16 @@ ;; end)) ;; "ok") -;; Give a primitive procedure in proc, but test val -(test (E-many `(,(make-PerformStatement (make-ExtendEnvironment/Prefix! '(+))) - ,(make-AssignImmediateStatement 'proc (make-EnvPrefixReference 0 0)) - ,(make-TestAndJumpStatement (make-TestPrimitiveProcedure (make-Reg 'val)) 'onTrue) - ,(make-AssignImmediateStatement 'val (make-Const 'not-a-procedure)) - ,(make-GotoStatement (make-Label 'end)) - onTrue - ,(make-AssignImmediateStatement 'val (make-Const 'a-procedure)) - end)) - "not-a-procedure") +;; ;; Give a primitive procedure in proc, but test val +;; (test (E-many `(,(make-PerformStatement (make-ExtendEnvironment/Prefix! '(+))) +;; ,(make-AssignImmediateStatement 'proc (make-EnvPrefixReference 0 0)) +;; ,(make-TestAndJumpStatement (make-TestPrimitiveProcedure (make-Reg 'val)) 'onTrue) +;; ,(make-AssignImmediateStatement 'val (make-Const 'not-a-procedure)) +;; ,(make-GotoStatement (make-Label 'end)) +;; onTrue +;; ,(make-AssignImmediateStatement 'val (make-Const 'a-procedure)) +;; end)) +;; "not-a-procedure") ;; ;; Give a primitive procedure in proc and test proc ;; (test (E-many `(,(make-PerformStatement (make-ExtendEnvironment/Prefix! '(+))) From 420df4165c878665ba0368f52549c62482e568ae Mon Sep 17 00:00:00 2001 From: Danny Yoo Date: Fri, 9 Sep 2011 15:08:39 -0400 Subject: [PATCH 08/27] continuing to shrink code --- js-assembler/assemble-perform-statement.rkt | 3 +- js-assembler/assemble.rkt | 23 ++++++++++++-- js-assembler/runtime-src/runtime.js | 35 +++++++++++++++++++++ 3 files changed, 57 insertions(+), 4 deletions(-) diff --git a/js-assembler/assemble-perform-statement.rkt b/js-assembler/assemble-perform-statement.rkt index 5944fc1..63cd936 100644 --- a/js-assembler/assemble-perform-statement.rkt +++ b/js-assembler/assemble-perform-statement.rkt @@ -22,8 +22,7 @@ [(CheckClosureAndArity!? op) - (format "if(!(M.proc instanceof RT.Closure)){RT.raiseOperatorIsNotClosure(M,M.proc);}if(!RT.isArityMatching(M.proc.racketArity,~a)){RT.raiseArityMismatchError(M, M.proc,~a);}" - (assemble-oparg (CheckClosureAndArity!-num-args op)) + (format "RT.checkClosureAndArity(M, ~a);\n" (assemble-oparg (CheckClosureAndArity!-num-args op)))] [(ExtendEnvironment/Prefix!? op) diff --git a/js-assembler/assemble.rkt b/js-assembler/assemble.rkt index 951d0b2..f4ad9da 100644 --- a/js-assembler/assemble.rkt +++ b/js-assembler/assemble.rkt @@ -14,7 +14,8 @@ "../sets.rkt" "../helpers.rkt" racket/string - racket/list) + racket/list + racket/match) (require/typed "../logger.rkt" [log-debug (String -> Void)]) @@ -44,7 +45,7 @@ (display "var RT = plt.runtime;\n" op) (define-values (basic-blocks entry-points) (fracture stmts)) - + (write-blocks basic-blocks (list->set entry-points) op) (write-linked-label-attributes stmts op) @@ -171,6 +172,23 @@ EOF (: assemble-basic-block (BasicBlock Blockht (Setof Symbol) Output-Port -> 'ok)) (define (assemble-basic-block a-basic-block blockht entry-points op) + (match (BasicBlock-stmts a-basic-block) + ;; [(list (struct PopEnvironment (n (and (? (lambda (c) (equal? c (Const 0)))) + ;; skip))) + ;; (struct GotoStatement ((and (? Label?) + ;; target)))) + ;; (fprintf op "~a=RT.si_popgoto(~a,function(){return ~a});\n" + ;; (assemble-label (make-Label (BasicBlock-name a-basic-block))) + ;; (assemble-oparg n) + ;; (assemble-label target)) + ;; 'ok] + [else + (default-assemble-basic-block a-basic-block blockht entry-points op)])) + + + +(: default-assemble-basic-block (BasicBlock Blockht (Setof Symbol) Output-Port -> 'ok)) +(define (default-assemble-basic-block a-basic-block blockht entry-points op) (fprintf op "var ~a = function(M) { if(--M.callsBeforeTrampoline < 0) { throw ~a; }\n" (assemble-label (make-Label (BasicBlock-name a-basic-block))) (assemble-label (make-Label (BasicBlock-name a-basic-block)))) @@ -184,6 +202,7 @@ EOF + (: assemble-block-statements (Symbol (Listof UnlabeledStatement) Blockht (Setof Symbol) Output-Port -> 'ok)) (define (assemble-block-statements name stmts blockht entry-points op) diff --git a/js-assembler/runtime-src/runtime.js b/js-assembler/runtime-src/runtime.js index 38465ba..c01f3c3 100644 --- a/js-assembler/runtime-src/runtime.js +++ b/js-assembler/runtime-src/runtime.js @@ -655,6 +655,37 @@ + var checkClosureAndArity = function(M, n) { + if(!(M.proc instanceof Closure)){ + raiseOperatorIsNotClosure(M,M.proc); + } + if(!isArityMatching(M.proc.racketArity,n)) { + raiseArityMismatchError(M, M.proc,n); + } + }; + + + + ////////////////////////////////////////////////////////////////////// + // Superinstructions to try to reduce code size. + + var si_popgoto = function(n, gotoTargetThunk) { + return function(M) { + --M.callsBeforeTrampoline; + M.env.length-=n; + return gotoTargetThunk()(M); + }; + }; + + + + + + + + + + ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// @@ -784,4 +815,8 @@ exports['getTracedAppKey'] = getTracedAppKey; exports['getTracedCalleeKey'] = getTracedCalleeKey; + exports['si_popgoto'] = si_popgoto; + exports['checkClosureAndArity'] = checkClosureAndArity; + + }(this.plt, this.plt.baselib)); \ No newline at end of file From f782010ede2dde91a8a753084455e4345b3cbabf Mon Sep 17 00:00:00 2001 From: Danny Yoo Date: Fri, 9 Sep 2011 15:20:20 -0400 Subject: [PATCH 09/27] checking for trampoline only at function returns. --- js-assembler/assemble.rkt | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/js-assembler/assemble.rkt b/js-assembler/assemble.rkt index f4ad9da..9ff1cc5 100644 --- a/js-assembler/assemble.rkt +++ b/js-assembler/assemble.rkt @@ -46,7 +46,13 @@ (define-values (basic-blocks entry-points) (fracture stmts)) - (write-blocks basic-blocks (list->set entry-points) op) + (define function-return-names + (list->set (map LinkedLabel-label (filter LinkedLabel? stmts)))) + + (write-blocks basic-blocks + (list->set entry-points) + function-return-names + op) (write-linked-label-attributes stmts op) @@ -65,9 +71,9 @@ EOF -(: write-blocks ((Listof BasicBlock) (Setof Symbol) Output-Port -> Void)) +(: write-blocks ((Listof BasicBlock) (Setof Symbol) (Setof Symbol) Output-Port -> Void)) ;; Write out all the basic blocks associated to an entry point. -(define (write-blocks blocks entry-points op) +(define (write-blocks blocks entry-points function-return-names op) (: blockht : Blockht) (define blockht (make-hash)) @@ -83,6 +89,7 @@ EOF (assemble-basic-block (hash-ref blockht s) blockht entry-points + function-return-names op) (newline op)) entry-points)) @@ -170,8 +177,8 @@ EOF -(: assemble-basic-block (BasicBlock Blockht (Setof Symbol) Output-Port -> 'ok)) -(define (assemble-basic-block a-basic-block blockht entry-points op) +(: assemble-basic-block (BasicBlock Blockht (Setof Symbol) (Setof Symbol) Output-Port -> 'ok)) +(define (assemble-basic-block a-basic-block blockht entry-points function-return-names op) (match (BasicBlock-stmts a-basic-block) ;; [(list (struct PopEnvironment (n (and (? (lambda (c) (equal? c (Const 0)))) ;; skip))) @@ -183,15 +190,20 @@ EOF ;; (assemble-label target)) ;; 'ok] [else - (default-assemble-basic-block a-basic-block blockht entry-points op)])) + (default-assemble-basic-block a-basic-block blockht entry-points function-return-names op)])) -(: default-assemble-basic-block (BasicBlock Blockht (Setof Symbol) Output-Port -> 'ok)) -(define (default-assemble-basic-block a-basic-block blockht entry-points op) - (fprintf op "var ~a = function(M) { if(--M.callsBeforeTrampoline < 0) { throw ~a; }\n" - (assemble-label (make-Label (BasicBlock-name a-basic-block))) - (assemble-label (make-Label (BasicBlock-name a-basic-block)))) +(: default-assemble-basic-block (BasicBlock Blockht (Setof Symbol) (Setof Symbol) Output-Port -> 'ok)) +(define (default-assemble-basic-block a-basic-block blockht entry-points function-return-names op) + (cond + [(set-contains? function-return-names (BasicBlock-name a-basic-block)) + (fprintf op "var ~a=function(M){if(--M.callsBeforeTrampoline<0){throw ~a;}\n" + (assemble-label (make-Label (BasicBlock-name a-basic-block))) + (assemble-label (make-Label (BasicBlock-name a-basic-block))))] + [else + (fprintf op "var ~a=function(M){--M.callsBeforeTrampoline<0;\n" + (assemble-label (make-Label (BasicBlock-name a-basic-block))))]) (assemble-block-statements (BasicBlock-name a-basic-block) (BasicBlock-stmts a-basic-block) blockht From 13bdc384185c15700b40c505f301f9a0297fe93c Mon Sep 17 00:00:00 2001 From: Danny Yoo Date: Fri, 9 Sep 2011 15:38:13 -0400 Subject: [PATCH 10/27] fixing the detection of function header names --- js-assembler/assemble-perform-statement.rkt | 2 +- js-assembler/assemble.rkt | 46 +++++++++++++++------ 2 files changed, 34 insertions(+), 14 deletions(-) diff --git a/js-assembler/assemble-perform-statement.rkt b/js-assembler/assemble-perform-statement.rkt index 63cd936..eda1874 100644 --- a/js-assembler/assemble-perform-statement.rkt +++ b/js-assembler/assemble-perform-statement.rkt @@ -22,7 +22,7 @@ [(CheckClosureAndArity!? op) - (format "RT.checkClosureAndArity(M, ~a);\n" + (format "RT.checkClosureAndArity(M, ~a);" (assemble-oparg (CheckClosureAndArity!-num-args op)))] [(ExtendEnvironment/Prefix!? op) diff --git a/js-assembler/assemble.rkt b/js-assembler/assemble.rkt index 9ff1cc5..c531c49 100644 --- a/js-assembler/assemble.rkt +++ b/js-assembler/assemble.rkt @@ -46,12 +46,12 @@ (define-values (basic-blocks entry-points) (fracture stmts)) - (define function-return-names - (list->set (map LinkedLabel-label (filter LinkedLabel? stmts)))) + (define function-entry-names + (list->set (get-function-entry-names stmts))) (write-blocks basic-blocks (list->set entry-points) - function-return-names + function-entry-names op) (write-linked-label-attributes stmts op) @@ -73,7 +73,7 @@ EOF (: write-blocks ((Listof BasicBlock) (Setof Symbol) (Setof Symbol) Output-Port -> Void)) ;; Write out all the basic blocks associated to an entry point. -(define (write-blocks blocks entry-points function-return-names op) +(define (write-blocks blocks entry-points function-entry-names op) (: blockht : Blockht) (define blockht (make-hash)) @@ -89,7 +89,7 @@ EOF (assemble-basic-block (hash-ref blockht s) blockht entry-points - function-return-names + function-entry-names op) (newline op)) entry-points)) @@ -178,7 +178,7 @@ EOF (: assemble-basic-block (BasicBlock Blockht (Setof Symbol) (Setof Symbol) Output-Port -> 'ok)) -(define (assemble-basic-block a-basic-block blockht entry-points function-return-names op) +(define (assemble-basic-block a-basic-block blockht entry-points function-entry-names op) (match (BasicBlock-stmts a-basic-block) ;; [(list (struct PopEnvironment (n (and (? (lambda (c) (equal? c (Const 0)))) ;; skip))) @@ -190,14 +190,14 @@ EOF ;; (assemble-label target)) ;; 'ok] [else - (default-assemble-basic-block a-basic-block blockht entry-points function-return-names op)])) + (default-assemble-basic-block a-basic-block blockht entry-points function-entry-names op)])) (: default-assemble-basic-block (BasicBlock Blockht (Setof Symbol) (Setof Symbol) Output-Port -> 'ok)) -(define (default-assemble-basic-block a-basic-block blockht entry-points function-return-names op) +(define (default-assemble-basic-block a-basic-block blockht entry-points function-entry-names op) (cond - [(set-contains? function-return-names (BasicBlock-name a-basic-block)) + [(set-contains? function-entry-names (BasicBlock-name a-basic-block)) (fprintf op "var ~a=function(M){if(--M.callsBeforeTrampoline<0){throw ~a;}\n" (assemble-label (make-Label (BasicBlock-name a-basic-block))) (assemble-label (make-Label (BasicBlock-name a-basic-block))))] @@ -466,10 +466,6 @@ EOF (format "if(~a===0){~a}" (assemble-oparg (TestZero-operand test)) jump)] - ;; [(TestPrimitiveProcedure? test) - ;; (format "if(typeof(~a)==='function'){~a}" - ;; (assemble-oparg (TestPrimitiveProcedure-operand test)) - ;; jump)] [(TestClosureArityMismatch? test) (format "if(!RT.isArityMatching((~a).racketArity,~a)){~a}" (assemble-oparg (TestClosureArityMismatch-closure test)) @@ -563,3 +559,27 @@ EOF (if (natural? n) n (error 'ensure-natural))) + + + +(: get-function-entry-names ((Listof Statement) -> (Listof Symbol))) +(define (get-function-entry-names stmts) + (cond + [(empty? stmts) + '()] + [else + (define first-stmt (first stmts)) + (cond + [(AssignPrimOpStatement? first-stmt) + (define op (AssignPrimOpStatement-op first-stmt)) + (cond + [(MakeCompiledProcedure? op) + (cons (MakeCompiledProcedure-label op) + (get-function-entry-names (rest stmts)))] + [(MakeCompiledProcedureShell? first-stmt) + (cons (MakeCompiledProcedureShell-label op) + (get-function-entry-names (rest stmts)))] + [else + (get-function-entry-names (rest stmts))])] + [else + (get-function-entry-names (rest stmts))])])) From 690e3a423c3d63131f271a14f62e2aaccc1ca986 Mon Sep 17 00:00:00 2001 From: Danny Yoo Date: Fri, 9 Sep 2011 15:46:43 -0400 Subject: [PATCH 11/27] check trampoline on function entry and function exit. --- js-assembler/assemble.rkt | 34 +++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/js-assembler/assemble.rkt b/js-assembler/assemble.rkt index c531c49..6e95b91 100644 --- a/js-assembler/assemble.rkt +++ b/js-assembler/assemble.rkt @@ -46,12 +46,12 @@ (define-values (basic-blocks entry-points) (fracture stmts)) - (define function-entry-names - (list->set (get-function-entry-names stmts))) + (define function-entry-and-exit-names + (list->set (get-function-entry-and-exit-names stmts))) (write-blocks basic-blocks (list->set entry-points) - function-entry-names + function-entry-and-exit-names op) (write-linked-label-attributes stmts op) @@ -73,7 +73,7 @@ EOF (: write-blocks ((Listof BasicBlock) (Setof Symbol) (Setof Symbol) Output-Port -> Void)) ;; Write out all the basic blocks associated to an entry point. -(define (write-blocks blocks entry-points function-entry-names op) +(define (write-blocks blocks entry-points function-entry-and-exit-names op) (: blockht : Blockht) (define blockht (make-hash)) @@ -89,7 +89,7 @@ EOF (assemble-basic-block (hash-ref blockht s) blockht entry-points - function-entry-names + function-entry-and-exit-names op) (newline op)) entry-points)) @@ -178,7 +178,7 @@ EOF (: assemble-basic-block (BasicBlock Blockht (Setof Symbol) (Setof Symbol) Output-Port -> 'ok)) -(define (assemble-basic-block a-basic-block blockht entry-points function-entry-names op) +(define (assemble-basic-block a-basic-block blockht entry-points function-entry-and-exit-names op) (match (BasicBlock-stmts a-basic-block) ;; [(list (struct PopEnvironment (n (and (? (lambda (c) (equal? c (Const 0)))) ;; skip))) @@ -190,14 +190,14 @@ EOF ;; (assemble-label target)) ;; 'ok] [else - (default-assemble-basic-block a-basic-block blockht entry-points function-entry-names op)])) + (default-assemble-basic-block a-basic-block blockht entry-points function-entry-and-exit-names op)])) (: default-assemble-basic-block (BasicBlock Blockht (Setof Symbol) (Setof Symbol) Output-Port -> 'ok)) -(define (default-assemble-basic-block a-basic-block blockht entry-points function-entry-names op) +(define (default-assemble-basic-block a-basic-block blockht entry-points function-entry-and-exit-names op) (cond - [(set-contains? function-entry-names (BasicBlock-name a-basic-block)) + [(set-contains? function-entry-and-exit-names (BasicBlock-name a-basic-block)) (fprintf op "var ~a=function(M){if(--M.callsBeforeTrampoline<0){throw ~a;}\n" (assemble-label (make-Label (BasicBlock-name a-basic-block))) (assemble-label (make-Label (BasicBlock-name a-basic-block))))] @@ -562,24 +562,28 @@ EOF -(: get-function-entry-names ((Listof Statement) -> (Listof Symbol))) -(define (get-function-entry-names stmts) +(: get-function-entry-and-exit-names ((Listof Statement) -> (Listof Symbol))) +(define (get-function-entry-and-exit-names stmts) (cond [(empty? stmts) '()] [else (define first-stmt (first stmts)) (cond + [(LinkedLabel? first-stmt) + (cons (LinkedLabel-label first-stmt) + (cons (LinkedLabel-linked-to first-stmt) + (get-function-entry-and-exit-names (rest stmts))))] [(AssignPrimOpStatement? first-stmt) (define op (AssignPrimOpStatement-op first-stmt)) (cond [(MakeCompiledProcedure? op) (cons (MakeCompiledProcedure-label op) - (get-function-entry-names (rest stmts)))] + (get-function-entry-and-exit-names (rest stmts)))] [(MakeCompiledProcedureShell? first-stmt) (cons (MakeCompiledProcedureShell-label op) - (get-function-entry-names (rest stmts)))] + (get-function-entry-and-exit-names (rest stmts)))] [else - (get-function-entry-names (rest stmts))])] + (get-function-entry-and-exit-names (rest stmts))])] [else - (get-function-entry-names (rest stmts))])])) + (get-function-entry-and-exit-names (rest stmts))])])) From 6d3a945478f46c53221fa07555c09c36d5b22e1f Mon Sep 17 00:00:00 2001 From: Danny Yoo Date: Fri, 9 Sep 2011 16:01:00 -0400 Subject: [PATCH 12/27] renaming callsBeforeTrampoline to cbt --- js-assembler/assemble.rkt | 4 ++-- js-assembler/package.rkt | 2 +- js-assembler/runtime-src/baselib-functions.js | 4 ++-- js-assembler/runtime-src/runtime.js | 10 +++++----- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/js-assembler/assemble.rkt b/js-assembler/assemble.rkt index 6e95b91..df19d39 100644 --- a/js-assembler/assemble.rkt +++ b/js-assembler/assemble.rkt @@ -198,11 +198,11 @@ EOF (define (default-assemble-basic-block a-basic-block blockht entry-points function-entry-and-exit-names op) (cond [(set-contains? function-entry-and-exit-names (BasicBlock-name a-basic-block)) - (fprintf op "var ~a=function(M){if(--M.callsBeforeTrampoline<0){throw ~a;}\n" + (fprintf op "var ~a=function(M){if(--M.cbt<0){throw ~a;}\n" (assemble-label (make-Label (BasicBlock-name a-basic-block))) (assemble-label (make-Label (BasicBlock-name a-basic-block))))] [else - (fprintf op "var ~a=function(M){--M.callsBeforeTrampoline<0;\n" + (fprintf op "var ~a=function(M){--M.cbt<0;\n" (assemble-label (make-Label (BasicBlock-name a-basic-block))))]) (assemble-block-statements (BasicBlock-name a-basic-block) (BasicBlock-stmts a-basic-block) diff --git a/js-assembler/package.rkt b/js-assembler/package.rkt index cad2582..655549d 100644 --- a/js-assembler/package.rkt +++ b/js-assembler/package.rkt @@ -155,7 +155,7 @@ module-requires)) (let ([module-body-text (format " - if(--M.callsBeforeTrampoline<0) { throw arguments.callee; } + if(--M.cbt<0) { throw arguments.callee; } var modrec = M.modules[~s]; var exports = {}; modrec.isInvoked = true; diff --git a/js-assembler/runtime-src/baselib-functions.js b/js-assembler/runtime-src/baselib-functions.js index 8529731..46ab471 100644 --- a/js-assembler/runtime-src/baselib-functions.js +++ b/js-assembler/runtime-src/baselib-functions.js @@ -61,7 +61,7 @@ // I'd personally love for this to be a macro and avoid the // extra function call here. var finalizeClosureCall = function (MACHINE) { - MACHINE.callsBeforeTrampoline--; + MACHINE.cbt--; var returnArgs = [].slice.call(arguments, 1); // clear out stack space @@ -323,7 +323,7 @@ return makeClosure(name, arity, function(M) { - --M.callsBeforeTrampoline; + --M.cbt; M.val = f(M); M.env.length -= M.argcount; return M.control.pop().label(M); diff --git a/js-assembler/runtime-src/runtime.js b/js-assembler/runtime-src/runtime.js index c01f3c3..3f1a97a 100644 --- a/js-assembler/runtime-src/runtime.js +++ b/js-assembler/runtime-src/runtime.js @@ -186,7 +186,7 @@ var defaultCurrentPrintImplementation = function defaultCurrentPrintImplementation(MACHINE) { - if(--MACHINE.callsBeforeTrampoline < 0) { + if(--MACHINE.cbt < 0) { throw defaultCurrentPrintImplementation; } var oldArgcount = MACHINE.argcount; @@ -211,7 +211,7 @@ // The MACHINE var Machine = function() { - this.callsBeforeTrampoline = STACK_LIMIT_ESTIMATE; + this.cbt = STACK_LIMIT_ESTIMATE; // calls before trampoline this.val = undefined; // value register this.proc = undefined; // procedure register this.argcount = undefined; // argument count @@ -446,7 +446,7 @@ Machine.prototype.trampoline = function(initialJump) { var thunk = initialJump; var startTime = (new Date()).valueOf(); - this.callsBeforeTrampoline = STACK_LIMIT_ESTIMATE; + this.cbt = STACK_LIMIT_ESTIMATE; this.params.numBouncesBeforeYield = this.params.maxNumBouncesBeforeYield; this.running = true; @@ -478,7 +478,7 @@ // The running flag is set to false. if (typeof(e) === 'function') { thunk = e; - this.callsBeforeTrampoline = STACK_LIMIT_ESTIMATE; + this.cbt = STACK_LIMIT_ESTIMATE; if (this.params.numBouncesBeforeYield-- < 0) { recomputeMaxNumBouncesBeforeYield( @@ -671,7 +671,7 @@ var si_popgoto = function(n, gotoTargetThunk) { return function(M) { - --M.callsBeforeTrampoline; + --M.cbt; M.env.length-=n; return gotoTargetThunk()(M); }; From b2610e496e8489f81d11beb483b31c5d345b0a9f Mon Sep 17 00:00:00 2001 From: Danny Yoo Date: Fri, 9 Sep 2011 16:19:33 -0400 Subject: [PATCH 13/27] context expected becomes a superinstruction --- js-assembler/assemble-open-coded.rkt | 10 +++++----- js-assembler/assemble.rkt | 15 ++++++--------- js-assembler/runtime-src/runtime.js | 14 +++++--------- 3 files changed, 16 insertions(+), 23 deletions(-) diff --git a/js-assembler/assemble-open-coded.rkt b/js-assembler/assemble-open-coded.rkt index 57bc7e3..c8196bd 100644 --- a/js-assembler/assemble-open-coded.rkt +++ b/js-assembler/assemble-open-coded.rkt @@ -70,7 +70,7 @@ (assemble-boolean-chain "plt.baselib.numbers.greaterThanOrEqual" checked-operands)] [(cons) - (format "RT.makePair(~a, ~a)" + (format "RT.makePair(~a,~a)" (first checked-operands) (second checked-operands))] @@ -93,13 +93,13 @@ (first checked-operands))] [(null?) - (format "(~a === RT.NULL)" (first checked-operands))] + (format "(~a===RT.NULL)" (first checked-operands))] [(not) - (format "(~a === false)" (first checked-operands))] + (format "(~a=== alse)" (first checked-operands))] [(eq?) - (format "(~a === ~a)" (first checked-operands) (second checked-operands))]))) + (format "(~a===~a)" (first checked-operands) (second checked-operands))]))) @@ -163,7 +163,7 @@ (format "RT.isPair")] [(box) (format "RT.isBox")])]) - (format "RT.testArgument(M, ~s, ~a, ~a, ~a, ~s)" + (format "RT.testArgument(M,~s,~a,~a,~a,~s)" (symbol->string domain) predicate operand-string diff --git a/js-assembler/assemble.rkt b/js-assembler/assemble.rkt index df19d39..283182d 100644 --- a/js-assembler/assemble.rkt +++ b/js-assembler/assemble.rkt @@ -180,15 +180,12 @@ EOF (: assemble-basic-block (BasicBlock Blockht (Setof Symbol) (Setof Symbol) Output-Port -> 'ok)) (define (assemble-basic-block a-basic-block blockht entry-points function-entry-and-exit-names op) (match (BasicBlock-stmts a-basic-block) - ;; [(list (struct PopEnvironment (n (and (? (lambda (c) (equal? c (Const 0)))) - ;; skip))) - ;; (struct GotoStatement ((and (? Label?) - ;; target)))) - ;; (fprintf op "~a=RT.si_popgoto(~a,function(){return ~a});\n" - ;; (assemble-label (make-Label (BasicBlock-name a-basic-block))) - ;; (assemble-oparg n) - ;; (assemble-label target)) - ;; 'ok] + [(list (struct PerformStatement ((struct RaiseContextExpectedValuesError! (expected)))) + stmts ...) + (fprintf op "~a=RT.si_context_expected(~a);\n" + (assemble-label (make-Label (BasicBlock-name a-basic-block))) + expected) + 'ok] [else (default-assemble-basic-block a-basic-block blockht entry-points function-entry-and-exit-names op)])) diff --git a/js-assembler/runtime-src/runtime.js b/js-assembler/runtime-src/runtime.js index 3f1a97a..23097b4 100644 --- a/js-assembler/runtime-src/runtime.js +++ b/js-assembler/runtime-src/runtime.js @@ -668,15 +668,11 @@ ////////////////////////////////////////////////////////////////////// // Superinstructions to try to reduce code size. - - var si_popgoto = function(n, gotoTargetThunk) { - return function(M) { - --M.cbt; - M.env.length-=n; - return gotoTargetThunk()(M); - }; + var si_context_expected = function(n) { + if (n === 1) { return si_context_expected_1; } + return function(M) { raiseContextExpectedValuesError(M, n); } }; - + var si_context_expected_1 = function(M) { raiseContextExpectedValuesError(M, 1); } @@ -815,7 +811,7 @@ exports['getTracedAppKey'] = getTracedAppKey; exports['getTracedCalleeKey'] = getTracedCalleeKey; - exports['si_popgoto'] = si_popgoto; + exports['si_context_expected'] = si_context_expected; exports['checkClosureAndArity'] = checkClosureAndArity; From 37272e135bc48852e00e8d19da3a08013c686a3a Mon Sep 17 00:00:00 2001 From: Danny Yoo Date: Fri, 9 Sep 2011 16:56:44 -0400 Subject: [PATCH 14/27] typo --- js-assembler/assemble-open-coded.rkt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js-assembler/assemble-open-coded.rkt b/js-assembler/assemble-open-coded.rkt index c8196bd..b788941 100644 --- a/js-assembler/assemble-open-coded.rkt +++ b/js-assembler/assemble-open-coded.rkt @@ -96,7 +96,7 @@ (format "(~a===RT.NULL)" (first checked-operands))] [(not) - (format "(~a=== alse)" (first checked-operands))] + (format "(~a===false)" (first checked-operands))] [(eq?) (format "(~a===~a)" (first checked-operands) (second checked-operands))]))) From 2777b193ff977155664689556c807f16302b9ad2 Mon Sep 17 00:00:00 2001 From: Danny Yoo Date: Fri, 9 Sep 2011 17:08:55 -0400 Subject: [PATCH 15/27] another test added --- tests/more-tests/weird-cc.expected | 1 + tests/more-tests/weird-cc.rkt | 5 +++++ tests/run-more-tests.rkt | 1 + 3 files changed, 7 insertions(+) create mode 100644 tests/more-tests/weird-cc.expected create mode 100644 tests/more-tests/weird-cc.rkt diff --git a/tests/more-tests/weird-cc.expected b/tests/more-tests/weird-cc.expected new file mode 100644 index 0000000..917fd9d --- /dev/null +++ b/tests/more-tests/weird-cc.expected @@ -0,0 +1 @@ +11213 diff --git a/tests/more-tests/weird-cc.rkt b/tests/more-tests/weird-cc.rkt new file mode 100644 index 0000000..291900d --- /dev/null +++ b/tests/more-tests/weird-cc.rkt @@ -0,0 +1,5 @@ +#lang planet dyoo/whalesong +(define program (lambda () (let ((y (call/cc (lambda (c) c)))) (display 1) (call/cc (lambda (c) (y c))) (display 2) (call/cc (lambda (c) (y c))) (display 3)))) + +(program) +(newline) \ No newline at end of file diff --git a/tests/run-more-tests.rkt b/tests/run-more-tests.rkt index 4a4e2a9..9a79ce7 100644 --- a/tests/run-more-tests.rkt +++ b/tests/run-more-tests.rkt @@ -27,3 +27,4 @@ (test "more-tests/conform.rkt") (test "more-tests/earley.rkt") (test "more-tests/view.rkt") +(test "more-tests/weird-cc.rkt") From 7a2ee5ad183c77728724a3656644e4949b80112c Mon Sep 17 00:00:00 2001 From: Danny Yoo Date: Sat, 10 Sep 2011 13:33:10 -0400 Subject: [PATCH 16/27] ie compatibility: can't treat childNodes as a normal collection with slice. --- web-world/js-impl.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/web-world/js-impl.js b/web-world/js-impl.js index 42292af..3176b9f 100644 --- a/web-world/js-impl.js +++ b/web-world/js-impl.js @@ -44,7 +44,12 @@ var domOpenF = // To go down, just take the children. function(n) { - return [].slice.call(n.childNodes, 0); + var i; + var result = []; + for (i = 0; i < n.childNodes.length; i++) { + result.push(n.childNodes[i]); + } + return result; }; var domCloseF = // To go back up, take the node, do a shallow cloning, and replace the children. From 3ba6c2dcc9bb1a903e99961384a5c0d2eda05373 Mon Sep 17 00:00:00 2001 From: Danny Yoo Date: Sat, 10 Sep 2011 13:41:07 -0400 Subject: [PATCH 17/27] closure compile is now dynamically required, rather than always required. This should relax the javascript requirement. --- js-assembler/package.rkt | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/js-assembler/package.rkt b/js-assembler/package.rkt index 655549d..0cd1ccd 100644 --- a/js-assembler/package.rkt +++ b/js-assembler/package.rkt @@ -19,10 +19,12 @@ racket/port (prefix-in query: "../lang/js/query.rkt") (prefix-in resource-query: "../resource/query.rkt") - (planet dyoo/closure-compile:1:1) (prefix-in runtime: "get-runtime.rkt") (prefix-in racket: racket/base)) +;; There is a dynamic require for (planet dyoo/closure-compile) that's done +;; if compression is turned on. + ;; TODO: put proper contracts here @@ -365,11 +367,13 @@ M.modules[~s] = (fprintf op "})(plt.runtime.currentMachine,\nfunction(){ plt.runtime.setReadyTrue(); },\nfunction(){},\n{});\n"))) - +(define closure-compile-ns (make-base-namespace)) (define (compress x) (cond [(current-compress-javascript?) (log-debug "compressing javascript...") - (closure-compile x)] + (parameterize ([current-namespace closure-compile-ns]) + (define closure-compile (dynamic-require '(planet dyoo/closure-compile) 'closure-compile)) + (closure-compile x))] [else (log-debug "not compressing javascript...") x])) From 3346f8874f9404f8a022f4e417fb2188a8ca02d0 Mon Sep 17 00:00:00 2001 From: Danny Yoo Date: Sat, 10 Sep 2011 14:10:33 -0400 Subject: [PATCH 18/27] ie compatibility: hasOwnProperty is not a method on dom nodes. --- web-world/js-impl.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/web-world/js-impl.js b/web-world/js-impl.js index 3176b9f..3a92787 100644 --- a/web-world/js-impl.js +++ b/web-world/js-impl.js @@ -544,8 +544,7 @@ var isDomNode = function(x) { - return (x.hasOwnProperty('nodeType') && - x.nodeType === 1); + return (x.nodeType && x.nodeType === 1); }; @@ -681,7 +680,7 @@ var key, val; var result = makeList(); for (key in obj) { - if (obj.hasOwnProperty(key)) { + if (obj.hasOwnProperty && obj.hasOwnProperty(key)) { val = obj[key]; if (typeof(val) === 'number') { result = makePair(makeList(makeSymbol(key), @@ -822,7 +821,9 @@ LocationEventSource.prototype.onStart = function(fireEvent) { if (this.id === undefined) { var success = function(position) { - if (position.hasOwnProperty('coords') && + if (position.hasOwnProperty && + position.hasOwnProperty('coords') && + position.coords.hasOwnProperty && position.coords.hasOwnProperty('latitude') && position.coords.hasOwnProperty('longitude')) { fireEvent(undefined, From 834e5897cfdb680658861b6c7e033e6922494452 Mon Sep 17 00:00:00 2001 From: Danny Yoo Date: Sat, 10 Sep 2011 14:12:43 -0400 Subject: [PATCH 19/27] simplifying --- web-world/js-impl.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web-world/js-impl.js b/web-world/js-impl.js index 3a92787..86d2516 100644 --- a/web-world/js-impl.js +++ b/web-world/js-impl.js @@ -544,7 +544,7 @@ var isDomNode = function(x) { - return (x.nodeType && x.nodeType === 1); + return (x.nodeType === 1); }; From ac2aaf2a08c343d1a14a881ee7e0a9d4fb26723f Mon Sep 17 00:00:00 2001 From: Danny Yoo Date: Sat, 10 Sep 2011 14:54:51 -0400 Subject: [PATCH 20/27] updating jquery to 1.6.3. Thanks to Jens for letting me know about an ugly IE8 bug. --- js-assembler/runtime-src/jquery.js | 8985 +--------------------------- 1 file changed, 4 insertions(+), 8981 deletions(-) diff --git a/js-assembler/runtime-src/jquery.js b/js-assembler/runtime-src/jquery.js index f3201aa..20d7f61 100644 --- a/js-assembler/runtime-src/jquery.js +++ b/js-assembler/runtime-src/jquery.js @@ -1,8981 +1,4 @@ -/*! - * jQuery JavaScript Library v1.6.2 - * http://jquery.com/ - * - * Copyright 2011, John Resig - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * Includes Sizzle.js - * http://sizzlejs.com/ - * Copyright 2011, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * - * Date: Thu Jun 30 14:16:56 2011 -0400 - */ -(function( window, undefined ) { - -// Use the correct document accordingly with window argument (sandbox) -var document = window.document, - navigator = window.navigator, - location = window.location; -var jQuery = (function() { - -// Define a local copy of jQuery -var jQuery = function( selector, context ) { - // The jQuery object is actually just the init constructor 'enhanced' - return new jQuery.fn.init( selector, context, rootjQuery ); - }, - - // Map over jQuery in case of overwrite - _jQuery = window.jQuery, - - // Map over the $ in case of overwrite - _$ = window.$, - - // A central reference to the root jQuery(document) - rootjQuery, - - // A simple way to check for HTML strings or ID strings - // (both of which we optimize for) - quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, - - // Check if a string has a non-whitespace character in it - rnotwhite = /\S/, - - // Used for trimming whitespace - trimLeft = /^\s+/, - trimRight = /\s+$/, - - // Check for digits - rdigit = /\d/, - - // Match a standalone tag - rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, - - // JSON RegExp - rvalidchars = /^[\],:{}\s]*$/, - rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, - rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, - rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, - - // Useragent RegExp - rwebkit = /(webkit)[ \/]([\w.]+)/, - ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, - rmsie = /(msie) ([\w.]+)/, - rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, - - // Matches dashed string for camelizing - rdashAlpha = /-([a-z])/ig, - - // Used by jQuery.camelCase as callback to replace() - fcamelCase = function( all, letter ) { - return letter.toUpperCase(); - }, - - // Keep a UserAgent string for use with jQuery.browser - userAgent = navigator.userAgent, - - // For matching the engine and version of the browser - browserMatch, - - // The deferred used on DOM ready - readyList, - - // The ready event handler - DOMContentLoaded, - - // Save a reference to some core methods - toString = Object.prototype.toString, - hasOwn = Object.prototype.hasOwnProperty, - push = Array.prototype.push, - slice = Array.prototype.slice, - trim = String.prototype.trim, - indexOf = Array.prototype.indexOf, - - // [[Class]] -> type pairs - class2type = {}; - -jQuery.fn = jQuery.prototype = { - constructor: jQuery, - init: function( selector, context, rootjQuery ) { - var match, elem, ret, doc; - - // Handle $(""), $(null), or $(undefined) - if ( !selector ) { - return this; - } - - // Handle $(DOMElement) - if ( selector.nodeType ) { - this.context = this[0] = selector; - this.length = 1; - return this; - } - - // The body element only exists once, optimize finding it - if ( selector === "body" && !context && document.body ) { - this.context = document; - this[0] = document.body; - this.selector = selector; - this.length = 1; - return this; - } - - // Handle HTML strings - if ( typeof selector === "string" ) { - // Are we dealing with HTML string or an ID? - if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { - // Assume that strings that start and end with <> are HTML and skip the regex check - match = [ null, selector, null ]; - - } else { - match = quickExpr.exec( selector ); - } - - // Verify a match, and that no context was specified for #id - if ( match && (match[1] || !context) ) { - - // HANDLE: $(html) -> $(array) - if ( match[1] ) { - context = context instanceof jQuery ? context[0] : context; - doc = (context ? context.ownerDocument || context : document); - - // If a single string is passed in and it's a single tag - // just do a createElement and skip the rest - ret = rsingleTag.exec( selector ); - - if ( ret ) { - if ( jQuery.isPlainObject( context ) ) { - selector = [ document.createElement( ret[1] ) ]; - jQuery.fn.attr.call( selector, context, true ); - - } else { - selector = [ doc.createElement( ret[1] ) ]; - } - - } else { - ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); - selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes; - } - - return jQuery.merge( this, selector ); - - // HANDLE: $("#id") - } else { - elem = document.getElementById( match[2] ); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE and Opera return items - // by name instead of ID - if ( elem.id !== match[2] ) { - return rootjQuery.find( selector ); - } - - // Otherwise, we inject the element directly into the jQuery object - this.length = 1; - this[0] = elem; - } - - this.context = document; - this.selector = selector; - return this; - } - - // HANDLE: $(expr, $(...)) - } else if ( !context || context.jquery ) { - return (context || rootjQuery).find( selector ); - - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor( context ).find( selector ); - } - - // HANDLE: $(function) - // Shortcut for document ready - } else if ( jQuery.isFunction( selector ) ) { - return rootjQuery.ready( selector ); - } - - if (selector.selector !== undefined) { - this.selector = selector.selector; - this.context = selector.context; - } - - return jQuery.makeArray( selector, this ); - }, - - // Start with an empty selector - selector: "", - - // The current version of jQuery being used - jquery: "1.6.2", - - // The default length of a jQuery object is 0 - length: 0, - - // The number of elements contained in the matched element set - size: function() { - return this.length; - }, - - toArray: function() { - return slice.call( this, 0 ); - }, - - // Get the Nth element in the matched element set OR - // Get the whole matched element set as a clean array - get: function( num ) { - return num == null ? - - // Return a 'clean' array - this.toArray() : - - // Return just the object - ( num < 0 ? this[ this.length + num ] : this[ num ] ); - }, - - // Take an array of elements and push it onto the stack - // (returning the new matched element set) - pushStack: function( elems, name, selector ) { - // Build a new jQuery matched element set - var ret = this.constructor(); - - if ( jQuery.isArray( elems ) ) { - push.apply( ret, elems ); - - } else { - jQuery.merge( ret, elems ); - } - - // Add the old object onto the stack (as a reference) - ret.prevObject = this; - - ret.context = this.context; - - if ( name === "find" ) { - ret.selector = this.selector + (this.selector ? " " : "") + selector; - } else if ( name ) { - ret.selector = this.selector + "." + name + "(" + selector + ")"; - } - - // Return the newly-formed element set - return ret; - }, - - // Execute a callback for every element in the matched set. - // (You can seed the arguments with an array of args, but this is - // only used internally.) - each: function( callback, args ) { - return jQuery.each( this, callback, args ); - }, - - ready: function( fn ) { - // Attach the listeners - jQuery.bindReady(); - - // Add the callback - readyList.done( fn ); - - return this; - }, - - eq: function( i ) { - return i === -1 ? - this.slice( i ) : - this.slice( i, +i + 1 ); - }, - - first: function() { - return this.eq( 0 ); - }, - - last: function() { - return this.eq( -1 ); - }, - - slice: function() { - return this.pushStack( slice.apply( this, arguments ), - "slice", slice.call(arguments).join(",") ); - }, - - map: function( callback ) { - return this.pushStack( jQuery.map(this, function( elem, i ) { - return callback.call( elem, i, elem ); - })); - }, - - end: function() { - return this.prevObject || this.constructor(null); - }, - - // For internal use only. - // Behaves like an Array's method, not like a jQuery method. - push: push, - sort: [].sort, - splice: [].splice -}; - -// Give the init function the jQuery prototype for later instantiation -jQuery.fn.init.prototype = jQuery.fn; - -jQuery.extend = jQuery.fn.extend = function() { - var options, name, src, copy, copyIsArray, clone, - target = arguments[0] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if ( typeof target === "boolean" ) { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - - // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !jQuery.isFunction(target) ) { - target = {}; - } - - // extend jQuery itself if only one argument is passed - if ( length === i ) { - target = this; - --i; - } - - for ( ; i < length; i++ ) { - // Only deal with non-null/undefined values - if ( (options = arguments[ i ]) != null ) { - // Extend the base object - for ( name in options ) { - src = target[ name ]; - copy = options[ name ]; - - // Prevent never-ending loop - if ( target === copy ) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { - if ( copyIsArray ) { - copyIsArray = false; - clone = src && jQuery.isArray(src) ? src : []; - - } else { - clone = src && jQuery.isPlainObject(src) ? src : {}; - } - - // Never move original objects, clone them - target[ name ] = jQuery.extend( deep, clone, copy ); - - // Don't bring in undefined values - } else if ( copy !== undefined ) { - target[ name ] = copy; - } - } - } - } - - // Return the modified object - return target; -}; - -jQuery.extend({ - noConflict: function( deep ) { - if ( window.$ === jQuery ) { - window.$ = _$; - } - - if ( deep && window.jQuery === jQuery ) { - window.jQuery = _jQuery; - } - - return jQuery; - }, - - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, - - // A counter to track how many items to wait for before - // the ready event fires. See #6781 - readyWait: 1, - - // Hold (or release) the ready event - holdReady: function( hold ) { - if ( hold ) { - jQuery.readyWait++; - } else { - jQuery.ready( true ); - } - }, - - // Handle when the DOM is ready - ready: function( wait ) { - // Either a released hold or an DOMready/load event and not yet ready - if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if ( !document.body ) { - return setTimeout( jQuery.ready, 1 ); - } - - // Remember that the DOM is ready - jQuery.isReady = true; - - // If a normal DOM Ready event fired, decrement, and wait if need be - if ( wait !== true && --jQuery.readyWait > 0 ) { - return; - } - - // If there are functions bound, to execute - readyList.resolveWith( document, [ jQuery ] ); - - // Trigger any bound ready events - if ( jQuery.fn.trigger ) { - jQuery( document ).trigger( "ready" ).unbind( "ready" ); - } - } - }, - - bindReady: function() { - if ( readyList ) { - return; - } - - readyList = jQuery._Deferred(); - - // Catch cases where $(document).ready() is called after the - // browser event has already occurred. - if ( document.readyState === "complete" ) { - // Handle it asynchronously to allow scripts the opportunity to delay ready - return setTimeout( jQuery.ready, 1 ); - } - - // Mozilla, Opera and webkit nightlies currently support this event - if ( document.addEventListener ) { - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); - - // A fallback to window.onload, that will always work - window.addEventListener( "load", jQuery.ready, false ); - - // If IE event model is used - } else if ( document.attachEvent ) { - // ensure firing before onload, - // maybe late but safe also for iframes - document.attachEvent( "onreadystatechange", DOMContentLoaded ); - - // A fallback to window.onload, that will always work - window.attachEvent( "onload", jQuery.ready ); - - // If IE and not a frame - // continually check to see if the document is ready - var toplevel = false; - - try { - toplevel = window.frameElement == null; - } catch(e) {} - - if ( document.documentElement.doScroll && toplevel ) { - doScrollCheck(); - } - } - }, - - // See test/unit/core.js for details concerning isFunction. - // Since version 1.3, DOM methods and functions like alert - // aren't supported. They return false on IE (#2968). - isFunction: function( obj ) { - return jQuery.type(obj) === "function"; - }, - - isArray: Array.isArray || function( obj ) { - return jQuery.type(obj) === "array"; - }, - - // A crude way of determining if an object is a window - isWindow: function( obj ) { - return obj && typeof obj === "object" && "setInterval" in obj; - }, - - isNaN: function( obj ) { - return obj == null || !rdigit.test( obj ) || isNaN( obj ); - }, - - type: function( obj ) { - return obj == null ? - String( obj ) : - class2type[ toString.call(obj) ] || "object"; - }, - - isPlainObject: function( obj ) { - // Must be an Object. - // Because of IE, we also have to check the presence of the constructor property. - // Make sure that DOM nodes and window objects don't pass through, as well - if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { - return false; - } - - // Not own constructor property must be Object - if ( obj.constructor && - !hasOwn.call(obj, "constructor") && - !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { - return false; - } - - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. - - var key; - for ( key in obj ) {} - - return key === undefined || hasOwn.call( obj, key ); - }, - - isEmptyObject: function( obj ) { - for ( var name in obj ) { - return false; - } - return true; - }, - - error: function( msg ) { - throw msg; - }, - - parseJSON: function( data ) { - if ( typeof data !== "string" || !data ) { - return null; - } - - // Make sure leading/trailing whitespace is removed (IE can't handle it) - data = jQuery.trim( data ); - - // Attempt to parse using the native JSON parser first - if ( window.JSON && window.JSON.parse ) { - return window.JSON.parse( data ); - } - - // Make sure the incoming data is actual JSON - // Logic borrowed from http://json.org/json2.js - if ( rvalidchars.test( data.replace( rvalidescape, "@" ) - .replace( rvalidtokens, "]" ) - .replace( rvalidbraces, "")) ) { - - return (new Function( "return " + data ))(); - - } - jQuery.error( "Invalid JSON: " + data ); - }, - - // Cross-browser xml parsing - // (xml & tmp used internally) - parseXML: function( data , xml , tmp ) { - - if ( window.DOMParser ) { // Standard - tmp = new DOMParser(); - xml = tmp.parseFromString( data , "text/xml" ); - } else { // IE - xml = new ActiveXObject( "Microsoft.XMLDOM" ); - xml.async = "false"; - xml.loadXML( data ); - } - - tmp = xml.documentElement; - - if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) { - jQuery.error( "Invalid XML: " + data ); - } - - return xml; - }, - - noop: function() {}, - - // Evaluates a script in a global context - // Workarounds based on findings by Jim Driscoll - // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context - globalEval: function( data ) { - if ( data && rnotwhite.test( data ) ) { - // We use execScript on Internet Explorer - // We use an anonymous function so that context is window - // rather than jQuery in Firefox - ( window.execScript || function( data ) { - window[ "eval" ].call( window, data ); - } )( data ); - } - }, - - // Converts a dashed string to camelCased string; - // Used by both the css and data modules - camelCase: function( string ) { - return string.replace( rdashAlpha, fcamelCase ); - }, - - nodeName: function( elem, name ) { - return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); - }, - - // args is for internal usage only - each: function( object, callback, args ) { - var name, i = 0, - length = object.length, - isObj = length === undefined || jQuery.isFunction( object ); - - if ( args ) { - if ( isObj ) { - for ( name in object ) { - if ( callback.apply( object[ name ], args ) === false ) { - break; - } - } - } else { - for ( ; i < length; ) { - if ( callback.apply( object[ i++ ], args ) === false ) { - break; - } - } - } - - // A special, fast, case for the most common use of each - } else { - if ( isObj ) { - for ( name in object ) { - if ( callback.call( object[ name ], name, object[ name ] ) === false ) { - break; - } - } - } else { - for ( ; i < length; ) { - if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { - break; - } - } - } - } - - return object; - }, - - // Use native String.trim function wherever possible - trim: trim ? - function( text ) { - return text == null ? - "" : - trim.call( text ); - } : - - // Otherwise use our own trimming functionality - function( text ) { - return text == null ? - "" : - text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); - }, - - // results is for internal usage only - makeArray: function( array, results ) { - var ret = results || []; - - if ( array != null ) { - // The window, strings (and functions) also have 'length' - // The extra typeof function check is to prevent crashes - // in Safari 2 (See: #3039) - // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 - var type = jQuery.type( array ); - - if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { - push.call( ret, array ); - } else { - jQuery.merge( ret, array ); - } - } - - return ret; - }, - - inArray: function( elem, array ) { - - if ( indexOf ) { - return indexOf.call( array, elem ); - } - - for ( var i = 0, length = array.length; i < length; i++ ) { - if ( array[ i ] === elem ) { - return i; - } - } - - return -1; - }, - - merge: function( first, second ) { - var i = first.length, - j = 0; - - if ( typeof second.length === "number" ) { - for ( var l = second.length; j < l; j++ ) { - first[ i++ ] = second[ j ]; - } - - } else { - while ( second[j] !== undefined ) { - first[ i++ ] = second[ j++ ]; - } - } - - first.length = i; - - return first; - }, - - grep: function( elems, callback, inv ) { - var ret = [], retVal; - inv = !!inv; - - // Go through the array, only saving the items - // that pass the validator function - for ( var i = 0, length = elems.length; i < length; i++ ) { - retVal = !!callback( elems[ i ], i ); - if ( inv !== retVal ) { - ret.push( elems[ i ] ); - } - } - - return ret; - }, - - // arg is for internal usage only - map: function( elems, callback, arg ) { - var value, key, ret = [], - i = 0, - length = elems.length, - // jquery objects are treated as arrays - isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; - - // Go through the array, translating each of the items to their - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret[ ret.length ] = value; - } - } - - // Go through every key on the object, - } else { - for ( key in elems ) { - value = callback( elems[ key ], key, arg ); - - if ( value != null ) { - ret[ ret.length ] = value; - } - } - } - - // Flatten any nested arrays - return ret.concat.apply( [], ret ); - }, - - // A global GUID counter for objects - guid: 1, - - // Bind a function to a context, optionally partially applying any - // arguments. - proxy: function( fn, context ) { - if ( typeof context === "string" ) { - var tmp = fn[ context ]; - context = fn; - fn = tmp; - } - - // Quick check to determine if target is callable, in the spec - // this throws a TypeError, but we will just return undefined. - if ( !jQuery.isFunction( fn ) ) { - return undefined; - } - - // Simulated bind - var args = slice.call( arguments, 2 ), - proxy = function() { - return fn.apply( context, args.concat( slice.call( arguments ) ) ); - }; - - // Set the guid of unique handler to the same of original handler, so it can be removed - proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; - - return proxy; - }, - - // Mutifunctional method to get and set values to a collection - // The value/s can optionally be executed if it's a function - access: function( elems, key, value, exec, fn, pass ) { - var length = elems.length; - - // Setting many attributes - if ( typeof key === "object" ) { - for ( var k in key ) { - jQuery.access( elems, k, key[k], exec, fn, value ); - } - return elems; - } - - // Setting one attribute - if ( value !== undefined ) { - // Optionally, function values get executed if exec is true - exec = !pass && exec && jQuery.isFunction(value); - - for ( var i = 0; i < length; i++ ) { - fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); - } - - return elems; - } - - // Getting an attribute - return length ? fn( elems[0], key ) : undefined; - }, - - now: function() { - return (new Date()).getTime(); - }, - - // Use of jQuery.browser is frowned upon. - // More details: http://docs.jquery.com/Utilities/jQuery.browser - uaMatch: function( ua ) { - ua = ua.toLowerCase(); - - var match = rwebkit.exec( ua ) || - ropera.exec( ua ) || - rmsie.exec( ua ) || - ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || - []; - - return { browser: match[1] || "", version: match[2] || "0" }; - }, - - sub: function() { - function jQuerySub( selector, context ) { - return new jQuerySub.fn.init( selector, context ); - } - jQuery.extend( true, jQuerySub, this ); - jQuerySub.superclass = this; - jQuerySub.fn = jQuerySub.prototype = this(); - jQuerySub.fn.constructor = jQuerySub; - jQuerySub.sub = this.sub; - jQuerySub.fn.init = function init( selector, context ) { - if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { - context = jQuerySub( context ); - } - - return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); - }; - jQuerySub.fn.init.prototype = jQuerySub.fn; - var rootjQuerySub = jQuerySub(document); - return jQuerySub; - }, - - browser: {} -}); - -// Populate the class2type map -jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { - class2type[ "[object " + name + "]" ] = name.toLowerCase(); -}); - -browserMatch = jQuery.uaMatch( userAgent ); -if ( browserMatch.browser ) { - jQuery.browser[ browserMatch.browser ] = true; - jQuery.browser.version = browserMatch.version; -} - -// Deprecated, use jQuery.browser.webkit instead -if ( jQuery.browser.webkit ) { - jQuery.browser.safari = true; -} - -// IE doesn't match non-breaking spaces with \s -if ( rnotwhite.test( "\xA0" ) ) { - trimLeft = /^[\s\xA0]+/; - trimRight = /[\s\xA0]+$/; -} - -// All jQuery objects should point back to these -rootjQuery = jQuery(document); - -// Cleanup functions for the document ready method -if ( document.addEventListener ) { - DOMContentLoaded = function() { - document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); - jQuery.ready(); - }; - -} else if ( document.attachEvent ) { - DOMContentLoaded = function() { - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if ( document.readyState === "complete" ) { - document.detachEvent( "onreadystatechange", DOMContentLoaded ); - jQuery.ready(); - } - }; -} - -// The DOM ready check for Internet Explorer -function doScrollCheck() { - if ( jQuery.isReady ) { - return; - } - - try { - // If IE is used, use the trick by Diego Perini - // http://javascript.nwbox.com/IEContentLoaded/ - document.documentElement.doScroll("left"); - } catch(e) { - setTimeout( doScrollCheck, 1 ); - return; - } - - // and execute any waiting functions - jQuery.ready(); -} - -return jQuery; - -})(); - - -var // Promise methods - promiseMethods = "done fail isResolved isRejected promise then always pipe".split( " " ), - // Static reference to slice - sliceDeferred = [].slice; - -jQuery.extend({ - // Create a simple deferred (one callbacks list) - _Deferred: function() { - var // callbacks list - callbacks = [], - // stored [ context , args ] - fired, - // to avoid firing when already doing so - firing, - // flag to know if the deferred has been cancelled - cancelled, - // the deferred itself - deferred = { - - // done( f1, f2, ...) - done: function() { - if ( !cancelled ) { - var args = arguments, - i, - length, - elem, - type, - _fired; - if ( fired ) { - _fired = fired; - fired = 0; - } - for ( i = 0, length = args.length; i < length; i++ ) { - elem = args[ i ]; - type = jQuery.type( elem ); - if ( type === "array" ) { - deferred.done.apply( deferred, elem ); - } else if ( type === "function" ) { - callbacks.push( elem ); - } - } - if ( _fired ) { - deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] ); - } - } - return this; - }, - - // resolve with given context and args - resolveWith: function( context, args ) { - if ( !cancelled && !fired && !firing ) { - // make sure args are available (#8421) - args = args || []; - firing = 1; - try { - while( callbacks[ 0 ] ) { - callbacks.shift().apply( context, args ); - } - } - finally { - fired = [ context, args ]; - firing = 0; - } - } - return this; - }, - - // resolve with this as context and given arguments - resolve: function() { - deferred.resolveWith( this, arguments ); - return this; - }, - - // Has this deferred been resolved? - isResolved: function() { - return !!( firing || fired ); - }, - - // Cancel - cancel: function() { - cancelled = 1; - callbacks = []; - return this; - } - }; - - return deferred; - }, - - // Full fledged deferred (two callbacks list) - Deferred: function( func ) { - var deferred = jQuery._Deferred(), - failDeferred = jQuery._Deferred(), - promise; - // Add errorDeferred methods, then and promise - jQuery.extend( deferred, { - then: function( doneCallbacks, failCallbacks ) { - deferred.done( doneCallbacks ).fail( failCallbacks ); - return this; - }, - always: function() { - return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments ); - }, - fail: failDeferred.done, - rejectWith: failDeferred.resolveWith, - reject: failDeferred.resolve, - isRejected: failDeferred.isResolved, - pipe: function( fnDone, fnFail ) { - return jQuery.Deferred(function( newDefer ) { - jQuery.each( { - done: [ fnDone, "resolve" ], - fail: [ fnFail, "reject" ] - }, function( handler, data ) { - var fn = data[ 0 ], - action = data[ 1 ], - returned; - if ( jQuery.isFunction( fn ) ) { - deferred[ handler ](function() { - returned = fn.apply( this, arguments ); - if ( returned && jQuery.isFunction( returned.promise ) ) { - returned.promise().then( newDefer.resolve, newDefer.reject ); - } else { - newDefer[ action ]( returned ); - } - }); - } else { - deferred[ handler ]( newDefer[ action ] ); - } - }); - }).promise(); - }, - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function( obj ) { - if ( obj == null ) { - if ( promise ) { - return promise; - } - promise = obj = {}; - } - var i = promiseMethods.length; - while( i-- ) { - obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ]; - } - return obj; - } - }); - // Make sure only one callback list will be used - deferred.done( failDeferred.cancel ).fail( deferred.cancel ); - // Unexpose cancel - delete deferred.cancel; - // Call given func if any - if ( func ) { - func.call( deferred, deferred ); - } - return deferred; - }, - - // Deferred helper - when: function( firstParam ) { - var args = arguments, - i = 0, - length = args.length, - count = length, - deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? - firstParam : - jQuery.Deferred(); - function resolveFunc( i ) { - return function( value ) { - args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; - if ( !( --count ) ) { - // Strange bug in FF4: - // Values changed onto the arguments object sometimes end up as undefined values - // outside the $.when method. Cloning the object into a fresh array solves the issue - deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) ); - } - }; - } - if ( length > 1 ) { - for( ; i < length; i++ ) { - if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) { - args[ i ].promise().then( resolveFunc(i), deferred.reject ); - } else { - --count; - } - } - if ( !count ) { - deferred.resolveWith( deferred, args ); - } - } else if ( deferred !== firstParam ) { - deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); - } - return deferred.promise(); - } -}); - - - -jQuery.support = (function() { - - var div = document.createElement( "div" ), - documentElement = document.documentElement, - all, - a, - select, - opt, - input, - marginDiv, - support, - fragment, - body, - testElementParent, - testElement, - testElementStyle, - tds, - events, - eventName, - i, - isSupported; - - // Preliminary tests - div.setAttribute("className", "t"); - div.innerHTML = "
a"; - - all = div.getElementsByTagName( "*" ); - a = div.getElementsByTagName( "a" )[ 0 ]; - - // Can't get basic test support - if ( !all || !all.length || !a ) { - return {}; - } - - // First batch of supports tests - select = document.createElement( "select" ); - opt = select.appendChild( document.createElement("option") ); - input = div.getElementsByTagName( "input" )[ 0 ]; - - support = { - // IE strips leading whitespace when .innerHTML is used - leadingWhitespace: ( div.firstChild.nodeType === 3 ), - - // Make sure that tbody elements aren't automatically inserted - // IE will insert them into empty tables - tbody: !div.getElementsByTagName( "tbody" ).length, - - // Make sure that link elements get serialized correctly by innerHTML - // This requires a wrapper element in IE - htmlSerialize: !!div.getElementsByTagName( "link" ).length, - - // Get the style information from getAttribute - // (IE uses .cssText instead) - style: /top/.test( a.getAttribute("style") ), - - // Make sure that URLs aren't manipulated - // (IE normalizes it by default) - hrefNormalized: ( a.getAttribute( "href" ) === "/a" ), - - // Make sure that element opacity exists - // (IE uses filter instead) - // Use a regex to work around a WebKit issue. See #5145 - opacity: /^0.55$/.test( a.style.opacity ), - - // Verify style float existence - // (IE uses styleFloat instead of cssFloat) - cssFloat: !!a.style.cssFloat, - - // Make sure that if no value is specified for a checkbox - // that it defaults to "on". - // (WebKit defaults to "" instead) - checkOn: ( input.value === "on" ), - - // Make sure that a selected-by-default option has a working selected property. - // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) - optSelected: opt.selected, - - // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) - getSetAttribute: div.className !== "t", - - // Will be defined later - submitBubbles: true, - changeBubbles: true, - focusinBubbles: false, - deleteExpando: true, - noCloneEvent: true, - inlineBlockNeedsLayout: false, - shrinkWrapBlocks: false, - reliableMarginRight: true - }; - - // Make sure checked status is properly cloned - input.checked = true; - support.noCloneChecked = input.cloneNode( true ).checked; - - // Make sure that the options inside disabled selects aren't marked as disabled - // (WebKit marks them as disabled) - select.disabled = true; - support.optDisabled = !opt.disabled; - - // Test to see if it's possible to delete an expando from an element - // Fails in Internet Explorer - try { - delete div.test; - } catch( e ) { - support.deleteExpando = false; - } - - if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { - div.attachEvent( "onclick", function() { - // Cloning a node shouldn't copy over any - // bound event handlers (IE does this) - support.noCloneEvent = false; - }); - div.cloneNode( true ).fireEvent( "onclick" ); - } - - // Check if a radio maintains it's value - // after being appended to the DOM - input = document.createElement("input"); - input.value = "t"; - input.setAttribute("type", "radio"); - support.radioValue = input.value === "t"; - - input.setAttribute("checked", "checked"); - div.appendChild( input ); - fragment = document.createDocumentFragment(); - fragment.appendChild( div.firstChild ); - - // WebKit doesn't clone checked state correctly in fragments - support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; - - div.innerHTML = ""; - - // Figure out if the W3C box model works as expected - div.style.width = div.style.paddingLeft = "1px"; - - body = document.getElementsByTagName( "body" )[ 0 ]; - // We use our own, invisible, body unless the body is already present - // in which case we use a div (#9239) - testElement = document.createElement( body ? "div" : "body" ); - testElementStyle = { - visibility: "hidden", - width: 0, - height: 0, - border: 0, - margin: 0 - }; - if ( body ) { - jQuery.extend( testElementStyle, { - position: "absolute", - left: -1000, - top: -1000 - }); - } - for ( i in testElementStyle ) { - testElement.style[ i ] = testElementStyle[ i ]; - } - testElement.appendChild( div ); - testElementParent = body || documentElement; - testElementParent.insertBefore( testElement, testElementParent.firstChild ); - - // Check if a disconnected checkbox will retain its checked - // value of true after appended to the DOM (IE6/7) - support.appendChecked = input.checked; - - support.boxModel = div.offsetWidth === 2; - - if ( "zoom" in div.style ) { - // Check if natively block-level elements act like inline-block - // elements when setting their display to 'inline' and giving - // them layout - // (IE < 8 does this) - div.style.display = "inline"; - div.style.zoom = 1; - support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 ); - - // Check if elements with layout shrink-wrap their children - // (IE 6 does this) - div.style.display = ""; - div.innerHTML = "
"; - support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); - } - - div.innerHTML = "
t
"; - tds = div.getElementsByTagName( "td" ); - - // Check if table cells still have offsetWidth/Height when they are set - // to display:none and there are still other visible table cells in a - // table row; if so, offsetWidth/Height are not reliable for use when - // determining if an element has been hidden directly using - // display:none (it is still safe to use offsets if a parent element is - // hidden; don safety goggles and see bug #4512 for more information). - // (only IE 8 fails this test) - isSupported = ( tds[ 0 ].offsetHeight === 0 ); - - tds[ 0 ].style.display = ""; - tds[ 1 ].style.display = "none"; - - // Check if empty table cells still have offsetWidth/Height - // (IE < 8 fail this test) - support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); - div.innerHTML = ""; - - // Check if div with explicit width and no margin-right incorrectly - // gets computed margin-right based on width of container. For more - // info see bug #3333 - // Fails in WebKit before Feb 2011 nightlies - // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right - if ( document.defaultView && document.defaultView.getComputedStyle ) { - marginDiv = document.createElement( "div" ); - marginDiv.style.width = "0"; - marginDiv.style.marginRight = "0"; - div.appendChild( marginDiv ); - support.reliableMarginRight = - ( parseInt( ( document.defaultView.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; - } - - // Remove the body element we added - testElement.innerHTML = ""; - testElementParent.removeChild( testElement ); - - // Technique from Juriy Zaytsev - // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ - // We only care about the case where non-standard event systems - // are used, namely in IE. Short-circuiting here helps us to - // avoid an eval call (in setAttribute) which can cause CSP - // to go haywire. See: https://developer.mozilla.org/en/Security/CSP - if ( div.attachEvent ) { - for( i in { - submit: 1, - change: 1, - focusin: 1 - } ) { - eventName = "on" + i; - isSupported = ( eventName in div ); - if ( !isSupported ) { - div.setAttribute( eventName, "return;" ); - isSupported = ( typeof div[ eventName ] === "function" ); - } - support[ i + "Bubbles" ] = isSupported; - } - } - - // Null connected elements to avoid leaks in IE - testElement = fragment = select = opt = body = marginDiv = div = input = null; - - return support; -})(); - -// Keep track of boxModel -jQuery.boxModel = jQuery.support.boxModel; - - - - -var rbrace = /^(?:\{.*\}|\[.*\])$/, - rmultiDash = /([a-z])([A-Z])/g; - -jQuery.extend({ - cache: {}, - - // Please use with caution - uuid: 0, - - // Unique for each copy of jQuery on the page - // Non-digits removed to match rinlinejQuery - expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), - - // The following elements throw uncatchable exceptions if you - // attempt to add expando properties to them. - noData: { - "embed": true, - // Ban all objects except for Flash (which handle expandos) - "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", - "applet": true - }, - - hasData: function( elem ) { - elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; - - return !!elem && !isEmptyDataObject( elem ); - }, - - data: function( elem, name, data, pvt /* Internal Use Only */ ) { - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache, - - // We have to handle DOM nodes and JS objects differently because IE6-7 - // can't GC object references properly across the DOM-JS boundary - isNode = elem.nodeType, - - // Only DOM nodes need the global jQuery cache; JS object data is - // attached directly to the object so GC can occur automatically - cache = isNode ? jQuery.cache : elem, - - // Only defining an ID for JS objects if its cache already exists allows - // the code to shortcut on the same path as a DOM node with no cache - id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando; - - // Avoid doing any more work than we need to when trying to get data on an - // object that has no data at all - if ( (!id || (pvt && id && !cache[ id ][ internalKey ])) && getByName && data === undefined ) { - return; - } - - if ( !id ) { - // Only DOM nodes need a new unique ID for each element since their data - // ends up in the global cache - if ( isNode ) { - elem[ jQuery.expando ] = id = ++jQuery.uuid; - } else { - id = jQuery.expando; - } - } - - if ( !cache[ id ] ) { - cache[ id ] = {}; - - // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery - // metadata on plain JS objects when the object is serialized using - // JSON.stringify - if ( !isNode ) { - cache[ id ].toJSON = jQuery.noop; - } - } - - // An object can be passed to jQuery.data instead of a key/value pair; this gets - // shallow copied over onto the existing cache - if ( typeof name === "object" || typeof name === "function" ) { - if ( pvt ) { - cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name); - } else { - cache[ id ] = jQuery.extend(cache[ id ], name); - } - } - - thisCache = cache[ id ]; - - // Internal jQuery data is stored in a separate object inside the object's data - // cache in order to avoid key collisions between internal data and user-defined - // data - if ( pvt ) { - if ( !thisCache[ internalKey ] ) { - thisCache[ internalKey ] = {}; - } - - thisCache = thisCache[ internalKey ]; - } - - if ( data !== undefined ) { - thisCache[ jQuery.camelCase( name ) ] = data; - } - - // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should - // not attempt to inspect the internal events object using jQuery.data, as this - // internal data object is undocumented and subject to change. - if ( name === "events" && !thisCache[name] ) { - return thisCache[ internalKey ] && thisCache[ internalKey ].events; - } - - return getByName ? - // Check for both converted-to-camel and non-converted data property names - thisCache[ jQuery.camelCase( name ) ] || thisCache[ name ] : - thisCache; - }, - - removeData: function( elem, name, pvt /* Internal Use Only */ ) { - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var internalKey = jQuery.expando, isNode = elem.nodeType, - - // See jQuery.data for more information - cache = isNode ? jQuery.cache : elem, - - // See jQuery.data for more information - id = isNode ? elem[ jQuery.expando ] : jQuery.expando; - - // If there is already no cache entry for this object, there is no - // purpose in continuing - if ( !cache[ id ] ) { - return; - } - - if ( name ) { - var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ]; - - if ( thisCache ) { - delete thisCache[ name ]; - - // If there is no data left in the cache, we want to continue - // and let the cache object itself get destroyed - if ( !isEmptyDataObject(thisCache) ) { - return; - } - } - } - - // See jQuery.data for more information - if ( pvt ) { - delete cache[ id ][ internalKey ]; - - // Don't destroy the parent cache unless the internal data object - // had been the only thing left in it - if ( !isEmptyDataObject(cache[ id ]) ) { - return; - } - } - - var internalCache = cache[ id ][ internalKey ]; - - // Browsers that fail expando deletion also refuse to delete expandos on - // the window, but it will allow it on all other JS objects; other browsers - // don't care - if ( jQuery.support.deleteExpando || cache != window ) { - delete cache[ id ]; - } else { - cache[ id ] = null; - } - - // We destroyed the entire user cache at once because it's faster than - // iterating through each key, but we need to continue to persist internal - // data if it existed - if ( internalCache ) { - cache[ id ] = {}; - // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery - // metadata on plain JS objects when the object is serialized using - // JSON.stringify - if ( !isNode ) { - cache[ id ].toJSON = jQuery.noop; - } - - cache[ id ][ internalKey ] = internalCache; - - // Otherwise, we need to eliminate the expando on the node to avoid - // false lookups in the cache for entries that no longer exist - } else if ( isNode ) { - // IE does not allow us to delete expando properties from nodes, - // nor does it have a removeAttribute function on Document nodes; - // we must handle all of these cases - if ( jQuery.support.deleteExpando ) { - delete elem[ jQuery.expando ]; - } else if ( elem.removeAttribute ) { - elem.removeAttribute( jQuery.expando ); - } else { - elem[ jQuery.expando ] = null; - } - } - }, - - // For internal use only. - _data: function( elem, name, data ) { - return jQuery.data( elem, name, data, true ); - }, - - // A method for determining if a DOM node can handle the data expando - acceptData: function( elem ) { - if ( elem.nodeName ) { - var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; - - if ( match ) { - return !(match === true || elem.getAttribute("classid") !== match); - } - } - - return true; - } -}); - -jQuery.fn.extend({ - data: function( key, value ) { - var data = null; - - if ( typeof key === "undefined" ) { - if ( this.length ) { - data = jQuery.data( this[0] ); - - if ( this[0].nodeType === 1 ) { - var attr = this[0].attributes, name; - for ( var i = 0, l = attr.length; i < l; i++ ) { - name = attr[i].name; - - if ( name.indexOf( "data-" ) === 0 ) { - name = jQuery.camelCase( name.substring(5) ); - - dataAttr( this[0], name, data[ name ] ); - } - } - } - } - - return data; - - } else if ( typeof key === "object" ) { - return this.each(function() { - jQuery.data( this, key ); - }); - } - - var parts = key.split("."); - parts[1] = parts[1] ? "." + parts[1] : ""; - - if ( value === undefined ) { - data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); - - // Try to fetch any internally stored data first - if ( data === undefined && this.length ) { - data = jQuery.data( this[0], key ); - data = dataAttr( this[0], key, data ); - } - - return data === undefined && parts[1] ? - this.data( parts[0] ) : - data; - - } else { - return this.each(function() { - var $this = jQuery( this ), - args = [ parts[0], value ]; - - $this.triggerHandler( "setData" + parts[1] + "!", args ); - jQuery.data( this, key, value ); - $this.triggerHandler( "changeData" + parts[1] + "!", args ); - }); - } - }, - - removeData: function( key ) { - return this.each(function() { - jQuery.removeData( this, key ); - }); - } -}); - -function dataAttr( elem, key, data ) { - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if ( data === undefined && elem.nodeType === 1 ) { - var name = "data-" + key.replace( rmultiDash, "$1-$2" ).toLowerCase(); - - data = elem.getAttribute( name ); - - if ( typeof data === "string" ) { - try { - data = data === "true" ? true : - data === "false" ? false : - data === "null" ? null : - !jQuery.isNaN( data ) ? parseFloat( data ) : - rbrace.test( data ) ? jQuery.parseJSON( data ) : - data; - } catch( e ) {} - - // Make sure we set the data so it isn't changed later - jQuery.data( elem, key, data ); - - } else { - data = undefined; - } - } - - return data; -} - -// TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON -// property to be considered empty objects; this property always exists in -// order to make sure JSON.stringify does not expose internal metadata -function isEmptyDataObject( obj ) { - for ( var name in obj ) { - if ( name !== "toJSON" ) { - return false; - } - } - - return true; -} - - - - -function handleQueueMarkDefer( elem, type, src ) { - var deferDataKey = type + "defer", - queueDataKey = type + "queue", - markDataKey = type + "mark", - defer = jQuery.data( elem, deferDataKey, undefined, true ); - if ( defer && - ( src === "queue" || !jQuery.data( elem, queueDataKey, undefined, true ) ) && - ( src === "mark" || !jQuery.data( elem, markDataKey, undefined, true ) ) ) { - // Give room for hard-coded callbacks to fire first - // and eventually mark/queue something else on the element - setTimeout( function() { - if ( !jQuery.data( elem, queueDataKey, undefined, true ) && - !jQuery.data( elem, markDataKey, undefined, true ) ) { - jQuery.removeData( elem, deferDataKey, true ); - defer.resolve(); - } - }, 0 ); - } -} - -jQuery.extend({ - - _mark: function( elem, type ) { - if ( elem ) { - type = (type || "fx") + "mark"; - jQuery.data( elem, type, (jQuery.data(elem,type,undefined,true) || 0) + 1, true ); - } - }, - - _unmark: function( force, elem, type ) { - if ( force !== true ) { - type = elem; - elem = force; - force = false; - } - if ( elem ) { - type = type || "fx"; - var key = type + "mark", - count = force ? 0 : ( (jQuery.data( elem, key, undefined, true) || 1 ) - 1 ); - if ( count ) { - jQuery.data( elem, key, count, true ); - } else { - jQuery.removeData( elem, key, true ); - handleQueueMarkDefer( elem, type, "mark" ); - } - } - }, - - queue: function( elem, type, data ) { - if ( elem ) { - type = (type || "fx") + "queue"; - var q = jQuery.data( elem, type, undefined, true ); - // Speed up dequeue by getting out quickly if this is just a lookup - if ( data ) { - if ( !q || jQuery.isArray(data) ) { - q = jQuery.data( elem, type, jQuery.makeArray(data), true ); - } else { - q.push( data ); - } - } - return q || []; - } - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - - var queue = jQuery.queue( elem, type ), - fn = queue.shift(), - defer; - - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - } - - if ( fn ) { - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift("inprogress"); - } - - fn.call(elem, function() { - jQuery.dequeue(elem, type); - }); - } - - if ( !queue.length ) { - jQuery.removeData( elem, type + "queue", true ); - handleQueueMarkDefer( elem, type, "queue" ); - } - } -}); - -jQuery.fn.extend({ - queue: function( type, data ) { - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - } - - if ( data === undefined ) { - return jQuery.queue( this[0], type ); - } - return this.each(function() { - var queue = jQuery.queue( this, type, data ); - - if ( type === "fx" && queue[0] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - }); - }, - dequeue: function( type ) { - return this.each(function() { - jQuery.dequeue( this, type ); - }); - }, - // Based off of the plugin by Clint Helfers, with permission. - // http://blindsignals.com/index.php/2009/07/jquery-delay/ - delay: function( time, type ) { - time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; - type = type || "fx"; - - return this.queue( type, function() { - var elem = this; - setTimeout(function() { - jQuery.dequeue( elem, type ); - }, time ); - }); - }, - clearQueue: function( type ) { - return this.queue( type || "fx", [] ); - }, - // Get a promise resolved when queues of a certain type - // are emptied (fx is the type by default) - promise: function( type, object ) { - if ( typeof type !== "string" ) { - object = type; - type = undefined; - } - type = type || "fx"; - var defer = jQuery.Deferred(), - elements = this, - i = elements.length, - count = 1, - deferDataKey = type + "defer", - queueDataKey = type + "queue", - markDataKey = type + "mark", - tmp; - function resolve() { - if ( !( --count ) ) { - defer.resolveWith( elements, [ elements ] ); - } - } - while( i-- ) { - if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || - ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || - jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && - jQuery.data( elements[ i ], deferDataKey, jQuery._Deferred(), true ) )) { - count++; - tmp.done( resolve ); - } - } - resolve(); - return defer.promise(); - } -}); - - - - -var rclass = /[\n\t\r]/g, - rspace = /\s+/, - rreturn = /\r/g, - rtype = /^(?:button|input)$/i, - rfocusable = /^(?:button|input|object|select|textarea)$/i, - rclickable = /^a(?:rea)?$/i, - rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, - rinvalidChar = /\:|^on/, - formHook, boolHook; - -jQuery.fn.extend({ - attr: function( name, value ) { - return jQuery.access( this, name, value, true, jQuery.attr ); - }, - - removeAttr: function( name ) { - return this.each(function() { - jQuery.removeAttr( this, name ); - }); - }, - - prop: function( name, value ) { - return jQuery.access( this, name, value, true, jQuery.prop ); - }, - - removeProp: function( name ) { - name = jQuery.propFix[ name ] || name; - return this.each(function() { - // try/catch handles cases where IE balks (such as removing a property on window) - try { - this[ name ] = undefined; - delete this[ name ]; - } catch( e ) {} - }); - }, - - addClass: function( value ) { - var classNames, i, l, elem, - setClass, c, cl; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).addClass( value.call(this, j, this.className) ); - }); - } - - if ( value && typeof value === "string" ) { - classNames = value.split( rspace ); - - for ( i = 0, l = this.length; i < l; i++ ) { - elem = this[ i ]; - - if ( elem.nodeType === 1 ) { - if ( !elem.className && classNames.length === 1 ) { - elem.className = value; - - } else { - setClass = " " + elem.className + " "; - - for ( c = 0, cl = classNames.length; c < cl; c++ ) { - if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { - setClass += classNames[ c ] + " "; - } - } - elem.className = jQuery.trim( setClass ); - } - } - } - } - - return this; - }, - - removeClass: function( value ) { - var classNames, i, l, elem, className, c, cl; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).removeClass( value.call(this, j, this.className) ); - }); - } - - if ( (value && typeof value === "string") || value === undefined ) { - classNames = (value || "").split( rspace ); - - for ( i = 0, l = this.length; i < l; i++ ) { - elem = this[ i ]; - - if ( elem.nodeType === 1 && elem.className ) { - if ( value ) { - className = (" " + elem.className + " ").replace( rclass, " " ); - for ( c = 0, cl = classNames.length; c < cl; c++ ) { - className = className.replace(" " + classNames[ c ] + " ", " "); - } - elem.className = jQuery.trim( className ); - - } else { - elem.className = ""; - } - } - } - } - - return this; - }, - - toggleClass: function( value, stateVal ) { - var type = typeof value, - isBool = typeof stateVal === "boolean"; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( i ) { - jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); - }); - } - - return this.each(function() { - if ( type === "string" ) { - // toggle individual class names - var className, - i = 0, - self = jQuery( this ), - state = stateVal, - classNames = value.split( rspace ); - - while ( (className = classNames[ i++ ]) ) { - // check each className given, space seperated list - state = isBool ? state : !self.hasClass( className ); - self[ state ? "addClass" : "removeClass" ]( className ); - } - - } else if ( type === "undefined" || type === "boolean" ) { - if ( this.className ) { - // store className if set - jQuery._data( this, "__className__", this.className ); - } - - // toggle whole className - this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; - } - }); - }, - - hasClass: function( selector ) { - var className = " " + selector + " "; - for ( var i = 0, l = this.length; i < l; i++ ) { - if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { - return true; - } - } - - return false; - }, - - val: function( value ) { - var hooks, ret, - elem = this[0]; - - if ( !arguments.length ) { - if ( elem ) { - hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; - - if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { - return ret; - } - - ret = elem.value; - - return typeof ret === "string" ? - // handle most common string cases - ret.replace(rreturn, "") : - // handle cases where value is null/undef or number - ret == null ? "" : ret; - } - - return undefined; - } - - var isFunction = jQuery.isFunction( value ); - - return this.each(function( i ) { - var self = jQuery(this), val; - - if ( this.nodeType !== 1 ) { - return; - } - - if ( isFunction ) { - val = value.call( this, i, self.val() ); - } else { - val = value; - } - - // Treat null/undefined as ""; convert numbers to string - if ( val == null ) { - val = ""; - } else if ( typeof val === "number" ) { - val += ""; - } else if ( jQuery.isArray( val ) ) { - val = jQuery.map(val, function ( value ) { - return value == null ? "" : value + ""; - }); - } - - hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ]; - - // If set returns undefined, fall back to normal setting - if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { - this.value = val; - } - }); - } -}); - -jQuery.extend({ - valHooks: { - option: { - get: function( elem ) { - // attributes.value is undefined in Blackberry 4.7 but - // uses .value. See #6932 - var val = elem.attributes.value; - return !val || val.specified ? elem.value : elem.text; - } - }, - select: { - get: function( elem ) { - var value, - index = elem.selectedIndex, - values = [], - options = elem.options, - one = elem.type === "select-one"; - - // Nothing was selected - if ( index < 0 ) { - return null; - } - - // Loop through all the selected options - for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { - var option = options[ i ]; - - // Don't return options that are disabled or in a disabled optgroup - if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && - (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { - - // Get the specific value for the option - value = jQuery( option ).val(); - - // We don't need an array for one selects - if ( one ) { - return value; - } - - // Multi-Selects return an array - values.push( value ); - } - } - - // Fixes Bug #2551 -- select.val() broken in IE after form.reset() - if ( one && !values.length && options.length ) { - return jQuery( options[ index ] ).val(); - } - - return values; - }, - - set: function( elem, value ) { - var values = jQuery.makeArray( value ); - - jQuery(elem).find("option").each(function() { - this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; - }); - - if ( !values.length ) { - elem.selectedIndex = -1; - } - return values; - } - } - }, - - attrFn: { - val: true, - css: true, - html: true, - text: true, - data: true, - width: true, - height: true, - offset: true - }, - - attrFix: { - // Always normalize to ensure hook usage - tabindex: "tabIndex" - }, - - attr: function( elem, name, value, pass ) { - var nType = elem.nodeType; - - // don't get/set attributes on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return undefined; - } - - if ( pass && name in jQuery.attrFn ) { - return jQuery( elem )[ name ]( value ); - } - - // Fallback to prop when attributes are not supported - if ( !("getAttribute" in elem) ) { - return jQuery.prop( elem, name, value ); - } - - var ret, hooks, - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); - - // Normalize the name if needed - if ( notxml ) { - name = jQuery.attrFix[ name ] || name; - - hooks = jQuery.attrHooks[ name ]; - - if ( !hooks ) { - // Use boolHook for boolean attributes - if ( rboolean.test( name ) ) { - - hooks = boolHook; - - // Use formHook for forms and if the name contains certain characters - } else if ( formHook && name !== "className" && - (jQuery.nodeName( elem, "form" ) || rinvalidChar.test( name )) ) { - - hooks = formHook; - } - } - } - - if ( value !== undefined ) { - - if ( value === null ) { - jQuery.removeAttr( elem, name ); - return undefined; - - } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; - - } else { - elem.setAttribute( name, "" + value ); - return value; - } - - } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { - return ret; - - } else { - - ret = elem.getAttribute( name ); - - // Non-existent attributes return null, we normalize to undefined - return ret === null ? - undefined : - ret; - } - }, - - removeAttr: function( elem, name ) { - var propName; - if ( elem.nodeType === 1 ) { - name = jQuery.attrFix[ name ] || name; - - if ( jQuery.support.getSetAttribute ) { - // Use removeAttribute in browsers that support it - elem.removeAttribute( name ); - } else { - jQuery.attr( elem, name, "" ); - elem.removeAttributeNode( elem.getAttributeNode( name ) ); - } - - // Set corresponding property to false for boolean attributes - if ( rboolean.test( name ) && (propName = jQuery.propFix[ name ] || name) in elem ) { - elem[ propName ] = false; - } - } - }, - - attrHooks: { - type: { - set: function( elem, value ) { - // We can't allow the type property to be changed (since it causes problems in IE) - if ( rtype.test( elem.nodeName ) && elem.parentNode ) { - jQuery.error( "type property can't be changed" ); - } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { - // Setting the type on a radio button after the value resets the value in IE6-9 - // Reset value to it's default in case type is set after value - // This is for element creation - var val = elem.value; - elem.setAttribute( "type", value ); - if ( val ) { - elem.value = val; - } - return value; - } - } - }, - tabIndex: { - get: function( elem ) { - // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set - // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ - var attributeNode = elem.getAttributeNode("tabIndex"); - - return attributeNode && attributeNode.specified ? - parseInt( attributeNode.value, 10 ) : - rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? - 0 : - undefined; - } - }, - // Use the value property for back compat - // Use the formHook for button elements in IE6/7 (#1954) - value: { - get: function( elem, name ) { - if ( formHook && jQuery.nodeName( elem, "button" ) ) { - return formHook.get( elem, name ); - } - return name in elem ? - elem.value : - null; - }, - set: function( elem, value, name ) { - if ( formHook && jQuery.nodeName( elem, "button" ) ) { - return formHook.set( elem, value, name ); - } - // Does not return so that setAttribute is also used - elem.value = value; - } - } - }, - - propFix: { - tabindex: "tabIndex", - readonly: "readOnly", - "for": "htmlFor", - "class": "className", - maxlength: "maxLength", - cellspacing: "cellSpacing", - cellpadding: "cellPadding", - rowspan: "rowSpan", - colspan: "colSpan", - usemap: "useMap", - frameborder: "frameBorder", - contenteditable: "contentEditable" - }, - - prop: function( elem, name, value ) { - var nType = elem.nodeType; - - // don't get/set properties on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return undefined; - } - - var ret, hooks, - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); - - if ( notxml ) { - // Fix name and attach hooks - name = jQuery.propFix[ name ] || name; - hooks = jQuery.propHooks[ name ]; - } - - if ( value !== undefined ) { - if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; - - } else { - return (elem[ name ] = value); - } - - } else { - if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== undefined ) { - return ret; - - } else { - return elem[ name ]; - } - } - }, - - propHooks: {} -}); - -// Hook for boolean attributes -boolHook = { - get: function( elem, name ) { - // Align boolean attributes with corresponding properties - return jQuery.prop( elem, name ) ? - name.toLowerCase() : - undefined; - }, - set: function( elem, value, name ) { - var propName; - if ( value === false ) { - // Remove boolean attributes when set to false - jQuery.removeAttr( elem, name ); - } else { - // value is true since we know at this point it's type boolean and not false - // Set boolean attributes to the same name and set the DOM property - propName = jQuery.propFix[ name ] || name; - if ( propName in elem ) { - // Only set the IDL specifically if it already exists on the element - elem[ propName ] = true; - } - - elem.setAttribute( name, name.toLowerCase() ); - } - return name; - } -}; - -// IE6/7 do not support getting/setting some attributes with get/setAttribute -if ( !jQuery.support.getSetAttribute ) { - - // propFix is more comprehensive and contains all fixes - jQuery.attrFix = jQuery.propFix; - - // Use this for any attribute on a form in IE6/7 - formHook = jQuery.attrHooks.name = jQuery.attrHooks.title = jQuery.valHooks.button = { - get: function( elem, name ) { - var ret; - ret = elem.getAttributeNode( name ); - // Return undefined if nodeValue is empty string - return ret && ret.nodeValue !== "" ? - ret.nodeValue : - undefined; - }, - set: function( elem, value, name ) { - // Check form objects in IE (multiple bugs related) - // Only use nodeValue if the attribute node exists on the form - var ret = elem.getAttributeNode( name ); - if ( ret ) { - ret.nodeValue = value; - return value; - } - } - }; - - // Set width and height to auto instead of 0 on empty string( Bug #8150 ) - // This is for removals - jQuery.each([ "width", "height" ], function( i, name ) { - jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { - set: function( elem, value ) { - if ( value === "" ) { - elem.setAttribute( name, "auto" ); - return value; - } - } - }); - }); -} - - -// Some attributes require a special call on IE -if ( !jQuery.support.hrefNormalized ) { - jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { - jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { - get: function( elem ) { - var ret = elem.getAttribute( name, 2 ); - return ret === null ? undefined : ret; - } - }); - }); -} - -if ( !jQuery.support.style ) { - jQuery.attrHooks.style = { - get: function( elem ) { - // Return undefined in the case of empty string - // Normalize to lowercase since IE uppercases css property names - return elem.style.cssText.toLowerCase() || undefined; - }, - set: function( elem, value ) { - return (elem.style.cssText = "" + value); - } - }; -} - -// Safari mis-reports the default selected property of an option -// Accessing the parent's selectedIndex property fixes it -if ( !jQuery.support.optSelected ) { - jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { - get: function( elem ) { - var parent = elem.parentNode; - - if ( parent ) { - parent.selectedIndex; - - // Make sure that it also works with optgroups, see #5701 - if ( parent.parentNode ) { - parent.parentNode.selectedIndex; - } - } - } - }); -} - -// Radios and checkboxes getter/setter -if ( !jQuery.support.checkOn ) { - jQuery.each([ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = { - get: function( elem ) { - // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified - return elem.getAttribute("value") === null ? "on" : elem.value; - } - }; - }); -} -jQuery.each([ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { - set: function( elem, value ) { - if ( jQuery.isArray( value ) ) { - return (elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0); - } - } - }); -}); - - - - -var rnamespaces = /\.(.*)$/, - rformElems = /^(?:textarea|input|select)$/i, - rperiod = /\./g, - rspaces = / /g, - rescape = /[^\w\s.|`]/g, - fcleanup = function( nm ) { - return nm.replace(rescape, "\\$&"); - }; - -/* - * A number of helper functions used for managing events. - * Many of the ideas behind this code originated from - * Dean Edwards' addEvent library. - */ -jQuery.event = { - - // Bind an event to an element - // Original by Dean Edwards - add: function( elem, types, handler, data ) { - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - if ( handler === false ) { - handler = returnFalse; - } else if ( !handler ) { - // Fixes bug #7229. Fix recommended by jdalton - return; - } - - var handleObjIn, handleObj; - - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - } - - // Make sure that the function being executed has a unique ID - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } - - // Init the element's event structure - var elemData = jQuery._data( elem ); - - // If no elemData is found then we must be trying to bind to one of the - // banned noData elements - if ( !elemData ) { - return; - } - - var events = elemData.events, - eventHandle = elemData.handle; - - if ( !events ) { - elemData.events = events = {}; - } - - if ( !eventHandle ) { - elemData.handle = eventHandle = function( e ) { - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? - jQuery.event.handle.apply( eventHandle.elem, arguments ) : - undefined; - }; - } - - // Add elem as a property of the handle function - // This is to prevent a memory leak with non-native events in IE. - eventHandle.elem = elem; - - // Handle multiple events separated by a space - // jQuery(...).bind("mouseover mouseout", fn); - types = types.split(" "); - - var type, i = 0, namespaces; - - while ( (type = types[ i++ ]) ) { - handleObj = handleObjIn ? - jQuery.extend({}, handleObjIn) : - { handler: handler, data: data }; - - // Namespaced event handlers - if ( type.indexOf(".") > -1 ) { - namespaces = type.split("."); - type = namespaces.shift(); - handleObj.namespace = namespaces.slice(0).sort().join("."); - - } else { - namespaces = []; - handleObj.namespace = ""; - } - - handleObj.type = type; - if ( !handleObj.guid ) { - handleObj.guid = handler.guid; - } - - // Get the current list of functions bound to this event - var handlers = events[ type ], - special = jQuery.event.special[ type ] || {}; - - // Init the event handler queue - if ( !handlers ) { - handlers = events[ type ] = []; - - // Check for a special event handler - // Only use addEventListener/attachEvent if the special - // events handler returns false - if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - // Bind the global event handler to the element - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle, false ); - - } else if ( elem.attachEvent ) { - elem.attachEvent( "on" + type, eventHandle ); - } - } - } - - if ( special.add ) { - special.add.call( elem, handleObj ); - - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; - } - } - - // Add the function to the element's handler list - handlers.push( handleObj ); - - // Keep track of which events have been used, for event optimization - jQuery.event.global[ type ] = true; - } - - // Nullify elem to prevent memory leaks in IE - elem = null; - }, - - global: {}, - - // Detach an event or set of events from an element - remove: function( elem, types, handler, pos ) { - // don't do events on text and comment nodes - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - if ( handler === false ) { - handler = returnFalse; - } - - var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, - elemData = jQuery.hasData( elem ) && jQuery._data( elem ), - events = elemData && elemData.events; - - if ( !elemData || !events ) { - return; - } - - // types is actually an event object here - if ( types && types.type ) { - handler = types.handler; - types = types.type; - } - - // Unbind all events for the element - if ( !types || typeof types === "string" && types.charAt(0) === "." ) { - types = types || ""; - - for ( type in events ) { - jQuery.event.remove( elem, type + types ); - } - - return; - } - - // Handle multiple events separated by a space - // jQuery(...).unbind("mouseover mouseout", fn); - types = types.split(" "); - - while ( (type = types[ i++ ]) ) { - origType = type; - handleObj = null; - all = type.indexOf(".") < 0; - namespaces = []; - - if ( !all ) { - // Namespaced event handlers - namespaces = type.split("."); - type = namespaces.shift(); - - namespace = new RegExp("(^|\\.)" + - jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)"); - } - - eventType = events[ type ]; - - if ( !eventType ) { - continue; - } - - if ( !handler ) { - for ( j = 0; j < eventType.length; j++ ) { - handleObj = eventType[ j ]; - - if ( all || namespace.test( handleObj.namespace ) ) { - jQuery.event.remove( elem, origType, handleObj.handler, j ); - eventType.splice( j--, 1 ); - } - } - - continue; - } - - special = jQuery.event.special[ type ] || {}; - - for ( j = pos || 0; j < eventType.length; j++ ) { - handleObj = eventType[ j ]; - - if ( handler.guid === handleObj.guid ) { - // remove the given handler for the given type - if ( all || namespace.test( handleObj.namespace ) ) { - if ( pos == null ) { - eventType.splice( j--, 1 ); - } - - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - - if ( pos != null ) { - break; - } - } - } - - // remove generic event handler if no more handlers exist - if ( eventType.length === 0 || pos != null && eventType.length === 1 ) { - if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { - jQuery.removeEvent( elem, type, elemData.handle ); - } - - ret = null; - delete events[ type ]; - } - } - - // Remove the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - var handle = elemData.handle; - if ( handle ) { - handle.elem = null; - } - - delete elemData.events; - delete elemData.handle; - - if ( jQuery.isEmptyObject( elemData ) ) { - jQuery.removeData( elem, undefined, true ); - } - } - }, - - // Events that are safe to short-circuit if no handlers are attached. - // Native DOM events should not be added, they may have inline handlers. - customEvent: { - "getData": true, - "setData": true, - "changeData": true - }, - - trigger: function( event, data, elem, onlyHandlers ) { - // Event object or event type - var type = event.type || event, - namespaces = [], - exclusive; - - if ( type.indexOf("!") >= 0 ) { - // Exclusive events trigger only for the exact event (no namespaces) - type = type.slice(0, -1); - exclusive = true; - } - - if ( type.indexOf(".") >= 0 ) { - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split("."); - type = namespaces.shift(); - namespaces.sort(); - } - - if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { - // No jQuery handlers for this event type, and it can't have inline handlers - return; - } - - // Caller can pass in an Event, Object, or just an event type string - event = typeof event === "object" ? - // jQuery.Event object - event[ jQuery.expando ] ? event : - // Object literal - new jQuery.Event( type, event ) : - // Just the event type (string) - new jQuery.Event( type ); - - event.type = type; - event.exclusive = exclusive; - event.namespace = namespaces.join("."); - event.namespace_re = new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)"); - - // triggerHandler() and global events don't bubble or run the default action - if ( onlyHandlers || !elem ) { - event.preventDefault(); - event.stopPropagation(); - } - - // Handle a global trigger - if ( !elem ) { - // TODO: Stop taunting the data cache; remove global events and always attach to document - jQuery.each( jQuery.cache, function() { - // internalKey variable is just used to make it easier to find - // and potentially change this stuff later; currently it just - // points to jQuery.expando - var internalKey = jQuery.expando, - internalCache = this[ internalKey ]; - if ( internalCache && internalCache.events && internalCache.events[ type ] ) { - jQuery.event.trigger( event, data, internalCache.handle.elem ); - } - }); - return; - } - - // Don't do events on text and comment nodes - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - // Clean up the event in case it is being reused - event.result = undefined; - event.target = elem; - - // Clone any incoming data and prepend the event, creating the handler arg list - data = data != null ? jQuery.makeArray( data ) : []; - data.unshift( event ); - - var cur = elem, - // IE doesn't like method names with a colon (#3533, #8272) - ontype = type.indexOf(":") < 0 ? "on" + type : ""; - - // Fire event on the current element, then bubble up the DOM tree - do { - var handle = jQuery._data( cur, "handle" ); - - event.currentTarget = cur; - if ( handle ) { - handle.apply( cur, data ); - } - - // Trigger an inline bound script - if ( ontype && jQuery.acceptData( cur ) && cur[ ontype ] && cur[ ontype ].apply( cur, data ) === false ) { - event.result = false; - event.preventDefault(); - } - - // Bubble up to document, then to window - cur = cur.parentNode || cur.ownerDocument || cur === event.target.ownerDocument && window; - } while ( cur && !event.isPropagationStopped() ); - - // If nobody prevented the default action, do it now - if ( !event.isDefaultPrevented() ) { - var old, - special = jQuery.event.special[ type ] || {}; - - if ( (!special._default || special._default.call( elem.ownerDocument, event ) === false) && - !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { - - // Call a native DOM method on the target with the same name name as the event. - // Can't use an .isFunction)() check here because IE6/7 fails that test. - // IE<9 dies on focus to hidden element (#1486), may want to revisit a try/catch. - try { - if ( ontype && elem[ type ] ) { - // Don't re-trigger an onFOO event when we call its FOO() method - old = elem[ ontype ]; - - if ( old ) { - elem[ ontype ] = null; - } - - jQuery.event.triggered = type; - elem[ type ](); - } - } catch ( ieError ) {} - - if ( old ) { - elem[ ontype ] = old; - } - - jQuery.event.triggered = undefined; - } - } - - return event.result; - }, - - handle: function( event ) { - event = jQuery.event.fix( event || window.event ); - // Snapshot the handlers list since a called handler may add/remove events. - var handlers = ((jQuery._data( this, "events" ) || {})[ event.type ] || []).slice(0), - run_all = !event.exclusive && !event.namespace, - args = Array.prototype.slice.call( arguments, 0 ); - - // Use the fix-ed Event rather than the (read-only) native event - args[0] = event; - event.currentTarget = this; - - for ( var j = 0, l = handlers.length; j < l; j++ ) { - var handleObj = handlers[ j ]; - - // Triggered event must 1) be non-exclusive and have no namespace, or - // 2) have namespace(s) a subset or equal to those in the bound event. - if ( run_all || event.namespace_re.test( handleObj.namespace ) ) { - // Pass in a reference to the handler function itself - // So that we can later remove it - event.handler = handleObj.handler; - event.data = handleObj.data; - event.handleObj = handleObj; - - var ret = handleObj.handler.apply( this, args ); - - if ( ret !== undefined ) { - event.result = ret; - if ( ret === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - - if ( event.isImmediatePropagationStopped() ) { - break; - } - } - } - return event.result; - }, - - props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), - - fix: function( event ) { - if ( event[ jQuery.expando ] ) { - return event; - } - - // store a copy of the original event object - // and "clone" to set read-only properties - var originalEvent = event; - event = jQuery.Event( originalEvent ); - - for ( var i = this.props.length, prop; i; ) { - prop = this.props[ --i ]; - event[ prop ] = originalEvent[ prop ]; - } - - // Fix target property, if necessary - if ( !event.target ) { - // Fixes #1925 where srcElement might not be defined either - event.target = event.srcElement || document; - } - - // check if target is a textnode (safari) - if ( event.target.nodeType === 3 ) { - event.target = event.target.parentNode; - } - - // Add relatedTarget, if necessary - if ( !event.relatedTarget && event.fromElement ) { - event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; - } - - // Calculate pageX/Y if missing and clientX/Y available - if ( event.pageX == null && event.clientX != null ) { - var eventDocument = event.target.ownerDocument || document, - doc = eventDocument.documentElement, - body = eventDocument.body; - - event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); - event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); - } - - // Add which for key events - if ( event.which == null && (event.charCode != null || event.keyCode != null) ) { - event.which = event.charCode != null ? event.charCode : event.keyCode; - } - - // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) - if ( !event.metaKey && event.ctrlKey ) { - event.metaKey = event.ctrlKey; - } - - // Add which for click: 1 === left; 2 === middle; 3 === right - // Note: button is not normalized, so don't use it - if ( !event.which && event.button !== undefined ) { - event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); - } - - return event; - }, - - // Deprecated, use jQuery.guid instead - guid: 1E8, - - // Deprecated, use jQuery.proxy instead - proxy: jQuery.proxy, - - special: { - ready: { - // Make sure the ready event is setup - setup: jQuery.bindReady, - teardown: jQuery.noop - }, - - live: { - add: function( handleObj ) { - jQuery.event.add( this, - liveConvert( handleObj.origType, handleObj.selector ), - jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) ); - }, - - remove: function( handleObj ) { - jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj ); - } - }, - - beforeunload: { - setup: function( data, namespaces, eventHandle ) { - // We only want to do this special case on windows - if ( jQuery.isWindow( this ) ) { - this.onbeforeunload = eventHandle; - } - }, - - teardown: function( namespaces, eventHandle ) { - if ( this.onbeforeunload === eventHandle ) { - this.onbeforeunload = null; - } - } - } - } -}; - -jQuery.removeEvent = document.removeEventListener ? - function( elem, type, handle ) { - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle, false ); - } - } : - function( elem, type, handle ) { - if ( elem.detachEvent ) { - elem.detachEvent( "on" + type, handle ); - } - }; - -jQuery.Event = function( src, props ) { - // Allow instantiation without the 'new' keyword - if ( !this.preventDefault ) { - return new jQuery.Event( src, props ); - } - - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false || - src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse; - - // Event type - } else { - this.type = src; - } - - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); - } - - // timeStamp is buggy for some events on Firefox(#3843) - // So we won't rely on the native value - this.timeStamp = jQuery.now(); - - // Mark it as fixed - this[ jQuery.expando ] = true; -}; - -function returnFalse() { - return false; -} -function returnTrue() { - return true; -} - -// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding -// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html -jQuery.Event.prototype = { - preventDefault: function() { - this.isDefaultPrevented = returnTrue; - - var e = this.originalEvent; - if ( !e ) { - return; - } - - // if preventDefault exists run it on the original event - if ( e.preventDefault ) { - e.preventDefault(); - - // otherwise set the returnValue property of the original event to false (IE) - } else { - e.returnValue = false; - } - }, - stopPropagation: function() { - this.isPropagationStopped = returnTrue; - - var e = this.originalEvent; - if ( !e ) { - return; - } - // if stopPropagation exists run it on the original event - if ( e.stopPropagation ) { - e.stopPropagation(); - } - // otherwise set the cancelBubble property of the original event to true (IE) - e.cancelBubble = true; - }, - stopImmediatePropagation: function() { - this.isImmediatePropagationStopped = returnTrue; - this.stopPropagation(); - }, - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse -}; - -// Checks if an event happened on an element within another element -// Used in jQuery.event.special.mouseenter and mouseleave handlers -var withinElement = function( event ) { - - // Check if mouse(over|out) are still within the same parent element - var related = event.relatedTarget, - inside = false, - eventType = event.type; - - event.type = event.data; - - if ( related !== this ) { - - if ( related ) { - inside = jQuery.contains( this, related ); - } - - if ( !inside ) { - - jQuery.event.handle.apply( this, arguments ); - - event.type = eventType; - } - } -}, - -// In case of event delegation, we only need to rename the event.type, -// liveHandler will take care of the rest. -delegate = function( event ) { - event.type = event.data; - jQuery.event.handle.apply( this, arguments ); -}; - -// Create mouseenter and mouseleave events -jQuery.each({ - mouseenter: "mouseover", - mouseleave: "mouseout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - setup: function( data ) { - jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); - }, - teardown: function( data ) { - jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); - } - }; -}); - -// submit delegation -if ( !jQuery.support.submitBubbles ) { - - jQuery.event.special.submit = { - setup: function( data, namespaces ) { - if ( !jQuery.nodeName( this, "form" ) ) { - jQuery.event.add(this, "click.specialSubmit", function( e ) { - var elem = e.target, - type = elem.type; - - if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { - trigger( "submit", this, arguments ); - } - }); - - jQuery.event.add(this, "keypress.specialSubmit", function( e ) { - var elem = e.target, - type = elem.type; - - if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { - trigger( "submit", this, arguments ); - } - }); - - } else { - return false; - } - }, - - teardown: function( namespaces ) { - jQuery.event.remove( this, ".specialSubmit" ); - } - }; - -} - -// change delegation, happens here so we have bind. -if ( !jQuery.support.changeBubbles ) { - - var changeFilters, - - getVal = function( elem ) { - var type = elem.type, val = elem.value; - - if ( type === "radio" || type === "checkbox" ) { - val = elem.checked; - - } else if ( type === "select-multiple" ) { - val = elem.selectedIndex > -1 ? - jQuery.map( elem.options, function( elem ) { - return elem.selected; - }).join("-") : - ""; - - } else if ( jQuery.nodeName( elem, "select" ) ) { - val = elem.selectedIndex; - } - - return val; - }, - - testChange = function testChange( e ) { - var elem = e.target, data, val; - - if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) { - return; - } - - data = jQuery._data( elem, "_change_data" ); - val = getVal(elem); - - // the current data will be also retrieved by beforeactivate - if ( e.type !== "focusout" || elem.type !== "radio" ) { - jQuery._data( elem, "_change_data", val ); - } - - if ( data === undefined || val === data ) { - return; - } - - if ( data != null || val ) { - e.type = "change"; - e.liveFired = undefined; - jQuery.event.trigger( e, arguments[1], elem ); - } - }; - - jQuery.event.special.change = { - filters: { - focusout: testChange, - - beforedeactivate: testChange, - - click: function( e ) { - var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; - - if ( type === "radio" || type === "checkbox" || jQuery.nodeName( elem, "select" ) ) { - testChange.call( this, e ); - } - }, - - // Change has to be called before submit - // Keydown will be called before keypress, which is used in submit-event delegation - keydown: function( e ) { - var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; - - if ( (e.keyCode === 13 && !jQuery.nodeName( elem, "textarea" ) ) || - (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || - type === "select-multiple" ) { - testChange.call( this, e ); - } - }, - - // Beforeactivate happens also before the previous element is blurred - // with this event you can't trigger a change event, but you can store - // information - beforeactivate: function( e ) { - var elem = e.target; - jQuery._data( elem, "_change_data", getVal(elem) ); - } - }, - - setup: function( data, namespaces ) { - if ( this.type === "file" ) { - return false; - } - - for ( var type in changeFilters ) { - jQuery.event.add( this, type + ".specialChange", changeFilters[type] ); - } - - return rformElems.test( this.nodeName ); - }, - - teardown: function( namespaces ) { - jQuery.event.remove( this, ".specialChange" ); - - return rformElems.test( this.nodeName ); - } - }; - - changeFilters = jQuery.event.special.change.filters; - - // Handle when the input is .focus()'d - changeFilters.focus = changeFilters.beforeactivate; -} - -function trigger( type, elem, args ) { - // Piggyback on a donor event to simulate a different one. - // Fake originalEvent to avoid donor's stopPropagation, but if the - // simulated event prevents default then we do the same on the donor. - // Don't pass args or remember liveFired; they apply to the donor event. - var event = jQuery.extend( {}, args[ 0 ] ); - event.type = type; - event.originalEvent = {}; - event.liveFired = undefined; - jQuery.event.handle.call( elem, event ); - if ( event.isDefaultPrevented() ) { - args[ 0 ].preventDefault(); - } -} - -// Create "bubbling" focus and blur events -if ( !jQuery.support.focusinBubbles ) { - jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { - - // Attach a single capturing handler while someone wants focusin/focusout - var attaches = 0; - - jQuery.event.special[ fix ] = { - setup: function() { - if ( attaches++ === 0 ) { - document.addEventListener( orig, handler, true ); - } - }, - teardown: function() { - if ( --attaches === 0 ) { - document.removeEventListener( orig, handler, true ); - } - } - }; - - function handler( donor ) { - // Donor event is always a native one; fix it and switch its type. - // Let focusin/out handler cancel the donor focus/blur event. - var e = jQuery.event.fix( donor ); - e.type = fix; - e.originalEvent = {}; - jQuery.event.trigger( e, null, e.target ); - if ( e.isDefaultPrevented() ) { - donor.preventDefault(); - } - } - }); -} - -jQuery.each(["bind", "one"], function( i, name ) { - jQuery.fn[ name ] = function( type, data, fn ) { - var handler; - - // Handle object literals - if ( typeof type === "object" ) { - for ( var key in type ) { - this[ name ](key, data, type[key], fn); - } - return this; - } - - if ( arguments.length === 2 || data === false ) { - fn = data; - data = undefined; - } - - if ( name === "one" ) { - handler = function( event ) { - jQuery( this ).unbind( event, handler ); - return fn.apply( this, arguments ); - }; - handler.guid = fn.guid || jQuery.guid++; - } else { - handler = fn; - } - - if ( type === "unload" && name !== "one" ) { - this.one( type, data, fn ); - - } else { - for ( var i = 0, l = this.length; i < l; i++ ) { - jQuery.event.add( this[i], type, handler, data ); - } - } - - return this; - }; -}); - -jQuery.fn.extend({ - unbind: function( type, fn ) { - // Handle object literals - if ( typeof type === "object" && !type.preventDefault ) { - for ( var key in type ) { - this.unbind(key, type[key]); - } - - } else { - for ( var i = 0, l = this.length; i < l; i++ ) { - jQuery.event.remove( this[i], type, fn ); - } - } - - return this; - }, - - delegate: function( selector, types, data, fn ) { - return this.live( types, data, fn, selector ); - }, - - undelegate: function( selector, types, fn ) { - if ( arguments.length === 0 ) { - return this.unbind( "live" ); - - } else { - return this.die( types, null, fn, selector ); - } - }, - - trigger: function( type, data ) { - return this.each(function() { - jQuery.event.trigger( type, data, this ); - }); - }, - - triggerHandler: function( type, data ) { - if ( this[0] ) { - return jQuery.event.trigger( type, data, this[0], true ); - } - }, - - toggle: function( fn ) { - // Save reference to arguments for access in closure - var args = arguments, - guid = fn.guid || jQuery.guid++, - i = 0, - toggler = function( event ) { - // Figure out which function to execute - var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i; - jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 ); - - // Make sure that clicks stop - event.preventDefault(); - - // and execute the function - return args[ lastToggle ].apply( this, arguments ) || false; - }; - - // link all the functions, so any of them can unbind this click handler - toggler.guid = guid; - while ( i < args.length ) { - args[ i++ ].guid = guid; - } - - return this.click( toggler ); - }, - - hover: function( fnOver, fnOut ) { - return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); - } -}); - -var liveMap = { - focus: "focusin", - blur: "focusout", - mouseenter: "mouseover", - mouseleave: "mouseout" -}; - -jQuery.each(["live", "die"], function( i, name ) { - jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) { - var type, i = 0, match, namespaces, preType, - selector = origSelector || this.selector, - context = origSelector ? this : jQuery( this.context ); - - if ( typeof types === "object" && !types.preventDefault ) { - for ( var key in types ) { - context[ name ]( key, data, types[key], selector ); - } - - return this; - } - - if ( name === "die" && !types && - origSelector && origSelector.charAt(0) === "." ) { - - context.unbind( origSelector ); - - return this; - } - - if ( data === false || jQuery.isFunction( data ) ) { - fn = data || returnFalse; - data = undefined; - } - - types = (types || "").split(" "); - - while ( (type = types[ i++ ]) != null ) { - match = rnamespaces.exec( type ); - namespaces = ""; - - if ( match ) { - namespaces = match[0]; - type = type.replace( rnamespaces, "" ); - } - - if ( type === "hover" ) { - types.push( "mouseenter" + namespaces, "mouseleave" + namespaces ); - continue; - } - - preType = type; - - if ( liveMap[ type ] ) { - types.push( liveMap[ type ] + namespaces ); - type = type + namespaces; - - } else { - type = (liveMap[ type ] || type) + namespaces; - } - - if ( name === "live" ) { - // bind live handler - for ( var j = 0, l = context.length; j < l; j++ ) { - jQuery.event.add( context[j], "live." + liveConvert( type, selector ), - { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); - } - - } else { - // unbind live handler - context.unbind( "live." + liveConvert( type, selector ), fn ); - } - } - - return this; - }; -}); - -function liveHandler( event ) { - var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret, - elems = [], - selectors = [], - events = jQuery._data( this, "events" ); - - // Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911) - if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) { - return; - } - - if ( event.namespace ) { - namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)"); - } - - event.liveFired = this; - - var live = events.live.slice(0); - - for ( j = 0; j < live.length; j++ ) { - handleObj = live[j]; - - if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) { - selectors.push( handleObj.selector ); - - } else { - live.splice( j--, 1 ); - } - } - - match = jQuery( event.target ).closest( selectors, event.currentTarget ); - - for ( i = 0, l = match.length; i < l; i++ ) { - close = match[i]; - - for ( j = 0; j < live.length; j++ ) { - handleObj = live[j]; - - if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) { - elem = close.elem; - related = null; - - // Those two events require additional checking - if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { - event.type = handleObj.preType; - related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; - - // Make sure not to accidentally match a child element with the same selector - if ( related && jQuery.contains( elem, related ) ) { - related = elem; - } - } - - if ( !related || related !== elem ) { - elems.push({ elem: elem, handleObj: handleObj, level: close.level }); - } - } - } - } - - for ( i = 0, l = elems.length; i < l; i++ ) { - match = elems[i]; - - if ( maxLevel && match.level > maxLevel ) { - break; - } - - event.currentTarget = match.elem; - event.data = match.handleObj.data; - event.handleObj = match.handleObj; - - ret = match.handleObj.origHandler.apply( match.elem, arguments ); - - if ( ret === false || event.isPropagationStopped() ) { - maxLevel = match.level; - - if ( ret === false ) { - stop = false; - } - if ( event.isImmediatePropagationStopped() ) { - break; - } - } - } - - return stop; -} - -function liveConvert( type, selector ) { - return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspaces, "&"); -} - -jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + - "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + - "change select submit keydown keypress keyup error").split(" "), function( i, name ) { - - // Handle event binding - jQuery.fn[ name ] = function( data, fn ) { - if ( fn == null ) { - fn = data; - data = null; - } - - return arguments.length > 0 ? - this.bind( name, data, fn ) : - this.trigger( name ); - }; - - if ( jQuery.attrFn ) { - jQuery.attrFn[ name ] = true; - } -}); - - - -/*! - * Sizzle CSS Selector Engine - * Copyright 2011, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * More information: http://sizzlejs.com/ - */ -(function(){ - -var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, - done = 0, - toString = Object.prototype.toString, - hasDuplicate = false, - baseHasDuplicate = true, - rBackslash = /\\/g, - rNonWord = /\W/; - -// Here we check if the JavaScript engine is using some sort of -// optimization where it does not always call our comparision -// function. If that is the case, discard the hasDuplicate value. -// Thus far that includes Google Chrome. -[0, 0].sort(function() { - baseHasDuplicate = false; - return 0; -}); - -var Sizzle = function( selector, context, results, seed ) { - results = results || []; - context = context || document; - - var origContext = context; - - if ( context.nodeType !== 1 && context.nodeType !== 9 ) { - return []; - } - - if ( !selector || typeof selector !== "string" ) { - return results; - } - - var m, set, checkSet, extra, ret, cur, pop, i, - prune = true, - contextXML = Sizzle.isXML( context ), - parts = [], - soFar = selector; - - // Reset the position of the chunker regexp (start from head) - do { - chunker.exec( "" ); - m = chunker.exec( soFar ); - - if ( m ) { - soFar = m[3]; - - parts.push( m[1] ); - - if ( m[2] ) { - extra = m[3]; - break; - } - } - } while ( m ); - - if ( parts.length > 1 && origPOS.exec( selector ) ) { - - if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { - set = posProcess( parts[0] + parts[1], context ); - - } else { - set = Expr.relative[ parts[0] ] ? - [ context ] : - Sizzle( parts.shift(), context ); - - while ( parts.length ) { - selector = parts.shift(); - - if ( Expr.relative[ selector ] ) { - selector += parts.shift(); - } - - set = posProcess( selector, set ); - } - } - - } else { - // Take a shortcut and set the context if the root selector is an ID - // (but not if it'll be faster if the inner selector is an ID) - if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && - Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { - - ret = Sizzle.find( parts.shift(), context, contextXML ); - context = ret.expr ? - Sizzle.filter( ret.expr, ret.set )[0] : - ret.set[0]; - } - - if ( context ) { - ret = seed ? - { expr: parts.pop(), set: makeArray(seed) } : - Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); - - set = ret.expr ? - Sizzle.filter( ret.expr, ret.set ) : - ret.set; - - if ( parts.length > 0 ) { - checkSet = makeArray( set ); - - } else { - prune = false; - } - - while ( parts.length ) { - cur = parts.pop(); - pop = cur; - - if ( !Expr.relative[ cur ] ) { - cur = ""; - } else { - pop = parts.pop(); - } - - if ( pop == null ) { - pop = context; - } - - Expr.relative[ cur ]( checkSet, pop, contextXML ); - } - - } else { - checkSet = parts = []; - } - } - - if ( !checkSet ) { - checkSet = set; - } - - if ( !checkSet ) { - Sizzle.error( cur || selector ); - } - - if ( toString.call(checkSet) === "[object Array]" ) { - if ( !prune ) { - results.push.apply( results, checkSet ); - - } else if ( context && context.nodeType === 1 ) { - for ( i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { - results.push( set[i] ); - } - } - - } else { - for ( i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && checkSet[i].nodeType === 1 ) { - results.push( set[i] ); - } - } - } - - } else { - makeArray( checkSet, results ); - } - - if ( extra ) { - Sizzle( extra, origContext, results, seed ); - Sizzle.uniqueSort( results ); - } - - return results; -}; - -Sizzle.uniqueSort = function( results ) { - if ( sortOrder ) { - hasDuplicate = baseHasDuplicate; - results.sort( sortOrder ); - - if ( hasDuplicate ) { - for ( var i = 1; i < results.length; i++ ) { - if ( results[i] === results[ i - 1 ] ) { - results.splice( i--, 1 ); - } - } - } - } - - return results; -}; - -Sizzle.matches = function( expr, set ) { - return Sizzle( expr, null, null, set ); -}; - -Sizzle.matchesSelector = function( node, expr ) { - return Sizzle( expr, null, null, [node] ).length > 0; -}; - -Sizzle.find = function( expr, context, isXML ) { - var set; - - if ( !expr ) { - return []; - } - - for ( var i = 0, l = Expr.order.length; i < l; i++ ) { - var match, - type = Expr.order[i]; - - if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { - var left = match[1]; - match.splice( 1, 1 ); - - if ( left.substr( left.length - 1 ) !== "\\" ) { - match[1] = (match[1] || "").replace( rBackslash, "" ); - set = Expr.find[ type ]( match, context, isXML ); - - if ( set != null ) { - expr = expr.replace( Expr.match[ type ], "" ); - break; - } - } - } - } - - if ( !set ) { - set = typeof context.getElementsByTagName !== "undefined" ? - context.getElementsByTagName( "*" ) : - []; - } - - return { set: set, expr: expr }; -}; - -Sizzle.filter = function( expr, set, inplace, not ) { - var match, anyFound, - old = expr, - result = [], - curLoop = set, - isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); - - while ( expr && set.length ) { - for ( var type in Expr.filter ) { - if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { - var found, item, - filter = Expr.filter[ type ], - left = match[1]; - - anyFound = false; - - match.splice(1,1); - - if ( left.substr( left.length - 1 ) === "\\" ) { - continue; - } - - if ( curLoop === result ) { - result = []; - } - - if ( Expr.preFilter[ type ] ) { - match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); - - if ( !match ) { - anyFound = found = true; - - } else if ( match === true ) { - continue; - } - } - - if ( match ) { - for ( var i = 0; (item = curLoop[i]) != null; i++ ) { - if ( item ) { - found = filter( item, match, i, curLoop ); - var pass = not ^ !!found; - - if ( inplace && found != null ) { - if ( pass ) { - anyFound = true; - - } else { - curLoop[i] = false; - } - - } else if ( pass ) { - result.push( item ); - anyFound = true; - } - } - } - } - - if ( found !== undefined ) { - if ( !inplace ) { - curLoop = result; - } - - expr = expr.replace( Expr.match[ type ], "" ); - - if ( !anyFound ) { - return []; - } - - break; - } - } - } - - // Improper expression - if ( expr === old ) { - if ( anyFound == null ) { - Sizzle.error( expr ); - - } else { - break; - } - } - - old = expr; - } - - return curLoop; -}; - -Sizzle.error = function( msg ) { - throw "Syntax error, unrecognized expression: " + msg; -}; - -var Expr = Sizzle.selectors = { - order: [ "ID", "NAME", "TAG" ], - - match: { - ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, - CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, - NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, - ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, - TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, - CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, - POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, - PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ - }, - - leftMatch: {}, - - attrMap: { - "class": "className", - "for": "htmlFor" - }, - - attrHandle: { - href: function( elem ) { - return elem.getAttribute( "href" ); - }, - type: function( elem ) { - return elem.getAttribute( "type" ); - } - }, - - relative: { - "+": function(checkSet, part){ - var isPartStr = typeof part === "string", - isTag = isPartStr && !rNonWord.test( part ), - isPartStrNotTag = isPartStr && !isTag; - - if ( isTag ) { - part = part.toLowerCase(); - } - - for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { - if ( (elem = checkSet[i]) ) { - while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} - - checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? - elem || false : - elem === part; - } - } - - if ( isPartStrNotTag ) { - Sizzle.filter( part, checkSet, true ); - } - }, - - ">": function( checkSet, part ) { - var elem, - isPartStr = typeof part === "string", - i = 0, - l = checkSet.length; - - if ( isPartStr && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - - for ( ; i < l; i++ ) { - elem = checkSet[i]; - - if ( elem ) { - var parent = elem.parentNode; - checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; - } - } - - } else { - for ( ; i < l; i++ ) { - elem = checkSet[i]; - - if ( elem ) { - checkSet[i] = isPartStr ? - elem.parentNode : - elem.parentNode === part; - } - } - - if ( isPartStr ) { - Sizzle.filter( part, checkSet, true ); - } - } - }, - - "": function(checkSet, part, isXML){ - var nodeCheck, - doneName = done++, - checkFn = dirCheck; - - if ( typeof part === "string" && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } - - checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); - }, - - "~": function( checkSet, part, isXML ) { - var nodeCheck, - doneName = done++, - checkFn = dirCheck; - - if ( typeof part === "string" && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } - - checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); - } - }, - - find: { - ID: function( match, context, isXML ) { - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - return m && m.parentNode ? [m] : []; - } - }, - - NAME: function( match, context ) { - if ( typeof context.getElementsByName !== "undefined" ) { - var ret = [], - results = context.getElementsByName( match[1] ); - - for ( var i = 0, l = results.length; i < l; i++ ) { - if ( results[i].getAttribute("name") === match[1] ) { - ret.push( results[i] ); - } - } - - return ret.length === 0 ? null : ret; - } - }, - - TAG: function( match, context ) { - if ( typeof context.getElementsByTagName !== "undefined" ) { - return context.getElementsByTagName( match[1] ); - } - } - }, - preFilter: { - CLASS: function( match, curLoop, inplace, result, not, isXML ) { - match = " " + match[1].replace( rBackslash, "" ) + " "; - - if ( isXML ) { - return match; - } - - for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { - if ( elem ) { - if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { - if ( !inplace ) { - result.push( elem ); - } - - } else if ( inplace ) { - curLoop[i] = false; - } - } - } - - return false; - }, - - ID: function( match ) { - return match[1].replace( rBackslash, "" ); - }, - - TAG: function( match, curLoop ) { - return match[1].replace( rBackslash, "" ).toLowerCase(); - }, - - CHILD: function( match ) { - if ( match[1] === "nth" ) { - if ( !match[2] ) { - Sizzle.error( match[0] ); - } - - match[2] = match[2].replace(/^\+|\s*/g, ''); - - // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' - var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( - match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || - !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); - - // calculate the numbers (first)n+(last) including if they are negative - match[2] = (test[1] + (test[2] || 1)) - 0; - match[3] = test[3] - 0; - } - else if ( match[2] ) { - Sizzle.error( match[0] ); - } - - // TODO: Move to normal caching system - match[0] = done++; - - return match; - }, - - ATTR: function( match, curLoop, inplace, result, not, isXML ) { - var name = match[1] = match[1].replace( rBackslash, "" ); - - if ( !isXML && Expr.attrMap[name] ) { - match[1] = Expr.attrMap[name]; - } - - // Handle if an un-quoted value was used - match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); - - if ( match[2] === "~=" ) { - match[4] = " " + match[4] + " "; - } - - return match; - }, - - PSEUDO: function( match, curLoop, inplace, result, not ) { - if ( match[1] === "not" ) { - // If we're dealing with a complex expression, or a simple one - if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { - match[3] = Sizzle(match[3], null, null, curLoop); - - } else { - var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); - - if ( !inplace ) { - result.push.apply( result, ret ); - } - - return false; - } - - } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { - return true; - } - - return match; - }, - - POS: function( match ) { - match.unshift( true ); - - return match; - } - }, - - filters: { - enabled: function( elem ) { - return elem.disabled === false && elem.type !== "hidden"; - }, - - disabled: function( elem ) { - return elem.disabled === true; - }, - - checked: function( elem ) { - return elem.checked === true; - }, - - selected: function( elem ) { - // Accessing this property makes selected-by-default - // options in Safari work properly - if ( elem.parentNode ) { - elem.parentNode.selectedIndex; - } - - return elem.selected === true; - }, - - parent: function( elem ) { - return !!elem.firstChild; - }, - - empty: function( elem ) { - return !elem.firstChild; - }, - - has: function( elem, i, match ) { - return !!Sizzle( match[3], elem ).length; - }, - - header: function( elem ) { - return (/h\d/i).test( elem.nodeName ); - }, - - text: function( elem ) { - var attr = elem.getAttribute( "type" ), type = elem.type; - // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) - // use getAttribute instead to test this case - return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); - }, - - radio: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; - }, - - checkbox: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; - }, - - file: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; - }, - - password: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; - }, - - submit: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && "submit" === elem.type; - }, - - image: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; - }, - - reset: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && "reset" === elem.type; - }, - - button: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && "button" === elem.type || name === "button"; - }, - - input: function( elem ) { - return (/input|select|textarea|button/i).test( elem.nodeName ); - }, - - focus: function( elem ) { - return elem === elem.ownerDocument.activeElement; - } - }, - setFilters: { - first: function( elem, i ) { - return i === 0; - }, - - last: function( elem, i, match, array ) { - return i === array.length - 1; - }, - - even: function( elem, i ) { - return i % 2 === 0; - }, - - odd: function( elem, i ) { - return i % 2 === 1; - }, - - lt: function( elem, i, match ) { - return i < match[3] - 0; - }, - - gt: function( elem, i, match ) { - return i > match[3] - 0; - }, - - nth: function( elem, i, match ) { - return match[3] - 0 === i; - }, - - eq: function( elem, i, match ) { - return match[3] - 0 === i; - } - }, - filter: { - PSEUDO: function( elem, match, i, array ) { - var name = match[1], - filter = Expr.filters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - - } else if ( name === "contains" ) { - return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0; - - } else if ( name === "not" ) { - var not = match[3]; - - for ( var j = 0, l = not.length; j < l; j++ ) { - if ( not[j] === elem ) { - return false; - } - } - - return true; - - } else { - Sizzle.error( name ); - } - }, - - CHILD: function( elem, match ) { - var type = match[1], - node = elem; - - switch ( type ) { - case "only": - case "first": - while ( (node = node.previousSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } - } - - if ( type === "first" ) { - return true; - } - - node = elem; - - case "last": - while ( (node = node.nextSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } - } - - return true; - - case "nth": - var first = match[2], - last = match[3]; - - if ( first === 1 && last === 0 ) { - return true; - } - - var doneName = match[0], - parent = elem.parentNode; - - if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { - var count = 0; - - for ( node = parent.firstChild; node; node = node.nextSibling ) { - if ( node.nodeType === 1 ) { - node.nodeIndex = ++count; - } - } - - parent.sizcache = doneName; - } - - var diff = elem.nodeIndex - last; - - if ( first === 0 ) { - return diff === 0; - - } else { - return ( diff % first === 0 && diff / first >= 0 ); - } - } - }, - - ID: function( elem, match ) { - return elem.nodeType === 1 && elem.getAttribute("id") === match; - }, - - TAG: function( elem, match ) { - return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; - }, - - CLASS: function( elem, match ) { - return (" " + (elem.className || elem.getAttribute("class")) + " ") - .indexOf( match ) > -1; - }, - - ATTR: function( elem, match ) { - var name = match[1], - result = Expr.attrHandle[ name ] ? - Expr.attrHandle[ name ]( elem ) : - elem[ name ] != null ? - elem[ name ] : - elem.getAttribute( name ), - value = result + "", - type = match[2], - check = match[4]; - - return result == null ? - type === "!=" : - type === "=" ? - value === check : - type === "*=" ? - value.indexOf(check) >= 0 : - type === "~=" ? - (" " + value + " ").indexOf(check) >= 0 : - !check ? - value && result !== false : - type === "!=" ? - value !== check : - type === "^=" ? - value.indexOf(check) === 0 : - type === "$=" ? - value.substr(value.length - check.length) === check : - type === "|=" ? - value === check || value.substr(0, check.length + 1) === check + "-" : - false; - }, - - POS: function( elem, match, i, array ) { - var name = match[2], - filter = Expr.setFilters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - } - } - } -}; - -var origPOS = Expr.match.POS, - fescape = function(all, num){ - return "\\" + (num - 0 + 1); - }; - -for ( var type in Expr.match ) { - Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); - Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); -} - -var makeArray = function( array, results ) { - array = Array.prototype.slice.call( array, 0 ); - - if ( results ) { - results.push.apply( results, array ); - return results; - } - - return array; -}; - -// Perform a simple check to determine if the browser is capable of -// converting a NodeList to an array using builtin methods. -// Also verifies that the returned array holds DOM nodes -// (which is not the case in the Blackberry browser) -try { - Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; - -// Provide a fallback method if it does not work -} catch( e ) { - makeArray = function( array, results ) { - var i = 0, - ret = results || []; - - if ( toString.call(array) === "[object Array]" ) { - Array.prototype.push.apply( ret, array ); - - } else { - if ( typeof array.length === "number" ) { - for ( var l = array.length; i < l; i++ ) { - ret.push( array[i] ); - } - - } else { - for ( ; array[i]; i++ ) { - ret.push( array[i] ); - } - } - } - - return ret; - }; -} - -var sortOrder, siblingCheck; - -if ( document.documentElement.compareDocumentPosition ) { - sortOrder = function( a, b ) { - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { - return a.compareDocumentPosition ? -1 : 1; - } - - return a.compareDocumentPosition(b) & 4 ? -1 : 1; - }; - -} else { - sortOrder = function( a, b ) { - // The nodes are identical, we can exit early - if ( a === b ) { - hasDuplicate = true; - return 0; - - // Fallback to using sourceIndex (in IE) if it's available on both nodes - } else if ( a.sourceIndex && b.sourceIndex ) { - return a.sourceIndex - b.sourceIndex; - } - - var al, bl, - ap = [], - bp = [], - aup = a.parentNode, - bup = b.parentNode, - cur = aup; - - // If the nodes are siblings (or identical) we can do a quick check - if ( aup === bup ) { - return siblingCheck( a, b ); - - // If no parents were found then the nodes are disconnected - } else if ( !aup ) { - return -1; - - } else if ( !bup ) { - return 1; - } - - // Otherwise they're somewhere else in the tree so we need - // to build up a full list of the parentNodes for comparison - while ( cur ) { - ap.unshift( cur ); - cur = cur.parentNode; - } - - cur = bup; - - while ( cur ) { - bp.unshift( cur ); - cur = cur.parentNode; - } - - al = ap.length; - bl = bp.length; - - // Start walking down the tree looking for a discrepancy - for ( var i = 0; i < al && i < bl; i++ ) { - if ( ap[i] !== bp[i] ) { - return siblingCheck( ap[i], bp[i] ); - } - } - - // We ended someplace up the tree so do a sibling check - return i === al ? - siblingCheck( a, bp[i], -1 ) : - siblingCheck( ap[i], b, 1 ); - }; - - siblingCheck = function( a, b, ret ) { - if ( a === b ) { - return ret; - } - - var cur = a.nextSibling; - - while ( cur ) { - if ( cur === b ) { - return -1; - } - - cur = cur.nextSibling; - } - - return 1; - }; -} - -// Utility function for retreiving the text value of an array of DOM nodes -Sizzle.getText = function( elems ) { - var ret = "", elem; - - for ( var i = 0; elems[i]; i++ ) { - elem = elems[i]; - - // Get the text from text nodes and CDATA nodes - if ( elem.nodeType === 3 || elem.nodeType === 4 ) { - ret += elem.nodeValue; - - // Traverse everything else, except comment nodes - } else if ( elem.nodeType !== 8 ) { - ret += Sizzle.getText( elem.childNodes ); - } - } - - return ret; -}; - -// Check to see if the browser returns elements by name when -// querying by getElementById (and provide a workaround) -(function(){ - // We're going to inject a fake input element with a specified name - var form = document.createElement("div"), - id = "script" + (new Date()).getTime(), - root = document.documentElement; - - form.innerHTML = ""; - - // Inject it into the root element, check its status, and remove it quickly - root.insertBefore( form, root.firstChild ); - - // The workaround has to do additional checks after a getElementById - // Which slows things down for other browsers (hence the branching) - if ( document.getElementById( id ) ) { - Expr.find.ID = function( match, context, isXML ) { - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - - return m ? - m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? - [m] : - undefined : - []; - } - }; - - Expr.filter.ID = function( elem, match ) { - var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); - - return elem.nodeType === 1 && node && node.nodeValue === match; - }; - } - - root.removeChild( form ); - - // release memory in IE - root = form = null; -})(); - -(function(){ - // Check to see if the browser returns only elements - // when doing getElementsByTagName("*") - - // Create a fake element - var div = document.createElement("div"); - div.appendChild( document.createComment("") ); - - // Make sure no comments are found - if ( div.getElementsByTagName("*").length > 0 ) { - Expr.find.TAG = function( match, context ) { - var results = context.getElementsByTagName( match[1] ); - - // Filter out possible comments - if ( match[1] === "*" ) { - var tmp = []; - - for ( var i = 0; results[i]; i++ ) { - if ( results[i].nodeType === 1 ) { - tmp.push( results[i] ); - } - } - - results = tmp; - } - - return results; - }; - } - - // Check to see if an attribute returns normalized href attributes - div.innerHTML = ""; - - if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && - div.firstChild.getAttribute("href") !== "#" ) { - - Expr.attrHandle.href = function( elem ) { - return elem.getAttribute( "href", 2 ); - }; - } - - // release memory in IE - div = null; -})(); - -if ( document.querySelectorAll ) { - (function(){ - var oldSizzle = Sizzle, - div = document.createElement("div"), - id = "__sizzle__"; - - div.innerHTML = "

"; - - // Safari can't handle uppercase or unicode characters when - // in quirks mode. - if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { - return; - } - - Sizzle = function( query, context, extra, seed ) { - context = context || document; - - // Only use querySelectorAll on non-XML documents - // (ID selectors don't work in non-HTML documents) - if ( !seed && !Sizzle.isXML(context) ) { - // See if we find a selector to speed up - var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); - - if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { - // Speed-up: Sizzle("TAG") - if ( match[1] ) { - return makeArray( context.getElementsByTagName( query ), extra ); - - // Speed-up: Sizzle(".CLASS") - } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { - return makeArray( context.getElementsByClassName( match[2] ), extra ); - } - } - - if ( context.nodeType === 9 ) { - // Speed-up: Sizzle("body") - // The body element only exists once, optimize finding it - if ( query === "body" && context.body ) { - return makeArray( [ context.body ], extra ); - - // Speed-up: Sizzle("#ID") - } else if ( match && match[3] ) { - var elem = context.getElementById( match[3] ); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE and Opera return items - // by name instead of ID - if ( elem.id === match[3] ) { - return makeArray( [ elem ], extra ); - } - - } else { - return makeArray( [], extra ); - } - } - - try { - return makeArray( context.querySelectorAll(query), extra ); - } catch(qsaError) {} - - // qSA works strangely on Element-rooted queries - // We can work around this by specifying an extra ID on the root - // and working up from there (Thanks to Andrew Dupont for the technique) - // IE 8 doesn't work on object elements - } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { - var oldContext = context, - old = context.getAttribute( "id" ), - nid = old || id, - hasParent = context.parentNode, - relativeHierarchySelector = /^\s*[+~]/.test( query ); - - if ( !old ) { - context.setAttribute( "id", nid ); - } else { - nid = nid.replace( /'/g, "\\$&" ); - } - if ( relativeHierarchySelector && hasParent ) { - context = context.parentNode; - } - - try { - if ( !relativeHierarchySelector || hasParent ) { - return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); - } - - } catch(pseudoError) { - } finally { - if ( !old ) { - oldContext.removeAttribute( "id" ); - } - } - } - } - - return oldSizzle(query, context, extra, seed); - }; - - for ( var prop in oldSizzle ) { - Sizzle[ prop ] = oldSizzle[ prop ]; - } - - // release memory in IE - div = null; - })(); -} - -(function(){ - var html = document.documentElement, - matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; - - if ( matches ) { - // Check to see if it's possible to do matchesSelector - // on a disconnected node (IE 9 fails this) - var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), - pseudoWorks = false; - - try { - // This should fail with an exception - // Gecko does not error, returns false instead - matches.call( document.documentElement, "[test!='']:sizzle" ); - - } catch( pseudoError ) { - pseudoWorks = true; - } - - Sizzle.matchesSelector = function( node, expr ) { - // Make sure that attribute selectors are quoted - expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); - - if ( !Sizzle.isXML( node ) ) { - try { - if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { - var ret = matches.call( node, expr ); - - // IE 9's matchesSelector returns false on disconnected nodes - if ( ret || !disconnectedMatch || - // As well, disconnected nodes are said to be in a document - // fragment in IE 9, so check for that - node.document && node.document.nodeType !== 11 ) { - return ret; - } - } - } catch(e) {} - } - - return Sizzle(expr, null, null, [node]).length > 0; - }; - } -})(); - -(function(){ - var div = document.createElement("div"); - - div.innerHTML = "
"; - - // Opera can't find a second classname (in 9.6) - // Also, make sure that getElementsByClassName actually exists - if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { - return; - } - - // Safari caches class attributes, doesn't catch changes (in 3.2) - div.lastChild.className = "e"; - - if ( div.getElementsByClassName("e").length === 1 ) { - return; - } - - Expr.order.splice(1, 0, "CLASS"); - Expr.find.CLASS = function( match, context, isXML ) { - if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { - return context.getElementsByClassName(match[1]); - } - }; - - // release memory in IE - div = null; -})(); - -function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - - if ( elem ) { - var match = false; - - elem = elem[dir]; - - while ( elem ) { - if ( elem.sizcache === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 && !isXML ){ - elem.sizcache = doneName; - elem.sizset = i; - } - - if ( elem.nodeName.toLowerCase() === cur ) { - match = elem; - break; - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } -} - -function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - - if ( elem ) { - var match = false; - - elem = elem[dir]; - - while ( elem ) { - if ( elem.sizcache === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 ) { - if ( !isXML ) { - elem.sizcache = doneName; - elem.sizset = i; - } - - if ( typeof cur !== "string" ) { - if ( elem === cur ) { - match = true; - break; - } - - } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { - match = elem; - break; - } - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } -} - -if ( document.documentElement.contains ) { - Sizzle.contains = function( a, b ) { - return a !== b && (a.contains ? a.contains(b) : true); - }; - -} else if ( document.documentElement.compareDocumentPosition ) { - Sizzle.contains = function( a, b ) { - return !!(a.compareDocumentPosition(b) & 16); - }; - -} else { - Sizzle.contains = function() { - return false; - }; -} - -Sizzle.isXML = function( elem ) { - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; - - return documentElement ? documentElement.nodeName !== "HTML" : false; -}; - -var posProcess = function( selector, context ) { - var match, - tmpSet = [], - later = "", - root = context.nodeType ? [context] : context; - - // Position selectors must be done after the filter - // And so must :not(positional) so we move all PSEUDOs to the end - while ( (match = Expr.match.PSEUDO.exec( selector )) ) { - later += match[0]; - selector = selector.replace( Expr.match.PSEUDO, "" ); - } - - selector = Expr.relative[selector] ? selector + "*" : selector; - - for ( var i = 0, l = root.length; i < l; i++ ) { - Sizzle( selector, root[i], tmpSet ); - } - - return Sizzle.filter( later, tmpSet ); -}; - -// EXPOSE -jQuery.find = Sizzle; -jQuery.expr = Sizzle.selectors; -jQuery.expr[":"] = jQuery.expr.filters; -jQuery.unique = Sizzle.uniqueSort; -jQuery.text = Sizzle.getText; -jQuery.isXMLDoc = Sizzle.isXML; -jQuery.contains = Sizzle.contains; - - -})(); - - -var runtil = /Until$/, - rparentsprev = /^(?:parents|prevUntil|prevAll)/, - // Note: This RegExp should be improved, or likely pulled from Sizzle - rmultiselector = /,/, - isSimple = /^.[^:#\[\.,]*$/, - slice = Array.prototype.slice, - POS = jQuery.expr.match.POS, - // methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; - -jQuery.fn.extend({ - find: function( selector ) { - var self = this, - i, l; - - if ( typeof selector !== "string" ) { - return jQuery( selector ).filter(function() { - for ( i = 0, l = self.length; i < l; i++ ) { - if ( jQuery.contains( self[ i ], this ) ) { - return true; - } - } - }); - } - - var ret = this.pushStack( "", "find", selector ), - length, n, r; - - for ( i = 0, l = this.length; i < l; i++ ) { - length = ret.length; - jQuery.find( selector, this[i], ret ); - - if ( i > 0 ) { - // Make sure that the results are unique - for ( n = length; n < ret.length; n++ ) { - for ( r = 0; r < length; r++ ) { - if ( ret[r] === ret[n] ) { - ret.splice(n--, 1); - break; - } - } - } - } - } - - return ret; - }, - - has: function( target ) { - var targets = jQuery( target ); - return this.filter(function() { - for ( var i = 0, l = targets.length; i < l; i++ ) { - if ( jQuery.contains( this, targets[i] ) ) { - return true; - } - } - }); - }, - - not: function( selector ) { - return this.pushStack( winnow(this, selector, false), "not", selector); - }, - - filter: function( selector ) { - return this.pushStack( winnow(this, selector, true), "filter", selector ); - }, - - is: function( selector ) { - return !!selector && ( typeof selector === "string" ? - jQuery.filter( selector, this ).length > 0 : - this.filter( selector ).length > 0 ); - }, - - closest: function( selectors, context ) { - var ret = [], i, l, cur = this[0]; - - // Array - if ( jQuery.isArray( selectors ) ) { - var match, selector, - matches = {}, - level = 1; - - if ( cur && selectors.length ) { - for ( i = 0, l = selectors.length; i < l; i++ ) { - selector = selectors[i]; - - if ( !matches[ selector ] ) { - matches[ selector ] = POS.test( selector ) ? - jQuery( selector, context || this.context ) : - selector; - } - } - - while ( cur && cur.ownerDocument && cur !== context ) { - for ( selector in matches ) { - match = matches[ selector ]; - - if ( match.jquery ? match.index( cur ) > -1 : jQuery( cur ).is( match ) ) { - ret.push({ selector: selector, elem: cur, level: level }); - } - } - - cur = cur.parentNode; - level++; - } - } - - return ret; - } - - // String - var pos = POS.test( selectors ) || typeof selectors !== "string" ? - jQuery( selectors, context || this.context ) : - 0; - - for ( i = 0, l = this.length; i < l; i++ ) { - cur = this[i]; - - while ( cur ) { - if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { - ret.push( cur ); - break; - - } else { - cur = cur.parentNode; - if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { - break; - } - } - } - } - - ret = ret.length > 1 ? jQuery.unique( ret ) : ret; - - return this.pushStack( ret, "closest", selectors ); - }, - - // Determine the position of an element within - // the matched set of elements - index: function( elem ) { - if ( !elem || typeof elem === "string" ) { - return jQuery.inArray( this[0], - // If it receives a string, the selector is used - // If it receives nothing, the siblings are used - elem ? jQuery( elem ) : this.parent().children() ); - } - // Locate the position of the desired element - return jQuery.inArray( - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[0] : elem, this ); - }, - - add: function( selector, context ) { - var set = typeof selector === "string" ? - jQuery( selector, context ) : - jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), - all = jQuery.merge( this.get(), set ); - - return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? - all : - jQuery.unique( all ) ); - }, - - andSelf: function() { - return this.add( this.prevObject ); - } -}); - -// A painfully simple check to see if an element is disconnected -// from a document (should be improved, where feasible). -function isDisconnected( node ) { - return !node || !node.parentNode || node.parentNode.nodeType === 11; -} - -jQuery.each({ - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return jQuery.dir( elem, "parentNode" ); - }, - parentsUntil: function( elem, i, until ) { - return jQuery.dir( elem, "parentNode", until ); - }, - next: function( elem ) { - return jQuery.nth( elem, 2, "nextSibling" ); - }, - prev: function( elem ) { - return jQuery.nth( elem, 2, "previousSibling" ); - }, - nextAll: function( elem ) { - return jQuery.dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return jQuery.dir( elem, "previousSibling" ); - }, - nextUntil: function( elem, i, until ) { - return jQuery.dir( elem, "nextSibling", until ); - }, - prevUntil: function( elem, i, until ) { - return jQuery.dir( elem, "previousSibling", until ); - }, - siblings: function( elem ) { - return jQuery.sibling( elem.parentNode.firstChild, elem ); - }, - children: function( elem ) { - return jQuery.sibling( elem.firstChild ); - }, - contents: function( elem ) { - return jQuery.nodeName( elem, "iframe" ) ? - elem.contentDocument || elem.contentWindow.document : - jQuery.makeArray( elem.childNodes ); - } -}, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var ret = jQuery.map( this, fn, until ), - // The variable 'args' was introduced in - // https://github.com/jquery/jquery/commit/52a0238 - // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed. - // http://code.google.com/p/v8/issues/detail?id=1050 - args = slice.call(arguments); - - if ( !runtil.test( name ) ) { - selector = until; - } - - if ( selector && typeof selector === "string" ) { - ret = jQuery.filter( selector, ret ); - } - - ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; - - if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { - ret = ret.reverse(); - } - - return this.pushStack( ret, name, args.join(",") ); - }; -}); - -jQuery.extend({ - filter: function( expr, elems, not ) { - if ( not ) { - expr = ":not(" + expr + ")"; - } - - return elems.length === 1 ? - jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : - jQuery.find.matches(expr, elems); - }, - - dir: function( elem, dir, until ) { - var matched = [], - cur = elem[ dir ]; - - while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { - if ( cur.nodeType === 1 ) { - matched.push( cur ); - } - cur = cur[dir]; - } - return matched; - }, - - nth: function( cur, result, dir, elem ) { - result = result || 1; - var num = 0; - - for ( ; cur; cur = cur[dir] ) { - if ( cur.nodeType === 1 && ++num === result ) { - break; - } - } - - return cur; - }, - - sibling: function( n, elem ) { - var r = []; - - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - r.push( n ); - } - } - - return r; - } -}); - -// Implement the identical functionality for filter and not -function winnow( elements, qualifier, keep ) { - - // Can't pass null or undefined to indexOf in Firefox 4 - // Set to 0 to skip string check - qualifier = qualifier || 0; - - if ( jQuery.isFunction( qualifier ) ) { - return jQuery.grep(elements, function( elem, i ) { - var retVal = !!qualifier.call( elem, i, elem ); - return retVal === keep; - }); - - } else if ( qualifier.nodeType ) { - return jQuery.grep(elements, function( elem, i ) { - return (elem === qualifier) === keep; - }); - - } else if ( typeof qualifier === "string" ) { - var filtered = jQuery.grep(elements, function( elem ) { - return elem.nodeType === 1; - }); - - if ( isSimple.test( qualifier ) ) { - return jQuery.filter(qualifier, filtered, !keep); - } else { - qualifier = jQuery.filter( qualifier, filtered ); - } - } - - return jQuery.grep(elements, function( elem, i ) { - return (jQuery.inArray( elem, qualifier ) >= 0) === keep; - }); -} - - - - -var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, - rleadingWhitespace = /^\s+/, - rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, - rtagName = /<([\w:]+)/, - rtbody = /", "" ], - legend: [ 1, "
", "
" ], - thead: [ 1, "", "
" ], - tr: [ 2, "", "
" ], - td: [ 3, "", "
" ], - col: [ 2, "", "
" ], - area: [ 1, "", "" ], - _default: [ 0, "", "" ] - }; - -wrapMap.optgroup = wrapMap.option; -wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; -wrapMap.th = wrapMap.td; - -// IE can't serialize and