Compiling

Automatic defaults

If you compile Duktape with no compiler options, Duktape will detect the compiler and the platform automatically and select defaults appropriate in most cases.

The default features are, at a high level:

Feature options (DUK_OPT_xxx)

If you wish to modify the defaults, you can provide feature options in the form of DUK_OPT_xxx compiler defines. These will be taken into account by the internal duk_features.h file, which resolves the final internal features based on feature requests, compiler features, and platform features.

The available feature options can be found in duk_features.h. The table below summarizes the available options, in no particular order:

Define Description
DUK_OPT_NO_PACKED_TVAL Don't use the packed 8-byte internal value representation even if otherwise possible. The packed representation has more platform/compiler portability issues than the unpacked one.
DUK_OPT_NO_REFERENCE_COUNTING Disable reference counting and use only mark-and-sweep for garbage collection. Although this reduces memory footprint of heap objects, the downside is much more fluctuation in memory usage.
DUK_OPT_NO_MARK_AND_SWEEP Disable mark-and-sweep and use only reference counting for garbage collection. This reduces code footprint and eliminates garbage collection pauses, but objects participating in unreachable reference cycles won't be collected until the Duktape heap is destroyed. In particular, function instances won't be collected because they're always in a reference cycle with their default prototype object. Unreachable objects are collected if you break reference cycles manually (and are always freed when a heap is destroyed).
DUK_OPT_NO_VOLUNTARY_GC Disable voluntary periodic mark-and-sweep collection. A mark-and-sweep collection is still triggered in an out-of-memory condition. This option should usually be combined with reference counting, which collects all non-cyclical garbage. Application code should also request an explicit garbage collection from time to time when appropriate. When this option is used, Duktape will have no garbage collection pauses in ordinary use, which is useful for timing sensitive applications like games.
DUK_OPT_NO_MS_STRINGTABLE_RESIZE Disable forced string intern table resize during mark-and-sweep garbage collection. This may be useful when reference counting is disabled, as mark-and-sweep collections will be more frequent and thus more expensive.
DUK_OPT_GC_TORTURE Development time option: force full mark-and-sweep on every allocation to stress test memory management.
DUK_OPT_NO_AUGMENT_ERRORS Don't augment Ecmascript error objects with custom fields like fileName, lineNumber, and traceback data. Implies DUK_OPT_NO_TRACEBACKS.
DUK_OPT_NO_TRACEBACKS Don't record traceback data into Ecmascript error objects (but still record fileName and lineNumber). Reduces footprint and makes error handling a bit faster, at the cost of less nformative Ecmascript errors.
DUK_OPT_NO_VERBOSE_ERRORS Don't provide error message strings or filename/line information for errors generated by Duktape. Reduces footprint, at the cost of much less informative Ecmascript errors.
DUK_OPT_TRACEBACK_DEPTH Override default traceback collection depth. The default is currently 10.
DUK_OPT_NO_PC2LINE Don't record a "pc2line" map into function instances. Without this map, exceptions won't have meaningful line numbers (virtual machine program counter values cannot be translated to line numbers) but function instances will have a smaller footprint.
DUK_OPT_NO_REGEXP_SUPPORT Disable support for regular expressions. Regexp literals are treated as a SyntaxError, RegExp constructor and prototype functions throw an error, String.prototype.replace() throws an error if given a regexp search value, String.prototype.split() throws an error if given a regexp separator value, String.prototype.search() and String.prototype.match() throw an error unconditionally.
DUK_OPT_STRICT_UTF8_SOURCE Enable strict UTF-8 parsing of source code. When enabled, non-shortest encodings (normally invalid UTF-8) and surrogate pair codepoints are accepted as valid source code characters. This option breaks compatibility with some test262 tests.
DUK_OPT_NO_OCTAL_SUPPORT Disable optional octal number support (Ecmascript E5/E5.1 Annex B).
DUK_OPT_NO_SOURCE_NONBMP Disable accurate Unicode support for non-BMP characters in source code. Non-BMP characters are then always accepted as identifier characters.
DUK_OPT_NO_BROWSER_LIKE Disable browser-like functions. Makes print() and alert() throw an error. This option is confusing when used with the Duktape command line tool, as the command like tool will immediately panic.
DUK_OPT_NO_SECTION_B Disable optional features in Ecmascript specification Annex B. Causes escape(), unescape(), and String.prototype.substr() to throw an error.
DUK_OPT_NO_FUNC_STMT Disable support for function declarations outside program or function top level (also known as "function statements"). Such declarations are non-standard and the strictly compliant behavior is to treat them as a SyntaxError. Default behavior is to treat them like ordinary function declarations ("hoist" them to function top) with V8-like semantics.
DUK_OPT_NO_JSONX Disable support for the JSONX format. Reduces code footprint. Causes JSONX calls to throw an error.
DUK_OPT_NO_JSONC Disable support for the JSONC format. Reduces code footprint. Causes JSONC calls to throw an error.
DUK_OPT_NO_FILE_IO Disable use of ANSI C file I/O which might be a portability issue on some platforms. Causes duk_eval_file() to throw an error, makes built-in print() and alert() no-ops, and suppresses writing of a panic message to stderr on panic. This option does not suppress debug printing so don't enable debug printing if you wish to avoid I/O.
DUK_OPT_NO_INTERRUPT_COUNTER Disable the internal bytecode executor periodic interrupt counter. The mechanism is used to implement e.g. execution step limit, custom profiling, and debugger interaction. Disabling the interrupt counter improves bytecode execution performance very slightly but disables all features depending on it.
DUK_OPT_PANIC_HANDLER(code,msg) Provide a custom panic handler, see detailed description below.
DUK_OPT_SEGFAULT_ON_PANIC Cause the default panic handler to cause a segfault instead of using abort() or exit(). This is useful when debugging with valgrind, as a segfault provides a nice C traceback in valgrind.
DUK_OPT_SELF_TESTS Perform run-time self tests when a Duktape heap is created. Catches platform/compiler problems which cannot be reliably detected during compile time. Not enabled by default because of the extra footprint.
DUK_OPT_ASSERTIONS Enable internal assert checks. These slow down execution considerably so only use when debugging.
DUK_OPT_DEBUG Enable debug printouts.
DUK_OPT_DDEBUG Enable more debug printouts.
DUK_OPT_DDDEBUG Enable even more debug printouts. Not recommended unless you have grep handy.
DUK_OPT_DPRINT_COLORS Enable coloring of debug prints with ANSI escape codes. The behavior is not sensitive to terminal settings.
DUK_OPT_DPRINT_RDTSC Print RDTSC cycle count in debug prints if available.
DUK_OPT_DEBUG_BUFSIZE Debug code uses a static buffer as a formatting temporary to avoid side effects in debug prints. The static buffer is large by default, which may be an issue in constrained environments. You can set the buffer size manually with this option. Example: -DDUK_OPT_DEBUG_BUFSIZE=2048.
DUK_OPT_HAVE_CUSTOM_H Enable user-provided duk_custom.h customization header (see below for details). Not recommended unless really necessary.

Suggested feature options for some environments

Timing sensitive applications (e.g. games)

Memory constrained applications

DUK_OPT_HAVE_CUSTOM_H and duk_custom.h

Normally you define DUK_OPT_xxx feature options and the internal duk_features.h header resolves these with platform/compiler constraints to determine effective compilation options for Duktape internals. The effective options are provided as DUK_USE_xxx defines which you normally never see.

If you define DUK_OPT_HAVE_CUSTOM_H, Duktape will include duk_custom.h after determining the appropriate DUK_USE_xxx defines but before compiling any code. The duk_custom.h header, which you provide, can then tweak the active DUK_USE_xxx defines freely. See duk_features.h for the available defines.

This approach is useful when the DUK_OPT_xxx feature options don't provide enough flexibility to tweak the build. The downside is that you can easily create inconsistent DUK_USE_xxx flags, the customization header will be version specific, and you need to peek into Duktape internals to know what defines to tweak.

DUK_OPT_PANIC_HANDLER

The default panic handler will print an error message to stdout unless I/O is disabled by DUK_OPT_NO_FILE_IO. It will then call abort() or cause a segfault if DUK_OPT_SEGFAULT_ON_PANIC is defined.

You can override the entire panic handler by defining DUK_OPT_PANIC_HANDLER. For example, you could add the following to your compiler options:

'-DDUK_OPT_PANIC_HANDLER(code,msg)={printf("*** %d:%s\n",(code),(msg));abort();}'

Or perhaps:

'-DDUK_OPT_PANIC_HANDLER(code,msg)={my_panic_handler((code),(msg))}'

which calls your custom handler:

void my_panic_handler(int code, const char *msg) {
    /* Your panic handling.  Must not return. */
}

Adding new feature options

This section only applies if you customize Duktape internals and wish to submit a patch to be included in the mainline distribution:

Memory management alternatives

There are three supported memory management alternatives:

When using only reference counting it is important to avoid creating unreachable reference cycles. Reference cycles are usually easy to avoid in application code e.g. by using only forward pointers in data structures. Even if reference cycles are necessary, garbage collection can be allowed to work simply by breaking the cycles before deleting the final references to such objects. For example, if you have a tree structure where nodes maintain references to both children and parents (creating reference cycles for each node) you could walk the tree and set the parent reference to null before deleting the final reference to the tree.

Unfortunately every Ecmascript function instance is, by default, in a reference loop with an automatic prototype object created for the object. The function instance's prototype property points to the prototype object, and the prototype's constructor property points back to the function instance. Only mark-and-sweep is able to collect these reference loops at the moment. If you build with reference counting only, function instances may appear to leak memory; the memory will be released when the relevant heap is destroyed. You can also break the reference loops manually (although this is a bit cumbersome):

var f = function() { };
var g = function() { };
var h = function() { };
Duktape.fin(f, function() { print('finalizer for f'); });
Duktape.fin(g, function() { print('finalizer for g'); });
Duktape.fin(h, function() { print('finalizer for h'); });

// not collected until heap destruction in a reference counting only build
f = null;            // not collected immediately

// break cycle by deleting 'prototype' reference (alternative 1)
g.prototype = null;
g = null;            // collected immediately, finalizer runs

// break cycle by deleting 'constructor' reference (alternative 2)
h.prototype.constructor = null;
h = null;            // collected immediately, finalizer runs

// no-op with refcount only, with mark-and-sweep finalizer for 'f' runs
Duktape.gc();

Compiler warnings

Current goal is for the Duktape compile to be clean when:

There are still some warnings present when you compile with -Wextra or equivalent option.

When your compiler is not C99 compliant, Duktape uses an awkward replacement for variadic macros. This may cause, as a side effect, a lot of harmless warnings if you set the compiler warning level too high. This is difficult to fix, so C99 compilation may not be clean at the moment.