Skip to content

Commit

Permalink
fix: #42
Browse files Browse the repository at this point in the history
  • Loading branch information
meixg committed Nov 6, 2019
1 parent 3685cff commit 1559fb0
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ import {
isClassLike,
isClassInstance,
isFunctionLike,
isVariable
isVariable,
shouldUseReference
} from './utilities/nodeTest';

import {
Expand Down Expand Up @@ -2749,6 +2750,11 @@ export function emitFile(
writeSpace();
emitTokenWithComment(SyntaxKind.EqualsToken, equalCommentStartPos, writeOperator, container);
writeSpace();

if (shouldUseReference(node, typeChecker)) {
writeBase("&");
}

emitExpression(node);
}
}
Expand Down
9 changes: 9 additions & 0 deletions src/utilities/nodeTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,15 @@ export function shouldUseArray(format: ts.ListFormat) {
return arrayBracketsMap[format] || '';
}

/**
* e.g. let a = []; let b = a; ==> $a = array(); $b = &$a;
* @param node node
*/
export function shouldUseReference(node: ts.Node, typeChecker: ts.TypeChecker) {
const nodeType = typeChecker.getTypeAtLocation(node);
return ts.isIdentifier(node) && !isFunctionLike(node, typeChecker) && (nodeType.flags === ts.TypeFlags.Object);
}

const stringLikeType = new Set([
ts.TypeFlags.String,
ts.TypeFlags.StringLiteral
Expand Down
8 changes: 8 additions & 0 deletions test/features/reference.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php
namespace test\case_reference;
$a = array();
$b = &$a;
$c = array();
$d = &$c;
$e = function () { };
$f = $e;
8 changes: 8 additions & 0 deletions test/features/reference.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
let a: number[] = [];
let b = a;

let c: {aaa?: string} = {};
let d = c;

let e = function () {};
let f = e;

0 comments on commit 1559fb0

Please sign in to comment.