or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

ast-nodes.mdcli-tools.mdcompilation.mdexecution.mdindex.mdrepl-interactive.mdutilities.md
tile.json

utilities.mddocs/

Utilities and Helpers

Comprehensive utility functions for string manipulation, array processing, error handling, and source location management used throughout the CoffeeScript compiler and available for external use.

Capabilities

String Utilities

Functions for common string manipulation operations used in compilation and code generation.

/**
 * Check if string starts with literal at given position
 * @param string - String to check
 * @param literal - Literal to look for
 * @param start - Starting position (default: 0)
 * @returns True if string starts with literal at position
 */
function starts(string, literal, start);

/**
 * Check if string ends with literal
 * @param string - String to check  
 * @param literal - Literal to look for
 * @param back - Offset from end (default: 0)
 * @returns True if string ends with literal
 */
function ends(string, literal, back);

/**
 * Repeat string n times efficiently
 * @param str - String to repeat
 * @param n - Number of repetitions
 * @returns Repeated string
 */
function repeat(str, n);

/**
 * Count occurrences of substring in string
 * @param string - String to search in
 * @param substr - Substring to count
 * @returns Number of occurrences
 */
function count(string, substr);

Usage Examples:

const { starts, ends, repeat, count } = require('coffee-script').helpers;

// String testing
console.log(starts('hello world', 'hello'));     // true
console.log(starts('hello world', 'world', 6));  // true
console.log(ends('script.coffee', '.coffee'));   // true

// String generation
console.log(repeat('=', 10));           // '=========='
console.log(repeat('abc', 3));          // 'abcabcabc'

// Substring counting
console.log(count('hello hello hello', 'hello'));  // 3
console.log(count('a.b.c.d', '.'));                // 3

Array and Object Utilities

Functions for manipulating arrays and objects commonly used in AST processing and compilation.

/**
 * Remove falsy values from array
 * @param array - Array to compact
 * @returns New array with falsy values removed
 */
function compact(array);

/**
 * Merge objects together, with later objects overriding earlier ones
 * @param options - Base options object
 * @param overrides - Object with overriding values
 * @returns Merged object
 */
function merge(options, overrides);

/**
 * Extend object with additional properties
 * @param object - Object to extend
 * @param properties - Properties to add
 * @returns Extended object (mutated)
 */
function extend(object, properties);

/**
 * Flatten nested arrays into single level
 * @param array - Array to flatten
 * @returns Flattened array
 */
function flatten(array);

/**
 * Delete property from object and return its value
 * @param obj - Object to modify
 * @param key - Property key to delete
 * @returns Value of deleted property
 */
function del(obj, key);

Usage Examples:

const { compact, merge, extend, flatten, del } = require('coffee-script').helpers;

// Array compacting
console.log(compact([1, 0, 2, false, 3, null, 4])); // [1, 2, 3, 4]

// Object merging
const options = merge({ bare: false, header: true }, { bare: true });
console.log(options); // { bare: true, header: true }

// Object extension
const obj = { a: 1 };
extend(obj, { b: 2, c: 3 });
console.log(obj); // { a: 1, b: 2, c: 3 }

// Array flattening
console.log(flatten([1, [2, 3], [4, [5, 6]]])); // [1, 2, 3, 4, 5, 6]

// Property deletion
const data = { x: 10, y: 20 };
const xValue = del(data, 'x');
console.log(xValue); // 10
console.log(data);   // { y: 20 }

File Utilities

Functions for working with file paths and determining CoffeeScript file types.

/**
 * Extract base filename from file path
 * @param file - File path
 * @param stripExt - Whether to strip extension
 * @param useWinPathSep - Use Windows path separator
 * @returns Base filename
 */
function baseFileName(file, stripExt, useWinPathSep);

/**
 * Check if file has CoffeeScript extension
 * @param file - File path to check
 * @returns True if file is a CoffeeScript file
 */
function isCoffee(file);

/**
 * Check if file is literate CoffeeScript format
 * @param file - File path to check  
 * @returns True if file is literate CoffeeScript
 */
function isLiterate(file);

/**
 * Convert literate CoffeeScript format
 * @param code - Literate CoffeeScript source
 * @returns Regular CoffeeScript source
 */
function invertLiterate(code);

Usage Examples:

const { baseFileName, isCoffee, isLiterate, invertLiterate } = require('coffee-script').helpers;

// Filename extraction
console.log(baseFileName('/path/to/script.coffee'));        // 'script.coffee'
console.log(baseFileName('/path/to/script.coffee', true));  // 'script'

// File type detection
console.log(isCoffee('app.coffee'));      // true
console.log(isCoffee('README.litcoffee')); // true
console.log(isCoffee('script.js'));       // false

console.log(isLiterate('docs.litcoffee'));   // true
console.log(isLiterate('guide.coffee.md')); // true
console.log(isLiterate('app.coffee'));      // false

// Literate format conversion
const literateCode = `
This is documentation.

    square = (x) -> x * x

More documentation here.

    console.log square 5
`;

const regularCode = invertLiterate(literateCode);
console.log(regularCode);
// 'square = (x) -> x * x\nconsole.log square 5'

Error Handling

Functions for creating and managing CoffeeScript-specific errors with source location information.

/**
 * Throw syntax error with location information
 * @param message - Error message
 * @param location - Source location data
 * @throws SyntaxError with CoffeeScript context
 */
function throwSyntaxError(message, location);

/**
 * Update error with source code context
 * @param error - Error object to update
 * @param code - Source code
 * @param filename - Optional filename
 * @returns Updated error with additional context
 */
function updateSyntaxError(error, code, filename);

/**
 * Get readable name for whitespace characters
 * @param string - String containing whitespace
 * @returns Human-readable character name
 */
function nameWhitespaceCharacter(string);

Usage Examples:

const { throwSyntaxError, updateSyntaxError, nameWhitespaceCharacter } = require('coffee-script').helpers;

// Error throwing with location
try {
  throwSyntaxError('unexpected token', {
    first_line: 5,
    first_column: 10,
    last_line: 5,
    last_column: 15
  });
} catch (error) {
  console.log(error.message); // Shows line/column information
}

// Error context enhancement
try {
  // Some CoffeeScript compilation error
} catch (error) {
  const enhancedError = updateSyntaxError(error, sourceCode, 'app.coffee');
  console.log(enhancedError.message); // Now includes source context
}

// Whitespace character naming
console.log(nameWhitespaceCharacter('\t'));    // 'tab'
console.log(nameWhitespaceCharacter('\n'));    // 'newline'  
console.log(nameWhitespaceCharacter('\r'));    // 'carriage return'
console.log(nameWhitespaceCharacter(' '));     // 'space'

Location Data Utilities

Functions for managing source code location information used in AST nodes and error reporting.

/**
 * Create function to add location data to AST nodes
 * @param first - Starting location
 * @param last - Ending location  
 * @returns Function that adds location data
 */
function addLocationDataFn(first, last);

/**
 * Convert location data object to string representation
 * @param obj - Object with location data
 * @returns String representation of location
 */
function locationDataToString(obj);

Usage Examples:

const { addLocationDataFn, locationDataToString } = require('coffee-script').helpers;

// Location data function creation
const addLocation = addLocationDataFn(
  { first_line: 1, first_column: 0 },
  { last_line: 1, last_column: 10 }
);

// Apply location to AST node
const node = new SomeASTNode();
addLocation(node);
console.log(node.locationData);

// Location string conversion
const locationStr = locationDataToString({
  locationData: {
    first_line: 5,
    first_column: 10,
    last_line: 5,
    last_column: 20
  }
});
console.log(locationStr); // "5:10-20"

Array Processing

Additional array manipulation functions for compiler internals.

/**
 * Array.prototype.some polyfill for older environments
 * @param fn - Test function
 * @returns True if any element passes test
 */
function some(fn);

Usage Example:

const { some } = require('coffee-script').helpers;

// Use with arrays that might not have native some() method
const hasPositive = some.call([-1, 0, 1, 2], x => x > 0);
console.log(hasPositive); // true

Lexer Utilities

Additional utilities from the lexer module for token processing.

/**
 * Check if identifier cannot be assigned to
 * @param name - Identifier name to check
 * @returns True if identifier is unassignable
 */
function isUnassignable(name);

/** Array of forbidden JavaScript keywords */
const JS_FORBIDDEN: string[];

Usage Examples:

const { isUnassignable, JS_FORBIDDEN } = require('coffee-script/lexer');

// Check assignability
console.log(isUnassignable('eval'));      // true
console.log(isUnassignable('arguments')); // true  
console.log(isUnassignable('myVar'));     // false

// Forbidden keywords
console.log(JS_FORBIDDEN.includes('class'));     // true
console.log(JS_FORBIDDEN.includes('function'));  // true

Source Map Utilities

The SourceMap class provides utilities for generating source maps during compilation.

/**
 * Source map generation class
 */
class SourceMap {
  constructor();
  
  /** Add mapping between source and generated positions */
  add(sourceLocation, generatedLocation, options);
  
  /** Generate source map object */
  generate(options, source);
  
  /** Get source location from generated position */
  sourceLocation(position);
}

Usage Example:

const SourceMap = require('coffee-script/sourcemap');

const map = new SourceMap();
map.add([0, 0], [0, 0]); // Map source line 0, col 0 to generated line 0, col 0
const v3Map = map.generate({ filename: 'app.coffee' }, sourceCode);
console.log(JSON.stringify(v3Map, null, 2));