Skip to content

Commit

Permalink
fixed some issues
Browse files Browse the repository at this point in the history
  • Loading branch information
Nimaoth committed Dec 17, 2023
1 parent 11fea4f commit 222ab7b
Show file tree
Hide file tree
Showing 7 changed files with 92 additions and 11 deletions.
8 changes: 8 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"nim.project": ["src/absytree.nim"],
"nim.projectMapping": [{
"projectFile": "src/absytree.nim",
"fileRegex": ".*\\.nim"
}
]
}
8 changes: 8 additions & 0 deletions src/ast/base_language_wasm.nim
Original file line number Diff line number Diff line change
Expand Up @@ -941,6 +941,14 @@ proc genNodeFunctionDefinition(self: BaseLanguageWasmCompiler, node: AstNode, de
self.instr(GlobalSet, globalIdx: self.stackPointer)
i

# check stack pointer
self.instr(GlobalGet, globalIdx: self.stackPointer)
self.instr(I32Const, i32Const: 0)
self.instr(I32LeS)
self.instr(If, ifType: WasmBlockType(kind: ValType, typ: WasmValueType.none),
ifThenInstr: @[WasmInstr(kind: Unreachable)],
ifElseInstr: @[])

let destination = if returnType.class == IdVoid:
Destination(kind: Discard)
elif passReturnAsOutParam:
Expand Down
40 changes: 35 additions & 5 deletions src/ast/generator_wasm.nim
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,9 @@ type
allocFunc: WasmFuncIdx
cstrToInternal*: WasmFuncIdx

stackSize: int32
activeDataOffset: int32

stackBase: WasmGlobalIdx
stackEnd: WasmGlobalIdx
stackPointer: WasmGlobalIdx
Expand Down Expand Up @@ -106,6 +109,8 @@ proc newBaseLanguageWasmCompiler*(ctx: ModelComputationContextBase): BaseLanguag
result.builder.addExport("memory", 0.WasmMemIdx)
result.functionRefTableIdx = result.builder.addTable()
result.builder.addExport("__indirect_function_table", result.functionRefTableIdx)
result.stackSize = wasmPageSize * 10
result.activeDataOffset = align(result.stackSize, wasmPageSize)

result.printI32 = result.builder.addImport("env", "print_i32", result.builder.addType([I32], []))
result.printU32 = result.builder.addImport("env", "print_u32", result.builder.addType([I32], []))
Expand All @@ -119,7 +124,7 @@ proc newBaseLanguageWasmCompiler*(ctx: ModelComputationContextBase): BaseLanguag
result.intToString = result.builder.addImport("env", "intToString", result.builder.addType([I32], [I32]))
result.stackBase = result.builder.addGlobal(I32, mut=true, 0, id="__stack_base")
result.stackEnd = result.builder.addGlobal(I32, mut=true, 0, id="__stack_end")
result.stackPointer = result.builder.addGlobal(I32, mut=true, 65536, id="__stack_pointer")
result.stackPointer = result.builder.addGlobal(I32, mut=true, result.stackSize, id="__stack_pointer")
result.memoryBase = result.builder.addGlobal(I32, mut=false, 0, id="__memory_base")
result.tableBase = result.builder.addGlobal(I32, mut=false, 0, id="__table_base")
result.heapBase = result.builder.addGlobal(I32, mut=false, 0, id="__heap_base")
Expand All @@ -134,6 +139,32 @@ proc newBaseLanguageWasmCompiler*(ctx: ModelComputationContextBase): BaseLanguag
WasmInstr(kind: LocalGet, localIdx: 0.WasmLocalIdx),
WasmInstr(kind: I32Add),
WasmInstr(kind: GlobalSet, globalIdx: result.heapSize),

# check/grow memory size
WasmInstr(kind: MemorySize),
WasmInstr(kind: I32Const, i32Const: wasmPageSize),
WasmInstr(kind: I32Mul),
WasmInstr(kind: GlobalGet, globalIdx: result.heapBase),
WasmInstr(kind: GlobalGet, globalIdx: result.heapSize),
WasmInstr(kind: I32Add),
WasmInstr(kind: I32LeS),
WasmInstr(kind: If, ifType: WasmBlockType(kind: ValType, typ: WasmValueType.none),
ifThenInstr: @[
WasmInstr(kind: LocalGet, localIdx: 0.WasmLocalIdx),
WasmInstr(kind: I32Const, i32Const: wasmPageSize),
WasmInstr(kind: I32DivS),
WasmInstr(kind: I32Const, i32Const: 1),
WasmInstr(kind: I32Add),
WasmInstr(kind: MemoryGrow),
WasmInstr(kind: I32Const, i32Const: -1),
WasmInstr(kind: I32Eq),
WasmInstr(kind: If, ifType: WasmBlockType(kind: ValType, typ: WasmValueType.none),
ifThenInstr: @[
WasmInstr(kind: Unreachable),
],
ifElseInstr: @[]),
],
ifElseInstr: @[]),
]))

discard result.builder.addFunction([I32], [], [], exportName="my_dealloc".some, body=WasmExpr(instr: @[
Expand Down Expand Up @@ -266,11 +297,10 @@ proc compileToBinary*(self: BaseLanguageWasmCompiler, node: AstNode): seq[uint8]
discard self.getOrCreateWasmFunc(node, exportName=functionName.some)
self.compileRemainingFunctions()

let activeDataOffset = wasmPageSize # todo: after stack
let activeDataSize = self.globalData.len.int32
discard self.builder.addActiveData(0.WasmMemIdx, activeDataOffset, self.globalData)
discard self.builder.addActiveData(0.WasmMemIdx, self.activeDataOffset, self.globalData)

let heapBase = align(activeDataOffset + activeDataSize, wasmPageSize)
let heapBase = align(self.activeDataOffset + activeDataSize, wasmPageSize)
self.builder.globals[self.heapBase.int].init = WasmInstr(kind: I32Const, i32Const: heapBase)

self.builder.getTable(self.functionRefTableIdx).typ.limits.min = self.functionRefIndices.len.uint32
Expand Down Expand Up @@ -395,7 +425,7 @@ proc addStringData*(self: BaseLanguageWasmCompiler, value: string): int32 =
self.globalData.add(value.toOpenArrayByte(0, value.high))
self.globalData.add(0)

result = offset + wasmPageSize
result = offset + self.activeDataOffset

macro instr*(self: WasmExpr, op: WasmInstrKind, args: varargs[untyped]): untyped =
result = genAst(self, op):
Expand Down
4 changes: 2 additions & 2 deletions src/model_document.nim
Original file line number Diff line number Diff line change
Expand Up @@ -2848,7 +2848,7 @@ proc insertTextAtCursor*(self: ModelDocumentEditor, input: string): bool {.expos
# typePostfixTransformations[(IdString, ".ptr")] = NodeTransformation(kind: Wrap, wrapClass: IdStringGetPointer, wrapRole: IdStringGetPointerValue, wrapCursorTargetRole: IdStringGetPointerValue, selectNextPlaceholder: true, wrapChildIndex: 0)
# typePostfixTransformations[(IdString, ".len")] = NodeTransformation(kind: Wrap, wrapClass: IdStringGetLength, wrapRole: IdStringGetLengthValue, wrapCursorTargetRole: IdStringGetLengthValue, selectNextPlaceholder: true, wrapChildIndex: 0)

if not self.selection.isEmpty:
if not self.selection.isEmpty and not self.showCompletions:
let (parentCell, _, _) = self.selection.getParentInfo
if self.selection.first < self.selection.last:
if postfixTransformations.findTransformation(parentCell.node.nodeClass, input).getSome(transformation):
Expand All @@ -2860,7 +2860,7 @@ proc insertTextAtCursor*(self: ModelDocumentEditor, input: string): bool {.expos
return true

if getTargetCell(self.cursor).getSome(cell):
if self.selection.isEmpty:
if self.selection.isEmpty and not self.showCompletions:
if self.cursor.isAtEndOfLastCellOfNode and postfixTransformations.findTransformation(cell.node.nodeClass, input).getSome(transformation):
self.cursor = self.applyTransformation(cell.node, transformation)
return true
Expand Down
7 changes: 4 additions & 3 deletions src/platform/widget_builder_text_document.nim
Original file line number Diff line number Diff line change
Expand Up @@ -450,9 +450,10 @@ proc createCompletions(self: TextDocumentEditor, builder: UINodeBuilder, app: Ap
builder.panel(&{UINodeFlag.MaskContent}, w = listWidth * charWidth, h = bottom - top):
builder.createLines(self.completionsBaseIndex, self.completionsScrollOffset, self.completions.high, false, false, backgroundColor, handleScroll, handleLine)

builder.panel(&{UINodeFlag.FillBackground, DrawText, MaskContent, TextWrap},
x = listWidth * charWidth, w = docsWidth * charWidth, h = bottom - top,
backgroundColor = backgroundColor, textColor = docsColor, text = self.completions[self.selectedCompletion].doc)
if self.selectedCompletion < self.completions.len:
builder.panel(&{UINodeFlag.FillBackground, DrawText, MaskContent, TextWrap},
x = listWidth * charWidth, w = docsWidth * charWidth, h = bottom - top,
backgroundColor = backgroundColor, textColor = docsColor, text = self.completions[self.selectedCompletion].doc)

if completionsPanel.bounds.yh > completionsPanel.parent.bounds.h:
completionsPanel.rawY = cursorBounds.y
Expand Down
35 changes: 34 additions & 1 deletion src/scripting/wasm.nim
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,15 @@ when defined(js):
functions: Table[cstring, proc()]
module: WasmModule

proc newUint8Array(memory: JsObject) {.importjs: "new Uint8Array(#.buffer)".}
proc newUint16Array(memory: JsObject) {.importjs: "new Uint16Array(#.buffer)".}
proc newUint32Array(memory: JsObject) {.importjs: "new Uint32Array(#.buffer)".}
proc newInt8Array(memory: JsObject) {.importjs: "new Int8Array(#.buffer)".}
proc newInt16Array(memory: JsObject) {.importjs: "new Int16Array(#.buffer)".}
proc newInt32Array(memory: JsObject) {.importjs: "new Int32Array(#.buffer)".}
proc newFloat32Array(memory: JsObject) {.importjs: "new Float32Array(#.buffer)".}
proc newFloat64Array(memory: JsObject) {.importjs: "new Float64Array(#.buffer)".}

else:
import wasm3, wasm3/[wasm3c, wasmconversions]

Expand All @@ -45,10 +54,22 @@ proc dealloc*(module: WasmModule, p: WasmPtr) =

when defined(js):
proc copyMem*(module: WasmModule, dest: WasmPtr, source: JsObject, len: int, offset = 0u32) =
let heap = module.memory["HEAPU8"]
proc setJs(arr: JsObject, source: JsObject, pos: WasmPtr) {.importjs: "#.set(#, #)".}
proc slice(arr: JsObject, first: int, last: int): JsObject {.importjs: "#.slice(#, #)".}
proc isDetached(arr: JsObject): bool {.importjs: "#.length == 0".}

if module.memory["HEAPU8"].isDetached:
let memory = module.memory["memory"]
module.memory["HEAPU32"] = newUint32Array(memory)
module.memory["HEAPU16"] = newUint16Array(memory)
module.memory["HEAPU8"] = newUint8Array(memory)
module.memory["HEAP32"] = newInt32Array(memory)
module.memory["HEAP16"] = newInt16Array(memory)
module.memory["HEAP8"] = newInt8Array(memory)
module.memory["HEAPF32"] = newFloat32Array(memory)
module.memory["HEAPF64"] = newFloat64Array(memory)

let heap = module.memory["HEAPU8"]
let s = source.slice(0, len)
heap.setJs(s, dest)

Expand All @@ -61,6 +82,18 @@ proc getString*(module: WasmModule, pos: WasmPtr): cstring =
proc indexOf(arr: JsObject, elem: uint8, start: WasmPtr): WasmPtr {.importjs: "#.indexOf(#, #)".}
proc slice(arr: JsObject, first: WasmPtr, last: WasmPtr): JsObject {.importjs: "#.slice(#, #)".}
proc jsDecodeString(str: JsObject): cstring {.importc.}
proc isDetached(arr: JsObject): bool {.importjs: "#.length == 0".}

if module.memory["HEAPU8"].isDetached:
let memory = module.memory["memory"]
module.memory["HEAPU32"] = newUint32Array(memory)
module.memory["HEAPU16"] = newUint16Array(memory)
module.memory["HEAPU8"] = newUint8Array(memory)
module.memory["HEAP32"] = newInt32Array(memory)
module.memory["HEAP16"] = newInt16Array(memory)
module.memory["HEAP8"] = newInt8Array(memory)
module.memory["HEAPF32"] = newFloat32Array(memory)
module.memory["HEAPF64"] = newFloat64Array(memory)

let heap = module.memory["HEAPU8"]
let terminator = heap.indexOf(0, pos)
Expand Down
1 change: 1 addition & 0 deletions src/scripting/wasm_builder.nim
Original file line number Diff line number Diff line change
Expand Up @@ -1477,6 +1477,7 @@ proc getStackChange*(self: WasmBuilder, instr: WasmInstr): int =

of Nop: return 0
of Drop: return -1
of Unreachable: return 0

of Block:
case instr.blockType.kind
Expand Down

0 comments on commit 222ab7b

Please sign in to comment.