### Navigation

- index
- modules |
- next |
- previous |
- PyV8 v1.0beta documentation »
- Public API »

# Javascript Engine

Besides to execute a Javascript code with `JSContext.eval()`, you could create a new `JSEngine` instance and compile the Javascript code with `JSEngine.compile()` before execute it. A `JSScript` object will be returned, and you could run it later with `JSScript.run()` method many times, or visit its AST [1] with `JSScript.visit()`.

`JSEngine` also contains some static properties and methods for the global v8 engine, for example:

Property or Method | Description
--- | ---
`JSEngine.version` | Get the compiled v8 version
`JSEngine.dead` | Check if V8 is dead and therefore unusable
`JSEngine.collect()` | Force a full garbage collection
`JSEngine.dispose()` | Releases any resources used by v8
`JSEngine.currentThreadId` | Get the current v8 thread id
`JSEngine.terminateAllThreads()` | Forcefully terminate the current JavaScript thread
`JSEngine.terminateThread()` | Forcefully terminate execution of a JavaScript thread

## Compile Script and Control Engine

When you use `JSEngine.compile()` compile a Javascript code, the v8 engine will parse the sytanx and store the AST in a `JSScript` object. You could execute it with `JSScript.run()` or access the source code with `JSScript.source` later.

    with JSContext() as ctxt:
        with JSEngine() as engine:
            s = engine.compile("1+2")

            print s.source # "1+2"
            print s.run()  # 3

You could only parse the sytanx with `JSEngine.precompile()` before use it, which return a `buffer` object contains some internal data. The buffer can’t be executed directly, but could be used as the precompied parameter when call the `JSEngine.compile()` later and improve the performance.

    with JSContext() as ctxt:
        with JSEngine() as engine:
            buf = engine.precompile("1+2")

            # do something

            s = engine.compile("1+2", precompiled=buf) # use the parsed data to improve performancee

            print s.source # "1+2"
            print s.run()  # 3

If you need reuse the script in different contexts, you could refer to the Reuseable Extension.

## JSEngine - the backend Javascript engine

class `PyV8.``JSEngine`
  `compile`(source, name='', line=-1, col=-1, precompiled=None) → JSScript object

    compile( (JSEngine)arg1, (str)source [, (str)name=’’ [, (int)line=-1 [, (int)col=-1 [, (object)precompiled=None]]]]) -> JSScript :

    > C++ signature :
    >   class boost::shared_ptr<class CScript> compile(class CEngine {lvalue},class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > [,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >=’’ [,int=-1 [,int=-1 [,class boost::python::api::object=None]]]])

    compile( (JSEngine)arg1, (unicode)source [, (unicode)name=u’’ [, (int)line=-1 [, (int)col=-1 [, (object)precompiled=None]]]]) -> JSScript :

    > C++ signature :
    >   class boost::shared_ptr<class CScript> compile(class CEngine {lvalue},class std::basic_string<wchar_t,struct std::char_traits<wchar_t>,class std::allocator<wchar_t> > [,class std::basic_string<wchar_t,struct std::char_traits<wchar_t>,class std::allocator<wchar_t> >=u’’ [,int=-1 [,int=-1 [,class boost::python::api::object=None]]]])

    Compile the Javascript code to a `JSScript` object, which could be execute many times or visit it’s AST.

    Parameters: | source (str or unicode) – the Javascript code name (str) – the name of the Javascript code line (integer) – the start line number of the Javascript code col (integer) – the start column number of the Javascript code precompiled (buffer) – the precompiled buffer of Javascript code
    Return type: | a compiled `JSScript` object

  `precompile`(source) → buffer object

    precompile( (JSEngine)arg1, (str)source) -> object :

    > C++ signature :
    >   class boost::python::api::object precompile(class CEngine {lvalue},class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)

    precompile( (JSEngine)arg1, (unicode)source) -> object :

    > C++ signature :
    >   class boost::python::api::object precompile(class CEngine {lvalue},class std::basic_string<wchar_t,struct std::char_traits<wchar_t>,class std::allocator<wchar_t> >)

    Precompile the Javascript code to an internal buffer, which could be used to improve the performance when compile the same script later.

    Parameters: | source (str or unicode) – the Javascript code
    Return type: | a buffer object contains the precompiled internal data

  `__enter__`() → JSEngine object
  `__exit__`(exc_type, exc_value, traceback) → None
  `version`

    Get the V8 engine version

  `dead`

    Check if V8 is dead and therefore unusable.

  `currentThreadId`

    The V8 thread id of the calling thread.

  `collect`()
    collect([ (bool)force=True]) -> None :

      Performs a full garbage collection. Force compaction if the parameter is true.

      C++ signature :
        void collect([ bool=True])
  `dispose`()
    dispose() -> bool :

      Releases any resources used by v8 and stops any utility threads that may be running. Note that disposing v8 is permanent, it cannot be reinitialized.

      C++ signature :
        bool dispose()
  `idle`()
    idle() -> bool :

      Optional notification that the embedder is idle.

      C++ signature :
        bool idle()
  `lowMemory`()
    lowMemory() -> None :

      Optional notification that the system is running low on memory.

      C++ signature :
        void lowMemory()
  `setFlags`()
    setFlags( (str)arg1) -> None :

      Sets V8 flags from a string.

      C++ signature :
        void setFlags(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)
  `setMemoryAllocationCallback`()
    setMemoryAllocationCallback( (object)callback [, (JSObjectSpace)space=_PyV8.JSObjectSpace.All [, (JSAllocationAction)action=_PyV8.JSAllocationAction.all]]) -> None :

      Enables the host application to provide a mechanism to be notified and perform custom logging when V8 Allocates Executable Memory.

      C++ signature :
        void setMemoryAllocationCallback(class boost::python::api::object [,enum v8::ObjectSpace=_PyV8.JSObjectSpace.All [,enum v8::AllocationAction=_PyV8.JSAllocationAction.all]])
  `setMemoryLimit`()
    setMemoryLimit([ (int)max_young_space_size=0 [, (int)max_old_space_size=0 [, (int)max_executable_size=0]]]) -> bool :

      Specifies the limits of the runtime’s memory use.You must set the heap size before initializing the VMthe size cannot be adjusted after the VM is initialized.

      C++ signature :
        bool setMemoryLimit([ int=0 [,int=0 [,int=0]]])
  `terminateAllThreads`()
    terminateAllThreads() -> None :

      Forcefully terminate the current thread of JavaScript execution.

      C++ signature :
        void terminateAllThreads()
  `terminateThread`()
    terminateThread( (int)thread_id) -> None :

      Forcefully terminate execution of a JavaScript thread.

      C++ signature :
        void terminateThread(int)

## JSScript - the compiled script

class `PyV8.``JSScript`

  JSScript is a compiled JavaScript script.

  `run`() → object
    run( (JSScript)arg1) -> object :

      Execute the compiled code.

      C++ signature :
        class boost::python::api::object run(class CScript {lvalue})
  `visit`(handler) → None
    visit( (JSScript)arg1, (object)handler) -> None :

      Visit the AST of code with the callback handler.

      C++ signature :
        void visit(class CScript {lvalue},class boost::python::api::object)

    Please refer to the Javascript AST (Abstract Syntax Tree) page for more detail.

  `source`

    the source code

Footnotes

[1] | Abstract Syntax Tree (AST) is a tree representation of the abstract syntactic structure of source code written in a programming language. Each node of the tree denotes a construct occurring in the source code. The syntax is ‘abstract’ in the sense that it does not represent every detail that appears in the real syntax. For instance, grouping parentheses are implicit in the tree structure, and a syntactic construct such as an if-condition-then expression may be denoted by a single node with two branches.

### Navigation

- index
- modules |
- next |
- previous |
- PyV8 v1.0beta documentation »
- Public API »