PrimeIntellect/SWE-rebench-V2 huggingface dataset:
Repository: ember-codemods/ember-angle-brackets-codemod (js)

Issue:
Simple block `link-to` not converted
```
{{#link-to 'data-access'}}Accessing the Crates.io Data{{/link-to}}.
```

I don't know why, but the snippet above was not converted to Angle Brackets for some reason 🤔 

source: https://github.com/rust-lang/crates.io

Pull request:
Fix false negatives for `link-to` with `data-` prefixed route name
The original logic would consider any parameter a data attribute if the `original` had the substring `data-` .  This fix further reduces the ambiguity of the  parameter by enforcing that it also can't be a `StringLiteral` and that it must be a `PathExpression`

This fixes #212 

Patch:
diff --git a/transforms/angle-brackets/transform.js b/transforms/angle-brackets/transform.js
index 988e3c1..c4a2ade 100755
--- a/transforms/angle-brackets/transform.js
+++ b/transforms/angle-brackets/transform.js
@@ -262,12 +262,16 @@ function transformNodeAttributes(tagName, node) {
   return node.params.concat(attributes);
 }
 
+function isDataAttrPathExpression(node) {
+  return node.type === 'PathExpression' && node.original.startsWith('data-');
+}
+
 function getDataAttributesFromParams(params) {
-  return params.filter(param => param.original && `${param.original}`.startsWith('data-'));
+  return params.filter(it => isDataAttrPathExpression(it));
 }
 
 function getNonDataAttributesFromParams(params) {
-  return params.filter(p => !(p.original && `${p.original}`.startsWith('data-')));
+  return params.filter(it => !isDataAttrPathExpression(it));
 }
 
 function shouldIgnoreMustacheStatement(fullName, config, invokableData) {


Test patch:
diff --git a/transforms/angle-brackets/transform.test.js b/transforms/angle-brackets/transform.test.js
index 534f52d..b4607a8 100644
--- a/transforms/angle-brackets/transform.test.js
+++ b/transforms/angle-brackets/transform.test.js
@@ -376,6 +376,7 @@ test('let', () => {
 test('link-to', () => {
   let input = `
     {{#link-to "about"}}About Us{{/link-to}}
+    {{#link-to "data-access"}}Accessing the Crates.io Data{{/link-to}}
     {{#link-to this.dynamicRoute}}About Us{{/link-to}}
     {{#link-to "user" this.first this.second}}Show{{/link-to}}
     {{#link-to "user" this.first this.second (query-params foo="baz")}}Show{{/link-to}}
@@ -386,6 +387,7 @@ test('link-to', () => {
   expect(runTest('link-to.hbs', input)).toMatchInlineSnapshot(`
     "
         <LinkTo @route=\\"about\\">About Us</LinkTo>
+        <LinkTo @route=\\"data-access\\">Accessing the Crates.io Data</LinkTo>
         <LinkTo @route={{this.dynamicRoute}}>About Us</LinkTo>
         <LinkTo @route=\\"user\\" @models={{array this.first this.second}}>Show</LinkTo>
         <LinkTo @route=\\"user\\" @models={{array this.first this.second}} @query={{hash foo=\\"baz\\"}}>Show</LinkTo>
Repository: octokit/webhooks.js (ts)

Issue:
Deprecate `createWebhooksApi`
The `createWebhooksApi` export is there for legacy reasons. We use constructors across the other @octokit modules

https://github.com/octokit/webhooks.js/blob/1891034b602a2193a08f1ac3ad31775df65ca578/src/index.ts#L69

We should deprecate `createWebhooksApi` by exporting a function with that name that logs a deprecation message and returns a `Webhooks` instance with the same options, then remove it as v9. 

I like creating a dedicated `deprecations-test.ts` file where we test that the deprecation message is logged and that the API still works. If we stay consistent with that flow, removing deprecated APIs as part of a breaking release becomes trivial

Pull request:
feat: deprecate `createWebhooksApi()`
Fixes #454

Patch:
diff --git a/src/index.ts b/src/index.ts
index 12ac19d..23c1e86 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -65,7 +65,13 @@ class Webhooks<TTransformed> {
   }
 }
 
-const createWebhooksApi = Webhooks.prototype.constructor;
+/** @deprecated `createWebhooksApi()` is deprecated and will be removed in a future release of `@octokit/webhooks`, please use the `Webhooks` class instead */
+const createWebhooksApi = <TTransformed>(options: Options<TTransformed>) => {
+  console.error(
+    "[@octokit/webhooks] `createWebhooksApi()` is deprecated and will be removed in a future release of `@octokit/webhooks`, please use the `Webhooks` class instead"
+  );
+  return new Webhooks<TTransformed>(options);
+};
 
 export {
   createEventHandler,


Test patch:
diff --git a/test/typescript-validate.ts b/test/typescript-validate.ts
index 400dbb2..19731e6 100644
--- a/test/typescript-validate.ts
+++ b/test/typescript-validate.ts
@@ -2,7 +2,6 @@ import {
   Webhooks,
   createEventHandler,
   createMiddleware,
-  createWebhooksApi,
   sign,
   verify,
   EmitterWebhookEvent,
@@ -78,11 +77,6 @@ export default async function () {
     },
   });
 
-  // Check named exports of new API work
-  createWebhooksApi({
-    secret: "blah",
-  });
-
   createEventHandler({ secret: "blah" });
 
   createMiddleware({
diff --git a/test/unit/deprecation.test.ts b/test/unit/deprecation.test.ts
new file mode 100644
index 0000000..ab4c36d
--- /dev/null
+++ b/test/unit/deprecation.test.ts
@@ -0,0 +1,12 @@
+import { createWebhooksApi } from "../../src";
+
+describe("Deprecated methods", () => {
+  test("createWebhooksApi", () => {
+    const spy = jest.spyOn(console, "error");
+    createWebhooksApi({ secret: "foo" });
+    expect(spy).toBeCalledWith(
+      "[@octokit/webhooks] `createWebhooksApi()` is deprecated and will be removed in a future release of `@octokit/webhooks`, please use the `Webhooks` class instead"
+    );
+    spy.mockClear();
+  });
+});
Repository: tweag/nickel (rust)

Issue:
crash in nls
The following input crashes nls, with a panic in the pretty-printer.

```nickel
{
  multipleOf
    : Number -> Dyn -> [| 'Ok, 'Error { message | String, notes] } |]
    = 1
}
```

There's a syntax error, but that isn't the point: it shouldn't cause a crash.

Pull request:
Fix nls crash when typechecking parse errors
Fixes #2153.

Nls attempts to typecheck the input even if parsing fails (as long as the failure is non-fatal). The problem is that the pretty-printing code (for diagnosing a type error) assumes that all dynamic fields of all records are `Term::StrChunks`. This may be true for successful parses, but if the parse fails then you can also have a `Term::ParseError` as a dynamic field.

Patch:
diff --git a/core/src/pretty.rs b/core/src/pretty.rs
index 50077d93..d0d78bb4 100644
--- a/core/src/pretty.rs
+++ b/core/src/pretty.rs
@@ -522,6 +522,7 @@ impl Allocator {
         match id_expr.as_ref() {
             // Nickel will not parse a multiline string literal in this position
             Term::StrChunks(chunks) => self.chunks(chunks, StringRenderStyle::ForceMonoline),
+            Term::ParseError(_) => docs![self, "<parse error>"],
             _ => unimplemented!("Dynamic record fields must be StrChunks currently"),
         }
         .append(self.field_body(field))


Test patch:
diff --git a/lsp/nls/tests/inputs/no-crash-on-pretty-print.ncl b/lsp/nls/tests/inputs/no-crash-on-pretty-print.ncl
new file mode 100644
index 00000000..2d04e81c
--- /dev/null
+++ b/lsp/nls/tests/inputs/no-crash-on-pretty-print.ncl
@@ -0,0 +1,7 @@
+### /main.ncl
+{
+  multiple_of
+    : Number -> Dyn -> [| 'Ok, 'Error { message | String, notes] } |]
+    = 1
+}
+### diagnostic = ["file:///main.ncl"]
diff --git a/lsp/nls/tests/snapshots/main__lsp__nls__tests__inputs__no-crash-on-pretty-print.ncl.snap b/lsp/nls/tests/snapshots/main__lsp__nls__tests__inputs__no-crash-on-pretty-print.ncl.snap
new file mode 100644
index 00000000..6de4221f
--- /dev/null
+++ b/lsp/nls/tests/snapshots/main__lsp__nls__tests__inputs__no-crash-on-pretty-print.ncl.snap
@@ -0,0 +1,11 @@
+---
+source: lsp/nls/tests/main.rs
+expression: output
+---
+(file:///main.ncl, 2:63-2:64: )
+(file:///main.ncl, 2:63-2:64: unexpected token)
+(file:///main.ncl, 3:6-3:7: incompatible types
+Expected an expression of type `Number -> Dyn -> [| 'Ok, 'Error { message | String, <parse error>, } |]`
+Found an expression of type `Number`
+These types are not compatible)
+(file:///main.ncl, 3:6-3:7: this expression)
Repository: sql-formatter-org/sql-formatter (ts)

Issue:
[FORMATTING] LIMIT format error
**Input data**
select * from account limit 10;
Indentation style: Tabular, Left
**Expected Output**

```sql
select    *
from      account
limit       10;
```

**Actual Output**

```sql
select    *
from      account
limit
          10;
```

**Usage**

- How are you calling / using the library?  I using https://sql-formatter-org.github.io/sql-formatter/
- What SQL language(s) does this apply to? SQL
- Which SQL Formatter version are you using? 10.0.0


Pull request:
Fix tabular style formatting of LIMIT clause
Fixes #412

Patch:
diff --git a/src/formatter/ExpressionFormatter.ts b/src/formatter/ExpressionFormatter.ts
index 8c0fb11f..9bcb42a7 100644
--- a/src/formatter/ExpressionFormatter.ts
+++ b/src/formatter/ExpressionFormatter.ts
@@ -170,13 +170,17 @@ export default class ExpressionFormatter {
     this.layout.add(WS.NEWLINE, WS.INDENT, this.showKw(node.name));
     this.layout.indentation.increaseTopLevel();
 
-    if (node.offset) {
+    if (isTabularStyle(this.cfg)) {
+      this.layout.add(WS.SPACE);
+    } else {
       this.layout.add(WS.NEWLINE, WS.INDENT);
+    }
+
+    if (node.offset) {
       this.layout = this.formatSubExpression(node.offset);
       this.layout.add(WS.NO_SPACE, ',', WS.SPACE);
       this.layout = this.formatSubExpression(node.count);
     } else {
-      this.layout.add(WS.NEWLINE, WS.INDENT);
       this.layout = this.formatSubExpression(node.count);
     }
     this.layout.indentation.decreaseTopLevel();
diff --git a/src/formatter/tabularStyle.ts b/src/formatter/tabularStyle.ts
index 0745b463..75bc8a75 100644
--- a/src/formatter/tabularStyle.ts
+++ b/src/formatter/tabularStyle.ts
@@ -35,6 +35,7 @@ export function isTabularToken(type: TokenType): boolean {
     type === TokenType.RESERVED_COMMAND ||
     type === TokenType.RESERVED_SELECT ||
     type === TokenType.RESERVED_SET_OPERATION ||
-    type === TokenType.RESERVED_JOIN
+    type === TokenType.RESERVED_JOIN ||
+    type === TokenType.LIMIT
   );
 }


Test patch:
diff --git a/test/features/limiting.ts b/test/features/limiting.ts
index 1afe4fbe..a6a33d5c 100644
--- a/test/features/limiting.ts
+++ b/test/features/limiting.ts
@@ -49,6 +49,16 @@ export default function supportsLimiting(format: FormatFn, types: LimitingTypes)
             6;
       `);
     });
+
+    // Regression test for #412
+    it('formats LIMIT in tabular style', () => {
+      const result = format('SELECT * FROM tbl LIMIT 5, 6;', { indentStyle: 'tabularLeft' });
+      expect(result).toBe(dedent`
+        SELECT    *
+        FROM      tbl
+        LIMIT     5, 6;
+      `);
+    });
   }
 
   if (types.limit && types.offset) {
Repository: FriendsOfPHP/PHP-CS-Fixer (php)

Issue:
PHP 8.1 Support
Do we have an issue tracking PHP 8.1 support? If not, could we use this issue to track this. My feeling here is that there isn't too much to do to support PHP 8.1 compared to what was required to support 8.0. :)

Changes to support:

* Support for `readonly` properties (both in class property definitions and also constructor property promotion).
* Support for `final` class constants.
* Support for intersection types (⚠️ lexing changes to `&` in PHP 8.1... maybe a transformer required. EDIT: https://github.com/FriendsOfPHP/PHP-CS-Fixer/pull/5861 looks to be exactly adding a transformer).
* Support for enums (definition sytnax only - i don't think there are any changes to parsing enum access - the same as class constant access).

---

Related: https://github.com/FriendsOfPHP/PHP-CS-Fixer/pull/5863.

Pull request:
PHP 8.1: add new_in_initializers to PHP 8.1 integration test
closes #5891

Patch:
diff --git a/composer.json b/composer.json
index 48ed1f2ad..4ac1cc25f 100644
--- a/composer.json
+++ b/composer.json
@@ -1,8 +1,8 @@
 {
     "name": "friendsofphp/php-cs-fixer",
+    "type": "application",
     "description": "A tool to automatically fix PHP code style",
     "license": "MIT",
-    "type": "application",
     "authors": [
         {
             "name": "Fabien Potencier",
@@ -52,6 +52,9 @@
         "ext-dom": "For handling output formats in XML",
         "ext-mbstring": "For handling non-UTF8 characters."
     },
+    "config": {
+        "sort-packages": true
+    },
     "autoload": {
         "psr-4": {
             "PhpCsFixer\\": "src/"
@@ -64,8 +67,5 @@
     },
     "bin": [
         "php-cs-fixer"
-    ],
-    "config": {
-        "sort-packages": true
-    }
+    ]
 }
diff --git a/dev-tools/composer.json b/dev-tools/composer.json
index c3b703edc..ff133c06b 100644
--- a/dev-tools/composer.json
+++ b/dev-tools/composer.json
@@ -3,7 +3,7 @@
         "php": "^7.4 || ^8.0"
     },
     "require-dev": {
-        "ergebnis/composer-normalize": "^2.17.0",
+        "ergebnis/composer-normalize": "^2.15.0",
         "humbug/box": "^3.8",
         "humbug/php-scoper": "dev-master#0a4e329 as 0.14.2",
         "jangregor/phpstan-prophecy": "^0.8.1",


Test patch:
diff --git a/tests/Fixtures/Integration/misc/PHP8_1.test b/tests/Fixtures/Integration/misc/PHP8_1.test
index 627d78629..e6c8f2f34 100644
--- a/tests/Fixtures/Integration/misc/PHP8_1.test
+++ b/tests/Fixtures/Integration/misc/PHP8_1.test
@@ -47,6 +47,15 @@ fsync($fp);
 // https://wiki.php.net/rfc/explicit_octal_notation
 0o16 === 14;
 
+// https://wiki.php.net/rfc/new_in_initializers
+class TestNewWithInitialiers
+{
+    public function __construct(
+        private Logger $logger = new NullLogger(),
+    ) {
+    }
+}
+
 --INPUT--
 <?php
 
@@ -85,3 +94,12 @@ FSYNC($fp);
 
 // https://wiki.php.net/rfc/explicit_octal_notation
 0O16 === 14;
+
+// https://wiki.php.net/rfc/new_in_initializers
+class TestNewWithInitialiers
+{
+    public function __construct(
+        private Logger $logger = new NullLogger,
+    ) {
+    }
+}
Repository: mattn/go-sqlite3 (c)

Issue:
Large Unix times are not retrieved correctly
My application stores dates as Unix times, integers that represent the number of seconds since January 1st, 1970. This works well in most cases but I noticed a spurious date -- August 30th, 1754 -- occasionally being returned in my Go queries. After some investigation I was able to trace this behaviour to go-sqlite3's handling of Unix times.

When writing to the database, I convert Time values to Unix times with the time.Unix() method. When reading from the database, go-sqlite3 handles the conversion from Unix time back to Time. However this can fail (silently) with large Unix times. For example, if you write a zero Time value to the database as an integer and then query it, you get the aforementioned date August 30th, 1754, even though the Unix time in the database is correct.

Calling time.Time{}.Unix() returns a large negative integer. To convert this integer to a Time value, go-sqlite3 first [converts it to nanoseconds](https://github.com/mattn/go-sqlite3/blob/master/sqlite3.go#L965) by multiplying by 1e9. This causes an integer overflow. It then passes the bad result to the time.Unix() function, resulting in an incorrect Time value. This could be avoided by passing the Unix time directly to the Unix() function. Converting to nanoseconds is unnecessary and increases the chance of an overflow. See this [code snippet](https://play.golang.org/p/-RVHH-W-LB) for an illustration.

Any sufficiently large Unix time will overflow when multiplied by a billion. According to my tests, go-sqlite3 will hit problems with dates pre-1677 or post-2262. These are edge cases for sure but the fix is trivial. I can submit a PR if there's any interest.

Pull request:
Don't convert Unix times to nanoseconds when querying datetime fields…
…. Fixes #430.

Patch:
diff --git a/sqlite3.go b/sqlite3.go
index b34c3a5..d3a6407 100644
--- a/sqlite3.go
+++ b/sqlite3.go
@@ -961,10 +961,11 @@ func (rc *SQLiteRows) Next(dest []driver.Value) error {
 				// large to be a reasonable timestamp in seconds.
 				if val > 1e12 || val < -1e12 {
 					val *= int64(time.Millisecond) // convert ms to nsec
+					t = time.Unix(0, val)
 				} else {
-					val *= int64(time.Second) // convert sec to nsec
+					t = time.Unix(val, 0)
 				}
-				t = time.Unix(0, val).UTC()
+				t = t.UTC()
 				if rc.s.c.loc != nil {
 					t = t.In(rc.s.c.loc)
 				}


Test patch:
diff --git a/sqlite3_test.go b/sqlite3_test.go
index 03b678d..e563479 100644
--- a/sqlite3_test.go
+++ b/sqlite3_test.go
@@ -403,6 +403,7 @@ func TestTimestamp(t *testing.T) {
 	}{
 		{"nonsense", time.Time{}},
 		{"0000-00-00 00:00:00", time.Time{}},
+		{time.Time{}.Unix(), time.Time{}},
 		{timestamp1, timestamp1},
 		{timestamp2.Unix(), timestamp2.Truncate(time.Second)},
 		{timestamp2.UnixNano() / int64(time.Millisecond), timestamp2.Truncate(time.Millisecond)},
Repository: PyCQA/pyflakes (python)

Issue:
Ignore "_" vars in "Unused Variable" check

*Original report by [archardlias](https://launchpad.net/~archardlias) on [Launchpad](https://bugs.launchpad.net/bugs/1328169):*

------------------------------------

Would it be possible to ignore variables named "_" from "Unused Variable" checks?

I'm not really sure whether "_" is officially specified anywhere. But I do see it a lot and in a lot of languages including python to denote a variable to be ignored (place holder dummy). PyLint implements this pseudo(?)-convention (? second-hand knowledge).

Would be great, since I would love to be explicit about "things returned but not used" instead of just calling without assignment which looks tantamount to "this function does never return anything / does not contain a return statement". A great plus in signature visibility throughout the code, specially for first-time readers.

Best regards,
~arlias


Pull request:
Don't warn about unused `_` magic var
Resolves #202

Patch:
diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index bd5eba5..648a224 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -425,7 +425,9 @@ class FunctionScope(Scope):
         Return a generator for the assignments which have not been used.
         """
         for name, binding in self.items():
-            if (not binding.used and name not in self.globals
+            if (not binding.used
+                    and name != '_'  # see issue #202
+                    and name not in self.globals
                     and not self.usesLocals
                     and isinstance(binding, Assignment)):
                 yield name, binding


Test patch:
diff --git a/pyflakes/test/test_imports.py b/pyflakes/test/test_imports.py
index 586a0a5..86e1d37 100644
--- a/pyflakes/test/test_imports.py
+++ b/pyflakes/test/test_imports.py
@@ -94,6 +94,13 @@ class TestImportationObject(TestCase):
         assert binding.source_statement == 'from __future__ import print_function'
         assert str(binding) == '__future__.print_function'
 
+    def test_unusedImport_underscore(self):
+        """
+        The magic underscore var should be reported as unused when used as an
+        import alias.
+        """
+        self.flakes('import fu as _', m.UnusedImport)
+
 
 class Test(TestCase):
 
diff --git a/pyflakes/test/test_other.py b/pyflakes/test/test_other.py
index 364b375..4dbaf23 100644
--- a/pyflakes/test/test_other.py
+++ b/pyflakes/test/test_other.py
@@ -1175,6 +1175,16 @@ class TestUnusedAssignment(TestCase):
             b = 1
         ''', m.UnusedVariable)
 
+    def test_unusedUnderscoreVariable(self):
+        """
+        Don't warn when the magic "_" (underscore) variable is unused.
+        See issue #202.
+        """
+        self.flakes('''
+        def a(unused_param):
+            _ = unused_param
+        ''')
+
     def test_unusedVariableAsLocals(self):
         """
         Using locals() it is perfectly valid to have unused variables
Repository: phpactor/phpactor (php)

Issue:
`new class-string<Foo>()` results in `class-string` not a class
![image](https://user-images.githubusercontent.com/530801/213912705-d08a20bc-6cad-4b58-9c5b-7a3f0c0ecda7.png)


Pull request:
gh-2056: Support new class-string
Fixes #2056 

Patch:
diff --git a/lib/WorseReflection/Core/Inference/Resolver/ObjectCreationExpressionResolver.php b/lib/WorseReflection/Core/Inference/Resolver/ObjectCreationExpressionResolver.php
index a48986c6..8a998be5 100644
--- a/lib/WorseReflection/Core/Inference/Resolver/ObjectCreationExpressionResolver.php
+++ b/lib/WorseReflection/Core/Inference/Resolver/ObjectCreationExpressionResolver.php
@@ -13,6 +13,8 @@ use Phpactor\WorseReflection\Core\Inference\NodeContext;
 use Phpactor\WorseReflection\Core\Inference\Resolver;
 use Phpactor\WorseReflection\Core\Inference\NodeContextResolver;
 use Phpactor\WorseReflection\Core\Type;
+use Phpactor\WorseReflection\Core\TypeFactory;
+use Phpactor\WorseReflection\Core\Type\ClassStringType;
 use Phpactor\WorseReflection\Core\Type\ClassType;
 use Phpactor\WorseReflection\Core\Type\GenericClassType;
 
@@ -33,6 +35,13 @@ class ObjectCreationExpressionResolver implements Resolver
         $classContext = $resolver->resolveNode($frame, $node->classTypeDesignator);
         $classType = $classContext->type();
 
+        if ($classType instanceof ClassStringType) {
+            if ($classType->className() === null) {
+                return $classContext->withType(TypeFactory::object());
+            }
+            $classType = TypeFactory::class($classType->className());
+        }
+
         if ($classType instanceof ClassType) {
             return $classContext->withType($this->resolveClassType($resolver, $frame, $node, $classType));
         }


Test patch:
diff --git a/lib/WorseReflection/Tests/Inference/type/class-string-new-no-type.test b/lib/WorseReflection/Tests/Inference/type/class-string-new-no-type.test
new file mode 100644
index 00000000..5d12778b
--- /dev/null
+++ b/lib/WorseReflection/Tests/Inference/type/class-string-new-no-type.test
@@ -0,0 +1,6 @@
+<?php
+
+/** @var class-string $f */
+$obj = new $f;
+
+wrAssertType('object', $obj);
diff --git a/lib/WorseReflection/Tests/Inference/type/class-string-new.test b/lib/WorseReflection/Tests/Inference/type/class-string-new.test
new file mode 100644
index 00000000..b3c93093
--- /dev/null
+++ b/lib/WorseReflection/Tests/Inference/type/class-string-new.test
@@ -0,0 +1,6 @@
+<?php
+
+$f = Foo::class;
+$f = new $f;
+
+wrAssertType('Foo', $f);
Repository: jsonata-js/jsonata (js)

Issue:
$formatNumber function returns NaN.00 when null in input
Hi,

We are using formatNumber to return an amount field properly formatted. But instead we are getting a "-NaN.00". 

Example:
$formatNumber($number(Account.Order[0].Product[2].Price), "#0.00")
returns "-NaN.00"
in the Account example of TryJSONata.

The expected behavior is it should return a null since the inside evaluation will return a null.

Pull request:
handle undefined inputs in $formatNumber
Add usual `undefined` handling to `$formatNumber` function

Resolves #165 

Patch:
diff --git a/jsonata.js b/jsonata.js
index 02b689c..d4da49f 100644
--- a/jsonata.js
+++ b/jsonata.js
@@ -3570,6 +3570,11 @@ var jsonata = (function() {
      * @returns {String} The formatted string
      */
     function functionFormatNumber(value, picture, options) {
+        // undefined inputs always return undefined
+        if(typeof value === 'undefined') {
+            return undefined;
+        }
+
         var defaults = {
             "decimal-separator": ".",
             "grouping-separator": ",",


Test patch:
diff --git a/test/test-suite/groups/function-formatNumber/case036.json b/test/test-suite/groups/function-formatNumber/case036.json
new file mode 100644
index 0000000..8a864ff
--- /dev/null
+++ b/test/test-suite/groups/function-formatNumber/case036.json
@@ -0,0 +1,6 @@
+{
+    "expr": "$formatNumber(foo, '#0.00')",
+    "dataset": null,
+    "bindings": {},
+    "undefinedResult": true
+}
\ No newline at end of file