littlewing 0.5.3 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  declare namespace exports_ast {
2
- export { unaryOp, subtract, number, nullishAssign, notEquals, negate, multiply, modulo, logicalOr, logicalAnd, lessThan, lessEqual, identifier, greaterThan, greaterEqual, functionCall, exponentiate, equals, divide, conditional, binaryOp, assign, add };
2
+ export { unaryOp, subtract, program, number, notEquals, negate, multiply, modulo, logicalOr, logicalAnd, lessThan, lessEqual, identifier, greaterThan, greaterEqual, functionCall, exponentiate, equals, divide, conditional, binaryOp, assign, add };
3
3
  }
4
4
  /**
5
5
  * Runtime value type - only numbers
@@ -44,7 +44,6 @@ declare enum TokenType {
44
44
  COMMA = "COMMA",
45
45
  QUESTION = "QUESTION",
46
46
  COLON = "COLON",
47
- NULLISH_ASSIGN = "NULLISH_ASSIGN",
48
47
  EOF = "EOF"
49
48
  }
50
49
  /**
@@ -58,7 +57,7 @@ interface Token {
58
57
  /**
59
58
  * AST Node - base type
60
59
  */
61
- type ASTNode = Program | NumberLiteral | Identifier | BinaryOp | UnaryOp | FunctionCall | Assignment | ConditionalExpression | NullishAssignment;
60
+ type ASTNode = Program | NumberLiteral | Identifier | BinaryOp | UnaryOp | FunctionCall | Assignment | ConditionalExpression;
62
61
  /**
63
62
  * Program node (multiple statements)
64
63
  */
@@ -124,16 +123,6 @@ interface ConditionalExpression {
124
123
  alternate: ASTNode;
125
124
  }
126
125
  /**
127
- * Nullish assignment (x ??= 5)
128
- * Assigns value only if variable is undefined (not provided in context)
129
- * Used for providing defaults for external variables
130
- */
131
- interface NullishAssignment {
132
- type: "NullishAssignment";
133
- name: string;
134
- value: ASTNode;
135
- }
136
- /**
137
126
  * Type guard functions for discriminated union narrowing
138
127
  */
139
128
  declare function isNumberLiteral(node: ASTNode): node is NumberLiteral;
@@ -144,11 +133,14 @@ declare function isFunctionCall(node: ASTNode): node is FunctionCall;
144
133
  declare function isAssignment(node: ASTNode): node is Assignment;
145
134
  declare function isProgram(node: ASTNode): node is Program;
146
135
  declare function isConditionalExpression(node: ASTNode): node is ConditionalExpression;
147
- declare function isNullishAssignment(node: ASTNode): node is NullishAssignment;
148
136
  /**
149
137
  * Builder functions for creating AST nodes manually
150
138
  */
151
139
  /**
140
+ * Create a program node
141
+ */
142
+ declare function program(statements: ASTNode[]): Program;
143
+ /**
152
144
  * Create a number literal node
153
145
  */
154
146
  declare function number(value: number): NumberLiteral;
@@ -173,11 +165,6 @@ declare function functionCall(name: string, args?: ASTNode[]): FunctionCall;
173
165
  */
174
166
  declare function assign(name: string, value: ASTNode): Assignment;
175
167
  /**
176
- * Create a nullish assignment node (x ??= 5)
177
- * Assigns only if variable is undefined
178
- */
179
- declare function nullishAssign(name: string, value: ASTNode): NullishAssignment;
180
- /**
181
168
  * Create a conditional expression node (ternary operator)
182
169
  */
183
170
  declare function conditional(condition: ASTNode, consequent: ASTNode, alternate: ASTNode): ConditionalExpression;
@@ -287,10 +274,6 @@ declare class CodeGenerator {
287
274
  */
288
275
  private generateAssignment;
289
276
  /**
290
- * Generate code for a nullish assignment
291
- */
292
- private generateNullishAssignment;
293
- /**
294
277
  * Generate code for a conditional expression (ternary operator)
295
278
  */
296
279
  private generateConditionalExpression;
@@ -311,36 +294,227 @@ declare class CodeGenerator {
311
294
  * Generate source code from an AST node
312
295
  */
313
296
  declare function generate(node: ASTNode): string;
297
+ declare namespace exports_date_utils {
298
+ export { TO_UNIX_SECONDS, START_OF_YEAR, START_OF_WEEK, START_OF_QUARTER, START_OF_MONTH, START_OF_DAY, NOW, IS_WEEKEND, IS_SAME_DAY, IS_LEAP_YEAR, IS_BEFORE, IS_AFTER, GET_YEAR, GET_WEEKDAY, GET_SECOND, GET_QUARTER, GET_MONTH, GET_MINUTE, GET_MILLISECOND, GET_HOUR, GET_DAY_OF_YEAR, GET_DAY, FROM_YEARS, FROM_WEEKS, FROM_UNIX_SECONDS, FROM_SECONDS, FROM_MONTHS, FROM_MINUTES, FROM_HOURS, FROM_DAYS, END_OF_YEAR, END_OF_MONTH, END_OF_DAY, DIFFERENCE_IN_WEEKS, DIFFERENCE_IN_SECONDS, DIFFERENCE_IN_MINUTES, DIFFERENCE_IN_HOURS, DIFFERENCE_IN_DAYS, DATE, ADD_YEARS, ADD_MONTHS, ADD_DAYS };
299
+ }
300
+ /**
301
+ * Date utility functions for working with timestamps
302
+ * All functions work with milliseconds since Unix epoch (numbers only)
303
+ */
304
+ /**
305
+ * Get current timestamp (milliseconds since Unix epoch)
306
+ */
307
+ declare const NOW: () => number;
308
+ /**
309
+ * Create timestamp from date components
310
+ * Year is required, all other parameters default to minimum values
311
+ * Month is 1-based (1 = January, 12 = December)
312
+ */
313
+ declare const DATE: (year: number, month?: number, day?: number, hour?: number, minute?: number, second?: number) => number;
314
+ /**
315
+ * Convert seconds to milliseconds
316
+ */
317
+ declare const FROM_SECONDS: (s: number) => number;
318
+ /**
319
+ * Convert minutes to milliseconds
320
+ */
321
+ declare const FROM_MINUTES: (m: number) => number;
322
+ /**
323
+ * Convert hours to milliseconds
324
+ */
325
+ declare const FROM_HOURS: (h: number) => number;
326
+ /**
327
+ * Convert days to milliseconds
328
+ */
329
+ declare const FROM_DAYS: (d: number) => number;
330
+ /**
331
+ * Convert weeks to milliseconds
332
+ */
333
+ declare const FROM_WEEKS: (w: number) => number;
334
+ /**
335
+ * Convert months to milliseconds (approximate: 30 days per month)
336
+ */
337
+ declare const FROM_MONTHS: (months: number) => number;
338
+ /**
339
+ * Convert years to milliseconds (approximate: 365 days per year)
340
+ */
341
+ declare const FROM_YEARS: (years: number) => number;
342
+ /**
343
+ * Get the year from a timestamp
344
+ */
345
+ declare const GET_YEAR: (timestamp: number) => number;
346
+ /**
347
+ * Get the month from a timestamp (1-based: 1 = January, 12 = December)
348
+ */
349
+ declare const GET_MONTH: (timestamp: number) => number;
350
+ /**
351
+ * Get the day of month from a timestamp (1-31)
352
+ */
353
+ declare const GET_DAY: (timestamp: number) => number;
354
+ /**
355
+ * Get the hour from a timestamp (0-23)
356
+ */
357
+ declare const GET_HOUR: (timestamp: number) => number;
358
+ /**
359
+ * Get the minute from a timestamp (0-59)
360
+ */
361
+ declare const GET_MINUTE: (timestamp: number) => number;
362
+ /**
363
+ * Get the second from a timestamp (0-59)
364
+ */
365
+ declare const GET_SECOND: (timestamp: number) => number;
366
+ /**
367
+ * Get the millisecond component from a timestamp (0-999)
368
+ */
369
+ declare const GET_MILLISECOND: (timestamp: number) => number;
370
+ /**
371
+ * Get the day of week from a timestamp (0 = Sunday, 6 = Saturday)
372
+ */
373
+ declare const GET_WEEKDAY: (timestamp: number) => number;
374
+ /**
375
+ * Get the day of year (1-366) from a timestamp
376
+ */
377
+ declare const GET_DAY_OF_YEAR: (timestamp: number) => number;
378
+ /**
379
+ * Get the quarter (1-4) from a timestamp
380
+ */
381
+ declare const GET_QUARTER: (timestamp: number) => number;
382
+ /**
383
+ * Get the absolute difference between two timestamps in seconds
384
+ */
385
+ declare const DIFFERENCE_IN_SECONDS: (ts1: number, ts2: number) => number;
386
+ /**
387
+ * Get the absolute difference between two timestamps in minutes
388
+ */
389
+ declare const DIFFERENCE_IN_MINUTES: (ts1: number, ts2: number) => number;
314
390
  /**
315
- * Default execution context with common Math functions and timestamp utilities
391
+ * Get the absolute difference between two timestamps in hours
392
+ */
393
+ declare const DIFFERENCE_IN_HOURS: (ts1: number, ts2: number) => number;
394
+ /**
395
+ * Get the absolute difference between two timestamps in days
396
+ */
397
+ declare const DIFFERENCE_IN_DAYS: (ts1: number, ts2: number) => number;
398
+ /**
399
+ * Get the absolute difference between two timestamps in weeks
400
+ */
401
+ declare const DIFFERENCE_IN_WEEKS: (ts1: number, ts2: number) => number;
402
+ /**
403
+ * Get the start of day (00:00:00.000) for a given timestamp
404
+ */
405
+ declare const START_OF_DAY: (timestamp: number) => number;
406
+ /**
407
+ * Get the end of day (23:59:59.999) for a given timestamp
408
+ */
409
+ declare const END_OF_DAY: (timestamp: number) => number;
410
+ /**
411
+ * Get the start of week (Sunday at 00:00:00.000) for a given timestamp
412
+ */
413
+ declare const START_OF_WEEK: (timestamp: number) => number;
414
+ /**
415
+ * Get the start of month (1st day at 00:00:00.000) for a given timestamp
416
+ */
417
+ declare const START_OF_MONTH: (timestamp: number) => number;
418
+ /**
419
+ * Get the end of month (last day at 23:59:59.999) for a given timestamp
420
+ */
421
+ declare const END_OF_MONTH: (timestamp: number) => number;
422
+ /**
423
+ * Get the start of year (Jan 1st at 00:00:00.000) for a given timestamp
424
+ */
425
+ declare const START_OF_YEAR: (timestamp: number) => number;
426
+ /**
427
+ * Get the end of year (Dec 31st at 23:59:59.999) for a given timestamp
428
+ */
429
+ declare const END_OF_YEAR: (timestamp: number) => number;
430
+ /**
431
+ * Add days to a timestamp
432
+ */
433
+ declare const ADD_DAYS: (timestamp: number, days: number) => number;
434
+ /**
435
+ * Add months to a timestamp (handles variable month lengths correctly)
436
+ */
437
+ declare const ADD_MONTHS: (timestamp: number, months: number) => number;
438
+ /**
439
+ * Add years to a timestamp
440
+ */
441
+ declare const ADD_YEARS: (timestamp: number, years: number) => number;
442
+ /**
443
+ * Check if ts1 is before ts2
444
+ * Returns 1 if true, 0 if false
445
+ */
446
+ declare const IS_BEFORE: (ts1: number, ts2: number) => number;
447
+ /**
448
+ * Check if ts1 is after ts2
449
+ * Returns 1 if true, 0 if false
450
+ */
451
+ declare const IS_AFTER: (ts1: number, ts2: number) => number;
452
+ /**
453
+ * Check if two timestamps are on the same calendar day
454
+ * Returns 1 if true, 0 if false
455
+ */
456
+ declare const IS_SAME_DAY: (ts1: number, ts2: number) => number;
457
+ /**
458
+ * Check if timestamp falls on a weekend (Saturday or Sunday)
459
+ * Returns 1 if true, 0 if false
460
+ */
461
+ declare const IS_WEEKEND: (timestamp: number) => number;
462
+ /**
463
+ * Check if timestamp is in a leap year
464
+ * Returns 1 if true, 0 if false
465
+ */
466
+ declare const IS_LEAP_YEAR: (timestamp: number) => number;
467
+ /**
468
+ * Get the start of quarter for a given timestamp
469
+ */
470
+ declare const START_OF_QUARTER: (timestamp: number) => number;
471
+ /**
472
+ * Convert millisecond timestamp to Unix seconds
473
+ */
474
+ declare const TO_UNIX_SECONDS: (timestamp: number) => number;
475
+ /**
476
+ * Convert Unix seconds to millisecond timestamp
477
+ */
478
+ declare const FROM_UNIX_SECONDS: (seconds: number) => number;
479
+ /**
480
+ * Default execution context with common Math functions and date/time utilities
316
481
  * Users can use this as-is or spread it into their own context
317
482
  *
483
+ * All functions use UPPERCASE naming convention to avoid collisions with user variables.
318
484
  * All date-related functions work with timestamps (milliseconds since Unix epoch)
319
485
  * to maintain the language's numbers-only type system.
320
486
  *
321
487
  * @example
322
488
  * // Use as-is
323
- * execute('abs(-5)', defaultContext)
489
+ * execute('ABS(-5)', defaultContext)
324
490
  *
325
491
  * @example
326
492
  * // Spread into custom context
327
- * execute('now() + minutes(5)', {
493
+ * execute('NOW() + FROM_MINUTES(5)', {
328
494
  * ...defaultContext,
329
495
  * variables: { customVar: 42 }
330
496
  * })
331
497
  *
332
498
  * @example
333
499
  * // Work with timestamps
334
- * const result = execute('now() + days(7)', defaultContext)
500
+ * const result = execute('NOW() + FROM_DAYS(7)', defaultContext)
335
501
  * const futureDate = new Date(result) // Convert back to Date if needed
502
+ *
503
+ * @example
504
+ * // Calculate time differences
505
+ * const ts1 = Date.now()
506
+ * const ts2 = ts1 + 1000 * 60 * 60 * 3 // 3 hours later
507
+ * execute('DIFFERENCE_IN_HOURS(ts1, ts2)', { ...defaultContext, variables: { ts1, ts2 } })
336
508
  */
337
509
  declare const defaultContext: ExecutionContext;
338
510
  /**
339
511
  * Executor - evaluates an AST with given context
512
+ * Uses a tree-walk interpreter with O(n) execution time where n is the number of AST nodes
340
513
  */
341
514
  declare class Executor {
342
515
  private context;
343
516
  private variables;
517
+ private externalVariables;
344
518
  constructor(context?: ExecutionContext);
345
519
  /**
346
520
  * Execute an AST node and return the result
@@ -372,15 +546,11 @@ declare class Executor {
372
546
  private executeFunctionCall;
373
547
  /**
374
548
  * Execute a variable assignment
549
+ * External variables (from context) take precedence over script assignments
550
+ * This allows scripts to define defaults that can be overridden at runtime
375
551
  */
376
552
  private executeAssignment;
377
553
  /**
378
- * Execute a nullish assignment (??=)
379
- * Only assigns if the variable is undefined (not in variables map)
380
- * Returns the existing value if defined, otherwise evaluates and assigns the value
381
- */
382
- private executeNullishAssignment;
383
- /**
384
554
  * Execute a conditional expression (ternary operator)
385
555
  * Returns consequent if condition !== 0, otherwise returns alternate
386
556
  */
@@ -392,10 +562,12 @@ declare class Executor {
392
562
  declare function execute(source: string, context?: ExecutionContext): RuntimeValue;
393
563
  /**
394
564
  * Lexer - converts source code into tokens
565
+ * Implements a single-pass O(n) tokenization algorithm
395
566
  */
396
567
  declare class Lexer {
397
568
  private source;
398
569
  private position;
570
+ private length;
399
571
  constructor(source: string);
400
572
  /**
401
573
  * Tokenize the entire source and return all tokens
@@ -419,23 +591,11 @@ declare class Lexer {
419
591
  */
420
592
  private readIdentifier;
421
593
  /**
422
- * Get character at position
423
- */
424
- private getCharAt;
425
- /**
426
- * Peek at the next character without consuming it
427
- */
428
- private peek;
429
- /**
430
- * Peek ahead n positions without consuming
431
- */
432
- private peekAhead;
433
- /**
434
- * Check if character is a digit
594
+ * Check if character is a digit (0-9)
435
595
  */
436
596
  private isDigit;
437
597
  /**
438
- * Check if character is a letter
598
+ * Check if character is a letter (a-z, A-Z)
439
599
  */
440
600
  private isLetter;
441
601
  /**
@@ -444,25 +604,25 @@ declare class Lexer {
444
604
  private isWhitespace;
445
605
  }
446
606
  /**
447
- * Optimize an AST using a theoretically optimal O(n) algorithm.
607
+ * Optimize an AST using constant folding and expression simplification.
608
+ *
609
+ * This optimizer performs LOCAL, SAFE optimizations that preserve program semantics:
610
+ * - Constant folding: Evaluates arithmetic with literal operands at compile-time
611
+ * - Function argument pre-evaluation: Simplifies expressions passed to functions
612
+ * - Conditional folding: Evaluates ternary with constant condition
448
613
  *
449
- * This optimizer implements a single-pass data-flow analysis algorithm that:
450
- * 1. Builds a dependency graph of all variables and expressions
451
- * 2. Performs constant propagation via forward data-flow analysis
452
- * 3. Eliminates dead code via backward reachability analysis
453
- * 4. Evaluates expressions in a single topological pass
614
+ * Optimizations that are NOT performed (because they're unsafe with context variables):
615
+ * - Variable propagation: Variables can be overridden by ExecutionContext
616
+ * - Dead code elimination: Cannot determine if variables are "dead" without knowing context
617
+ * - Cross-statement analysis: Each statement may affect external state
454
618
  *
455
619
  * Time complexity: O(n) where n is the number of AST nodes
456
- * Space complexity: O(n) for the dependency graph
620
+ * Space complexity: O(d) where d is the max depth (recursion stack)
457
621
  *
458
622
  * Algorithm properties:
459
623
  * - Sound: Preserves program semantics exactly
460
- * - Complete: Finds all optimization opportunities
461
- * - Optimal: No redundant traversals or recomputation
462
- *
463
- * Based on classical compiler optimization theory:
464
- * - Cytron et al. "Efficiently Computing Static Single Assignment Form" (1991)
465
- * - Wegman & Zadeck "Constant Propagation with Conditional Branches" (1991)
624
+ * - Safe: No assumptions about variable values or liveness
625
+ * - Local: Only optimizes within individual expressions
466
626
  *
467
627
  * @param node - The AST node to optimize
468
628
  * @returns Optimized AST node
@@ -470,6 +630,7 @@ declare class Lexer {
470
630
  declare function optimize(node: ASTNode): ASTNode;
471
631
  /**
472
632
  * Parser using Pratt parsing (top-down operator precedence)
633
+ * Implements an efficient O(n) parsing algorithm
473
634
  */
474
635
  declare class Parser {
475
636
  private tokens;
@@ -477,11 +638,12 @@ declare class Parser {
477
638
  constructor(tokens: Token[]);
478
639
  /**
479
640
  * Parse tokens into an AST
480
- * Supports multiple statements separated by semicolons
641
+ * Supports multiple statements separated by semicolons or newlines
481
642
  */
482
643
  parse(): ASTNode;
483
644
  /**
484
645
  * Parse an expression with Pratt parsing (precedence climbing)
646
+ * This is the core of the parser - handles infix operators with proper precedence
485
647
  */
486
648
  private parseExpression;
487
649
  /**
@@ -496,15 +658,15 @@ declare class Parser {
496
658
  * Get unary operator precedence
497
659
  * Returns 6 which is higher than add/sub (6) but lower than exponentiation (8)
498
660
  * This means: -2^2 parses as -(2^2) = -4, not (-2)^2 = 4
499
- * This matches the behavior of Python, Ruby, and most languages
661
+ * Matches the behavior of Python, Ruby, and most languages
500
662
  */
501
663
  private getUnaryPrecedence;
502
664
  /**
503
- * Check if token is a binary operator
665
+ * Check if token is a binary operator (O(1) Set lookup)
504
666
  */
505
667
  private isBinaryOperator;
506
668
  /**
507
- * Get current token
669
+ * Get current token without advancing
508
670
  */
509
671
  private peek;
510
672
  /**
@@ -514,9 +676,10 @@ declare class Parser {
514
676
  }
515
677
  /**
516
678
  * Parse source code string into AST
679
+ * Convenience function that creates lexer and parser
517
680
  *
518
681
  * @param source - The source code to parse
519
682
  * @returns Parsed AST
520
683
  */
521
684
  declare function parseSource(source: string): ASTNode;
522
- export { parseSource, optimize, isUnaryOp, isProgram, isNumberLiteral, isNullishAssignment, isIdentifier, isFunctionCall, isConditionalExpression, isBinaryOp, isAssignment, generate, execute, defaultContext, exports_ast as ast, TokenType, Token, RuntimeValue, Parser, Lexer, Executor, ExecutionContext, CodeGenerator, ASTNode };
685
+ export { parseSource, optimize, isUnaryOp, isProgram, isNumberLiteral, isIdentifier, isFunctionCall, isConditionalExpression, isBinaryOp, isAssignment, generate, execute, defaultContext, exports_date_utils as dateUtils, exports_ast as ast, UnaryOp, TokenType, Token, RuntimeValue, Program, Parser, Operator, NumberLiteral, Lexer, Identifier, FunctionCall, Executor, ExecutionContext, ConditionalExpression, CodeGenerator, BinaryOp, Assignment, ASTNode };