Skip to content

Implement --noUnsafe compiler option #710

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

Merged
merged 5 commits into from
Jul 22, 2019
Merged
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
1 change: 1 addition & 0 deletions cli/asc.js
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,7 @@ exports.main = function main(argv, options, callback) {
assemblyscript.setMemoryBase(compilerOptions, args.memoryBase >>> 0);
assemblyscript.setSourceMap(compilerOptions, args.sourceMap != null);
assemblyscript.setOptimizeLevelHints(compilerOptions, optimizeLevel, shrinkLevel);
assemblyscript.setNoUnsafe(compilerOptions, args.noUnsafe);

// Initialize default aliases
assemblyscript.setGlobalAlias(compilerOptions, "Math", "NativeMath");
Expand Down
8 changes: 8 additions & 0 deletions cli/asc.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,14 @@
"type": "s",
"default": "full"
},
"noUnsafe": {
"description": [
"Disallows the use of unsafe features in user code.",
"Does not affect library files and external modules."
],
"type": "b",
"default": false
},
"debug": {
"description": "Enables debug information in emitted binaries.",
"type": "b",
Expand Down
22 changes: 12 additions & 10 deletions src/ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1585,12 +1585,14 @@ export abstract class Statement extends Node { }

/** Indicates the specific kind of a source. */
export enum SourceKind {
/** Default source. Usually imported from an entry file. */
DEFAULT,
/** Entry file. */
ENTRY,
/** Library file. */
LIBRARY
/** User-provided file. */
USER = 0,
/** User-provided entry file. */
USER_ENTRY = 1,
/** Library-provided file. */
LIBRARY = 2,
/** Library-provided entry file. */
LIBRARY_ENTRY = 3
}

/** A top-level source node. */
Expand Down Expand Up @@ -1631,10 +1633,10 @@ export class Source extends Node {
this.text = text;
}

/** Tests if this source is an entry file. */
get isEntry(): bool { return this.sourceKind == SourceKind.ENTRY; }
/** Tests if this source is a stdlib file. */
get isLibrary(): bool { return this.sourceKind == SourceKind.LIBRARY; }
get isLibrary(): bool {
var kind = this.sourceKind;
return kind == SourceKind.LIBRARY || kind == SourceKind.LIBRARY_ENTRY;
}
}

/** Base class of all declaration statements. */
Expand Down
36 changes: 29 additions & 7 deletions src/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,8 @@ import {
nodeIsConstantValue,
findDecorator,
isTypeOmitted,
ExportDefaultStatement
ExportDefaultStatement,
SourceKind
} from "./ast";

import {
Expand Down Expand Up @@ -201,6 +202,8 @@ export class Options {
globalAliases: Map<string,string> | null = null;
/** Additional features to activate. */
features: Feature = Feature.NONE;
/** If true, disallows unsafe features in user code. */
noUnsafe: bool = false;

/** Hinted optimize level. Not applied by the compiler itself. */
optimizeLevelHint: i32 = 0;
Expand Down Expand Up @@ -360,7 +363,7 @@ export class Compiler extends DiagnosticEmitter {
// compile entry file(s) while traversing reachable elements
var files = program.filesByName;
for (let file of files.values()) {
if (file.source.isEntry) {
if (file.source.sourceKind == SourceKind.USER_ENTRY) {
this.compileFile(file);
this.compileExports(file);
}
Expand Down Expand Up @@ -451,7 +454,7 @@ export class Compiler extends DiagnosticEmitter {

// set up module exports
for (let file of this.program.filesByName.values()) {
if (file.source.isEntry) this.ensureModuleExports(file);
if (file.source.sourceKind == SourceKind.USER_ENTRY) this.ensureModuleExports(file);
}
return module;
}
Expand Down Expand Up @@ -5145,12 +5148,10 @@ export class Compiler extends DiagnosticEmitter {
if (!this.compileGlobal(<Global>target)) return this.module.unreachable(); // reports
// fall-through
}
case ElementKind.LOCAL:
case ElementKind.FIELD: {
targetType = (<VariableLikeElement>target).type;
break;
}
case ElementKind.LOCAL: {
targetType = (<VariableLikeElement>target).type;
if (target.hasDecorator(DecoratorFlags.UNSAFE)) this.checkUnsafe(expression);
break;
}
case ElementKind.PROPERTY_PROTOTYPE: { // static property
Expand All @@ -5166,6 +5167,7 @@ export class Compiler extends DiagnosticEmitter {
if (!setterInstance) return this.module.unreachable();
assert(setterInstance.signature.parameterTypes.length == 1); // parser must guarantee this
targetType = setterInstance.signature.parameterTypes[0];
if (setterPrototype.hasDecorator(DecoratorFlags.UNSAFE)) this.checkUnsafe(expression);
break;
}
case ElementKind.PROPERTY: { // instance property
Expand All @@ -5179,6 +5181,7 @@ export class Compiler extends DiagnosticEmitter {
}
assert(setterInstance.signature.parameterTypes.length == 1); // parser must guarantee this
targetType = setterInstance.signature.parameterTypes[0];
if (setterInstance.hasDecorator(DecoratorFlags.UNSAFE)) this.checkUnsafe(expression);
break;
}
case ElementKind.CLASS: {
Expand Down Expand Up @@ -5215,6 +5218,7 @@ export class Compiler extends DiagnosticEmitter {
}
assert(indexedSet.signature.parameterTypes.length == 2); // parser must guarantee this
targetType = indexedSet.signature.parameterTypes[1]; // 2nd parameter is the element
if (indexedSet.hasDecorator(DecoratorFlags.UNSAFE)) this.checkUnsafe(expression);
break;
}
// fall-through
Expand Down Expand Up @@ -5872,6 +5876,7 @@ export class Compiler extends DiagnosticEmitter {
makeMap<string,Type>(flow.contextualTypeArguments)
);
if (!instance) return this.module.unreachable();
if (prototype.hasDecorator(DecoratorFlags.UNSAFE)) this.checkUnsafe(expression);
return this.makeCallDirect(instance, argumentExprs, expression, contextualType == Type.void);
// TODO: this skips inlining because inlining requires compiling its temporary locals in
// the scope of the inlined flow. might need another mechanism to lock temp. locals early,
Expand Down Expand Up @@ -6009,6 +6014,8 @@ export class Compiler extends DiagnosticEmitter {
expression: CallExpression,
contextualType: Type
): ExpressionRef {
if (prototype.hasDecorator(DecoratorFlags.UNSAFE)) this.checkUnsafe(expression);

var typeArguments: Type[] | null = null;

// builtins handle omitted type arguments on their own. if present, however, resolve them here
Expand Down Expand Up @@ -6107,6 +6114,17 @@ export class Compiler extends DiagnosticEmitter {
return true;
}

/** Checks that an unsafe expression is allowed. */
private checkUnsafe(reportNode: Node): void {
// Library files may always use unsafe features
if (this.options.noUnsafe && !reportNode.range.source.isLibrary) {
this.error(
DiagnosticCode.Expression_is_unsafe,
reportNode.range
);
}
}

/** Compiles a direct call to a concrete function. */
compileCallDirect(
instance: Function,
Expand All @@ -6126,6 +6144,7 @@ export class Compiler extends DiagnosticEmitter {
this.currentType = signature.returnType;
return this.module.unreachable();
}
if (instance.hasDecorator(DecoratorFlags.UNSAFE)) this.checkUnsafe(reportNode);

// Inline if explicitly requested
if (instance.hasDecorator(DecoratorFlags.INLINE)) {
Expand Down Expand Up @@ -7687,6 +7706,7 @@ export class Compiler extends DiagnosticEmitter {
);
return module.unreachable();
}
if (ctor.hasDecorator(DecoratorFlags.UNSAFE)) this.checkUnsafe(expression);
}

// check and compile field values
Expand Down Expand Up @@ -7904,6 +7924,7 @@ export class Compiler extends DiagnosticEmitter {
reportNode: Node
): ExpressionRef {
var ctor = this.ensureConstructor(classInstance, reportNode);
if (ctor.hasDecorator(DecoratorFlags.UNSAFE)) this.checkUnsafe(reportNode);
var expr = this.compileCallDirect( // no need for another autoreleased local
ctor,
argumentExpressions,
Expand Down Expand Up @@ -7934,6 +7955,7 @@ export class Compiler extends DiagnosticEmitter {

var target = this.resolver.resolvePropertyAccessExpression(propertyAccess, flow, contextualType); // reports
if (!target) return module.unreachable();
if (target.hasDecorator(DecoratorFlags.UNSAFE)) this.checkUnsafe(propertyAccess);

switch (target.kind) {
case ElementKind.GLOBAL: { // static field
Expand Down
6 changes: 5 additions & 1 deletion src/definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ import {
TypeKind
} from "./types";

import {
SourceKind
} from "./ast";

import {
indent
} from "./util";
Expand All @@ -55,7 +59,7 @@ abstract class ExportsWalker {
/** Walks all elements and calls the respective handlers. */
walk(): void {
for (let file of this.program.filesByName.values()) {
if (file.source.isEntry) this.visitFile(file);
if (file.source.sourceKind == SourceKind.USER_ENTRY) this.visitFile(file);
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/diagnosticMessages.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export enum DiagnosticCode {
Module_cannot_have_multiple_start_functions = 221,
_0_must_be_a_value_between_1_and_2_inclusive = 222,
_0_must_be_a_power_of_two = 223,
TODO_Cannot_inline_inferred_calls_and_specific_internals_yet = 224,
Expression_is_unsafe = 224,
Expression_is_never_null = 225,
Unterminated_string_literal = 1002,
Identifier_expected = 1003,
Expand Down Expand Up @@ -173,7 +173,7 @@ export function diagnosticCodeToString(code: DiagnosticCode): string {
case 221: return "Module cannot have multiple start functions.";
case 222: return "'{0}' must be a value between '{1}' and '{2}' inclusive.";
case 223: return "'{0}' must be a power of two.";
case 224: return "TODO: Cannot inline inferred calls and specific internals yet.";
case 224: return "Expression is unsafe.";
case 225: return "Expression is never 'null'.";
case 1002: return "Unterminated string literal.";
case 1003: return "Identifier expected.";
Expand Down
2 changes: 1 addition & 1 deletion src/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"Module cannot have multiple start functions.": 221,
"'{0}' must be a value between '{1}' and '{2}' inclusive.": 222,
"'{0}' must be a power of two.": 223,
"TODO: Cannot inline inferred calls and specific internals yet.": 224,
"Expression is unsafe.": 224,
"Expression is never 'null'.": 225,

"Unterminated string literal.": 1002,
Expand Down
5 changes: 5 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,11 @@ export function setExplicitStart(options: Options, explicitStart: bool): void {
options.explicitStart = explicitStart;
}

/** Sets the `noUnsafe` option. */
export function setNoUnsafe(options: Options, noUnsafe: bool): void {
options.noUnsafe = noUnsafe;
}

/** Sign extension operations. */
export const FEATURE_SIGN_EXTENSION = Feature.SIGN_EXTENSION;
/** Mutable global imports and exports. */
Expand Down
10 changes: 6 additions & 4 deletions src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,10 +128,12 @@ export class Parser extends DiagnosticEmitter {
normalizedPath,
text,
isEntry
? SourceKind.ENTRY
: path.startsWith(LIBRARY_PREFIX) && path.indexOf(PATH_DELIMITER, LIBRARY_PREFIX.length) < 0
? SourceKind.LIBRARY
: SourceKind.DEFAULT
? SourceKind.USER_ENTRY
: path.startsWith(LIBRARY_PREFIX)
? path.indexOf(PATH_DELIMITER, LIBRARY_PREFIX.length) < 0
? SourceKind.LIBRARY_ENTRY
: SourceKind.LIBRARY
: SourceKind.USER
);
var program = this.program;
program.sources.push(source);
Expand Down
12 changes: 8 additions & 4 deletions src/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ export class Program extends DiagnosticEmitter {
diagnostics: DiagnosticMessage[] | null = null
) {
super(diagnostics);
var nativeSource = new Source(LIBRARY_SUBST, "[native code]", SourceKind.LIBRARY);
var nativeSource = new Source(LIBRARY_SUBST, "[native code]", SourceKind.LIBRARY_ENTRY);
this.nativeSource = nativeSource;
var nativeFile = new File(this, nativeSource);
this.nativeFile = nativeFile;
Expand Down Expand Up @@ -876,8 +876,9 @@ export class Program extends DiagnosticEmitter {
// mark module exports, i.e. to apply proper wrapping behavior on the boundaries
for (let file of this.filesByName.values()) {
let exports = file.exports;
if (!(file.source.isEntry && exports)) continue;
for (let element of exports.values()) this.markModuleExport(element);
if (exports !== null && file.source.sourceKind == SourceKind.USER_ENTRY) {
for (let element of exports.values()) this.markModuleExport(element);
}
}
}

Expand Down Expand Up @@ -2188,7 +2189,7 @@ export class File extends Element {
var exports = this.exports;
if (!exports) this.exports = exports = new Map();
exports.set(name, element);
if (this.source.isLibrary) this.program.ensureGlobal(name, element);
if (this.source.sourceKind == SourceKind.LIBRARY_ENTRY) this.program.ensureGlobal(name, element);
}

/** Ensures that another file is a re-export of this file. */
Expand Down Expand Up @@ -2876,6 +2877,7 @@ export class Field extends VariableLikeElement {
);
this.prototype = prototype;
this.flags = prototype.flags;
this.decoratorFlags = prototype.decoratorFlags;
assert(type != Type.void);
this.setType(type);
registerConcreteElement(this.program, this);
Expand Down Expand Up @@ -2945,6 +2947,8 @@ export class Property extends VariableLikeElement {
)
);
this.prototype = prototype;
this.flags = prototype.flags;
this.decoratorFlags = prototype.decoratorFlags;
registerConcreteElement(this.program, this);
}

Expand Down
20 changes: 12 additions & 8 deletions src/resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1492,10 +1492,12 @@ export class Resolver extends DiagnosticEmitter {
}
let typeNode = parameterDeclaration.type;
if (isTypeOmitted(typeNode)) {
this.error(
DiagnosticCode.Type_expected,
typeNode.range
);
if (reportMode == ReportMode.REPORT) {
this.error(
DiagnosticCode.Type_expected,
typeNode.range
);
}
return null;
}
let parameterType = this.resolveType(
Expand All @@ -1518,10 +1520,12 @@ export class Resolver extends DiagnosticEmitter {
} else {
let typeNode = signatureNode.returnType;
if (isTypeOmitted(typeNode)) {
this.error(
DiagnosticCode.Type_expected,
typeNode.range
);
if (reportMode == ReportMode.REPORT) {
this.error(
DiagnosticCode.Type_expected,
typeNode.range
);
}
return null;
}
let type = this.resolveType(
Expand Down
Loading