Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add type inference for function calls #189

Open
wants to merge 5 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions lib/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,9 @@ const evalFunction = (argsObj, infile, outfile) => {
const core = libName ? importCore(libName) : ''
const tree = parser(program)
if (tree.error) showAndExit(makeErrStr(tree, infile))
const maybeTypeErr = argsObj.t ? null : inferTypes(tree.body)
if (maybeTypeErr !== null) showAndExit(maybeTypeErr.message)
if (argsObj.ast) showAndExit(JSON.stringify(tree, null, 2))
const maybeTypeErr = argsObj.t ? tree.body : inferTypes(tree.body)
if (maybeTypeErr.error) showAndExit(JSON.stringify(maybeTypeErr))
const out = escodegen.generate(tree, { format, comment: true })
fs.writeFileSync(outfile, core + out + '\n', 'utf8')
const commandLineArgs = argsObj._.slice(1)
Expand Down
170 changes: 107 additions & 63 deletions lib/typeInference.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ const inbuiltPropSpec = require('./inbuiltMethods').inbuiltProps
const inbuiltObjects = require('./inbuiltMethods').inbuiltObjects
const jsFunctions = require('./jsFunctions')
const isEmptyObj = require('./utilityFunctions').isEmptyObj

const globalTypesObj = {}
const funcCallTypesObj = {}

const isFunction = (id, typeObj) =>
typeObj[id] !== undefined &&
Expand Down Expand Up @@ -44,6 +46,7 @@ const unaryExprType = (expr) => {
const getType = (expr, expectedType, localTypeObj, id) => {
if (expr !== undefined) {
const type = exprType(expr, localTypeObj, id)
if (expr.type === 'Identifier') return type
return type === expectedType || expectedType === 'bool'
? type
: type === 'needsInference'
Expand Down Expand Up @@ -73,8 +76,12 @@ const checkTypes = (expr, expectedType, localTypeObj, id) => {
const assignTypeToUninferredIdentifier = (expr, inferredType, localTypeObj) => {
if (isEmptyObj(localTypeObj)) return localTypeObj
const [left, right] = [expr.left.name, expr.right.name]
if (left !== undefined && localTypeObj[left] === 'needsInference') { localTypeObj[left] = inferredType }
if (right !== undefined && localTypeObj[right] === 'needsInference') { localTypeObj[right] = inferredType }
if (left !== undefined && localTypeObj[left] === 'needsInference') {
localTypeObj[left] = inferredType
}
if (right !== undefined && localTypeObj[right] === 'needsInference') {
localTypeObj[right] = inferredType
}
}

const binaryExprType = (expr, localTypeObj, id) => {
Expand Down Expand Up @@ -134,13 +141,13 @@ const conditionalExprType = (expr, localTypeObj, id) => {
return consequentType === alternateType ? consequentType : null
}

const mapArgTypeToParams = (params, args, localTypeObj, id) => {
return params.map((param, index) =>
args[index].sType === undefined
? exprType(args[index], localTypeObj, id)
: args[index].sType
)
}
// const mapArgTypeToParams = (params, args, localTypeObj, id) => {
// return params.map((param, index) =>
// args[index].sType === undefined
// ? exprType(args[index], localTypeObj, id)
// : args[index].sType
// )
// }

const makeParamTypeArray = (localTypeObj) => {
const paramTypes = []
Expand Down Expand Up @@ -217,33 +224,34 @@ const checkForRecursion = (callee, id, localTypeObj, args) => {
const getFunctionType = (calleeName) => jsFunctions[calleeName]

const callExprType = (expr, localTypeObj = {}, id) => {
const calleeName = expr.callee.name
if (
expr.callee.type === 'Identifier' &&
globalTypesObj[expr.callee.name] === undefined
globalTypesObj[calleeName] === undefined
) {
const calleeName = expr.callee.name
globalTypesObj[calleeName] = getFunctionType(calleeName)
}
const [params, body, args] = [
expr.callee.params,
expr.callee.body,
expr.arguments
]
if (expr.sType !== undefined) return expr.sType // if call has type already set
if (
params !== undefined &&
body !== undefined &&
(!isEmptyObj(localTypeObj) || expr.callee.id === null)
) {
const typesOfParams = mapArgTypeToParams(params, args, localTypeObj, id)
args.map((arg) => exprType(arg, localTypeObj, id))
params.map((param, index) => {
localTypeObj[param.name] = typesOfParams[index]
return param
})
return exprType(body, localTypeObj, id)
}
const isRecursive = checkForRecursion(expr.callee.name, id, localTypeObj, args)
const args = expr.arguments
// const [params, body, args] = [
// expr.callee.params,
// expr.callee.body,
// expr.arguments
// ]
// if (expr.sType !== undefined) return expr.sType // if call has type already set
// if (
// params !== undefined &&
// body !== undefined &&
// (!isEmptyObj(localTypeObj) || expr.callee.id === null)
// ) {
// const typesOfParams = mapArgTypeToParams(params, args, localTypeObj, id)
// args.map((arg) => exprType(arg, localTypeObj, id))
// params.map((param, index) => {
// localTypeObj[param.name] = typesOfParams[index]
// return param
// })
// return exprType(body, localTypeObj, id)
// }
const isRecursive = checkForRecursion(calleeName, id, localTypeObj, args)
let result = exprType(expr.callee, localTypeObj, id)
if (result === null) return null
if (expr.callee.id === null) result = [result.paramTypes, result.returnType]
Expand All @@ -255,13 +263,19 @@ const callExprType = (expr, localTypeObj = {}, id) => {
localTypeObj,
id
)
return match ? returnType : null
returnType = match ? returnType : null
if (calleeName) {
funcCallTypesObj[calleeName] = returnType
}
return returnType
}

const reduceTypes = (typesArr, localTypeObj, id) => {
const reducedType = typesArr
.map((e) => {
if (e.type !== undefined && e.type === 'Identifier') { return { id: e.name, type: exprType(e, localTypeObj, id) } }
if (e.type !== undefined && e.type === 'Identifier') {
return { id: e.name, type: exprType(e, localTypeObj, id) }
}
return { id: null, type: exprType(e, localTypeObj, id) }
})
.reduce((exp1, exp2) => {
Expand All @@ -278,39 +292,34 @@ const reduceTypes = (typesArr, localTypeObj, id) => {
localTypeObj[exp2.id] = exp1.type
}
if (typeof exp1.type === 'object' && typeof exp2.type === 'object') {
return exp1.type.type === exp2.type.type ? exp1.type : false
return exp1.type.type === exp2.type.type ? exp1.type : null
}
return exp1.type === exp2.type ? exp1 : false
return exp1.type === exp2.type ? exp1 : null
})
return reducedType !== false ? reducedType.type : false
return reducedType !== null ? reducedType.type : null
}

const switchStatementType = (body, localTypeObj, id) => {
const cases = body.cases
const [initialPattern] = cases
let [returnType, acceptedType] = [
initialPattern.consequent[0].argument,
initialPattern.test
].map((exp) => exprType(exp, localTypeObj, id))
const initialPattern = cases[0]
let returnType = exprType(initialPattern.consequent[0].argument, localTypeObj, id)
const acceptedType = exprType(initialPattern.test, localTypeObj, id)
const paramId = body.discriminant.name
localTypeObj[paramId] = acceptedType
const [caseArgArray, caseTestArray] = [
cases.map((c) => c.consequent[0].argument),
cases.map((c) =>
c.test === null
? { type: 'Identifier', name: paramId, sType: acceptedType }
: c.test
)
]
const checkTestType = reduceTypes(caseTestArray, localTypeObj, id)
const checkArgsType = reduceTypes(caseArgArray, localTypeObj, id)
if (returnType === 'needsInference') returnType = checkArgsType
const caseConseqArray = cases.map((c) => c.consequent[0].argument)
const caseTestArray = cases.map((c) => c.test === null
? { type: 'Identifier', name: paramId, sType: acceptedType }
: c.test
)
const conseqType = reduceTypes(caseConseqArray, localTypeObj, id)
const testType = reduceTypes(caseTestArray, localTypeObj, id)
if (returnType === 'needsInference') returnType = conseqType
globalTypesObj[id] = {
type: 'function',
paramTypes: makeParamTypeArray(localTypeObj, id),
returnType
}
return checkArgsType === false || checkTestType === false ? null : returnType
return (conseqType && testType) ? returnType : null
}

const arrayExprType = (expr, localTypeObj, id) => {
Expand Down Expand Up @@ -537,7 +546,6 @@ const blockStatementType = (stmnt, localTypeObj, id) => {
const exprType = (expr, localTypeObj = {}, id = null) => {
if (expr !== null && expr.sType !== undefined && expr.sType === 'IO') { return 'IO' }
if (expr === null) return 'needsInference'
if (expr.type === 'ExpressionStatement') expr = expr.expression
const type = expr.type
switch (type) {
case 'Literal':
Expand Down Expand Up @@ -579,6 +587,21 @@ const declTypeExtract = (stmnt) => {
globalTypesObj[id] = type
}
}
const exprTypeExtract = (stmnt) => {
const expr = stmnt.expression
if (expr.sType === 'IO' && !isIOCall(expr)) {
const args = expr.arguments
args.forEach(arg => exprType(arg))
} else if (!isIOCall(expr)) {
exprType(expr)
}
}

const isIOCall = (expr) => {
if (!expr.callee.object) return false
const method = expr.callee.object.name
return globalTypesObj[method] === 'IO'
}

const loadInbuiltObjects = () => {
for (const obj in inbuiltObjects) {
Expand All @@ -592,22 +615,43 @@ const delObj = (obj) => {
}
}

const types = (body) => {
loadInbuiltObjects()
body.forEach((expr) => {
const type = expr.type
if (type === 'VariableDeclaration') declTypeExtract(expr)
})
const errorObj = { error: false }
const errorObj = { error: false }

const makeTypeError = (error) => {
return `TypeError at ${error.type} '${error.id}'`
}

const checkForErrors = () => {
for (const decl in globalTypesObj) {
if (globalTypesObj[decl] === null) {
errorObj.error = true
errorObj.id = decl
break
errorObj.type = 'VariableDeclaration'
return
}
}
for (const call in funcCallTypesObj) {
if (funcCallTypesObj[call] === null) {
errorObj.error = true
errorObj.id = call
errorObj.type = 'CallExpression'
return
}
}
}

const types = (body) => {
delObj(errorObj)
loadInbuiltObjects()
body.forEach((expr) => {
const type = expr.type
if (type === 'VariableDeclaration') declTypeExtract(expr)
else if (type === 'ExpressionStatement') exprTypeExtract(expr)
})
checkForErrors()
delObj(globalTypesObj)
return errorObj.error ? errorObj : body
delObj(funcCallTypesObj)
return errorObj.error ? { ...errorObj, message: makeTypeError(errorObj) } : null
}

/* Module Exports types */
Expand Down
18 changes: 18 additions & 0 deletions test/assert/funcDecl.json
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,24 @@
}
],
"kind": "const"
},
{
"type": "ExpressionStatement",
"expression": {
"type": "CallExpression",
"callee": {
"type": "Identifier",
"name": "fact"
},
"arguments": [
{
"type": "Literal",
"value": 10,
"raw": "10",
"sType": "number"
}
]
}
}
],
"sourceType": "script"
Expand Down
7 changes: 7 additions & 0 deletions test/assert/typeErrors/funcDeclWithTypeError.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"error": true,
"id": "fact",
"message": "TypeError at CallExpression 'fact'",
"type": "CallExpression"
}

7 changes: 6 additions & 1 deletion test/assert/typeErrors/typeError.json
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
{ "error": true, "id": "a" }
{
"error": true,
"id": "a",
"message": "TypeError at VariableDeclaration 'a'",
"type": "VariableDeclaration"
}
5 changes: 2 additions & 3 deletions test/sourceFiles.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@ const generateTree = input => {
}
const tree = parser(rest)
if (tree.error) return tree
const newTree = typeInfer(tree.body)
if (newTree.error) return newTree
tree.body = newTree
const maybeTypeErrors = typeInfer(tree.body)
if (maybeTypeErrors !== null) return maybeTypeErrors
return tree
}

Expand Down
2 changes: 2 additions & 0 deletions test/src/funcDecl.cl
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
fact 0 = 1
fact 1 = 1
fact n = n * fact (n - 1)

fact 10
5 changes: 5 additions & 0 deletions test/src/typeErrors/funcDeclWithTypeError.cl
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
fact 0 = 1
fact 1 = 1
fact n = n * fact (n - 1)

fact 'a'