content
stringlengths
0
376M
<filename>hw/vendor/lowrisc_opentitan/spi_host/Bender.yml package: name: lowrisc_spi_host description: "lowRISC RISC-V Platform Level Interrupt Controller" authors: ["lowRISC Contributors"] dependencies: lowrisc_prim: {path: ../prim} sources: # Level 0: - rtl/spi_host_reg_pkg.sv # Level 1: - rtl/spi_host_reg_top.sv - rtl/spi_host.sv
cryoAsicGen1: enable: True ForceWrite: False InitAfterConfig: False PollEn: True dataWriter: enable: True DataFile: '' IsOpen: False BufferSize: 0 MaxFileSize: 0 EpixHRGen1Cryo: enable: True MMCM7Registers: enable: False CLKOUT0PhaseMux: 0 CLKOUT0HighTime: 0 CLKOUT0LowTime: 0 CLKOUT0Frac: 0 CLKOUT0FracEn: 0 CLKOUT0Edge: 0 CLKOUT0NoCount: 0 CLKOUT0DelayTime: 0 CLKOUT1PhaseMux: 0 CLKOUT1HighTime: 0 CLKOUT1LowTime: 0 CLKOUT1Edge: 0 CLKOUT1NoCount: 0 CLKOUT1DelayTime: 0 CLKOUT2PhaseMux: 0 CLKOUT2HighTime: 0 CLKOUT2LowTime: 0 CLKOUT2Edge: 0 CLKOUT2NoCount: 0 CLKOUT2DelayTime: 0 CLKOUT3PhaseMux: 0 CLKOUT3HighTime: 0 CLKOUT3LowTime: 0 CLKOUT3Edge: 0 CLKOUT3NoCount: 0 CLKOUT3DelayTime: 0 CLKOUT4PhaseMux: 0 CLKOUT4HighTime: 0 CLKOUT4LowTime: 0 CLKOUT4Edge: 0 CLKOUT4NoCount: 0 CLKOUT4DelayTime: 0 CLKOUT5PhaseMux: 0 CLKOUT5HighTime: 0 CLKOUT5LowTime: 0 CLKOUT5Edge: 0 CLKOUT5NoCount: 0 CLKOUT5DelayTime: 0 CLKOUT6PhaseMux: 0 CLKOUT6HighTime: 0 CLKOUT6LowTime: 0 CLKOUT6Edge: 0 CLKOUT6NoCount: 0 CLKOUT6DelayTime: 0 MMCMSerdesRegisters: enable: True CLKOUT0PhaseMux: 0 CLKOUT0HighTime: 4 CLKOUT0LowTime: 4 CLKOUT0Frac: 0 CLKOUT0FracEn: 0 CLKOUT0Edge: 0 CLKOUT0NoCount: 0 CLKOUT0DelayTime: 0 CLKOUT1PhaseMux: 0 CLKOUT1HighTime: 16 CLKOUT1LowTime: 16 CLKOUT1Edge: 0 CLKOUT1NoCount: 0 CLKOUT1DelayTime: 0 CLKOUT2PhaseMux: 0 CLKOUT2HighTime: 28 CLKOUT2LowTime: 28 CLKOUT2Edge: 0 CLKOUT2NoCount: 0 CLKOUT2DelayTime: 0 CLKOUT3PhaseMux: 0 CLKOUT3HighTime: 8 CLKOUT3LowTime: 8 CLKOUT3Edge: 0 CLKOUT3NoCount: 0 CLKOUT3DelayTime: 0
<reponame>StanfordAHA/garnet name: sim-gl-run parameters: waveform: False saif: True tool: "XCELIUM" num_glb_tiles: 16 test: "test1.pwr" commands: - bash run_sim.sh outputs: - run.log - run.saif postconditions: - assert File( 'outputs/run.log' ) # must exist - assert File( 'outputs/run.saif' ) # must exist # Basic error checking - assert 'Error,' not in File( 'outputs/run.log' ) - assert '*E,' not in File( 'outputs/run.log' )
<gh_stars>0 name: 'test' on: [ push, pull_request ] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - run: docker run --rm -tv $(pwd):/src -w /src ghdl/vunit:llvm python3 run.py # - uses: actions/upload-artifact@master # with: # name: <name of the resulting zipfile # path: <directory to zip and upload>
<reponame>mfkiwl/garnet<filename>mflowgen/common/init-fullchip/configure.yml #========================================================================= # Custom Scripts -- init #========================================================================= name: init-fullchip #------------------------------------------------------------------------- # Inputs and Outputs #------------------------------------------------------------------------- inputs: - io_file # FIXME I'm sure this is not how this is supposed to work...[sr02.2020] commands: - cp inputs/io_file outputs/io_file # Default order can be found in e.g. # mflowgen/steps/cadence-innovus-init/configure.yml # - main.tcl # - quality-of-life.tcl # - floorplan.tcl # - pin-assignments.tcl # - make-path-groups.tcl # - reporting.tcl # # Todo: I think we're gonna move endcaps to a separate stage, # maybe power or placement? # Also: pad frame does not need pin assignments, uses io_file instead. # Also: adding io_fillers as a separate script, hope that's okay. # Adding stylus compatibility and alignment cell scripts # Also (maybe temporary) script to attach results/gds to outputs/gds # [sr05.2020] Adding analog-bumps directory for analog bump routing scripts outputs: - add-endcaps-welltaps.tcl - stylus-compatibility-procs.tcl - floorplan.tcl - io-fillers.tcl - alignment-cells.tcl - sealring.tcl - attach-results-to-outputs.tcl - io_file # Bump routing inc. entire directory of analog (PHY) bump scripts - gen-bumps.tcl - check-bumps.tcl - route-bumps.tcl - analog-bumps
package: name: pytblink-rpc-hdl version: 0.0.1 dev-deps: - name: tblink-rpc-core url: https://github.com/tblink-rpc/tblink-rpc-core.git - name: tblink-rpc-hdl url: https://github.com/tblink-rpc/tblink-rpc-hdl.git - name: pytblink-rpc url: https://github.com/tblink-rpc/pytblink-rpc.git - name: mkdv url: https://github.com/fvutils/mkdv.git
theme: jekyll-theme-dinky title: AHB-Lite Multi-Layer Switch description: Parameterised AHB-Lite Multi-layer Interconnect Switch show_downloads: true show_license: true license: Non-Commercial License github: [metadata]
<reponame>yufat48/pulpissimo tbtools: flags: [ 'skip_synthesis' ] files: [ dpi_models/dpi_models.sv, tb_driver/tb_driver.sv, ]
--- - import_playbook: actions/datagen_stop_multigrid.yml - import_playbook: actions/datagen_stop_NMX_overlap.yml - import_playbook: actions/datagen_stop_multiblade.yml - import_playbook: actions/datagen_stop_loki.yml - import_playbook: actions/datagen_stop_dream.yml - import_playbook: actions/datagen_stop_pktgen.yml - import_playbook: actions/datagen_stop_let.yml - import_playbook: actions/utils_stop.yml
<reponame>ikwzm/merge_sorter --- input_file : ../akane/08_merge_sort_node_multi.akd output_file : 08_merge_sort_node_multi.md image_url : "Fig.1 マルチワードマージソートのアーキテクチャ" : "https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/24981/a646223d-c72d-1a84-1f0a-82102ddddab8.jpeg" "Fig.2 マルチワードマージソートの動作例(1)" : "https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/24981/fda984da-540d-bae3-9665-71229d906c52.jpeg" "Fig.3 マルチワードマージソートの動作例(2)" : "https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/24981/845920e6-b49c-8818-5a08-6f43735fda68.jpeg" "Fig.4 マルチワードマージソートの動作例(3)" : "https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/24981/c6d9408f-ee39-440f-2e9f-ccb7cd3de568.jpeg" "Fig.5 マルチワードマージソートの動作例(4)" : "https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/24981/f0daf1d9-0739-86a4-2d90-77443b5328a3.jpeg" "Fig.6 マルチワードマージソートの動作例(5)" : "https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/24981/b0a1fcd3-ced5-2978-d9bc-2b011eda09dc.jpeg" link_list : - id : "「はじめに」" title: "「VHDL で書くマージソーター(はじめに)」@Qiita" url : "https://qiita.com/ikwzm/items/6665b2ef44d878a5b85f" - id : "「ワードの定義」" title: "「VHDL で書くマージソーター(ワードの定義)」@Qiita" url : "https://qiita.com/ikwzm/items/bdcd8876317b908ff492" - id : "「ワード比較器」" title: "「VHDL で書くマージソーター(ワード比較器)」@Qiita" url : "https://qiita.com/ikwzm/items/d5d1dd264b1670f33bd7" - id : "「ソーティングネットワーク」" title: "「VHDL で書くマージソーター(ソーティングネットワーク)」@Qiita" url : "https://qiita.com/ikwzm/items/a1d06e47523759c726ae" - id : "「バイトニックマージソート」" title: "「VHDL で書くマージソーター(バイトニックマージソート)」@Qiita" url : "https://qiita.com/ikwzm/items/366eacbf6a877994c955" - id : "「バッチャー奇偶マージソート」" title: "「VHDL で書くマージソーター(バッチャー奇偶マージソート)」@Qiita" url : "https://qiita.com/ikwzm/items/c21a53f21b87408a7805" - id : "「シングルワード マージソート ノード」" title: "「VHDL で書くマージソーター(シングルワード マージソート ノード)」@Qiita" url : "https://qiita.com/ikwzm/items/7fd7ef9ffc4d9b314fee" - id : "「マルチワード マージソート ノード」" title: "「VHDL で書くマージソーター(マルチワード マージソート ノード)」@Qiita" url : "https://qiita.com/ikwzm/items/ed96b7a44b83bcee4ba5" - id : "「マージソート ツリー」" title: "「VHDL で書くマージソーター(マージソート ツリー)」@Qiita" url : "https://qiita.com/ikwzm/items/1f76ae5cda95aaf92501" - id : "「端数ワード処理」" title: "「VHDL で書くマージソーター(端数ワード処理)」@Qiita" url : "https://qiita.com/ikwzm/items/6b15340f1e05ef03f8d0" - id : "「ストリーム入力」" title: "「VHDL で書くマージソーター(ストリーム入力)」@Qiita" url : "https://qiita.com/ikwzm/items/56e22511021a082a2ccd" - id : "「ストリームフィードバック」" title: "「VHDL で書くマージソーター(ストリームフィードバック)」@Qiita" url : "https://qiita.com/ikwzm/items/e8c59c0ec92956c9355f" - id : "「ArgSort IP」" title: "「VHDL で書くマージソーター(ArgSort IP)」@Qiita" url : "https://qiita.com/ikwzm/items/89fc9542492fca74c9e3" - id : "「ArgSort-Ultra96」" title: "「VHDL で書くマージソーター(ArgSort-Ultra96)」@Qiita" url : "https://qiita.com/ikwzm/items/d58c9b77d038e23ac792" - id : "「ArgSort-Kv260」" title: "「VHDL で書くマージソーター(ArgSort-Kv260)」@Qiita" url : "https://qiita.com/ikwzm/items/ec0f779534c44b35334a" - id : "ACRi" title: "アダプティブコンピューティング研究推進体(ACRi)" url : "https://www.acri.c.titech.ac.jp/wp" - id : "アダプティブコンピューティング研究推進体(ACRi)" title: "アダプティブコンピューティング研究推進体(ACRi)" url : "https://www.acri.c.titech.ac.jp/wp" - id : "「FPGAを使って基本的なアルゴリズムのソーティングを劇的に高速化(1)」" title: "「FPGAを使って基本的なアルゴリズムのソーティングを劇的に高速化(1)」" url : "https://www.acri.c.titech.ac.jp/wordpress/archives/132" - id : "「FPGAを使って基本的なアルゴリズムのソーティングを劇的に高速化(2)」" title: "「FPGAを使って基本的なアルゴリズムのソーティングを劇的に高速化(2)」" url : "https://www.acri.c.titech.ac.jp/wordpress/archives/501" - id : "「FPGAを使って基本的なアルゴリズムのソーティングを劇的に高速化(3)」" title: "「FPGAを使って基本的なアルゴリズムのソーティングを劇的に高速化(3)」" url : "https://www.acri.c.titech.ac.jp/wordpress/archives/2393" - id : "「FPGAを使って基本的なアルゴリズムのソーティングを劇的に高速化(4)」" title: "「FPGAを使って基本的なアルゴリズムのソーティングを劇的に高速化(4)」" url : "https://www.acri.c.titech.ac.jp/wordpress/archives/3888" - id : "「FPGAを使って基本的なアルゴリズムのソーティングを劇的に高速化(5)」" title: "「FPGAを使って基本的なアルゴリズムのソーティングを劇的に高速化(5)」" url : "https://www.acri.c.titech.ac.jp/wordpress/archives/4713" seg_level : -1 ---
<reponame>AlSaqr-platform/udma_sdio package: name: udma_sdio authors: - "<NAME> <<EMAIL>>" - "<NAME> <<EMAIL>>" - "<NAME> <<EMAIL>>" - "<NAME> <<EMAIL>>" - "<NAME> <<EMAIL>>" dependencies: udma_core: { git: "https://github.com/Alsaqr-platform/udma_core.git", version: 2.0.0 } common_cells: { git: "https://github.com/pulp-platform/common_cells.git", version: 1.21.0 } tech_cells_generic: { git: "https://github.com/pulp-platform/tech_cells_generic.git", version: 0.2.3 } sources: # Source files grouped in levels. Files in level 0 have no dependencies on files in this # package. Files in level 1 only depend on files in level 0, files in level 2 on files in # levels 1 and 0, etc. Files within a level are ordered alphabetically. # Level 0 - rtl/sdio_crc16.sv - rtl/sdio_crc7.sv - rtl/udma_sdio_reg_if.sv # Level 1 - rtl/sdio_txrx_cmd.sv - rtl/sdio_txrx_data.sv # Level 2 - rtl/sdio_txrx.sv # Level 3 - rtl/udma_sdio_top.sv
axi_spi_slave: files: [ axi_spi_slave.sv, spi_slave_axi_plug.sv, spi_slave_cmd_parser.sv, spi_slave_controller.sv, spi_slave_dc_fifo.sv, spi_slave_regs.sv, spi_slave_rx.sv, spi_slave_syncro.sv, spi_slave_tx.sv, ]
GitBase: .. TopRoguePackage: simple_10gbe_rudp_kcu105_example RoguePackages: - submodules/surf/python - python RogueConfig: - ../software/config RogueScripts: - ../software/scripts/devGui.py Targets: Simple10GbeRudpKcu105Example: ImageDir: targets/Simple10GbeRudpKcu105Example/images Extensions: - bit - mcs - ltx Releases: simple_10gbe_rudp_kcu105_example: Primary: True Targets: - Simple10GbeRudpKcu105Example Types: - Rogue
<filename>src_files.yml cluster_control_unit: vlog_opts: [ +nowarnSVCHK, -suppress 2275, -L hci_lib, ] files: [ cluster_control_unit/cluster_control_unit.sv, ] event_unit: incdirs: [ include, event_unit/include, ] files: [ event_unit/event_unit_arbiter.sv, event_unit/event_unit_input.sv, event_unit/event_unit_mux.sv, event_unit/event_unit_sm.sv, event_unit/event_unit.sv, event_unit/HW_barrier_logic.sv, event_unit/HW_barrier.sv, event_unit/interrupt_mask.sv, ] icache_ctrl_unit: incdirs: [ ../../rtl/includes, ] files: [ icache_ctrl_unit/icache_ctrl_unit.sv, icache_ctrl_unit/new_icache_ctrl_unit.sv, icache_ctrl_unit/mp_icache_ctrl_unit.sv, icache_ctrl_unit/sp_icache_ctrl_unit.sv, icache_ctrl_unit/pri_icache_ctrl_unit.sv, icache_ctrl_unit/mp_pf_icache_ctrl_unit.sv, ] mmu_config_unit: files: [ mmu_config_unit/mmu_config_unit.sv, ] perf_counters_unit: files: [ perf_counters_unit/perf_counters_unit.sv, ] tcdm_pipe_unit: files: [ tcdm_pipe_unit/tcdm_pipe_unit.sv, ]
jobs: - job: ArchDebug displayName: run coverage (archlinux, dbg, g++) pool: vmImage: 'Ubuntu 16.04' steps: - bash: ./scripts/run-docker-test.sh `pwd` dbg mascucsc/archlinux-masc /root/livehd g++ coverage - job: ArchLong displayName: run archlinux-masc with debug and g++ long1 tests pool: vmImage: 'Ubuntu 16.04' steps: - bash: ./scripts/run-docker-test.sh `pwd` dbg mascucsc/kaliriscv-masc /root/livehd g++ . long1 - job: ClangLong displayName: run archlinux-masc with debug and clang++ long1 tests pool: vmImage: 'Ubuntu 16.04' steps: - bash: ./scripts/run-docker-test.sh `pwd` dbg mascucsc/archlinux-masc /root/livehd g++ . long1 - job: AlpineGcc displayName: run alpine-masc with debug and g++ tests pool: vmImage: 'Ubuntu 16.04' steps: - bash: ./scripts/run-docker-test.sh `pwd` dbg mascucsc/alpine-masc /home/user/livehd g++ - job: AlpineClang displayName: run alpine-masc with debug and clang++ tests pool: vmImage: 'Ubuntu 16.04' steps: - bash: ./scripts/run-docker-test.sh `pwd` dbg mascucsc/alpine-masc /home/user/livehd clang++
sklearnPkl: example-sklearn-model-files/bdt_eg.pkl OutputDir: my-hls-test ProjectName: myproject XilinxPart: xc7vx690tffg1927-2 ClockPeriod: 5 IOType: io_parallel # options: io_serial/io_parallel ReuseFactor: 1 DefaultPrecision: ap_fixed<18,8>
dummy_test_to_trigger_pulpino_ci: stage: test script: - ci/dummy.csh trigger_build: stage: deploy script: - "curl -X POST -F token=<KEY> -F ref=master https://iis-git.ee.ethz.ch/api/v4/projects/72/trigger/pipeline"
<gh_stars>1-10 name: vga_enh_top clock_port: wb_clk_i verilog: - generic_dpram.v - generic_spram.v - timescale.v - vga_clkgen.v - vga_colproc.v - vga_csm_pb.v - vga_cur_cregs.v - vga_curproc.v - vga_defines.v - vga_enh_top.v - vga_fifo.v - vga_fifo_dc.v - vga_pgen.v - vga_tgen.v - vga_vtim.v - vga_wb_master.v - vga_wb_slave.v
--- project: description: "VGA sprite generator for the SKY130 Open MPW shuttles." foundry: "SkyWater" git_url: "https://github.com/dan-rodrigues/caravel-vdp-lite.git" organization: "<NAME>" organization_url: "https://github.com/dan-rodrigues" owner: "<NAME>" process: "SKY130" project_name: "vdp-lite" tags: - "Open MPW" category: "SoC" top_level_netlist: "verilog/gl/caravel.v" user_level_netlist: "verilog/gl/user_project_wrapper.v" version: "1.00" cover_image: "demo.gif"
<reponame>bver/GERET --- algorithm: class: Spea2 population_size: 300 max_archive_size: 200 duplicate_elimination: false shorten_archive_individual: true probabilities: crossover: 0.5 mutation: 0.01 injection: 0.9 init: method: ramped # grow or full or ramped sensible_depth: 9 inject: method: grow # grow or full or random sensible_depth: 9 termination: max_steps: 1000 on_individual: stopping_condition grammar: class: AttributeGrammar filename: sample/ant_trail_tcc/attr_grammar/grammar.abnf semantic: sample/ant_trail_tcc/attr_grammar/semantic.yaml mapper: class: AttrGrDepthFirst selection: class: Tournament tournament_size: 2 selection_rank: # do not change class: Spea2Ranking crossover: class: CrossoverRipple margin: 2 #1 step: 2 mutation: class: MutationRipple store: class: Store filename: ./ant_ag_spea2.store report: class: PopulationReport individual: class: PipedIndividual shorten_chromozome: true _weak_pareto: :fitness: maximize :used_length: minimize _pipe_output: - :fitness: to_i _thresholds: :fitness: 89 _mark_phenotype: "\nMARKER\n" evaluator: class: WorkPipes commands: - 'ruby sample/ant_trail_tcc/ant_pipe.rb ONE sample/ant_trail_tcc/attr_grammar/ag_evaluate.c' - 'ruby sample/ant_trail_tcc/ant_pipe.rb TWO sample/ant_trail_tcc/attr_grammar/ag_evaluate.c'
steps: - label: "test" command: | # set up environment source /cad/modules/tcl/init/bash module load base xcelium/19.03.003 export DW_TAP=/cad/synopsys/syn/L-2016.03-SP5-5/dw/sim_ver/DW_tap.v printenv # create virtual environment /usr/local/miniconda/bin/python3.7 -m venv venv source venv/bin/activate # run regression script source regress.sh # deactivate virtual environment deactivate artifact_paths: - "tests/*/*/build/*.eps" - "tests/other_tests/sparams/*.eps" timeout_in_minutes: 90 # we're currently at ~55 min so 60 min was cutting it close agents: fault2: "true" - label: "test_mflowgen" command: | # set up environment # modules loaded aim to match those used by Garnet source /cad/modules/tcl/init/bash module load base xcelium/19.03.003 lc pts syn/latest genus innovus/19.10.000 icadv/12.30.712 calibre/2019.1 export DRAGONPHY_PROCESS=FREEPDK45 export FREEPDK45=/cad/freepdk/FreePDK45 printenv # create virtual environment /usr/local/miniconda/bin/python3.7 -m venv venv source venv/bin/activate # run mflowgen script source mflowgen.sh # deactivate virtual environment deactivate artifact_paths: - "tests/*/*/build/*.eps" - "build/*/*-synopsys-dc-synthesis/logs/dc.log" - "build/*/*-synopsys-dc-synthesis/outputs/design.v" - "build/*/*-synopsys-dc-synthesis/reports/*.mapped.qor.rpt" - "build/*/*-synopsys-dc-synthesis/reports/*.mapped.constraints.violators.rpt" timeout_in_minutes: 60 agents: fault2: "true" - label: "test_emu" command: | # set up environment source /etc/environment export FPGA_SERVER=1 export DW_TAP=/tools/synopsys/syn/L-2016.03-SP5-5/dw/sim_ver/DW_tap.v export TAP_CORE_LOC=/tools/synopsys/syn/L-2016.03-SP5-5/dw/syn_ver/tap_core.edf printenv # create virtual environment python3.7 -m venv venv source venv/bin/activate # scale down the size of the FFE and MLSD to fit on the regression FPGA sed -i 's/\&ffe_length [[:digit:]]\+/\&ffe_length 4/g' config/system.yml sed -i 's/\&estimate_depth [[:digit:]]\+/\&estimate_depth 4/g' config/system.yml # scale down the channel response length to fit on the regression FPGA sed -i 's/num_terms: [[:digit:]]\+/num_terms: 5/g' config/fpga/chan.yml # run regression script source regress.sh # deactivate virtual environment deactivate artifact_paths: - "tests/fpga_system_tests/*/build/*/prj/prj.runs/*/*.log" - "tests/fpga_system_tests/*/build/*/prj/prj.runs/*/*.bit" - "tests/fpga_system_tests/*/build/*/prj/prj.runs/*/*.ltx" - "tests/fpga_system_tests/*/build/*/prj/prj.runs/*/*.xsa" - "tests/fpga_system_tests/*/build/*/prj/prj.runs/*/ps7_init.tcl" - "tests/fpga_system_tests/*/build/*/prj/prj.runs/*/*.hwdef" - "tests/fpga_system_tests/*/build/*/prj/prj.runs/*/*.sysdef" - "tests/fpga_system_tests/*/build/*/prj/prj.sdk/*/*/*.elf" - "tests/fpga_system_tests/*/build/*/prj/prj.sim/*/behav/xsim/*.log" - "tests/fpga_system_tests/*/build/*/prj/prj.sim/*/behav/xsim/*.sh" - "tests/fpga_system_tests/*/prj.yaml" - "tests/fpga_system_tests/*/source.yaml" - "build/all/jtag/reg_list.json" - "build/cpu_models/jtag/jtag_reg_pack.sv" - "build/tb/jtag_drv_pack.sv" timeout_in_minutes: 60 agents: fpga_verif: "true"
timer_unit: files: [ timer_unit.sv, timer_unit_counter.sv, timer_unit_counter_presc.sv, ]
# need to change the credentials (xxxxx) global: resolve_timeout: 5m #slack_api_url: "https://cse220-ucsc-fall2020.slack.com/services/XXXXXXXXXXXXXXX" route: group_by: ['alertname'] group_wait: 10s group_interval: 10s repeat_interval: 10s receiver: "default" receivers: - name: default email_configs: - to: '<EMAIL>' from: '<EMAIL>' smarthost: 'smtp.gmail.com:587' auth_username: '<EMAIL>' auth_password: '<PASSWORD>' auth_identity: '<EMAIL>' html: '{{ template "email" .}}' templates: - '../prometheus/alert.tmpl'
<filename>riscv-zig-blink/src/main.zig const std = @import("std"); const fomu = @import("./fomu.zig"); pub fn panic(message: []const u8, stack_trace: ?*std.builtin.StackTrace) noreturn { @setCold(true); fomu.panic(message, stack_trace); } fn rgb_init() void { // Turn on the RGB block and current enable, as well as enabling led control fomu.RGB.CTRL.* = .{ .EXE = true, .CURREN = true, .RGBLEDEN = true, .RRAW = false, .GRAW = false, .BRAW = false, }; // Enable the LED driver, and set 250 Hz mode. // Also set quick stop, which we'll use to switch patterns quickly. fomu.RGB.setControlRegister(.{ .enable = true, .fr = .@"250", .quick_stop = true, .outskew = false, .output_polarity = .active_high, .pwm_mode = .linear, .BRMSBEXT = 0, }); // Set clock register to 12 MHz / 64 kHz - 1 fomu.RGB.setRegister(.BR, (fomu.SYSTEM_CLOCK_FREQUENCY / 64000) - 1); // Blink on/off time is in 32 ms increments fomu.RGB.setRegister(.ONR, 1); // Amount of time to stay "on" fomu.RGB.setRegister(.OFR, 0); // Amount of time to stay "off" fomu.RGB.setBreatheRegister(.On, .{ .enable = true, .pwm_range_extend = false, .mode = .fixed, .rate = 1, }); fomu.RGB.setBreatheRegister(.Off, .{ .enable = true, .pwm_range_extend = false, .mode = .fixed, .rate = 1, }); } const Colour = struct { r: u8, g: u8, b: u8, }; /// Input a value 0 to 255 to get a colour value. /// The colours are a transition r - g - b - back to r. fn colourWheel(wheelPos: u8) Colour { var c: Colour = undefined; var wp = 255 - wheelPos; switch (wp) { 0...84 => { c = .{ .r = 255 - wp * 3, .g = 0, .b = wp * 3, }; }, 85...169 => { wp -= 85; c = .{ .r = 0, .g = wp * 3, .b = 255 - wp * 3, }; }, 170...255 => { wp -= 170; c = .{ .r = wp * 3, .g = 255 - wp * 3, .b = 0, }; }, } return c; } fn msleep(ms: usize) void { fomu.TIMER0.stop(); fomu.TIMER0.reload(0); fomu.TIMER0.load(fomu.SYSTEM_CLOCK_FREQUENCY / 1000 * ms); fomu.TIMER0.start(); while (fomu.TIMER0.value() != 0) {} } pub fn main() noreturn { rgb_init(); var i: u8 = 0; while (true) : (i +%= 1) { const colour = colourWheel(i); fomu.RGB.setColour(colour.r, colour.g, colour.b); msleep(80); } unreachable; }
<reponame>GingerIndustries/Fibonacci const std = @import("std"); pub fn main() !void { const stdout = std.io.getStdOut().writer(); try stdout.print("0\n1\n", .{}); var a: u32 = 1; try stdout.print("{}\n", .{a}); var b: u32 = 2 * a; try stdout.print("{}\n", .{b}); while (a < 1000000) { a += b; try stdout.print("{}\n", .{a}); b += a; try stdout.print("{}\n", .{b}); } }
<reponame>MasterQ32/spu-mark-ii const std = @import("std"); const pcx = @import("pcx.zig"); const argsParser = @import("args"); pub fn main() !u8 { const cli_args = argsParser.parseForCurrentProcess(struct { help: bool = false, output: ?[]const u8 = null, pub const shorthands = .{ .h = "help", .o = "output", }; }, std.heap.page_allocator, .print) catch return 1; defer cli_args.deinit(); if (cli_args.options.help or cli_args.positionals.len != 1) { try std.io.getStdOut().writer().writeAll( \\bit-converter --help [--output file] pcx-file \\Converts a PCX file into a bit-bang sequence for the \\ \\-h, --help Displays this help text. \\-o, --output Defines the name of the output file. If not given, \\ the bit-converter will write the bit sequence to stdout. \\ ); return if (cli_args.options.help) @as(u8, 0) else @as(u8, 1); } var file = try std.fs.cwd().openFile(cli_args.positionals[0], .{ .read = true, .write = false }); defer file.close(); var img = try pcx.load(std.heap.page_allocator, &file); defer img.deinit(); if (img != .bpp8) { try std.io.getStdErr().writer().print("The provided file is not a file with 8 bit per pixel, but uses the format {}!\n", .{ @as(pcx.Format, img), }); return 1; } var out = if (cli_args.options.output) |outfile| try std.fs.cwd().createFile(outfile, .{ .truncate = true }) else std.io.getStdOut(); defer if (cli_args.options.output) |_| out.close(); var ostream = out.writer(); var y: usize = 0; while (y < 128) : (y += 1) { var x: usize = 0; while (x < 256) : (x += 1) { try ostream.writeIntLittle(u8, 'B'); try ostream.writeIntLittle(u24, 0x810000 | @intCast(u24, y << 8) | @intCast(u24, x)); try ostream.writeIntLittle(u8, img.bpp8.pixels[y * img.bpp8.width + x]); } } return 0; }
// 11 lines 5 code 3 comments 3 blanks /// Documentation comment pub fn main() void { const a = 5; // not-counted // Leading-comment const b = c"line comment embedded //"; const c = \\line comment embedded // // }
//! this is a top level doc, starts with "//!" const std = @import("std"); pub fn main() anyerror!void { const stdout = std.io.getStdOut().writer(); try stdout.print("Hello, {}!\n", .{"world"}); } const expect = std.testing.expect; test "comments" { // comments start with "//" until newline // foo bar baz const x = true; // another comment expect(x); } /// a doc comment starts with "///" /// multiple lines are merged together const Timestamp = struct { /// number of seconds since epoch seconds: i64, /// number of nanoseconds past the second nano: u32, const Self = @This(); pub fn unixEpoch() Self { return Self{ .seconds = 0, .nanos = 0, }; } }; const my_val = switch (std.Target.current.os.tag) { .linux => "Linux", else => "not Linux", }; const Book = enum { paperback, hardcover, ebook, pdf, }; const TokenType = union(enum) { int: isize, float: f64, string: []const u8, }; const array_lit: [4]u8 = .{ 11, 22, 33, 44 }; const sentinal_lit = [_:0]u8{ 1, 2, 3, 4 }; test "address of syntax" { // Get the address of a variable: const x: i32 = 1234; const x_ptr = &x; // Dereference a pointer: expect(x_ptr.* == 1234); // When you get the address of a const variable, you get a const pointer to a single item. expect(@TypeOf(x_ptr) == *const i32); // If you want to mutate the value, you'd need an address of a mutable variable: var y: i32 = 5678; const y_ptr = &y; expect(@TypeOf(y_ptr) == *i32); y_ptr.* += 1; expect(y_ptr.* == 5679); } // integer literals const decimal_int = 98222; const hex_int = 0xff; const another_hex_int = 0xFF; const octal_int = 0o755; const binary_int = 0b11110000; // underscores may be placed between two digits as a visual separator const one_billion = 1_000_000_000; const binary_mask = 0b1_1111_1111; const permissions = 0o7_5_5; const big_address = 0xFF80_0000_0000_0000; // float literals const floating_point = 123.0E+77; const another_float = 123.0; const yet_another = 123.0e+77; const hex_floating_point = 0x103.70p-5; const another_hex_float = 0x103.70; const yet_another_hex_float = 0x103.70P-5; // underscores may be placed between two digits as a visual separator const lightspeed = 299_792_458.000_000; const nanosecond = 0.000_000_001; const more_hex = 0x1234_5678.9ABC_CDEFp-10; fn max(comptime T: type, a: T, b: T) T { return if (a > b) a else b; }
const std = @import("std"); const lpc1768 = @import("lpc1768"); const ISRHandler = fn () callconv(.C) void; const start_of_ram = 0x10000000; const stack_size = 0x2000; const initial_sp = start_of_ram + stack_size; var mutable_vector_table: @TypeOf(fixed_vector_table) = undefined; extern var __bss__start: c_void; extern var __bss__end: c_void; extern var __text__end: c_void; extern var __data__start: c_void; extern var __data__end: c_void; export fn _start() callconv(.C) noreturn { mutable_vector_table = fixed_vector_table; lpc1768.SCB.VTOR = @ptrToInt(&mutable_vector_table); lpc1768.SCB.SHP[7] = 1; // SVC has less priority than all fault handlers lpc1768.SCB.SHCSR = 0x00070000; // enable fault handler const bss = @ptrCast([*]u8, &__bss__start)[0 .. @ptrToInt(&__bss__end) - @ptrToInt(&__bss__end)]; const ro_data = @ptrCast([*]const u8, &__text__end)[0 .. @ptrToInt(&__data__end) - @ptrToInt(&__data__start)]; const rw_data = @ptrCast([*]u8, &__data__start)[0..ro_data.len]; // BSS Segment löschen std.mem.set(u8, bss, 0); // Datasegment aus Flash in RAM kopieren std.mem.copy(u8, rw_data, ro_data); @import("root").main() catch |err| { @panic(@errorName(err)); }; while (true) { lpc1768.__disable_irq(); lpc1768.__disable_fault_irq(); lpc1768.__WFE(); } } export fn _nmi() callconv(.C) void { @panic("nmi"); } export fn _hardFault() callconv(.C) void { @panic("hard fault"); } export fn _mpuFault() callconv(.C) void { @panic("mpu fault"); } export fn _busFault() callconv(.C) void { @panic("bus fault"); } export fn _usageFault() callconv(.C) void { @panic("usage fault"); } export fn _unhandledInterrupt() callconv(.C) void { @panic("Unhandled interrupt!"); } comptime { _ = fixed_vector_table; } const VectorTable = extern struct { initial_stack_pointer: u32 = initial_sp, reset: ISRHandler = _start, nmi: ISRHandler = _nmi, hard_fault: ISRHandler = _hardFault, mpu_fault: ISRHandler = _mpuFault, bus_fault: ISRHandler = _busFault, usage_fault: ISRHandler = _usageFault, checksum: u32 = undefined, reserved0: u32 = 0, reserved1: u32 = 0, reserved2: u32 = 0, svcall: ISRHandler = _unhandledInterrupt, debug_monitor: ISRHandler = _unhandledInterrupt, reserved3: u32 = 0, pendsv: ISRHandler = _unhandledInterrupt, systick: ISRHandler = _unhandledInterrupt, wdt: ISRHandler = _unhandledInterrupt, timer0: ISRHandler = _unhandledInterrupt, timer1: ISRHandler = _unhandledInterrupt, timer2: ISRHandler = _unhandledInterrupt, timer3: ISRHandler = _unhandledInterrupt, uart0: ISRHandler = _unhandledInterrupt, uart1: ISRHandler = _unhandledInterrupt, uart2: ISRHandler = _unhandledInterrupt, uart3: ISRHandler = _unhandledInterrupt, pwm1: ISRHandler = _unhandledInterrupt, i2c0: ISRHandler = _unhandledInterrupt, i2c1: ISRHandler = _unhandledInterrupt, i2c2: ISRHandler = _unhandledInterrupt, spi: ISRHandler = _unhandledInterrupt, ssp0: ISRHandler = _unhandledInterrupt, ssp1: ISRHandler = _unhandledInterrupt, pll0: ISRHandler = _unhandledInterrupt, rtc: ISRHandler = _unhandledInterrupt, eint0: ISRHandler = _unhandledInterrupt, eint1: ISRHandler = _unhandledInterrupt, eint2: ISRHandler = _unhandledInterrupt, eint3: ISRHandler = _unhandledInterrupt, adc: ISRHandler = _unhandledInterrupt, bod: ISRHandler = _unhandledInterrupt, usb: ISRHandler = _unhandledInterrupt, can: ISRHandler = _unhandledInterrupt, dma: ISRHandler = _unhandledInterrupt, i2s: ISRHandler = _unhandledInterrupt, enet: ISRHandler = _unhandledInterrupt, rit: ISRHandler = _unhandledInterrupt, mcpwm: ISRHandler = _unhandledInterrupt, qei: ISRHandler = _unhandledInterrupt, pll1: ISRHandler = _unhandledInterrupt, }; export const fixed_vector_table: VectorTable linksection(".isr_vector") = VectorTable{};
const std = @import("std"); const zpm = @import(".zpm/pkgs.zig"); const packages = zpm.pkgs; const examples = [_][]const u8{ // "apps/hello-world/main", // "apps/ascii-printer/main", }; pub fn addTest(b: *std.build.Builder, global_step: *std.build.Step, comptime tool_name: []const u8, src: []const u8) *std.build.LibExeObjStep { const test_runner = b.addTest(src); const test_step = b.step("test-" ++ tool_name, "Runs the test suite for " ++ tool_name); test_step.dependOn(&test_runner.step); global_step.dependOn(&test_runner.step); return test_runner; } pub fn build(b: *std.build.Builder) !void { const target = b.standardTargetOptions(.{}); const mode = b.standardReleaseOptions(); const hex2bin = b.addExecutable("hex2bin", "tools/hex2bin/main.zig"); hex2bin.addPackage(packages.args); hex2bin.addPackage(packages.ihex); hex2bin.setTarget(target); hex2bin.setBuildMode(mode); hex2bin.install(); const emulator = b.addExecutable("emulator", "tools/emulator/pc-main.zig"); emulator.addPackage(packages.args); emulator.addPackage(packages.ihex); emulator.addPackage(packages.@"spu-mk2"); emulator.setTarget(target); emulator.setBuildMode(mode); emulator.install(); const disassembler = b.addExecutable("disassembler", "tools/disassembler/main.zig"); disassembler.addPackage(packages.args); disassembler.addPackage(packages.ihex); disassembler.addPackage(packages.@"spu-mk2"); disassembler.setTarget(target); disassembler.setBuildMode(mode); disassembler.install(); const assembler = b.addExecutable("assembler", "tools/assembler/main.zig"); assembler.addPackage(packages.args); assembler.addPackage(packages.ihex); assembler.addPackage(packages.@"spu-mk2"); assembler.setTarget(target); assembler.setBuildMode(mode); assembler.install(); const test_step = b.step("test", "Runs the full test suite"); { const asm_test = addTest(b, test_step, "assembler", "tools/assembler/main.zig"); asm_test.addPackage(zpm.pkgs.@"spu-mk2"); asm_test.addPackage(zpm.pkgs.args); _ = addTest(b, test_step, "debugger", "tools/debugger/main.zig"); _ = addTest(b, test_step, "emulator", "tools/emulator/pc-main.zig"); } inline for (examples) |src_file| { const step = assembler.run(); step.addArgs(&[_][]const u8{ "-o", "./zig-out/firmware/" ++ std.fs.path.basename(std.fs.path.dirname(src_file).?) ++ ".hex", src_file ++ ".asm", }); b.getInstallStep().dependOn(&step.step); } const assemble_step = assembler.run(); assemble_step.addArgs(&[_][]const u8{ "-o", "./zig-out/firmware/ashet-bios.hex", "./apps/ashet-bios/main.asm", }); // const refresh_cmd = make_vhd.run(); // refresh_cmd.step.dependOn(&gen_firmware_blob.step); // refresh_cmd.addArgs(&[_][]const u8{ // "--output", // "./soc/vhdl/src/builtin-rom.vhd", // "./zig-out/firmware/firmware.bin", // }); // const gen_mem_file = hex2mem.run(); // gen_mem_file.step.dependOn(&assemble_step.step); // gen_mem_file.addArgs(&[_][]const u8{ // "--output", // "./soc/vhdl/firmware.mem", // "./zig-out/firmware/firmware.hex", // }); // b.getInstallStep().dependOn(&gen_mem_file.step); // b.getInstallStep().dependOn(&refresh_cmd.step); const emulate_cmd = emulator.run(); emulate_cmd.step.dependOn(&assemble_step.step); emulate_cmd.addArgs(&[_][]const u8{ "./zig-out/firmware/firmware.hex", }); { const assemble_wasm_step = assembler.run(); assemble_wasm_step.addArgs(&[_][]const u8{ "-o", "./zig-out/firmware/wasm.hex", "./apps/web-firmware/main.asm", }); const gen_wasm_firmware_blob = hex2bin.run(); gen_wasm_firmware_blob.step.dependOn(&assemble_wasm_step.step); gen_wasm_firmware_blob.addArgs(&[_][]const u8{ "-o", "./zig-out/firmware/wasm.bin", "./zig-out/firmware/wasm.hex", }); const wasm_emulator = b.addSharedLibrary("emulator", "tools/emulator/web-main.zig", .unversioned); wasm_emulator.addPackage(packages.ihex); wasm_emulator.addPackage(packages.@"spu-mk2"); wasm_emulator.setTarget(.{ .cpu_arch = .wasm32, .os_tag = .freestanding }); wasm_emulator.setBuildMode(mode); wasm_emulator.step.dependOn(&gen_wasm_firmware_blob.step); wasm_emulator.install(); const wasm_step = b.step("wasm", "Builds the WASM emulator"); wasm_step.dependOn(&wasm_emulator.install_step.?.step); } // Cross-target // { // const cross_step = b.step("cross-build", "Builds all the toolchain for all cross targets."); // const MyTarget = struct { // target: std.zig.CrossTarget, // folder: []const u8, // }; // const targets = [_]MyTarget{ // .{ .target = try std.zig.CrossTarget.parse(.{ .arch_os_abi = "x86_64-windows" }), .folder = "build/x86_64-windows" }, // // .{ .target = try std.zig.CrossTarget.parse(.{ .arch_os_abi = "x86_64-macosx" }), .folder = "build/x86_64-macosx" }, // not supported by zig-serial atm // .{ .target = try std.zig.CrossTarget.parse(.{ .arch_os_abi = "x86_64-linux" }), .folder = "build/x86_64-linux" }, // .{ .target = try std.zig.CrossTarget.parse(.{ .arch_os_abi = "i386-windows" }), .folder = "build/i386-windows" }, // linker error _GetCommState // }; // for (targets) |cross_target| { // const crossToolchain = try buildToolchain(b, sdl_sdk, cross_target.folder, cross_target.target, mode); // cross_step.dependOn(&crossToolchain.debugger.step); // cross_step.dependOn(&crossToolchain.emulator.step); // cross_step.dependOn(&crossToolchain.disassembler.step); // cross_step.dependOn(&crossToolchain.assembler.step); // cross_step.dependOn(&crossToolchain.hex2bin.step); // cross_step.dependOn(&crossToolchain.ashet_emulator.step); // } // } }
<gh_stars>10-100 const std = @import("std"); /// rgb color tuple with 8 bit color values. pub const RGB = packed struct { r: u8, g: u8, b: u8, }; pub const Header = packed struct { id: u8 = 0x0A, version: u8, compression: u8, bpp: u8, xmin: u16, ymin: u16, xmax: u16, ymax: u16, horizontalDPI: u16, verticalDPI: u16, builtinPalette: [16 * 3]u8, _reserved0: u8 = 0, planes: u8, stride: u16, paletteInformation: u16, screenWidth: u16, screenHeight: u16, var padding: [54]u8 = undefined; comptime { std.debug.assert(@sizeOf(@This()) == 74); } }; fn SubImage(comptime Pixel: type) type { return struct { const Self = @This(); const PaletteType = switch (Pixel) { u1 => [2]RGB, u4 => [16]RGB, u8 => [256]RGB, RGB => void, else => @compileError(@typeName(Pixel) ++ " not supported yet!"), }; allocator: std.mem.Allocator, pixels: []Pixel, width: usize, height: usize, palette: ?*PaletteType, pub fn initLinear(allocator: std.mem.Allocator, header: Header, file: *std.fs.File, stream: anytype) !Self { const width = @as(usize, header.xmax - header.xmin + 1); const height = @as(usize, header.ymax - header.ymin + 1); var img = Self{ .allocator = allocator, .pixels = try allocator.alloc(Pixel, width * height), .width = width, .height = height, .palette = null, }; errdefer img.deinit(); var decoder = RLEDecoder.init(stream); var y: usize = 0; while (y < img.height) : (y += 1) { var offset: usize = 0; var x: usize = 0; // read all pixels from the current row while (offset < header.stride and x < img.width) : (offset += 1) { const byte = try decoder.readByte(); switch (Pixel) { u1 => {}, u4 => { img.pixels[y * img.width + x + 0] = @truncate(u4, byte); x += 1; if (x < img.width - 1) { img.pixels[y * img.width + x + 1] = @truncate(u4, byte >> 4); x += 1; } }, u8 => { img.pixels[y * img.width + x] = byte; x += 1; }, RGB => {}, else => @compileError(@typeName(Pixel) ++ " not supported yet!"), } } // discard the rest of the bytes in the current row while (offset < header.stride) : (offset += 1) { _ = try decoder.readByte(); } } try decoder.finish(); if (Pixel != RGB) { var pal = try allocator.create(PaletteType); errdefer allocator.destroy(pal); var i: usize = 0; while (i < std.math.min(pal.len, header.builtinPalette.len / 3)) : (i += 1) { pal[i].r = header.builtinPalette[3 * i + 0]; pal[i].g = header.builtinPalette[3 * i + 1]; pal[i].b = header.builtinPalette[3 * i + 2]; } if (Pixel == u8) { try file.seekFromEnd(-769); if ((try stream.readByte()) != 0x0C) return error.MissingPalette; for (pal) |*c| { c.r = try stream.readByte(); c.g = try stream.readByte(); c.b = try stream.readByte(); } } img.palette = pal; } return img; } pub fn deinit(self: Self) void { if (self.palette) |pal| { self.allocator.destroy(pal); } self.allocator.free(self.pixels); } }; } pub const Format = enum { bpp1, bpp4, bpp8, bpp24, }; pub const Image = union(Format) { bpp1: SubImage(u1), bpp4: SubImage(u4), bpp8: SubImage(u8), bpp24: SubImage(RGB), pub fn deinit(image: Image) void { switch (image) { .bpp1 => |img| img.deinit(), .bpp4 => |img| img.deinit(), .bpp8 => |img| img.deinit(), .bpp24 => |img| img.deinit(), } } }; pub fn load(allocator: std.mem.Allocator, file: *std.fs.File) !Image { var stream = file.reader(); var header: Header = undefined; try stream.readNoEof(std.mem.asBytes(&header)); try stream.readNoEof(&Header.padding); if (header.id != 0x0A) return error.InvalidFileFormat; if (header.planes != 1) return error.UnsupportedFormat; var img: Image = undefined; switch (header.bpp) { 1 => img = Image{ .bpp1 = try SubImage(u1).initLinear(allocator, header, file, stream), }, 4 => img = Image{ .bpp4 = try SubImage(u4).initLinear(allocator, header, file, stream), }, 8 => img = Image{ .bpp8 = try SubImage(u8).initLinear(allocator, header, file, stream), }, 24 => img = Image{ .bpp24 = try SubImage(RGB).initLinear(allocator, header, file, stream), }, else => return error.UnsupportedFormat, } return img; } const RLEDecoder = struct { const Run = struct { value: u8, remaining: usize, }; stream: std.fs.File.Reader, currentRun: ?Run, fn init(stream: std.fs.File.Reader) RLEDecoder { return RLEDecoder{ .stream = stream, .currentRun = null, }; } fn readByte(self: *RLEDecoder) !u8 { if (self.currentRun) |*run| { var result = run.value; run.remaining -= 1; if (run.remaining == 0) self.currentRun = null; return result; } else { while (true) { var byte = try self.stream.readByte(); if (byte == 0xC0) // skip over "zero length runs" continue; if ((byte & 0xC0) == 0xC0) { const len = byte & 0x3F; std.debug.assert(len > 0); const result = try self.stream.readByte(); if (len > 1) { // we only need to store a run in the decoder if it is longer than 1 self.currentRun = .{ .value = result, .remaining = len - 1, }; } return result; } else { return byte; } } } } fn finish(decoder: RLEDecoder) !void { if (decoder.currentRun != null) return error.RLEStreamIncomplete; } }; test "PCX bpp1 (linear)" { var file = try std.fs.cwd().openRead("test/test-bpp1.pcx"); defer file.close(); var img = try load(std.debug.global_allocator, &file); errdefer img.deinit(); std.debug.assert(img == .bpp1); std.debug.assert(img.bpp1.width == 27); std.debug.assert(img.bpp1.height == 27); std.debug.assert(img.bpp1.palette != null); std.debug.assert(img.bpp1.palette.?.len == 2); } test "PCX bpp4 (linear)" { var file = try std.fs.cwd().openRead("test/test-bpp4.pcx"); defer file.close(); var img = try load(std.debug.global_allocator, &file); errdefer img.deinit(); std.debug.assert(img == .bpp4); std.debug.assert(img.bpp4.width == 27); std.debug.assert(img.bpp4.height == 27); std.debug.assert(img.bpp4.palette != null); std.debug.assert(img.bpp4.palette.?.len == 16); } test "PCX bpp8 (linear)" { var file = try std.fs.cwd().openRead("test/test-bpp8.pcx"); defer file.close(); var img = try load(std.debug.global_allocator, &file); errdefer img.deinit(); std.debug.assert(img == .bpp8); std.debug.assert(img.bpp8.width == 27); std.debug.assert(img.bpp8.height == 27); std.debug.assert(img.bpp8.palette != null); std.debug.assert(img.bpp8.palette.?.len == 256); } // TODO: reimplement as soon as planar mode is implemented // test "PCX bpp24 (planar)" { // var file = try std.fs.cwd().openRead("test/test-bpp24.pcx"); // defer file.close(); // var img = try load(std.debug.global_allocator, &file); // errdefer img.deinit(); // std.debug.assert(img == .bpp24); // std.debug.assert(img.bpp24.width == 27); // std.debug.assert(img.bpp24.height == 27); // std.debug.assert(img.bpp24.palette == null); // }
/// https://rm.fomu.im/touch.html pub const TOUCH = struct { const base = 0xe0005800; /// Output values for pads 1-4 pub const TOUCH_O = @intToPtr(*volatile u4, base + 0x0); /// Output enable control for pads 1-4 pub const TOUCH_OE = @intToPtr(*volatile u4, base + 0x4); /// Input value for pads 1-4 pub const TOUCH_1 = @intToPtr(*volatile u4, base + 0x8); };
<filename>.zpm/pkgs.zig<gh_stars>10-100 const std = @import("std"); fn pkgRoot() []const u8 { return std.fs.path.dirname(@src().file) orelse "."; } pub const pkgs = struct { pub const ihex = std.build.Pkg{ .name = "ihex", .path = .{ .path = pkgRoot() ++ "/../.zpm/../tools/modules/zig-ihex/ihex.zig" }, .dependencies = &[_]std.build.Pkg{}, }; pub const serial = std.build.Pkg{ .name = "serial", .path = .{ .path = pkgRoot() ++ "/../.zpm/../tools/modules/zig-serial/serial.zig" }, .dependencies = &[_]std.build.Pkg{}, }; pub const @"spu-mk2" = std.build.Pkg{ .name = "spu-mk2", .path = .{ .path = pkgRoot() ++ "/../.zpm/../tools/common/spu-mk2.zig" }, .dependencies = &[_]std.build.Pkg{}, }; pub const sdl2 = std.build.Pkg{ .name = "sdl2", .path = .{ .path = pkgRoot() ++ "/../.zpm/../tools/modules/SDL.zig/src/lib.zig" }, .dependencies = &[_]std.build.Pkg{}, }; pub const args = std.build.Pkg{ .name = "args", .path = .{ .path = pkgRoot() ++ "/../tools/modules/zig-args/args.zig" }, .dependencies = &[_]std.build.Pkg{}, }; }; pub const imports = struct { };
const std = @import("std"); const argsParser = @import("args"); const ihex = @import("ihex"); const spu = @import("spu-mk2"); const Instruction = spu.Instruction; const FileFormat = enum { ihex, binary }; pub fn main() !u8 { const cli_args = argsParser.parseForCurrentProcess(struct { help: bool = false, format: FileFormat = .ihex, output: []const u8 = "a.out", map: bool = false, pub const shorthands = .{ .h = "help", .f = "format", .o = "output", .m = "map", }; }, std.heap.page_allocator, .print) catch return 1; defer cli_args.deinit(); if (cli_args.options.help or cli_args.positionals.len == 0) { try std.io.getStdOut().writer().writeAll( \\assembler --help [--format ihex|binary] [--output file] fileA fileB … \\Assembles code for the SPU Mark II platform. \\ \\-h, --help Displays this help text. \\-f, --format Selects the output format (binary or ihex). \\ If not given, the assembler will emit raw binaries. \\-o, --output Defines the name of the output file. If not given, \\ the assembler will chose a.out as the output file name. \\-m, --map Output all global symbols to stdout \\ ); return if (cli_args.options.help) @as(u8, 0) else @as(u8, 1); } var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); var assembler = try Assembler.init(arena.allocator()); defer assembler.deinit(); var root_dir = try std.fs.cwd().openDir(".", .{ .access_sub_paths = true, .iterate = false }); defer root_dir.close(); for (cli_args.positionals) |path| { var file = try root_dir.openFile(path, .{ .read = true, .write = false }); defer file.close(); var dir = try root_dir.openDir(std.fs.path.dirname(path) orelse ".", .{ .access_sub_paths = true, .iterate = false }); defer dir.close(); try assembler.assemble(path, dir, file.reader()); } try assembler.finalize(); if (assembler.errors.items.len > 0) { const stdout = std.io.getStdOut().writer(); try stdout.writeAll("Errors appeared while assembling:\n"); for (assembler.errors.items) |err| { const file_name = if (err.location) |loc| loc.file orelse "unknown" else "unknown"; if (err.location) |loc| { try stdout.print("{s}: {s}:{}:{}: {s}\n", .{ @tagName(err.type), file_name, loc.line, loc.column, err.message, }); } else { try stdout.print("{s}: {s}:{}:{}: {s}\n", .{ @tagName(err.type), file_name, 0, 0, err.message, }); } } return 1; } if (cli_args.options.map) { var stdout = std.io.getStdOut().writer(); var it = assembler.symbols.iterator(); while (it.next()) |entry| { try stdout.print("{s}\t0x{X:0>4}\n", .{ entry.key_ptr.*, @bitCast(u64, try entry.value_ptr.getValue()), }); } } { var file = try root_dir.createFile(cli_args.options.output, .{ .truncate = true, .exclusive = false }); defer file.close(); var outstream = file.writer(); switch (cli_args.options.format) { .binary => { var iter = assembler.sections.first; while (iter) |section_node| : (iter = section_node.next) { const section = &section_node.data; try file.seekTo(section.phys_offset); try file.writeAll(section.bytes.items); } }, .ihex => { var iter = assembler.sections.first; while (iter) |section_node| : (iter = section_node.next) { const section = &section_node.data; var i: usize = 0; while (i < section.bytes.items.len) : (i += 16) { const length = std.math.min(section.bytes.items.len - i, 16); const source = section.bytes.items[i..][0..length]; var buffer: [256 + 5]u8 = undefined; std.mem.writeIntBig(u8, buffer[0..][0..1], @intCast(u8, length)); std.mem.writeIntBig(u16, buffer[1..][0..2], @intCast(u16, section.phys_offset + i)); std.mem.writeIntBig(u8, buffer[3..][0..1], 0x00); // data record std.mem.copy(u8, buffer[4..], source); var checksum: u8 = 0; for (buffer[0 .. 4 + length]) |b| { checksum -%= b; } std.mem.writeIntBig(u8, buffer[4 + length ..][0..1], checksum); // data record // data records try outstream.print( ":{}\n", .{std.fmt.fmtSliceHexUpper(buffer[0 .. length + 5])}, ); } } // file/stream terminator try outstream.writeAll(":00000001FF\n"); }, } } return 0; } pub const Patch = struct { offset: u16, value: Expression, locals: *std.StringHashMap(Symbol), }; pub const Section = struct { const Self = @This(); load_offset: u16, phys_offset: u32, bytes: std.ArrayList(u8), patches: std.ArrayList(Patch), dot_offset: u16, fn deinit(self: *Self) void { self.bytes.deinit(); for (self.patches.items) |*patch| { patch.value.deinit(); } self.patches.deinit(); self.* = undefined; } fn getLocalOffset(sect: Self) u16 { return @intCast(u16, sect.bytes.items.len); } fn getGlobalOffset(sect: Self) u16 { return @intCast(u16, sect.load_offset + sect.bytes.items.len); } fn getDotOffset(sect: Self) u16 { return sect.dot_offset; } }; pub const CompileError = struct { pub const Type = enum { @"error", warning }; location: ?Location, message: []const u8, type: Type, pub fn format(err: CompileError, comptime fmt: []const u8, options: std.fmt.FormatOptions, stream: anytype) !void { _ = fmt; _ = options; try stream.print("{}: {s}: {s}", .{ err.location, @tagName(err.type), err.message, }); } }; pub const Symbol = struct { /// The value of the symbol. If a section is given, this is the relative offset inside the /// section. Otherwise, it's a global offset. value: i64, section: ?*Section, pub fn getPhysicalAddress(self: Symbol) !u32 { const sect = self.section orelse return error.InvalidSymbol; return try std.math.cast(u32, sect.phys_offset + self.value); } pub fn getValue(self: Symbol) !i64 { return if (self.section) |sect| sect.load_offset + self.value else self.value; } }; pub const Assembler = struct { const Self = @This(); const SectionNode = std.TailQueue(Section).Node; // utilities allocator: std.mem.Allocator, string_cache: StringCache, arena: std.heap.ArenaAllocator, // assembling result sections: std.TailQueue(Section), symbols: std.StringHashMap(Symbol), local_symbols: *std.StringHashMap(Symbol), errors: std.ArrayList(CompileError), // in-flight symbols fileName: []const u8, directory: ?std.fs.Dir, fn appendSection(assembler: *Assembler, load_offset: u16, phys_offset: u32) !*Section { var node = try assembler.allocator.create(SectionNode); errdefer assembler.allocator.destroy(node); node.* = SectionNode{ .data = Section{ .load_offset = load_offset, .phys_offset = phys_offset, .bytes = std.ArrayList(u8).init(assembler.allocator), .patches = std.ArrayList(Patch).init(assembler.allocator), .dot_offset = load_offset, }, }; assembler.sections.append(node); return &node.data; } fn currentSection(assembler: *Assembler) *Section { return &(assembler.sections.last orelse unreachable).data; } pub fn init(allocator: std.mem.Allocator) !Assembler { var a = Self{ .allocator = allocator, .sections = std.TailQueue(Section){}, .symbols = std.StringHashMap(Symbol).init(allocator), .local_symbols = undefined, .errors = std.ArrayList(CompileError).init(allocator), .fileName = undefined, .directory = undefined, .string_cache = StringCache.init(allocator), .arena = std.heap.ArenaAllocator.init(allocator), }; errdefer a.arena.deinit(); errdefer a.string_cache.deinit(); a.local_symbols = try a.arena.allocator().create(std.StringHashMap(Symbol)); a.local_symbols.* = std.StringHashMap(Symbol).init(a.arena.allocator()); _ = try a.appendSection(0x0000, 0x0000_0000); return a; } pub fn deinit(self: *Self) void { while (self.sections.pop()) |sect| { sect.data.deinit(); self.allocator.destroy(sect); } self.string_cache.deinit(); self.arena.deinit(); self.symbols.deinit(); self.* = undefined; } pub fn finalize(self: *Self) !void { var iter = self.sections.first; while (iter) |section_node| : (iter = section_node.next) { const section = &section_node.data; for (section.patches.items) |patch| { self.local_symbols = patch.locals; // hacky const value = self.evaluate(patch.value, true) catch |err| switch (err) { error.MissingIdentifiers => continue, else => return err, }; const patch_value = value.toWord(self) catch 0xAAAA; std.mem.writeIntLittle(u16, section.bytes.items[patch.offset..][0..2], patch_value); } for (section.patches.items) |*patch| { patch.value.deinit(); } section.patches.shrinkRetainingCapacity(0); } } fn emitError(self: *Self, kind: CompileError.Type, location: ?Location, comptime fmt: []const u8, args: anytype) !void { const msg = try std.fmt.allocPrint(self.string_cache.string_arena.allocator(), fmt, args); errdefer self.allocator.free(msg); var location_clone = location; if (location_clone) |*l| { l.file = try self.string_cache.internString(self.fileName); } try self.errors.append(CompileError{ .location = location_clone, .type = kind, .message = msg, }); } const AssembleError = std.fs.File.OpenError || std.fs.File.ReadError || std.fs.File.SeekError || EvaluationError || Parser.ParseError || error{ UnexpectedEndOfFile, UnrecognizedCharacter, IncompleteStringLiteral, UnexpectedToken, OutOfMemory, UnknownMnemonic, UnexpectedOperand, DuplicateModifier, InvalidModifier, OutOfRange, UnknownDirective, DuplicateSymbol, EndOfStream, StreamTooLong, ParensImbalance, }; pub fn assemble(self: *Assembler, fileName: []const u8, directory: ?std.fs.Dir, stream: anytype) AssembleError!void { var parser = try Parser.fromStream(&self.string_cache, self.allocator, stream); defer parser.deinit(); self.fileName = fileName; self.directory = directory; while (true) { const token = try parser.peek(); if (token == null) // end of file break; // Update the dot offset to the start of the next *thing*. self.currentSection().dot_offset = self.currentSection().getGlobalOffset(); switch (token.?.type) { // process directive .dot_identifier => try parseDirective(self, &parser), // label, .label => { const label = try parser.expect(.label); const name = try self.string_cache.internString(label.text[0 .. label.text.len - 1]); const section = self.currentSection(); const offset = section.getLocalOffset(); const symbol = Symbol{ .value = offset, .section = section, }; if (name[0] == '.') { // local label try self.local_symbols.put(name, symbol); } else { // global label self.local_symbols = try self.arena.allocator().create(std.StringHashMap(Symbol)); self.local_symbols.* = std.StringHashMap(Symbol).init(self.arena.allocator()); try self.symbols.put(name, symbol); } }, // modifier .identifier, .opening_brackets => try parseInstruction(self, &parser), // empty line, skip those .line_break => _ = try parser.expect(.line_break), else => return error.UnexpectedToken, } } self.fileName = undefined; self.directory = null; } fn getInstructionForMnemonic(name: []const u8, argc: usize) ?Instruction { const mnemonics = @import("mnemonics.zig").mnemonics; for (mnemonics) |mnemonic| { if (mnemonic.argc == argc and std.mem.eql(u8, mnemonic.name, name)) return mnemonic.instruction; } return null; } fn parseInstruction(assembler: *Assembler, parser: *Parser) !void { var modifiers = Modifiers{}; var instruction_token: ?Token = null; // parse modifiers and while (true) { var tok = try parser.expectAny(.{ .identifier, // label or equ .opening_brackets, // modifier }); switch (tok.type) { .identifier => { instruction_token = tok; break; }, .opening_brackets => try modifiers.parse(assembler, parser), else => unreachable, // parse expression } } var operands: [2]Expression = undefined; var operand_count: usize = 0; var end_of_operands = false; // parse modifiers and operands while (true) { var tok = try parser.peek(); if (tok == null) break; switch (tok.?.type) { .line_break => { _ = parser.expect(.line_break) catch unreachable; break; }, .opening_brackets => { _ = parser.expect(.opening_brackets) catch unreachable; try modifiers.parse(assembler, parser); }, else => { if (operand_count >= operands.len or end_of_operands) { return error.UnexpectedOperand; } const expr_result = try parser.parseExpression(assembler.allocator, .{ .line_break, .comma, .opening_brackets }); operands[operand_count] = expr_result.expression; operand_count += 1; switch (expr_result.terminator.type) { .line_break => break, .opening_brackets => { try modifiers.parse(assembler, parser); end_of_operands = true; }, .comma => {}, else => unreachable, } }, } } // search for instruction template var instruction = getInstructionForMnemonic(instruction_token.?.text, operand_count) orelse { return try assembler.emitError(.@"error", instruction_token.?.location, "Unknown mnemonic: {s}", .{instruction_token.?.text}); }; // apply modifiers inline for (std.meta.fields(Modifiers)) |fld| { if (@field(modifiers, fld.name)) |mod| { @field(instruction, fld.name) = mod; } } // emit results try assembler.emitU16(@bitCast(u16, instruction)); { var i: usize = 0; while (i < operand_count) : (i += 1) { try assembler.emitExpr(operands[i]); } } } fn parseDirective(assembler: *Self, parser: *Parser) !void { var token = try parser.expect(.dot_identifier); inline for (std.meta.declarations(Directives)) |decl| { if (decl.data != .Fn) continue; if (decl.name[0] != '.') continue; if (std.mem.eql(u8, decl.name, token.text)) { try @field(Directives, decl.name)(assembler, parser); return; } } if (@import("builtin").mode == .Debug) { std.log.warn("unknown directive: {s}\n", .{token.text}); } return error.UnknownDirective; } const FunctionCallError = error{ OutOfMemory, TypeMismatch, InvalidArgument, WrongArgumentCount }; const Functions = struct { fn substr(assembler: *Assembler, argv: []const Value) FunctionCallError!Value { switch (argv.len) { 2 => { const str = try argv[0].toString(assembler); const start = try argv[1].toLong(assembler); return if (start < str.len) Value{ .string = str[start..] } else Value{ .string = "" }; }, 3 => { const str = try argv[0].toString(assembler); const start = try argv[1].toLong(assembler); const length = try argv[2].toLong(assembler); const offset_str = if (start < str.len) str[start..] else ""; const len = std.math.min(offset_str.len, length); return Value{ .string = offset_str[0..len] }; }, else => return error.WrongArgumentCount, } } fn physicalAddress(assembler: *Assembler, argv: []const Value) FunctionCallError!Value { if (argv.len != 1) return error.WrongArgumentCount; const symbol_name = try argv[0].toString(assembler); const lut = if (std.mem.startsWith(u8, symbol_name, ".")) assembler.local_symbols.* else assembler.symbols; if (lut.get(symbol_name)) |sym| { const value = sym.getPhysicalAddress() catch |err| { err catch {}; return error.InvalidArgument; }; return Value{ .number = value, }; } else { return error.InvalidArgument; } } }; const Directives = struct { fn @".org"(assembler: *Assembler, parser: *Parser) !void { const offset_expr = try parser.parseExpression(assembler.allocator, .{ .line_break, .comma }); const physical_expr = if (offset_expr.terminator.type == .comma) // parse the physical offset expr here try parser.parseExpression(assembler.allocator, .{.line_break}) else null; const load_offset_val = try assembler.evaluate(offset_expr.expression, true); const phys_offset_val = if (physical_expr) |expr| try assembler.evaluate(expr.expression, true) else null; const load_offset = load_offset_val.toWord(assembler) catch return; const phys_offset = if (phys_offset_val) |val| val.toLong(assembler) catch return else null; const sect = if (assembler.currentSection().bytes.items.len == 0) assembler.currentSection() else try assembler.appendSection(load_offset, phys_offset orelse load_offset); sect.load_offset = load_offset; sect.phys_offset = phys_offset orelse load_offset; } fn @".ascii"(assembler: *Assembler, parser: *Parser) !void { var string_expr = try parser.parseExpression(assembler.allocator, .{.line_break}); defer string_expr.expression.deinit(); const string_val = try assembler.evaluate(string_expr.expression, true); const string = string_val.toString(assembler) catch return; try assembler.emit(string); } fn @".asciiz"(assembler: *Assembler, parser: *Parser) !void { var string_expr = try parser.parseExpression(assembler.allocator, .{.line_break}); defer string_expr.expression.deinit(); const string_val = try assembler.evaluate(string_expr.expression, true); const string = string_val.toString(assembler) catch return; try assembler.emit(string); try assembler.emitU8(0x00); // null terminator } fn @".align"(assembler: *Assembler, parser: *Parser) !void { const alignment_expr = try parser.parseExpression(assembler.allocator, .{.line_break}); const alignment_val = try assembler.evaluate(alignment_expr.expression, true); const alignment = alignment_val.toWord(assembler) catch return; const sect = assembler.currentSection(); const newSize = std.mem.alignForward(sect.bytes.items.len, alignment); if (newSize != sect.bytes.items.len) { try sect.bytes.appendNTimes(0x00, newSize - sect.bytes.items.len); } std.debug.assert(sect.bytes.items.len == newSize); } fn @".space"(assembler: *Assembler, parser: *Parser) !void { const size_expr = try parser.parseExpression(assembler.allocator, .{.line_break}); const size_val = try assembler.evaluate(size_expr.expression, true); const size = size_val.toWord(assembler) catch return; const sect = assembler.currentSection(); try sect.bytes.appendNTimes(0x00, size); } fn @".dw"(assembler: *Assembler, parser: *Parser) !void { while (true) { const value_expr = try parser.parseExpression(assembler.allocator, .{ .line_break, .comma }); try assembler.emitExpr(value_expr.expression); if (value_expr.terminator.type == .line_break) break; } } fn @".db"(assembler: *Assembler, parser: *Parser) !void { while (true) { var value_expr = try parser.parseExpression(assembler.allocator, .{ .line_break, .comma }); defer value_expr.expression.deinit(); const byte_val = try assembler.evaluate(value_expr.expression, true); try assembler.emitU8(if (byte_val.toByte(assembler)) |byte| byte else |_| 0xAA); if (value_expr.terminator.type == .line_break) break; } } fn @".equ"(assembler: *Assembler, parser: *Parser) !void { const name_tok = try parser.expect(.identifier); _ = try parser.expect(.comma); const name = try assembler.string_cache.internString(name_tok.text); var value_expr = try parser.parseExpression(assembler.allocator, .{.line_break}); defer value_expr.expression.deinit(); const equ_val = try assembler.evaluate(value_expr.expression, true); // TODO: Decide whether unreferenced symbol or invalid value is better! const equ = equ_val.toNumber(assembler) catch 0xAAAA; // TODO: reinclude duplicatesymbol try assembler.symbols.put(name, Symbol{ .value = equ, .section = null }); } fn @".incbin"(assembler: *Assembler, parser: *Parser) !void { const filename_expr = try parser.parseExpression(assembler.allocator, .{.line_break}); const filename = try assembler.evaluate(filename_expr.expression, true); if (filename != .string) return error.TypeMismatch; if (assembler.directory) |dir| { var blob = try dir.readFileAlloc(assembler.allocator, filename.string, 65536); defer assembler.allocator.free(blob); try assembler.currentSection().bytes.writer().writeAll(blob); } else { try assembler.emitError(.@"error", filename_expr.expression.location, "Cannot open file {s}: No filesystem available", .{filename.string}); } } fn @".include"(assembler: *Assembler, parser: *Parser) !void { const filename_expr = try parser.parseExpression(assembler.allocator, .{.line_break}); const filename = try assembler.evaluate(filename_expr.expression, true); if (filename != .string) return error.TypeMismatch; if (assembler.directory) |dir| { var file = dir.openFile(filename.string, .{ .read = true, .write = false }) catch |err| switch (err) { error.FileNotFound => { try assembler.emitError(.@"error", filename_expr.expression.location, "Cannot open file {s}: File not found.", .{filename.string}); return; }, else => |e| return e, }; defer file.close(); const old_file_name = assembler.fileName; defer assembler.fileName = old_file_name; defer assembler.directory = dir; var new_dir = try dir.openDir(std.fs.path.dirname(filename.string) orelse ".", .{ .access_sub_paths = true, .iterate = false }); defer new_dir.close(); try assembler.assemble(filename.string, new_dir, file.reader()); } else { try assembler.emitError(.@"error", filename_expr.expression.location, "Cannot open file {s}: No filesystem available", .{filename}); } } }; // Output handling: fn emit(assembler: *Assembler, bytes: []const u8) !void { const sect = assembler.currentSection(); try sect.bytes.writer().writeAll(bytes); } fn emitU8(assembler: *Assembler, value: u8) !void { const bytes = [1]u8{value}; try assembler.emit(&bytes); } fn emitU16(assembler: *Assembler, value: u16) !void { var bytes: [2]u8 = undefined; std.mem.writeIntLittle(u16, &bytes, value); try assembler.emit(&bytes); } // Consumes a expression and takes ownership of its resources fn emitExpr(assembler: *Assembler, expression: Expression) !void { var copy = expression; errdefer copy.deinit(); if (assembler.evaluate(copy, false)) |value| { const int_val = value.toWord(assembler) catch 0xAAAA; try assembler.emitU16(int_val); copy.deinit(); } else |err| switch (err) { error.MissingIdentifiers => { const sect = assembler.currentSection(); const ptr = sect.getLocalOffset(); // Defer evaluation to end of assembling, // store label context (for locals) and expr for later, write dummy value try assembler.emitU16(0x5555); try sect.patches.append(Patch{ .offset = ptr, .value = copy, .locals = assembler.local_symbols, }); }, else => return err, } } // Expression handling const EvaluationError = FunctionCallError || error{ InvalidExpression, UnknownFunction, MissingIdentifiers, OutOfMemory, TypeMismatch, Overflow, InvalidCharacter }; fn evaluate(assembler: *Assembler, expression: Expression, emitErrorOnMissing: bool) EvaluationError!Value { return try expression.evaluate(assembler, emitErrorOnMissing); // .operator_plus => { // const rhs = stack.popOrNull() orelse return error.InvalidExpression; // const lhs = stack.popOrNull() orelse return error.InvalidExpression; // if (@as(ValueType, lhs) != @as(ValueType, rhs)) // return error.TypeMismatch; // try stack.append(switch (lhs) { // .number => Value{ .number = lhs.number +% rhs.number }, // .string => Value{ // .string = try std.mem.concat(assembler.allocator, u8, &[_][]const u8{ // lhs.string, // rhs.string, // }), // }, // }); // }, // } // } } }; const StringCache = struct { const Self = @This(); string_arena: std.heap.ArenaAllocator, interned_strings: std.StringHashMap(void), scratch_buffer: std.ArrayList(u8), pub fn init(allocator: std.mem.Allocator) Self { return .{ .string_arena = std.heap.ArenaAllocator.init(allocator), .interned_strings = std.StringHashMap(void).init(allocator), .scratch_buffer = std.ArrayList(u8).init(allocator), }; } pub fn deinit(self: *Self) void { self.interned_strings.deinit(); self.string_arena.deinit(); self.scratch_buffer.deinit(); self.* = undefined; } const EscapingResult = struct { char: u8, length: usize, }; fn translateEscapedChar(pattern: []const u8) !EscapingResult { if (pattern[0] != '\\') return EscapingResult{ .char = pattern[0], .length = 1 }; return EscapingResult{ .length = 2, .char = switch (pattern[1]) { 'a' => 0x07, 'b' => 0x08, 'e' => 0x1B, 'n' => 0x0A, 'r' => 0x0D, 't' => 0x0B, '\\' => 0x5C, '\'' => 0x27, '\"' => 0x22, 'x' => { return EscapingResult{ .length = 4, .char = std.fmt.parseInt(u8, pattern[2..4], 16) catch |err| switch (err) { error.Overflow => unreachable, // 2 hex chars can never overflow a byte! else => |e| return e, }, }; }, else => |c| c, }, }; } pub fn escapeAndInternString(self: *Self, raw_string: []const u8) ![]const u8 { self.scratch_buffer.shrinkRetainingCapacity(0); // we can safely resize the buffer here to the source string length, as // in the worst case, we will not change the size and in the best case we will // be left with 1/4th of the char count (\x??) try self.scratch_buffer.ensureTotalCapacity(raw_string.len); var offset: usize = 0; while (offset < raw_string.len) { const c = try translateEscapedChar(raw_string[offset..]); offset += c.length; self.scratch_buffer.append(c.char) catch unreachable; } return try self.internString(self.scratch_buffer.items); } pub fn internString(self: *Self, string: []const u8) ![]const u8 { const gop = try self.interned_strings.getOrPut(string); if (!gop.found_existing) { gop.key_ptr.* = try self.string_arena.allocator().dupe(u8, string); } return gop.key_ptr.*; } }; pub const TokenType = enum { const Self = @This(); whitespace, comment, // ; … line_break, // "\n" identifier, // fooas2_3 dot_identifier, // .fooas2_3 label, //foobar:, .foobar: function, // #symbol bin_number, // 0b0000 oct_number, // 0o0000 dec_number, // 0000 hex_number, // 0x0000 char_literal, // 'A', '\n' string_literal, // "Abc", "a\nc" dot, // . colon, // : comma, // , opening_parens, // ( closing_parens, // ) opening_brackets, // [ closing_brackets, // ] operator_plus, // + operator_minus, // - operator_multiply, // * operator_divide, // / operator_modulo, // % operator_bitand, // & operator_bitor, // | operator_bitxor, // ^ operator_shl, // << operator_shr, // >> operator_asr, // >>> operator_bitnot, // ~ fn isOperator(self: Self) bool { return switch (self) { .operator_plus, .operator_minus, .operator_multiply, .operator_divide, .operator_modulo, .operator_bitand, .operator_bitor, .operator_bitxor, .operator_shl, .operator_shr, .operator_asr, .operator_bitnot => true, else => false, }; } }; pub const Location = struct { file: ?[]const u8, line: u32, column: u32, fn merge(a: Location, b: Location) Location { std.debug.assert(std.meta.eql(a.file, b.file)); return if (a.line < b.line) a else if (a.line > b.line) b else if (a.column < b.column) a else b; } }; pub const Token = struct { const Self = @This(); text: []const u8, type: TokenType, location: Location, fn duplicate(self: Self, allocator: std.mem.Allocator) !Self { return Self{ .type = self.type, .text = try std.mem.dupe(allocator, u8, self.text), .location = self.location, }; } }; pub const Parser = struct { allocator: ?std.mem.Allocator, string_cache: *StringCache, source: []u8, offset: usize, peeked_token: ?Token, current_location: Location, const Self = @This(); fn fromStream(string_cache: *StringCache, allocator: std.mem.Allocator, stream: anytype) !Self { return Self{ .string_cache = string_cache, .allocator = allocator, .source = try stream.readAllAlloc(allocator, 16 << 20), // 16 MB .offset = 0, .peeked_token = null, .current_location = Location{ .line = 1, .column = 1, .file = null, }, }; } fn fromSlice(string_cache: *StringCache, text: []const u8) Self { return Self{ .string_cache = string_cache, .allocator = null, .source = text, .offset = 0, .peeked_token = null, .current_location = Location{ .line = 1, .column = 1, .file = null, }, }; } fn deinit(self: *Self) void { if (self.allocator) |a| a.free(self.source); self.* = undefined; } fn expect(parser: *Self, t: TokenType) !Token { var state = parser.saveState(); errdefer parser.restoreState(state); const tok = (try parser.parse()) orelse return error.UnexpectedEndOfFile; if (tok.type == t) return tok; if (@import("builtin").mode == .Debug) { // std.debug.warn("Unexpected token: {}\nexpected: {}\n", .{ // tok, // t, // }); } return error.UnexpectedToken; } fn expectAny(parser: *Self, types: anytype) !Token { var state = parser.saveState(); errdefer parser.restoreState(state); const tok = (try parser.parse()) orelse return error.UnexpectedEndOfFile; inline for (types) |t| { if (tok.type == @as(TokenType, t)) return tok; } // if (std.builtin.mode == .Debug) { // std.debug.warn("Unexpected token: {}\nexpected one of: {}\n", .{ // tok, // types, // }); // } return error.UnexpectedToken; } fn peek(parser: *Self) !?Token { if (parser.peeked_token) |tok| { return tok; } parser.peeked_token = try parser.parse(); return parser.peeked_token; } fn parse(parser: *Self) !?Token { if (parser.peeked_token) |tok| { parser.peeked_token = null; return tok; } while (true) { var token = try parser.parseRaw(); if (token) |tok| { switch (tok.type) { .whitespace => continue, .comment => continue, else => return tok, } } else { return null; } } } fn singleCharToken(parser: *Self, t: TokenType) Token { return Token{ .text = parser.source[parser.offset..][0..1], .type = t, .location = parser.current_location, }; } fn isWordCharacter(c: u8) bool { return switch (c) { 'a'...'z' => true, 'A'...'Z' => true, '0'...'9' => true, '_' => true, '.' => true, else => false, }; } fn isDigit(c: u8, number_format: TokenType) bool { return switch (number_format) { .dec_number => switch (c) { '0'...'9' => true, else => false, }, .oct_number => switch (c) { '0'...'7' => true, else => false, }, .bin_number => switch (c) { '0', '1' => true, else => false, }, .hex_number => switch (c) { '0'...'9' => true, 'a'...'f' => true, 'A'...'F' => true, else => false, }, else => unreachable, }; } fn parseRaw(parser: *Self) !?Token { // Return a .line_break when we reached the end of the file // Prevents a whole class of errors in the rest of the code :) if (parser.offset == parser.source.len) { parser.offset += 1; return Token{ .text = "\n", .type = .line_break, .location = parser.current_location, }; } else if (parser.offset >= parser.source.len) { return null; } var token = switch (parser.source[parser.offset]) { '\n' => parser.singleCharToken(.line_break), ' ', '\t', '\r' => parser.singleCharToken(.whitespace), ';' => blk: { var off = parser.offset; while (off < parser.source.len and parser.source[off] != '\n') { off += 1; } break :blk Token{ .type = .comment, .text = parser.source[parser.offset..off], .location = parser.current_location, }; }, ':' => parser.singleCharToken(.colon), ',' => parser.singleCharToken(.comma), '(' => parser.singleCharToken(.opening_parens), ')' => parser.singleCharToken(.closing_parens), '[' => parser.singleCharToken(.opening_brackets), ']' => parser.singleCharToken(.closing_brackets), '+' => parser.singleCharToken(.operator_plus), '-' => parser.singleCharToken(.operator_minus), '*' => parser.singleCharToken(.operator_multiply), '/' => parser.singleCharToken(.operator_divide), '%' => parser.singleCharToken(.operator_modulo), '&' => parser.singleCharToken(.operator_bitand), '|' => parser.singleCharToken(.operator_bitor), '^' => parser.singleCharToken(.operator_bitxor), '~' => parser.singleCharToken(.operator_bitnot), '.' => if (parser.offset + 1 >= parser.source.len or !isWordCharacter(parser.source[parser.offset + 1])) parser.singleCharToken(.dot) else blk: { var off = parser.offset + 1; while (off < parser.source.len and isWordCharacter(parser.source[off])) { off += 1; } if (off < parser.source.len and parser.source[off] == ':') { off += 1; break :blk Token{ .type = .label, .text = parser.source[parser.offset..off], .location = parser.current_location, }; } else { break :blk Token{ .type = .dot_identifier, .text = parser.source[parser.offset..off], .location = parser.current_location, }; } }, // operator_shr, // >> // operator_asr, // >>> '>' => blk: { if (parser.offset + 1 >= parser.source.len) return error.UnexpectedEndOfFile; if (parser.source[parser.offset + 1] != '>') return error.UnrecognizedCharacter; if (parser.offset + 2 < parser.source.len and parser.source[parser.offset + 2] == '>') { break :blk Token{ .type = .operator_asr, .text = parser.source[parser.offset..][0..3], .location = parser.current_location, }; } else { break :blk Token{ .type = .operator_shr, .text = parser.source[parser.offset..][0..2], .location = parser.current_location, }; } }, '<' => blk: { if (parser.offset + 1 >= parser.source.len) return error.UnexpectedEndOfFile; if (parser.source[parser.offset + 1] != '<') return error.UnrecognizedCharacter; break :blk Token{ .type = .operator_shl, .text = parser.source[parser.offset..][0..2], .location = parser.current_location, }; }, // '<<' => parser.singleCharToken(.operator_shl), // bin_number: 0b0000 // oct_number: 0o0000 // dec_number: 0000 // hex_number: 0x0000 '0'...'9' => blk: { if (parser.offset + 1 < parser.source.len) { const spec = parser.source[parser.offset + 1]; switch (spec) { 'x', 'o', 'b' => { var num_type: TokenType = switch (spec) { 'x' => .hex_number, 'b' => .bin_number, 'o' => .oct_number, else => unreachable, }; var off = parser.offset + 2; while (off < parser.source.len and isDigit(parser.source[off], num_type)) { off += 1; } // .dotword break :blk Token{ .type = num_type, .text = parser.source[parser.offset..off], .location = parser.current_location, }; }, '0'...'9' => { var off = parser.offset + 1; while (off < parser.source.len and isDigit(parser.source[off], .dec_number)) { off += 1; } // .dotword break :blk Token{ .type = .dec_number, .text = parser.source[parser.offset..off], .location = parser.current_location, }; }, else => break :blk Token{ .type = .dec_number, .text = parser.source[parser.offset .. parser.offset + 1], .location = parser.current_location, }, } } else { break :blk Token{ .type = .dec_number, .text = parser.source[parser.offset .. parser.offset + 1], .location = parser.current_location, }; } }, // identifier 'a'...'z', 'A'...'Z', '_' => blk: { var off = parser.offset; while (off < parser.source.len and isWordCharacter(parser.source[off])) { off += 1; } if (off < parser.source.len and parser.source[off] == ':') { off += 1; break :blk Token{ .type = .label, .text = parser.source[parser.offset..off], .location = parser.current_location, }; } else { break :blk Token{ .type = .identifier, .text = parser.source[parser.offset..off], .location = parser.current_location, }; } }, // string_literal, char_literal '\'', '\"' => blk: { var off = parser.offset + 1; if (off == parser.source.len) return error.IncompleteStringLiteral; const delimiter = parser.source[parser.offset]; while (parser.source[off] != delimiter) { if (parser.source[off] == '\n') return error.IncompleteStringLiteral; if (parser.source[off] == '\\') { off += 1; } off += 1; if (off >= parser.source.len) return error.IncompleteStringLiteral; } off += 1; break :blk Token{ .type = if (delimiter == '\'') .char_literal else .string_literal, .text = parser.source[parser.offset..off], .location = parser.current_location, }; }, else => |c| { if (@import("builtin").mode == .Debug) { std.log.warn("unrecognized character: {c}", .{c}); } return error.UnrecognizedCharacter; }, }; parser.offset += token.text.len; for (token.text) |c| { if (c == '\n') { parser.current_location.line += 1; parser.current_location.column = 1; } else { parser.current_location.column += 1; } } return token; } fn lastOfSlice(slice: anytype) @TypeOf(slice[0]) { return slice[slice.len - 1]; } const ParserState = struct { source: []u8, offset: usize, peeked_token: ?Token, current_location: Location, }; fn saveState(parser: Parser) ParserState { return ParserState{ .source = parser.source, .offset = parser.offset, .peeked_token = parser.peeked_token, .current_location = parser.current_location, }; } fn restoreState(parser: *Parser, state: ParserState) void { parser.source = state.source; parser.offset = state.offset; parser.peeked_token = state.peeked_token; parser.current_location = state.current_location; } // parses an expression from the token stream const ParseExpressionResult = struct { expression: Expression, terminator: Token, }; fn parseExpression(parser: *Parser, allocator: std.mem.Allocator, terminators: anytype) !ParseExpressionResult { _ = terminators; const state = parser.saveState(); errdefer parser.restoreState(state); var expr = Expression{ .arena = std.heap.ArenaAllocator.init(allocator), .root = undefined, .location = undefined, }; errdefer expr.arena.deinit(); expr.root = try parser.acceptExpression(expr.arena.allocator()); expr.location = expr.root.location; return ParseExpressionResult{ .expression = expr, .terminator = try parser.expectAny(terminators), }; } fn moveToHeap(allocator: std.mem.Allocator, value: anytype) !*@TypeOf(value) { const T = @TypeOf(value); std.debug.assert(@typeInfo(T) != .Pointer); const ptr = try allocator.create(T); ptr.* = value; std.debug.assert(std.meta.eql(ptr.*, value)); return ptr; } const ParseError = error{ OutOfMemory, UnexpectedEndOfFile, UnrecognizedCharacter, IncompleteStringLiteral, UnexpectedToken, InvalidNumber, InvalidCharacter, }; const acceptExpression = acceptSumExpression; fn acceptSumExpression(self: *Parser, allocator: std.mem.Allocator) ParseError!ExpressionNode { const state = self.saveState(); errdefer self.restoreState(state); var expr = try self.acceptMulExpression(allocator); while (true) { var and_or = self.expectAny(.{ .operator_plus, .operator_minus, }) catch break; var rhs = try self.acceptMulExpression(allocator); var new_expr = ExpressionNode{ .location = expr.location.merge(and_or.location).merge(rhs.location), .type = .{ .binary_op = .{ .operator = switch (and_or.type) { .operator_plus => .add, .operator_minus => .sub, else => unreachable, }, .lhs = try moveToHeap(allocator, expr), .rhs = try moveToHeap(allocator, rhs), }, }, }; expr = new_expr; } return expr; } fn acceptMulExpression(self: *Parser, allocator: std.mem.Allocator) ParseError!ExpressionNode { const state = self.saveState(); errdefer self.restoreState(state); var expr = try self.acceptBitwiseExpression(allocator); while (true) { var and_or = self.expectAny(.{ .operator_multiply, .operator_divide, .operator_modulo, }) catch break; var rhs = try self.acceptBitwiseExpression(allocator); var new_expr = ExpressionNode{ .location = expr.location.merge(and_or.location).merge(rhs.location), .type = .{ .binary_op = .{ .operator = switch (and_or.type) { .operator_multiply => .mul, .operator_divide => .div, .operator_modulo => .mod, else => unreachable, }, .lhs = try moveToHeap(allocator, expr), .rhs = try moveToHeap(allocator, rhs), }, }, }; expr = new_expr; } return expr; } fn acceptBitwiseExpression(self: *Parser, allocator: std.mem.Allocator) ParseError!ExpressionNode { const state = self.saveState(); errdefer self.restoreState(state); var expr = try self.acceptShiftExpression(allocator); while (true) { var and_or = self.expectAny(.{ .operator_bitand, .operator_bitor, .operator_bitxor, }) catch break; var rhs = try self.acceptShiftExpression(allocator); var new_expr = ExpressionNode{ .location = expr.location.merge(and_or.location).merge(rhs.location), .type = .{ .binary_op = .{ .operator = switch (and_or.type) { .operator_bitand => .bit_and, .operator_bitor => .bit_or, .operator_bitxor => .bit_xor, else => unreachable, }, .lhs = try moveToHeap(allocator, expr), .rhs = try moveToHeap(allocator, rhs), }, }, }; expr = new_expr; } return expr; } fn acceptShiftExpression(self: *Parser, allocator: std.mem.Allocator) ParseError!ExpressionNode { const state = self.saveState(); errdefer self.restoreState(state); var expr = try self.acceptUnaryPrefixOperatorExpression(allocator); while (true) { var and_or = self.expectAny(.{ .operator_shl, .operator_shr, .operator_asr, }) catch break; var rhs = try self.acceptUnaryPrefixOperatorExpression(allocator); var new_expr = ExpressionNode{ .location = expr.location.merge(and_or.location).merge(rhs.location), .type = .{ .binary_op = .{ .operator = switch (and_or.type) { .operator_shl => .lsl, .operator_shr => .lsr, .operator_asr => .asr, else => unreachable, }, .lhs = try moveToHeap(allocator, expr), .rhs = try moveToHeap(allocator, rhs), }, }, }; expr = new_expr; } return expr; } fn acceptUnaryPrefixOperatorExpression(self: *Parser, allocator: std.mem.Allocator) ParseError!ExpressionNode { const state = self.saveState(); errdefer self.restoreState(state); if (self.expectAny(.{ .operator_bitnot, .operator_minus })) |prefix| { // this must directly recurse as we can write `not not x` const value = try self.acceptUnaryPrefixOperatorExpression(allocator); return ExpressionNode{ .location = prefix.location.merge(value.location), .type = .{ .unary_op = .{ .operator = switch (prefix.type) { .operator_bitnot => .bit_invert, .operator_minus => .negate, else => unreachable, }, .value = try moveToHeap(allocator, value), }, }, }; } else |_| { return try self.acceptCallExpression(allocator); } } fn acceptCallExpression(self: *Parser, allocator: std.mem.Allocator) ParseError!ExpressionNode { const state = self.saveState(); errdefer self.restoreState(state); var value = try self.acceptValueExpression(allocator); if (value.type == .symbol_reference) { if (self.expect(.opening_parens)) |_| { var args = std.ArrayList(ExpressionNode).init(allocator); defer args.deinit(); var loc = value.location; if (self.expect(.closing_parens)) |_| { // this is the end of the argument list } else |_| { while (true) { const arg = try self.acceptExpression(allocator); try args.append(arg); const terminator = try self.expectAny(.{ .closing_parens, .comma }); loc = terminator.location.merge(loc); if (terminator.type == .closing_parens) break; } } const name = value.type.symbol_reference; value = ExpressionNode{ .location = loc, .type = .{ .fn_call = .{ .function = name, .arguments = args.toOwnedSlice(), }, }, }; } else |_| {} } return value; } fn acceptValueExpression(self: *Parser, allocator: std.mem.Allocator) ParseError!ExpressionNode { const state = self.saveState(); errdefer self.restoreState(state); const token = try self.expectAny(.{ .opening_parens, .bin_number, .oct_number, .dec_number, .hex_number, .string_literal, .char_literal, .identifier, .dot_identifier, .dot, }); switch (token.type) { .opening_parens => { const value = try self.acceptExpression(allocator); _ = try self.expect(.closing_parens); return value; }, .bin_number => return ExpressionNode{ .location = token.location, .type = .{ .numeric_literal = std.fmt.parseInt(i64, token.text[2..], 2) catch return error.InvalidNumber, }, }, .oct_number => return ExpressionNode{ .location = token.location, .type = .{ .numeric_literal = std.fmt.parseInt(i64, token.text[2..], 8) catch return error.InvalidNumber, }, }, .dec_number => return ExpressionNode{ .location = token.location, .type = .{ .numeric_literal = std.fmt.parseInt(i64, token.text, 10) catch return error.InvalidNumber, }, }, .hex_number => return ExpressionNode{ .location = token.location, .type = .{ .numeric_literal = std.fmt.parseInt(i64, token.text[2..], 16) catch return error.InvalidNumber, }, }, .string_literal => { std.debug.assert(token.text.len >= 2); return ExpressionNode{ .location = token.location, .type = .{ .string_literal = try self.string_cache.escapeAndInternString(token.text[1 .. token.text.len - 1]), }, }; }, .char_literal => return ExpressionNode{ .location = token.location, .type = .{ .numeric_literal = (StringCache.translateEscapedChar(token.text[1..]) catch return error.InvalidCharacter).char, }, }, .identifier => return ExpressionNode{ .location = token.location, .type = .{ .symbol_reference = try self.string_cache.internString(token.text), }, }, .dot_identifier => return ExpressionNode{ .location = token.location, .type = .{ .local_symbol_reference = try self.string_cache.internString(token.text), }, }, .dot => return ExpressionNode{ .location = token.location, .type = .current_location, }, else => unreachable, } } }; const ExpressionNode = struct { location: Location, type: ExpressionType, const ExpressionType = union(enum) { const Self = @This(); string_literal: []const u8, numeric_literal: i64, symbol_reference: []const u8, local_symbol_reference: []const u8, current_location, binary_op: BinaryExpr, unary_op: UnaryExpr, fn_call: FunctionCall, const BinaryExpr = struct { operator: BinaryOperator, lhs: *ExpressionNode, rhs: *ExpressionNode, }; const UnaryExpr = struct { operator: UnaryOperator, value: *ExpressionNode, }; const FunctionCall = struct { function: []const u8, arguments: []ExpressionNode, }; const BinaryOperator = enum { add, sub, mul, div, mod, bit_and, bit_or, bit_xor, lsl, lsr, asr, }; const UnaryOperator = enum { negate, bit_invert, }; }; }; const Value = union(enum) { string: []const u8, // does not need to be freed, will be string-pooled number: i64, // TODO: Decide how to enable truncation warnings pub const warn_truncation = false; fn toInteger(self: Value, assembler: ?*Assembler, comptime T: type) !T { if (comptime !std.meta.trait.isIntegral(T)) @compileError("T must be a integer type!"); switch (self) { .number => |src| { const result = switch (@typeInfo(T).Int.signedness) { .signed => @truncate(T, src), .unsigned => @truncate(T, @bitCast(u64, src)), }; if (warn_truncation) { if (src < std.math.minInt(T) or src > std.math.maxInt(T)) { if (assembler) |as| { try as.emitError(.warning, null, "Truncating number {} to {}-bit value {}", .{ src, @bitSizeOf(T), result }); } } } return result; }, else => { if (assembler) |as| { try as.emitError(.warning, null, "Type mismatch: Expected number, found {s}", .{std.meta.tagName(self)}); } return error.TypeMismatch; }, } } pub fn toByte(self: Value, assembler: ?*Assembler) !u8 { return try self.toInteger(assembler, u8); } pub fn toWord(self: Value, assembler: ?*Assembler) !u16 { return try self.toInteger(assembler, u16); } pub fn toLong(self: Value, assembler: ?*Assembler) !u32 { return try self.toInteger(assembler, u32); } pub fn toNumber(self: Value, assembler: ?*Assembler) !i64 { return try self.toInteger(assembler, i64); } pub fn toString(self: Value, assembler: ?*Assembler) ![]const u8 { return switch (self) { .string => |v| v, else => { if (assembler) |as| { try as.emitError(.warning, null, "Type mismatch: Expected string, found {s}", .{std.meta.tagName(self)}); } return error.TypeMismatch; }, }; } }; const ValueType = std.meta.Tag(Value); /// A sequence of tokens created with a shunting yard algorithm. /// Can be parsed/executed left-to-right const Expression = struct { const Self = @This(); arena: std.heap.ArenaAllocator, location: Location, root: ExpressionNode, fn deinit(expr: *Expression) void { expr.arena.deinit(); expr.* = undefined; } pub const EvalError = Assembler.FunctionCallError || error{ MissingIdentifiers, UnknownFunction, OutOfMemory, TypeMismatch, Overflow }; pub fn evaluate(self: *const Self, context: *Assembler, emitErrorOnMissing: bool) EvalError!Value { const errors = ErrorEmitter{ .context = context, .emitErrorOnMissing = emitErrorOnMissing, }; return try self.evaluateRecursive(context, errors, &self.root); } const EvalValue = Value; const ErrorEmitter = struct { context: *Assembler, emitErrorOnMissing: bool, pub fn emit(self: @This(), err: EvalError, location: ?Location, comptime fmt: []const u8, args: anytype) EvalError { if (self.emitErrorOnMissing) { try self.context.emitError(.@"error", location, fmt, args); } return err; } fn requireValueType(errors: ErrorEmitter, comptime valtype: std.meta.Tag(EvalValue), value: EvalValue) !switch (valtype) { .number => i64, .string => []const u8, } { return switch (value) { valtype => |v| v, else => errors.emit(error.TypeMismatch, null, "Expected {s}, got {s}", .{ std.meta.tagName(valtype), std.meta.tagName(value) }), }; } fn requireNumber(errors: ErrorEmitter, value: EvalValue) !i64 { return requireValueType(errors, .number, value); } fn requireString(errors: ErrorEmitter, value: EvalValue) ![]const u8 { return requireValueType(errors, .string, value); } fn truncateTo(errors: ErrorEmitter, src: i64) !u16 { const result = @truncate(u16, @bitCast(u64, src)); if (src < 0 or src > 0xFFFF) { if (errors.emitErrorOnMissing) { try errors.context.emitError(.warning, null, "Truncating numeric {} to 16-bit value {}", .{ src, result }); } } return result; } }; fn evaluateRecursive(self: *const Self, context: *Assembler, errors: ErrorEmitter, node: *const ExpressionNode) EvalError!EvalValue { return switch (node.type) { .numeric_literal => |number| EvalValue{ .number = number }, .string_literal => |str| EvalValue{ .string = try context.string_cache.internString(str), }, .current_location => EvalValue{ .number = @intCast(u16, context.currentSection().getDotOffset()), }, .symbol_reference => |symbol_name| if (context.symbols.get(symbol_name)) |sym| EvalValue{ .number = try sym.getValue() } else return errors.emit(error.MissingIdentifiers, null, "Missing identifier: {s}", .{symbol_name}), // TODO: Store locations of symbol refs .local_symbol_reference => |symbol_name| if (context.local_symbols.get(symbol_name)) |sym| EvalValue{ .number = try sym.getValue() } else return errors.emit(error.MissingIdentifiers, null, "Missing identifier: {s}", .{symbol_name}), // TODO: Store locations of symbol refs .binary_op => |op| blk: { const lhs = try self.evaluateRecursive(context, errors, op.lhs); const rhs = try self.evaluateRecursive(context, errors, op.rhs); break :blk switch (op.operator) { .add => EvalValue{ .number = (try errors.requireNumber(lhs)) +% (try errors.requireNumber(rhs)), }, .sub => EvalValue{ .number = (try errors.requireNumber(lhs)) -% (try errors.requireNumber(rhs)), }, .mul => EvalValue{ .number = (try errors.requireNumber(lhs)) *% (try errors.requireNumber(rhs)), }, .div => EvalValue{ .number = @divTrunc(try errors.requireNumber(lhs), try errors.requireNumber(rhs)), }, .mod => EvalValue{ .number = @mod(try errors.requireNumber(lhs), try errors.requireNumber(rhs)), }, .bit_and => EvalValue{ .number = (try errors.requireNumber(lhs)) & (try errors.requireNumber(rhs)), }, .bit_or => EvalValue{ .number = (try errors.requireNumber(lhs)) | (try errors.requireNumber(rhs)), }, .bit_xor => EvalValue{ .number = (try errors.requireNumber(lhs)) ^ (try errors.requireNumber(rhs)), }, .lsl => EvalValue{ .number = @truncate(u16, @bitCast(u64, try errors.requireNumber(lhs))) << @truncate(u4, @bitCast(u64, try errors.requireNumber(rhs))), }, .lsr => EvalValue{ .number = @truncate(u16, @bitCast(u64, try errors.requireNumber(lhs))) >> @truncate(u4, @bitCast(u64, try errors.requireNumber(rhs))), }, .asr => asr_res: { const lhs_n = try errors.truncateTo(try errors.requireNumber(lhs)); const rhs_n = try errors.truncateTo(try errors.requireNumber(rhs)); const bits = @truncate(u4, rhs_n); const shifted = (lhs_n >> bits); if (lhs_n >= 0x8000) { const mask_mask: u16 = @as(u16, 0xFFFF) >> bits; const mask: u16 = @as(u16, 0xFFFF) & ~mask_mask; break :asr_res EvalValue{ .number = shifted | mask, }; } break :asr_res EvalValue{ .number = shifted, }; // } else { // break :asr_res (lhs_n >> bits); // } }, }; }, .unary_op => |op| blk: { const value = try errors.requireNumber(try self.evaluateRecursive(context, errors, op.value)); break :blk switch (op.operator) { .bit_invert => EvalValue{ .number = ~value, }, .negate => EvalValue{ .number = 0 -% value, }, }; }, .fn_call => |fun| { const argv = try context.allocator.alloc(Value, fun.arguments.len); defer context.allocator.free(argv); for (fun.arguments) |*src_node, i| { argv[i] = try self.evaluateRecursive(context, errors, src_node); } inline for (std.meta.declarations(Assembler.Functions)) |decl| { if (std.mem.eql(u8, fun.function, decl.name)) { const result: Assembler.FunctionCallError!Value = @field(Assembler.Functions, decl.name)(context, argv); if (result) |val| { return val; } else |err| { return errors.emit(err, null, "Failed to invoke the function {s}: {s}", .{ fun, @errorName(err) }); } } } return errors.emit(error.UnknownFunction, null, "The function {s} does not exist!", .{fun}); }, }; } pub fn format(value: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, stream: anytype) !void { _ = fmt; _ = options; for (value.sequence) |item, i| { if (i > 0) try stream.writeAll(" "); try stream.writeAll(item.text); } } }; const Modifiers = struct { const Self = @This(); condition: ?spu.ExecutionCondition = null, input0: ?spu.InputBehaviour = null, input1: ?spu.InputBehaviour = null, modify_flags: ?bool = null, output: ?spu.OutputBehaviour = null, command: ?spu.Command = null, /// will start at identifier, not `[`! fn parse(mods: *Self, assembler: *Assembler, parser: *Parser) !void { const mod_type = try parser.expect(.label); // type + ':' const mod_value = try parser.expect(.identifier); // value _ = try parser.expect(.closing_brackets); if (std.mem.eql(u8, mod_type.text, "ex:")) { if (mods.condition != null) return error.DuplicateModifier; inline for (condition_items) |item| { if (std.mem.eql(u8, item[0], mod_value.text)) { mods.condition = item[1]; return; } } } else if (std.mem.eql(u8, mod_type.text, "i0:")) { if (mods.input0 != null) return error.DuplicateModifier; inline for (input_items) |item| { if (std.mem.eql(u8, item[0], mod_value.text)) { mods.input0 = item[1]; return; } } } else if (std.mem.eql(u8, mod_type.text, "i1:")) { if (mods.input1 != null) return error.DuplicateModifier; inline for (input_items) |item| { if (std.mem.eql(u8, item[0], mod_value.text)) { mods.input1 = item[1]; return; } } } else if (std.mem.eql(u8, mod_type.text, "f:")) { if (mods.modify_flags != null) return error.DuplicateModifier; inline for (flag_items) |item| { if (std.mem.eql(u8, item[0], mod_value.text)) { mods.modify_flags = item[1]; return; } } } else if (std.mem.eql(u8, mod_type.text, "out:")) { if (mods.output != null) return error.DuplicateModifier; inline for (output_items) |item| { if (std.mem.eql(u8, item[0], mod_value.text)) { mods.output = item[1]; return; } } } else if (std.mem.eql(u8, mod_type.text, "cmd:")) { if (mods.command != null) return error.DuplicateModifier; inline for (command_items) |item| { if (std.mem.eql(u8, item[0], mod_value.text)) { mods.command = item[1]; return; } } } try assembler.emitError(.@"error", mod_type.location, "Unknown modifier: {s}{s}", .{ mod_type.text, mod_value.text }); } const condition_items = .{ .{ "always", .always }, .{ "zero", .when_zero }, .{ "nonzero", .not_zero }, .{ "greater", .greater_zero }, .{ "less", .less_than_zero }, .{ "gequal", .greater_or_equal_zero }, .{ "lequal", .less_or_equal_zero }, .{ "ovfl", .overflow }, }; const flag_items = .{ .{ "no", false }, .{ "yes", true }, }; const input_items = .{ .{ "zero", .zero }, .{ "immediate", .immediate }, .{ "peek", .peek }, .{ "pop", .pop }, .{ "arg", .immediate }, .{ "imm", .immediate }, }; const output_items = .{ .{ "discard", .discard }, .{ "push", .push }, }; const command_items = .{ .{ "copy", .copy }, .{ "get", .get }, .{ "set", .set }, .{ "store8", .store8 }, .{ "store16", .store16 }, .{ "load8", .load8 }, .{ "load16", .load16 }, .{ "frget", .frget }, .{ "frset", .frset }, .{ "bpget", .bpget }, .{ "bpset", .bpset }, .{ "spget", .spget }, .{ "spset", .spset }, .{ "add", .add }, .{ "sub", .sub }, .{ "mul", .mul }, .{ "div", .div }, .{ "mod", .mod }, .{ "and", .@"and" }, .{ "or", .@"or" }, .{ "xor", .xor }, .{ "not", .not }, .{ "signext", .signext }, .{ "rol", .rol }, .{ "ror", .ror }, .{ "bswap", .bswap }, .{ "asr", .asr }, .{ "lsl", .lsl }, .{ "lsr", .lsr }, .{ "setip", .setip }, .{ "addip", .addip }, .{ "intr", .intr }, }; }; test { _ = main; } const TestSectionDesc = struct { load_offset: u16, phys_offset: u32, contents: []const u8, fn initZeroOffset(content: []const u8) TestSectionDesc { return .{ .load_offset = 0, .phys_offset = 0, .contents = content, }; } fn initOffset(offset: u16, content: []const u8) TestSectionDesc { return .{ .load_offset = offset, .phys_offset = offset, .contents = content, }; } }; fn testCodeGenerationGeneratesOutput(expected: []const TestSectionDesc, comptime source: []const u8) !void { var as = try Assembler.init(std.testing.allocator); defer as.deinit(); { var source_cpy = source[0..source.len].*; var stream = std.io.fixedBufferStream(source); try as.assemble("memory", std.fs.cwd(), stream.reader()); // destroy all evidence std.mem.set(u8, &source_cpy, 0x55); try as.finalize(); } for (as.errors.items) |err| { std.log.err("compile error: {}", .{err}); } try std.testing.expectEqual(@as(usize, 0), as.errors.items.len); var section = as.sections.first; for (expected) |output| { try std.testing.expect(section != null); try std.testing.expectEqual(output.load_offset, section.?.data.load_offset); try std.testing.expectEqual(output.phys_offset, section.?.data.phys_offset); try std.testing.expectEqualSlices(u8, output.contents, section.?.data.bytes.items); section = section.?.next; } } fn testCodeGenerationEqual(expected: []const u8, comptime source: []const u8) !void { try testCodeGenerationGeneratesOutput(&[_]TestSectionDesc{TestSectionDesc.initZeroOffset(expected)}, source); } test "empty file" { try testCodeGenerationGeneratesOutput(&[_]TestSectionDesc{TestSectionDesc.initZeroOffset("")}, ""); } test "section deduplication" { try testCodeGenerationGeneratesOutput(&[_]TestSectionDesc{TestSectionDesc.initOffset(0x8000, "hello")}, \\.org 0x0000 \\.org 0x8000 \\.ascii "hello" ); } test "section physical offset setup" { try testCodeGenerationGeneratesOutput(&[_]TestSectionDesc{ .{ .load_offset = 0x0000, .phys_offset = 0x8000, .contents = "hello", }, .{ .load_offset = 0x2000, .phys_offset = 0x10_0000, .contents = "bye", }, }, \\.org 0x0000, 0x8000 \\.ascii "hello" \\.org 0x2000, 0x100000 \\.ascii "bye" ); } test "emit raw word" { try testCodeGenerationEqual(&[_]u8{ 0x34, 0x12, 0x78, 0x56, 0xBC, 0x9A }, \\.dw 0x1234 \\.dw 0x5678, 0x9ABC ); } test "emit raw byte" { try testCodeGenerationEqual(&[_]u8{ 0x12, 0x34, 0x56, 0x78 }, \\.db 0x12 \\.db 0x34, 0x56, 0x78 ); } fn testExpressionEvaluation(expected: u16, comptime source: []const u8) !void { var buf: [2]u8 = undefined; std.mem.writeIntLittle(u16, &buf, expected); return try testCodeGenerationEqual(&buf, source); } test "parsing integer literals" { try testExpressionEvaluation(100, \\.dw 100 ; decimal ); try testExpressionEvaluation(0b100, \\.dw 0b100 ; binary ); try testExpressionEvaluation(0o100, \\.dw 0o100 ; octal ); try testExpressionEvaluation(0x100, \\.dw 0x100 ; hexadecimal ); } test "basic (non-nested) basic arithmetic" { try testExpressionEvaluation(30, \\.dw 20+10 ); try testExpressionEvaluation(10, \\.dw 20-10 ); try testExpressionEvaluation(200, \\.dw 20*10 ); try testExpressionEvaluation(2, \\.dw 20/10 ); } test "basic (non-nested) bitwise arithmetic" { try testExpressionEvaluation(3, \\.dw 7&3 ); try testExpressionEvaluation(12, \\.dw 8|12 ); try testExpressionEvaluation(4, \\.dw 13^9 ); } test "basic (non-nested) shift arithmetic" { try testExpressionEvaluation(256, \\.dw 16<<4 ); try testExpressionEvaluation(4, \\.dw 16>>2 ); try testExpressionEvaluation(0xFFFF, \\.dw 0x8000>>>15 ); try testExpressionEvaluation(0x0000, \\.dw 0x7FFF>>>15 ); } test "basic unary operators" { try testExpressionEvaluation(0x00FF, \\.dw ~0xFF00 ); try testExpressionEvaluation(65526, \\.dw -10 ); } test "operator precedence" { try testExpressionEvaluation(610, \\.dw 10+20*30 ); try testExpressionEvaluation(900, \\.dw (10+20)*30 ); } test "backward references" { try testExpressionEvaluation(0, \\backward: \\.dw backward ); } test "forward references" { try testExpressionEvaluation(2, \\.dw forward \\forward: ); } test "basic string generation" { try testCodeGenerationEqual("abc", \\.db 'a', 'b' \\.db 'c' ); try testCodeGenerationEqual("abc", \\.ascii "abc" ); try testCodeGenerationEqual("abc", \\.ascii "ab" \\.ascii "c" ); try testCodeGenerationEqual("abc", \\.ascii "abc" ); try testCodeGenerationEqual("ab\x00c\x00", \\.asciiz "ab" \\.asciiz "c" ); } test "string escaping" { try testCodeGenerationEqual(&[_]u8{ 0x07, 0x08, 0x1B, 0x0A, 0x0D, 0x0B, 0x5C, 0x27, 0x22, 0x12, 0xFF, 0x00 }, \\.db '\a', '\b', '\e', '\n', '\r', '\t', '\\', '\'', '\"', '\x12', '\xFF', '\x00' ); try testCodeGenerationEqual(&[_]u8{ 0x07, 0x08, 0x1B, 0x0A, 0x0D, 0x0B, 0x5C, 0x27, 0x22, 0x12, 0xFF, 0x00 }, \\.ascii "\a\b\e\n\r\t\\\'\"\x12\xFF\x00" ); } test ".equ" { try testExpressionEvaluation(42, \\.equ constant, 40 \\.equ forward, constant \\.equ result, forward + 2 \\.dw result ); } test ".equ with big numbers" { try testExpressionEvaluation(1, \\.equ big_a, 0x1000000000 \\.equ big_b, 0x0FFFFFFFFF \\.dw big_a - big_b ); } test ".space" { try testCodeGenerationEqual(&[_]u8{ 1, 0, 0, 0, 2 }, \\.db 1 \\.space 3 \\.db 2 ); } test ".incbin" { try testCodeGenerationEqual(".ascii \"include\"", \\.incbin "test/include.inc" ); } test ".include" { try testCodeGenerationEqual("[include]", \\.db '[' \\.include "test/include.inc" \\.db ']' ); } fn testInstructionGeneration(expected: Instruction, operands: []const u16, comptime source: []const u8) !void { var buf: [6]u8 = undefined; std.mem.copy(u8, buf[0..2], std.mem.asBytes(&expected)); for (operands) |o, i| { std.mem.writeIntLittle(u16, buf[2 * (i + 1) ..][0..2], o); } const slice = buf[0 .. 2 * operands.len + 2]; try testCodeGenerationEqual(slice, source); } test "nop generation" { try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy, }, &[_]u16{}, \\nop , ); } test "[ex:] modifier application" { try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [ex:always] , ); try testInstructionGeneration( Instruction{ .condition = .when_zero, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [ex:zero] , ); try testInstructionGeneration( Instruction{ .condition = .not_zero, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [ex:nonzero] , ); try testInstructionGeneration( Instruction{ .condition = .greater_zero, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [ex:greater] , ); try testInstructionGeneration( Instruction{ .condition = .less_than_zero, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [ex:less] , ); try testInstructionGeneration( Instruction{ .condition = .greater_or_equal_zero, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [ex:gequal] , ); try testInstructionGeneration( Instruction{ .condition = .less_or_equal_zero, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [ex:lequal] , ); try testInstructionGeneration( Instruction{ .condition = .overflow, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [ex:ovfl] , ); } test "[f:] modifier application" { try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [f:no] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .zero, .modify_flags = true, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [f:yes] , ); } test "[i0:] modifier application" { try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i0:zero] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .immediate, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i0:immediate] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .peek, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i0:peek] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .pop, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i0:pop] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .immediate, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i0:arg] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .immediate, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i0:imm] , ); } test "[i1:] modifier application" { try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i1:zero] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .immediate, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i1:immediate] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .peek, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i1:peek] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .pop, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i1:pop] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .immediate, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i1:arg] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .immediate, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [i1:imm] , ); } test "[out:] modifier application" { try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = .copy }, &[_]u16{}, \\nop [out:discard] , ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .push, .command = .copy }, &[_]u16{}, \\nop [out:push] , ); } test "[cmd:] modifier application" { inline for (Modifiers.command_items) |cmd| { try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .zero, .input1 = .zero, .modify_flags = false, .output = .discard, .command = cmd[1] }, &[_]u16{}, "nop [cmd:" ++ cmd[0] ++ "]", ); } } test "input count selection" { try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .pop, .input1 = .pop, .command = .store16, .output = .discard, .modify_flags = false }, &[_]u16{}, "st", ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .pop, .input1 = .immediate, .command = .store16, .output = .discard, .modify_flags = false }, &[_]u16{0x1234}, "st 0x1234", ); try testInstructionGeneration( Instruction{ .condition = .always, .input0 = .immediate, .input1 = .immediate, .command = .store16, .output = .discard, .modify_flags = false }, &[_]u16{ 0x1234, 0x4567 }, "st 0x1234, 0x4567", ); } test "function 'substr'" { try testCodeGenerationEqual("ll", \\.ascii substr("hello", 2, 2) ); try testCodeGenerationEqual("o", \\.ascii substr("hello", 4, 100) ); try testCodeGenerationEqual("", \\.ascii substr("hello", 5, 1) ); try testCodeGenerationEqual("", \\.ascii substr("hello", 1000, 1000) ); try testCodeGenerationEqual("llo", \\.ascii substr("hello", 2) ); try testCodeGenerationEqual("", \\.ascii substr("hello", 7) ); } test "function 'physicalAddress'" { try testCodeGenerationGeneratesOutput(&[_]TestSectionDesc{ .{ .contents = "\x00\x00\x00\x10", .load_offset = 0x0000, .phys_offset = 0x1000 }, }, \\.org 0x0000, 0x1000 \\this: \\.dw 0 \\.dw physicalAddress("this") ); } test "offset address emission" { try testCodeGenerationGeneratesOutput(&[_]TestSectionDesc{ .{ .contents = "\x00\x00\x02\x80", .load_offset = 0x8000, .phys_offset = 0x8000, }, }, \\.org 0x8000 \\.dw 0 \\this: \\.dw this ); }
<reponame>MasterQ32/spu-mark-ii const std = @import("std"); const mnemonics = @import("../assembler/mnemonics.zig"); pub fn main() !void { const stdout = std.io.getStdOut().writer(); var items = mnemonics.mnemonics; std.sort.sort(mnemonics.Mnemonic, &items, {}, lt); try stdout.writeAll("module.exports = [\n"); for (items) |m| { try stdout.print(" {{ name: '{s}', desc: \"{}\", argc: {}, input0: '{s}', input1: '{s}', output: '{s}', command: '{s}', flags: {}, condition: '{s}' }},\n", .{ m.name, std.zig.fmtEscapes(m.info), m.argc, @tagName(m.instruction.input0), @tagName(m.instruction.input1), @tagName(m.instruction.output), @tagName(m.instruction.command), m.instruction.modify_flags, @tagName(m.instruction.condition), }); } try stdout.writeAll("];\n"); } fn lt(_: void, a: mnemonics.Mnemonic, b: mnemonics.Mnemonic) bool { if (std.mem.lessThan(u8, a.name, b.name)) return true; if (a.argc < b.argc) return true; return false; }
<reponame>btashton/pygments<filename>tests/examplefiles/example.zig<gh_stars>100-1000 const std = @import("std"); const Allocator = mem.Allocator; const mem = std.mem; const ast = std.zig.ast; const Visib = @import("visib.zig").Visib; const event = std.event; const Value = @import("value.zig").Value; const Token = std.zig.Token; const errmsg = @import("errmsg.zig"); const Scope = @import("scope.zig").Scope; const Compilation = @import("compilation.zig").Compilation; pub const Decl = struct { id: Id, name: []const u8, visib: Visib, resolution: event.Future(Compilation.BuildError!void), parent_scope: *Scope, // TODO when we destroy the decl, deref the tree scope tree_scope: *Scope.AstTree, pub const Table = std.HashMap([]const u8, *Decl, mem.hash_slice_u8, mem.eql_slice_u8); pub fn cast(base: *Decl, comptime T: type) ?*T { if (base.id != @field(Id, @typeName(T))) return null; return @fieldParentPtr(T, "base", base); } pub fn isExported(base: *const Decl, tree: *ast.Tree) bool { switch (base.id) { Id.Fn => { const fn_decl = @fieldParentPtr(Fn, "base", base); return fn_decl.isExported(tree); }, else => return false, } } pub fn getSpan(base: *const Decl) errmsg.Span { switch (base.id) { Id.Fn => { const fn_decl = @fieldParentPtr(Fn, "base", base); const fn_proto = fn_decl.fn_proto; const start = fn_proto.fn_token; const end = fn_proto.name_token orelse start; return errmsg.Span{ .first = start, .last = end + 1, }; }, else => @panic("TODO"), } } pub fn findRootScope(base: *const Decl) *Scope.Root { return base.parent_scope.findRoot(); } pub const Id = enum { Var, Fn, CompTime, }; pub const Var = struct { base: Decl, }; pub const Fn = struct { base: Decl, value: Val, fn_proto: *ast.Node.FnProto, // TODO https://github.com/ziglang/zig/issues/683 and then make this anonymous pub const Val = union(enum) { Unresolved: void, Fn: *Value.Fn, FnProto: *Value.FnProto, }; pub fn externLibName(self: Fn, tree: *ast.Tree) ?[]const u8 { return if (self.fn_proto.extern_export_inline_token) |tok_index| x: { const token = tree.tokens.at(tok_index); break :x switch (token.id) { Token.Id.Extern => tree.tokenSlicePtr(token), else => null, }; } else null; } pub fn isExported(self: Fn, tree: *ast.Tree) bool { if (self.fn_proto.extern_export_inline_token) |tok_index| { const token = tree.tokens.at(tok_index); return token.id == Token.Id.Keyword_export; } else { return false; } } }; pub const CompTime = struct { base: Decl, }; }; pub const info_zen = \\ \\ * Communicate intent precisely. \\ * Edge cases matter. \\ * Favor reading code over writing code. \\ * Only one obvious way to do things. \\ * Runtime crashes are better than bugs. \\ * Compile errors are better than runtime crashes. \\ * Incremental improvements. \\ * Avoid local maximums. \\ * Reduce the amount one must remember. \\ * Minimize energy spent on coding style. \\ * Together we serve end users. \\ \\ ; fn cmdZen(allocator: *Allocator, args: []const []const u8) !void { try stdout.write(info_zen); } const usage_internal = \\usage: zig internal [subcommand] \\ \\Sub-Commands: \\ build-info Print static compiler build-info \\ \\ ; fn cmdInternal(allocator: *Allocator, args: []const []const u8) !void { if (args.len == 0) { try stderr.write(usage_internal); os.exit(1); } const sub_commands = []Command{Command{ .name = "build-info", .exec = cmdInternalBuildInfo, }}; for (sub_commands) |sub_command| { if (mem.eql(u8, sub_command.name, args[0])) { try sub_command.exec(allocator, args[1..]); return; } } try stderr.print("unknown sub command: {}\n\n", args[0]); try stderr.write(usage_internal); } fn cmdInternalBuildInfo(allocator: *Allocator, args: []const []const u8) !void { try stdout.print( \\ZIG_CMAKE_BINARY_DIR {} \\ZIG_CXX_COMPILER {} \\ZIG_LLVM_CONFIG_EXE {} \\ZIG_LLD_INCLUDE_PATH {} \\ZIG_LLD_LIBRARIES {} \\ZIG_STD_FILES {} \\ZIG_C_HEADER_FILES {} \\ZIG_DIA_GUIDS_LIB {} \\ , std.cstr.toSliceConst(c.ZIG_CMAKE_BINARY_DIR), std.cstr.toSliceConst(c.ZIG_CXX_COMPILER), std.cstr.toSliceConst(c.ZIG_LLVM_CONFIG_EXE), std.cstr.toSliceConst(c.ZIG_LLD_INCLUDE_PATH), std.cstr.toSliceConst(c.ZIG_LLD_LIBRARIES), std.cstr.toSliceConst(c.ZIG_STD_FILES), std.cstr.toSliceConst(c.ZIG_C_HEADER_FILES), std.cstr.toSliceConst(c.ZIG_DIA_GUIDS_LIB), ); } fn test__floatuntisf(a: u128, expected: f32) void { const x = __floatuntisf(a); testing.expect(x == expected); } test "floatuntisf" { test__floatuntisf(0, 0.0); test__floatuntisf(1, 1.0); test__floatuntisf(2, 2.0); test__floatuntisf(20, 20.0); test__floatuntisf(0x7FFFFF8000000000, 0x1.FFFFFEp+62); test__floatuntisf(0x7FFFFF0000000000, 0x1.FFFFFCp+62); test__floatuntisf(make_ti(0x8000008000000000, 0), 0x1.000001p+127); test__floatuntisf(make_ti(0x8000000000000800, 0), 0x1.0p+127); test__floatuntisf(make_ti(0x8000010000000000, 0), 0x1.000002p+127); test__floatuntisf(make_ti(0x8000000000000000, 0), 0x1.000000p+127); test__floatuntisf(0x0007FB72E8000000, 0x1.FEDCBAp+50); test__floatuntisf(0x0007FB72EA000000, 0x1.FEDCBA8p+50); test__floatuntisf(0x0007FB72EB000000, 0x1.FEDCBACp+50); test__floatuntisf(0x0007FB72EC000000, 0x1.FEDCBBp+50); test__floatuntisf(0x0007FB72E6000000, 0x1.FEDCB98p+50); test__floatuntisf(0x0007FB72E7000000, 0x1.FEDCB9Cp+50); test__floatuntisf(0x0007FB72E4000000, 0x1.FEDCB9p+50); test__floatuntisf(0xFFFFFFFFFFFFFFFE, 0x1p+64); test__floatuntisf(0xFFFFFFFFFFFFFFFF, 0x1p+64); test__floatuntisf(0x0007FB72E8000000, 0x1.FEDCBAp+50); test__floatuntisf(0x0007FB72EA000000, 0x1.FEDCBAp+50); test__floatuntisf(0x0007FB72EB000000, 0x1.FEDCBAp+50); test__floatuntisf(0x0007FB72EBFFFFFF, 0x1.FEDCBAp+50); test__floatuntisf(0x0007FB72EC000000, 0x1.FEDCBCp+50); test__floatuntisf(0x0007FB72E8000001, 0x1.FEDCBAp+50); test__floatuntisf(0x0007FB72E6000000, 0x1.FEDCBAp+50); test__floatuntisf(0x0007FB72E7000000, 0x1.FEDCBAp+50); test__floatuntisf(0x0007FB72E7FFFFFF, 0x1.FEDCBAp+50); test__floatuntisf(0x0007FB72E4000001, 0x1.FEDCBAp+50); test__floatuntisf(0x0007FB72E4000000, 0x1.FEDCB8p+50); test__floatuntisf(make_ti(0x0000000000001FED, 0xCB90000000000001), 0x1.FEDCBAp+76); test__floatuntisf(make_ti(0x0000000000001FED, 0xCBA0000000000000), 0x1.FEDCBAp+76); test__floatuntisf(make_ti(0x0000000000001FED, 0xCBAFFFFFFFFFFFFF), 0x1.FEDCBAp+76); test__floatuntisf(make_ti(0x0000000000001FED, 0xCBB0000000000000), 0x1.FEDCBCp+76); test__floatuntisf(make_ti(0x0000000000001FED, 0xCBB0000000000001), 0x1.FEDCBCp+76); test__floatuntisf(make_ti(0x0000000000001FED, 0xCBBFFFFFFFFFFFFF), 0x1.FEDCBCp+76); test__floatuntisf(make_ti(0x0000000000001FED, 0xCBC0000000000000), 0x1.FEDCBCp+76); test__floatuntisf(make_ti(0x0000000000001FED, 0xCBC0000000000001), 0x1.FEDCBCp+76); test__floatuntisf(make_ti(0x0000000000001FED, 0xCBD0000000000000), 0x1.FEDCBCp+76); test__floatuntisf(make_ti(0x0000000000001FED, 0xCBD0000000000001), 0x1.FEDCBEp+76); test__floatuntisf(make_ti(0x0000000000001FED, 0xCBDFFFFFFFFFFFFF), 0x1.FEDCBEp+76); test__floatuntisf(make_ti(0x0000000000001FED, 0xCBE0000000000000), 0x1.FEDCBEp+76); } fn trimStart(slice: []const u8, ch: u8) []const u8 { var i: usize = 0; const test_string = "test\"string"; for (slice) |b| { if (b == '\xa3') break; if (b == '\ua3d3') break; if (b == '\Ua3d3d3') break; if (b == '\t') break; if (b == '\n') break; if (b == '\\') break; if (b == '\'') break; if (b == '"') break; if (b != 'n') break; if (b != '-') break; i += 1; } return slice[i..]; }
<reponame>MasterQ32/spu-mark-ii const std = @import("std"); const argsParser = @import("args"); const ihex = @import("ihex"); extern fn configure_serial(fd: c_int) u8; extern fn flush_serial(fd: c_int) void; pub fn main() anyerror!u8 { const cli_args = argsParser.parseForCurrentProcess(struct { // This declares long options for double hyphen output: ?[]const u8 = null, help: bool = false, size: ?usize = null, // This declares short-hand options for single hyphen pub const shorthands = .{ .o = "output", .h = "help", .s = "size", }; }, std.heap.page_allocator, .print) catch return 1; defer cli_args.deinit(); const stdout = std.io.getStdOut().writer(); // const stdin = std.io.getStdOut().reader(); if (cli_args.options.help or cli_args.positionals.len == 0 or cli_args.options.output == null) { try stdout.writeAll( \\ hex2bin [-h] [-o outfile] infile.hex [infile.hex …] \\ -h, --help Outputs this help text \\ -o, --output Defines the name of the output file, required \\ -s, --size If given, the file will have this size in bytes, \\ otherwise the size will be determined automatically. \\ \\ Combines one or more intel hex files into a binary file. \\ The output file will have all bytes set to zero for all bytes \\ not contained in the hex files. \\ ); return if (cli_args.options.help) @as(u8, 0) else 1; // when we explicitly call help, we succeed } const outfile = try std.fs.cwd().createFile(cli_args.options.output.?, .{ .truncate = true, .read = true }); defer outfile.close(); const HexParser = struct { const Self = @This(); const Error = error{InvalidHexFile} || std.os.WriteError || std.os.SeekError; file: *const std.fs.File, fn load(p: *const Self, base: u32, data: []const u8) Error!void { try p.file.seekTo(base); try p.file.writeAll(data); } }; const parseMode = ihex.ParseMode{ .pedantic = true, }; const parser = HexParser{ .file = &outfile, }; for (cli_args.positionals) |file_name| { var infile = try std.fs.cwd().openFile(file_name, .{ .read = true, .write = false }); defer infile.close(); _ = try ihex.parseData(infile.reader(), parseMode, &parser, HexParser.Error, HexParser.load); } return 0; }
<filename>mt9x9.zig // 9x9 multiplication table in Zig // CC0, <NAME> <<EMAIL>>, 2021. // zig build-exe mt9x9.zig && ./mt9x9 || zig run mt9x9.zig const std = @import("std"); pub fn main() !void { var i: u8 = 1; while (i < 10) : (i += 3) { var j: u8 = 1; while (j < 10) : (j += 1) { for ([_]u8{i, i+1, i+2}) |k| { std.debug.print("{d}x{d}={d: >2}\t", .{k, j, k*j}); } std.debug.print("\n", .{}); } std.debug.print("\n", .{}); } }
const std = @import("std"); pub const DebugInterface = struct { const Self = @This(); pub const TraceError = error{DebugBreak}; traceInstructionFn: fn (self: *Self, ip: u16, instruction: Instruction, input0: u16, input1: u16, output: u16) void, traceAddressFn: fn (self: *Self, virt: u16) TraceError!void, /// Traces a address to the debugger. If a breakpoint is set there, /// it must return `error.DebugBreak`. pub fn traceAddress(self: *Self, virt: u16) TraceError!void { return self.traceAddressFn(self, virt); } /// Traces a successfully executed instructions. pub fn traceInstruction(self: *Self, ip: u16, instruction: Instruction, input0: u16, input1: u16, output: u16) void { self.traceInstructionFn(self, ip, instruction, input0, input1, output); } }; pub const Interrupt = enum(u3) { reset, nmi, bus, unused_3, arith, software, reserved, irq, }; pub fn SpuMk2(comptime MemoryInterface: type) type { return struct { const Self = @This(); memory: MemoryInterface, debug_interface: ?*DebugInterface, ip: u16, bp: u16, fr: FlagRegister, sp: u16, ir: u16, pub fn init(memory: MemoryInterface) Self { return Self{ .memory = memory, .debug_interface = null, .ip = 0x0000, .fr = std.mem.zeroes(FlagRegister), .bp = undefined, .sp = undefined, .ir = 0x0001, // reset on start }; } pub fn reset(self: *Self) void { self.ip = 0x0000; self.fr = std.mem.zeroes(FlagRegister); self.bp = undefined; self.sp = undefined; self.ir = 0x0001; // reset on start } pub fn triggerInterrupt(self: *Self, intr: Interrupt) void { self.ir |= @as(u16, 1) << @enumToInt(intr); } pub fn readByte(self: *Self, address: u16) !u8 { return self.memory.read8(address); } pub fn writeByte(self: *Self, address: u16, value: u8) !void { return self.memory.write8(address, value); } pub fn readWord(self: *Self, address: u16) !u16 { if ((address & 1) != 0) return error.UnalignedAccess; return self.memory.read16(address); } pub fn writeWord(self: *Self, address: u16, value: u16) !void { if ((address & 1) != 0) return error.UnalignedAccess; return self.memory.write16(address, value); } pub fn fetch(self: *Self) !u16 { const value = try self.readWord(self.ip); self.ip +%= 2; return value; } pub fn peek(self: *Self) !u16 { return try self.readWord(self.sp); } pub fn pop(self: *Self) !u16 { const value = try self.readWord(self.sp); self.sp +%= 2; return value; } pub fn push(self: *Self, value: u16) !void { self.sp -%= 2; try self.writeWord(self.sp, value); } pub fn executeSingle(self: *Self) !void { if (self.debug_interface) |debug| { try debug.traceAddress(self.ip); } { comptime var i = 7; inline while (i >= 0) : (i -= 1) { const mask: u16 = (1 << i); if ((self.ir & mask) != 0) { if (i < 4 or (self.fr.int & mask) != 0) { self.ir &= ~mask; // mask interrupt if (i >= 4) { self.fr.int &= ~mask; } const ip = try self.readWord(2 * i); // RESET is a special case! if (i != 0) { try self.push(if (i < 4) 0 else mask); try self.push(self.ip); } else { self.fr = std.mem.zeroes(FlagRegister); } self.ip = ip; // std.debug.print("Interrupt {} was triggered, jump to 0x{X:0>4}, FR={b:0>8}, IR={b:0>8}\n", .{ // i, // ip, // self.fr.int, // self.ir, // }); } } } } const start_ip = self.ip; const instruction = @bitCast(Instruction, try self.fetch()); if (instruction.reserved == 1) { switch (@bitCast(u16, instruction)) { // 0x8000 => self.trace_enabled = false, // 0x8001 => self.trace_enabled = true, // 0x8002 => try @import("root").dumpState(self), else => return error.BadInstruction, } return; } const execute = switch (instruction.condition) { .always => true, .when_zero => self.fr.bits.zero, .not_zero => !self.fr.bits.zero, .greater_zero => !self.fr.bits.zero and !self.fr.bits.negative, .less_than_zero => !self.fr.bits.zero and self.fr.bits.negative, .greater_or_equal_zero => self.fr.bits.zero or !self.fr.bits.negative, .less_or_equal_zero => self.fr.bits.zero or self.fr.bits.negative, .overflow => self.fr.bits.carry, }; if (execute) { const input0 = switch (instruction.input0) { .zero => @as(u16, 0), .immediate => try self.fetch(), .peek => try self.peek(), .pop => try self.pop(), }; const input1 = switch (instruction.input1) { .zero => @as(u16, 0), .immediate => try self.fetch(), .peek => try self.peek(), .pop => try self.pop(), }; const output = switch (instruction.command) { .copy => input0, .get => try self.readWord(self.bp +% 2 *% input0), .set => blk: { try self.writeWord(self.bp +% 2 *% input0, input1); break :blk input1; }, .store8 => blk: { const val = @truncate(u8, input0); try self.writeByte(input1, val); break :blk val; }, .store16 => blk: { try self.writeWord(input1, input0); break :blk input1; }, .load8 => try self.readByte(input0), .load16 => try self.readWord(input0), .frget => self.fr.int & ~input1, .frset => blk: { const previous = self.fr.int; self.fr.int = (self.fr.int & input1) | (input0 & ~input1); break :blk previous; }, .bpget => self.bp, .bpset => blk: { self.bp = input0; break :blk self.bp; }, .spget => self.sp, .spset => blk: { self.sp = input0; break :blk self.sp; }, .add => blk: { var result: u16 = undefined; self.fr.bits.carry = @addWithOverflow(u16, input0, input1, &result); break :blk result; }, .sub => blk: { var result: u16 = undefined; self.fr.bits.carry = @subWithOverflow(u16, input0, input1, &result); break :blk result; }, .mul => blk: { var result: u16 = undefined; self.fr.bits.carry = @mulWithOverflow(u16, input0, input1, &result); break :blk result; }, .div => input0 / input1, .mod => input0 % input1, .@"and" => input0 & input1, .@"or" => input0 | input1, .xor => input0 ^ input1, .not => ~input0, .signext => if ((input0 & 0x80) != 0) (input0 & 0xFF) | 0xFF00 else (input0 & 0xFF), .rol => (input0 << 1) | (input0 >> 15), .ror => (input0 >> 1) | (input0 << 15), .bswap => (input0 << 8) | (input0 >> 8), .asr => (input0 & 0x8000) | (input0 >> 1), .lsl => input0 << 1, .lsr => input0 >> 1, .cpuid => 0, .halt => switch (input1) { 0xDEAD => return error.DebugBreak, // "hidden" control else => return error.CpuHalted, }, .setip => blk: { const out = self.ip; self.ip = input0; self.fr.int |= input1; break :blk out; }, .addip => blk: { const out = self.ip; self.ip += input0; self.fr.int |= input1; break :blk out; }, .intr => blk: { self.ir |= input0; break :blk input0; }, _ => return error.BadInstruction, }; switch (instruction.output) { .discard => {}, .push => try self.push(output), } if (instruction.modify_flags) { self.fr.bits.negative = (output & 0x8000) != 0; self.fr.bits.zero = (output == 0x0000); } if (self.debug_interface) |intf| { intf.traceInstruction(start_ip, instruction, input0, input1, output); } } else { if (instruction.input0 == .immediate) self.ip +%= 2; if (instruction.input1 == .immediate) self.ip +%= 2; } } pub fn runBatch(self: *Self, count: u64) !void { var i: u64 = count; while (i > 0) { i -= 1; try self.executeSingle(); } } }; } pub const ExecutionCondition = enum(u3) { always = 0, when_zero = 1, not_zero = 2, greater_zero = 3, less_than_zero = 4, greater_or_equal_zero = 5, less_or_equal_zero = 6, overflow = 7, }; pub const InputBehaviour = enum(u2) { zero = 0, immediate = 1, peek = 2, pop = 3, }; pub const OutputBehaviour = enum(u1) { discard = 0, push = 1, }; pub const Command = enum(u6) { copy = 0b000000, get = 0b000010, set = 0b000011, store8 = 0b000100, store16 = 0b000101, load8 = 0b000110, load16 = 0b000111, cpuid = 0b001000, halt = 0b001001, frget = 0b001010, frset = 0b001011, bpget = 0b001100, bpset = 0b001101, spget = 0b001110, spset = 0b001111, add = 0b010000, sub = 0b010001, mul = 0b010010, div = 0b010011, mod = 0b010100, @"and" = 0b010101, @"or" = 0b010110, xor = 0b010111, not = 0b011000, signext = 0b011001, rol = 0b011010, ror = 0b011011, bswap = 0b011100, asr = 0b011101, lsl = 0b011110, lsr = 0b011111, setip = 0b100000, addip = 0b100001, intr = 0b100010, _, }; pub const Instruction = packed struct { condition: ExecutionCondition, input0: InputBehaviour, input1: InputBehaviour, modify_flags: bool, output: OutputBehaviour, command: Command, reserved: u1 = 0, pub fn format(instr: Instruction, comptime fmt: []const u8, options: std.fmt.FormatOptions, out: anytype) !void { _ = options; _ = fmt; try out.writeAll(switch (instr.condition) { .always => " ", .when_zero => "== 0", .not_zero => "!= 0", .greater_zero => " > 0", .less_than_zero => " < 0", .greater_or_equal_zero => ">= 0", .less_or_equal_zero => "<= 0", .overflow => "ovfl", }); try out.writeAll(" "); try out.writeAll(switch (instr.input0) { .zero => "zero", .immediate => "imm ", .peek => "peek", .pop => "pop ", }); try out.writeAll(" "); try out.writeAll(switch (instr.input1) { .zero => "zero", .immediate => "imm ", .peek => "peek", .pop => "pop ", }); try out.writeAll(" "); const tag = @tagName(instr.command); var tagstr = [_]u8{' '} ** 9; std.mem.copy(u8, &tagstr, tag); try out.writeAll(&tagstr); try out.writeAll(" "); try out.writeAll(switch (instr.output) { .discard => "discard", .push => "push ", }); try out.writeAll(" "); try out.writeAll(if (instr.modify_flags) "+ flags" else " "); } }; pub const FlagRegister = extern union { int: u16, bits: packed struct { zero: bool, negative: bool, carry: bool, carry_enabled: bool, interrupt0_enabled: bool, interrupt1_enabled: bool, interrupt2_enabled: bool, interrupt3_enabled: bool, reserved: u8 = 0, }, };
const std = @import("std"); const lpc = @import("lpc1768"); const F_CPU = 100_000_000; comptime { // Provides the initialization routines _ = @import("boot.zig"); } const LED1 = GPIO(1, 18); const LED2 = GPIO(1, 20); const LED3 = GPIO(1, 21); const LED4 = GPIO(1, 23); const SD_SELECT = GPIO(0, 16); // DIP14 const pinConfig = comptime blk: { var cfg = PinConfig{}; cfg.configure(0, 10, .Func01, .PullUp, false); // P28 TXD2 cfg.configure(0, 11, .Func01, .PullUp, false); // P27 RXD2 cfg.configure(0, 16, .Func00, .PullUp, false); // P14 GPIO / SD_SELECT | CH0 | Blue cfg.configure(0, 15, .Func10, .PullUp, false); // P13 SCK | CH1 | Green cfg.configure(0, 17, .Func10, .PullUp, false); // P12 MISO0 | CH2 | Yellow cfg.configure(0, 18, .Func10, .PullUp, false); // P11 MOSI0 | CH3 | Orange break :blk cfg; }; pub fn main() !void { //pinConfig.apply(); LED1.setDirection(.out); LED2.setDirection(.out); LED3.setDirection(.out); LED4.setDirection(.out); // SD_SELECT.setDirection(.out); LED1.clear(); LED2.clear(); LED3.set(); LED4.set(); // SD_SELECT.setTo(.high); while (true) { asm volatile ("wfi"); } // // Enable PLL & serial for debug output // PLL.init(); // Serial.init(115_200); // SPI.init(); // var sync_serial = Serial.syncWriter(); // try sync_serial.writeAll("Serial port initialized.\r\n"); // SysTick.init(1_000); // try sync_serial.writeAll("SysTick initialized.\r\n"); // EventLoop.init(); // try sync_serial.writeAll("Starting event loop...\r\n"); // LED4.set(); // var core_loop = async coreMain(); // var blinky_frame = async doBlinkyLoop(); // EventLoop.run(); // try nosuspend await core_loop; // nosuspend await blinky_frame; // try sync_serial.writeAll("Event loop finished!\r\n"); } fn doBlinkyLoop() void { while (true) { LED1.set(); EventLoop.waitForMillis(250); LED1.clear(); EventLoop.waitForMillis(750); } } fn coreMain() !void { var serin = Serial.reader(); var serout = Serial.writer(); while (true) { var cmd = try serin.readByte(); LED2.set(); switch (std.ascii.toLower(cmd)) { 's' => { SD_SELECT.setTo(.low); try serout.writeAll("select chip\r\n"); }, 'u' => { SD_SELECT.setTo(.high); try serout.writeAll("unselect chip\r\n"); }, 't' => { try serout.writeAll("write test burst...\r\n"); var i: u32 = 0; while (i < 256) : (i += 1) { SPI.write(@truncate(u8, i)); } try serout.writeAll("done!\r\n"); }, 'i' => { try serout.writeAll("initialize sd card...\r\n"); if (SDCard.get()) |maybe_card| { try serout.print("found card: {}\r\n", .{maybe_card}); if (maybe_card) |card| { try serout.print(" status: {}\r\n", .{ try card.getStatus(), }); const T = struct { var boot_block: [512]u8 = undefined; }; try card.readBlock(0, &T.boot_block); try serout.writeAll(" boot block:\r\n"); var offset: usize = 0; while (offset < T.boot_block.len) : (offset += 32) { const line = T.boot_block[offset..][0..32]; try serout.print(" {} |", .{std.fmt.fmtSliceHexUpper(line)}); for (line) |c| { if (c >= 0x20 and c < 0x7F) { try serout.print("{c}", .{c}); } else { try serout.writeAll("."); } } try serout.writeAll("|\r\n"); } } } else |err| { try serout.print("could not detect card: {}\r\n", .{err}); } }, else => try serout.print("Unknown command '{c}'\r\n", .{cmd}), } LED2.clear(); } } const SDCard = struct { const Self = @This(); const Type = enum { mmc, sd1, sd2, sdhc, }; type: Type, fn range(comptime size: usize) [size]void { return [_]void{{}} ** size; } fn get() !?Self { assertCard(); for (range(10)) |_| _ = readRawByte(); deassertCard(); for (range(10)) |_| { cmdGoIdleState() catch |err| switch (err) { error.NotInitialized => break, else => continue, }; } else return null; // no card present var card = Self{ .type = undefined, }; if (sendInterfaceCondition(.standard_3v3, 0x55)) |supported_voltages| { if (supported_voltages != .standard_3v3) { return error.VoltageMismatch; } card.type = .sd2; const ocr = try readOcr(); if ((ocr & ((1 << 20) | (1 << 21))) == 0) { return error.VoltageMismatch; } } else |err| { if (err != error.IllegalCommand) return err; card.type = .sd1; } if (card.type == .sd2) { for (range(10)) |_| { const r1 = try sdSendOpCond(true); r1.throw() catch continue; break; } else return error.Timeout; const ocr2 = try readOcr(); if ((ocr2 & 0x4000_0000) != 0) { card.type = .sdhc; } } else { if (sdSendOpCond(false)) |_| { // Success card.type = .sd1; } else |_| { try sendOpCond(false); card.type = .mmc; } } // try setBlockLength(512); return card; } pub fn getStatus(self: Self) !R2Response { return try sendStatus(); } pub fn readBlock(self: Self, block_index: u32, buffer: *[512]u8) !void { defer deassertCard(); const index = if (self.type == .sdhc) block_index else 512 * block_index; const r1 = try writeR1Command(.CMD17, index, false); try r1.throw(); for (range(0xFF)) |_| { const start_token = readRawByte(); if (start_token == 0xFE) break; } else return error.Timeout; for (buffer) |*b| { b.* = readRawByte(); } var crc16_buf: [2]u8 = undefined; crc16_buf[0] = readRawByte(); crc16_buf[1] = readRawByte(); // TODO: Verify CRC16 } const Command = enum(u6) { CMD0 = 0, // R1 GO_IDLE_STATE CMD1 = 1, // R1 SEND_OP_COND CMD5 = 5, // R1 ?? CMD6 = 6, // R1 SWITCH_FUNC CMD8 = 8, // R7 SEND_IF_COND CMD9 = 9, // R1 SEND_CSD CMD10 = 10, // R1 SEND_CID CMD12 = 12, // R1b STOP_TRANSMISSION CMD13 = 13, // R2 SEND_STATUS CMD16 = 16, // R1 SET_BLOCKLEN CMD17 = 17, // R1 READ_SINGLE_BLOCK CMD18 = 18, // R1 READ_MULTIPLE_BLOCK CMD24 = 24, // R1 WRITE_BLOCK CMD25 = 25, // R1 WRITE_MULTIPLE_BLOCK CMD27 = 27, // R1 PROGRAM_CSD CMD28 = 28, // R1b SET_WRITE_PROT CMD29 = 29, // R1b CLR_WRITE_PRO CMD30 = 30, // R1 SEND_WRITE_PROT CMD32 = 32, // R1 ERASE_WR_BL_START_ADDR CMD33 = 33, // R1 ERASE_WR_BLK_END_ADDR CMD34 = 34, // ?? CMD35 = 35, // ?? CMD36 = 36, // ?? CMD37 = 37, // ?? CMD38 = 38, // R1b ERASE CMD42 = 42, // R1 LOCK_UNLOCK CMD50 = 50, // ?? CMD52 = 52, // ?? CMD53 = 53, // ?? CMD55 = 55, // R1 APP_CMD CMD56 = 56, // R1 GEN_CMD CMD57 = 57, // ?? CMD58 = 58, // R3 READ_OCR CMD59 = 59, // R3 CRC_ON_OFF }; const AppCommand = enum(u6) { ACMD13 = 13, // R2 SD_STATUS ACMD22 = 22, // R1 SEND_NUM_WR_BLOCKS ACMD23 = 23, // R1 SET_WR_BLK_ERASE_COUNT ACMD41 = 41, // R1 SD_SEND_OP_COND ACMD42 = 42, // R1 SET_CLR_CARD_DETECT ACMD51 = 51, // R1 SEND_SCR }; fn cmdGoIdleState() !void { return (try writeR1Command(.CMD0, 0, true)).throw(); } fn sendOpCond(high_capacity_support: bool) !void { const erg = try writeR1Command( .CMD1, if (high_capacity_support) 0x4000_0000 else 0x0000_0000, true, ); return erg.throw(); } fn switchFunc() !void { @panic("switchFunc not implemented yet!"); // try writeR1Command(.CMD6, 0,true); } fn sendCsd() !void { try writeR1Command(.CMD9, 0, true); } fn sendCid() !void { try writeR1Command(.CMD10, 0, true); } fn setBlockLength(block_length: u32) !void { try (try writeR1Command(.CMD16, block_length, true)).throw(); } fn programCsd() !void { try writeR1Command(.CMD27, 0, true); } fn sendWriteProt(address: u32) !void { try writeR1Command(.CMD30, address, true); } fn eraseWrBlStartAddr(address: u32) !void { try writeR1Command(.CMD32, address, true); } fn eraseWrBlkEndAddr(address: u32) !void { try writeR1Command(.CMD33, address, true); } fn lockUnlock() !void { try writeR1Command(.CMD42, 0, true); } fn appCmd() !void { try writeR1Command(.CMD55, 0, true); } fn genCmd(write: bool) !void { try writeR1Command(.CMD56, if (write) 0 else 1, true); } // R1b commands: fn stopTransmission() !void { try writeR1bCommand(.CMD12, 0); } fn setWriteProt(address: u32) !void { try writeR1bCommand(.CMD28, address); } fn clrWritePro(address: u32) !void { try writeR1bCommand(.CMD29, address); } fn erase() !void { try writeR1bCommand(.CMD38, 0); } // R2 commands: fn sendStatus() !R2Response { return try writeR2Command(.CMD13, 0); } // R3 commands: fn readOcr() !u32 { const ocr = try writeR3Command(.CMD58, 0); ocr.r1.throw() catch |err| switch (err) { error.NotInitialized => {}, else => return err, }; return ocr.value; } fn crcOnOff(enabled: bool) !void { const ocr = try writeR3Command(.CMD59, if (enabled) 1 else 0); try ocr.r1.throw(); } // R7 commands: const VoltageRange = enum(u4) { standard_3v3 = 0b0001, low_voltage_range = 0b0010, reserved0 = 0b0100, reserved1 = 0b1000, _, }; fn sendInterfaceCondition(voltage_support: VoltageRange, pattern: u8) !VoltageRange { const arg = (@as(u32, @enumToInt(voltage_support)) << 8) | (@as(u32, pattern)); const response = try writeR7Command(.CMD8, arg); response.r1.throw() catch |err| switch (err) { error.NotInitialized => {}, else => return err, }; if ((response.value & 0xFF) != pattern) return error.PatternMismatch; return @intToEnum(VoltageRange, @truncate(u4, response.value >> 8)); } // app commands: fn sdSendOpCond(high_capacity_support: bool) !ResponseBits { assertCard(); defer deassertCard(); writeRawCommand(Command.CMD55, 0); _ = try readResponseR1(); deassertCard(); _ = readRawByte(); assertCard(); writeRawCommand(AppCommand.ACMD41, @as(u32, if (high_capacity_support) 0x4000_0000 else 0x0000_0000)); return try readResponseR1(); } // raw interface: fn writeR1Command(cmd: Command, arg: u32, deassert: bool) !ResponseBits { assertCard(); defer if (deassert) deassertCard(); writeRawCommand(cmd, arg); return readResponseR1(); } fn writeR1bCommand(cmd: Command, arg: u32) !ResponseBits { assertCard(); defer deassertCard(); writeRawCommand(cmd, arg); return try readResponseR1b(); } fn writeR2Command(cmd: Command, arg: u32) !R2Response { assertCard(); defer deassertCard(); writeRawCommand(cmd, arg); return try readResponseR2(); } fn writeR3Command(cmd: Command, arg: u32) !R3Response { assertCard(); defer deassertCard(); writeRawCommand(cmd, arg); return readResponseR3(); } fn writeR7Command(cmd: Command, arg: u32) !R7Response { assertCard(); defer deassertCard(); writeRawCommand(cmd, arg); return readResponseR7(); } fn assertCard() void { SD_SELECT.setTo(.low); // Give card some time _ = readRawByte(); } fn deassertCard() void { // Give card some time _ = readRawByte(); SD_SELECT.setTo(.high); } // //SD card accepts byte address while SDHC accepts block address in multiples of 512 // //so, if it's SD card we need to convert block address into corresponding byte address by // //multipying it with 512. which is equivalent to shifting it left 9 times // //following 'if' loop does that // const arg = if (self.sdhc) // arg_ro // else switch (cmd) { // .READ_SINGLE_BLOCK, // .READ_MULTIPLE_BLOCKS, // .WRITE_SINGLE_BLOCK, // .WRITE_MULTIPLE_BLOCKS, // .ERASE_BLOCK_START_ADDR, // .ERASE_BLOCK_END_ADDR, // => arg_ro << 9, // else => arg_ro, // }; fn writeRawCommand(cmd: anytype, arg: u32) void { Serial.syncWriter().writeAll(@tagName(cmd)) catch {}; Serial.syncWriter().writeAll("\r\n") catch {}; var msg: [6]u8 = undefined; msg[0] = @enumToInt(cmd) | @as(u8, 0b01000000); std.mem.writeIntBig(u32, msg[1..5], arg); msg[5] = (@as(u8, CRC7.compute(msg[0..5])) << 1) | 1; writeRaw(&msg); } const ResponseBits = packed struct { idle: bool, erase_reset: bool, illegal_command: bool, com_crc_error: bool, erase_sequence_error: bool, address_error: bool, parameter_error: bool, must_be_zero: u1, fn throw(self: @This()) !void { if (self.illegal_command) return error.IllegalCommand; if (self.address_error) return error.AddressError; if (self.com_crc_error) return error.CrcError; if (self.erase_sequence_error) return error.EraseSequenceError; if (self.parameter_error) return error.ParameterError; if (self.idle) return error.NotInitialized; } }; fn readResponseR1() !ResponseBits { for (range(0x10)) |_| { const byte = readRawByte(); if (byte == 0xFF) continue; return @bitCast(ResponseBits, byte); } else return error.Timeout; } fn readResponseR1b() !ResponseBits { for (range(0xFF)) |_| { const byte = readRawByte(); if (byte == 0x00) continue; if (byte == 0xFF) continue; return @bitCast(ResponseBits, byte); } else return error.Timeout; } const R2Response = packed struct { card_is_locked: bool, wp_erase_skip_or_lock_unlock_cmd_failed: bool, @"error": bool, cc_error: bool, card_ecc_failed: bool, wp_violation: bool, erase_param: bool, out_of_range_csd_overwrite: bool, in_idle_state: bool, erase_reset: bool, illegal_command: bool, com_crc_error: bool, erase_sequence_error: bool, address_error: bool, parameter_error: bool, zero: u1 = 0, }; fn readResponseR2() !R2Response { var resp: [2]u8 = undefined; for (range(20)) |_| { resp[0] = readRawByte(); if (resp[0] != 0xFF) break; } else return error.Timeout; resp[1] = readRawByte(); return @bitCast(R2Response, resp); } const R3Response = struct { r1: ResponseBits, value: u32, }; fn readResponseR3() !R3Response { var result: R3Response = undefined; result.r1 = try readResponseR1(); var buf: [4]u8 = undefined; readRaw(&buf); result.value = std.mem.readIntBig(u32, &buf); return result; } const R7Response = struct { r1: ResponseBits, value: u32, }; fn readResponseR7() !R7Response { var result: R7Response = undefined; result.r1 = try readResponseR1(); var resp: [4]u8 = undefined; readRaw(&resp); result.value = std.mem.readIntBig(u32, &resp); return result; } fn writeRaw(buffer: []const u8) void { for (buffer) |b| writeRawByte(b); } fn writeRawByte(val: u8) void { try Serial.syncWriter().print("→ 0x{X:0>2}\r\n", .{val}); _ = SPI.xmit(val); } fn readRawByte() u8 { const res = @intCast(u8, SPI.xmit(0xFF)); try Serial.syncWriter().print("← 0x{X:0>2}\r\n", .{res}); return res; } fn readRaw(buf: []u8) void { for (buf) |*b| b.* = readRawByte(); } }; // Implemented after https://github.com/hazelnusse/crc7/blob/master/crc7.cc const CRC7 = struct { const table = blk: { @setEvalBranchQuota(10_000); var items: [256]u8 = undefined; const poly: u8 = 0x89; // the value of our CRC-7 polynomial // generate a table value for all 256 possible byte values for (items) |*item, i| { item.* = if ((i & 0x80) != 0) i ^ poly else i; var j: usize = 1; while (j < 8) : (j += 1) { item.* <<= 1; if ((item.* & 0x80) != 0) item.* ^= poly; } } break :blk items; }; // adds a message byte to the current CRC-7 to get a the new CRC-7 fn add(crc: u8, message_byte: u8) u8 { return table[(crc << 1) ^ message_byte]; } // returns the CRC-7 for a message of "length" bytes fn compute(message: []const u8) u7 { var crc: u8 = 0; for (message) |byte| { crc = add(crc, byte); } return @intCast(u7, crc); } }; // Three examples from the SD spec test "CRC7" { { var crc = compute(&[_]u8{ 0b01000000, 0x00, 0x00, 0x00, 0x00, }); std.debug.assert(crc == 0b1001010); } { var crc = compute(&[_]u8{ 0b01010001, 0x00, 0x00, 0x00, 0x00, }); std.debug.assert(crc == 0b0101010); } { var crc = compute(&[_]u8{ 0b00010001, 0b00000000, 0b00000000, 0b00001001, 0b00000000, }); std.debug.assert(crc == 0b0110011); } } pub fn panic(message: []const u8, maybe_stack_trace: ?*std.builtin.StackTrace) noreturn { lpc.__disable_irq(); LED1.set(); LED2.set(); LED3.set(); LED4.clear(); var serial = Serial.syncWriter(); serial.print("reached panic: {s}\r\n", .{message}) catch unreachable; if (maybe_stack_trace) |stack_trace| printStackTrace(stack_trace); while (true) { lpc.__disable_irq(); lpc.__disable_fault_irq(); lpc.__WFE(); } } fn printStackTrace(stack_trace: *std.builtin.StackTrace) void { var serial = Serial.syncWriter(); var frame_index: usize = 0; var frames_left: usize = std.math.min(stack_trace.index, stack_trace.instruction_addresses.len); while (frames_left != 0) : ({ frames_left -= 1; frame_index = (frame_index + 1) % stack_trace.instruction_addresses.len; }) { const return_address = stack_trace.instruction_addresses[frame_index]; serial.print("[{d}] 0x{X}\r\n", .{ frames_left, return_address, }) catch unreachable; } } const PinDirection = enum { in, out }; fn GPIO(comptime portIndex: u32, comptime index: u32) type { return struct { const port_number = port_index; const pin_number = index; const pin_mask: u32 = (1 << index); const io = @intToPtr(*volatile lpc.LPC_GPIO_TypeDef, lpc.GPIO_BASE + 0x00020 * portIndex); fn setDirection(d: PinDirection) void { switch (d) { .out => io.FIODIR |= pin_mask, .in => io.FIODIR &= ~pin_mask, } } fn direction() PinDirection { return if ((io.FIODIR & pin_mask) != 0) .out else .in; } fn getValue() bool { return (io.FIOPIN & pin_mask) != 0; } fn clear() void { io.FIOCLR = pin_mask; } fn set() void { io.FIOSET = pin_mask; } const Level = enum { high, low }; fn setTo(level: Level) void { if (level == .high) { set(); } else { clear(); } } fn toggle() void { if (getValue()) { clear(); } else { set(); } } }; } const PLL = struct { fn init() void { reset_overclocking(); } fn reset_overclocking() void { overclock_flash(5); // 5 cycles access time overclock_pll(3); // 100 MHz } fn overclock_flash(timing: u8) void { lpc.sc.FLASHCFG = (@as(u32, timing - 1) << 12) | (lpc.sc.FLASHCFG & 0xFFFF0FFF); } fn feed_pll() callconv(.Inline) void { lpc.sc.PLL0FEED = 0xAA; // mit anschliessendem FEED lpc.sc.PLL0FEED = 0x55; } fn overclock_pll(divider: u8) void { // PLL einrichten für RC lpc.sc.PLL0CON = 0; // PLL disconnect feed_pll(); lpc.sc.CLKSRCSEL = 0x00; // RC-Oszillator als Quelle lpc.sc.PLL0CFG = ((1 << 16) | 74); // SysClk = (4MHz / 2) * (2 * 75) = 300 MHz lpc.sc.CCLKCFG = divider - 1; // CPU Takt = SysClk / divider feed_pll(); lpc.sc.PLL0CON = 1; // PLL einschalten feed_pll(); var i: usize = 0; while (i < 1_000) : (i += 1) { lpc.__NOP(); } lpc.sc.PLL0CON = 3; // PLL connecten feed_pll(); } }; const PinConfig = struct { const Function = enum(u2) { Func00 = 0, Func01 = 1, Func10 = 2, Func11 = 3, }; const Mode = enum(u2) { PullUp = 0, Repeater = 1, Floating = 2, PullDown = 3, }; // contain the register values if any selector: [10]?u32 = [1]?u32{null} ** 10, pinmode: [10]?u32 = [1]?u32{null} ** 10, opendrain: [5]?u32 = [1]?u32{null} ** 5, fn setup(val: *?u32, mask: u32, value: u32) void { if (val.* == null) val.* = 0; val.*.? = (val.*.? & ~mask) | (value & mask); } fn selectFunction(cfg: *PinConfig, port: u32, pin: u32, function: Function) void { const offset = (pin / 16); const index = @intCast(u5, (pin % 16) << 1); const mask = (@as(u32, 3) << index); const value = @as(u32, @enumToInt(function)) << index; setup(&cfg.selector[2 * port + offset], mask, value); } fn setMode(cfg: *PinConfig, port: u32, pin: u32, mode: Mode) void { const offset = (pin / 16); const index = @intCast(u5, pin % 16); const mask = (@as(u32, 3) << (2 * index)); const value = (@as(u32, @enumToInt(mode)) << (2 * index)); setup(&cfg.pinmode[2 * port + offset], mask, value); // P0.0 } fn setOpenDrain(cfg: *PinConfig, port: u32, pin: u32, enabled: bool) void { const index = @intCast(u5, pin % 16); const mask = (@as(u32, 1) << index); const value = if (enabled) mask else 0; setup(&cfg.opendrain[port], mask, value); } fn configure(cfg: *PinConfig, port: u32, pin: u32, func: Function, mode: Mode, open_drain: bool) void { cfg.selectFunction(port, pin, func); cfg.setMode(port, pin, mode); cfg.setOpenDrain(port, pin, open_drain); } fn apply(cfg: PinConfig) void { for (cfg.selector) |opt_value, i| { if (opt_value) |value| { lpc.pincon.PINSEL[i] = value; } } for (cfg.pinmode) |opt_value, i| { if (opt_value) |value| { lpc.pincon.PINMODE[i] = value; } } for (cfg.opendrain) |opt_value, i| { if (opt_value) |value| { lpc.pincon.PINMODE_OD[i] = value; } } } }; const DynamicPinConfig = struct { const Function = enum(u2) { Func00 = 0, Func01 = 1, Func10 = 2, Func11 = 3, }; const Mode = enum(u2) { PullUp = 0, Repeater = 1, Floating = 2, PullDown = 3, }; fn setup(val: *volatile u32, mask: u32, value: u32) callconv(.Inline) void { val.* = (val.* & ~mask) | (value & mask); } fn selectFunction(port: u32, pin: u32, function: Function) callconv(.Inline) void { const offset = (pin / 16); const index = @intCast(u5, (pin % 16) << 1); const mask = (@as(u32, 3) << index); const value = @as(u32, @enumToInt(function)) << index; setup(&@ptrCast([*]volatile u32, &lpc.pincon.PINSEL0)[2 * port + offset], mask, value); // P0.0 } fn setMode(port: u32, pin: u32, mode: Mode) callconv(.Inline) void { const offset = (pin / 16); const index = @intCast(u5, pin % 16); const mask = (@as(u32, 3) << (2 * index)); const value = (@as(u32, @enumToInt(mode)) << (2 * index)); setup(&@ptrCast([*]volatile u32, &lpc.pincon.PINMODE0)[2 * port + offset], mask, value); // P0.0 } fn setOpenDrain(port: u32, pin: u32, enabled: bool) callconv(.Inline) void { const index = @intCast(u5, pin % 16); const mask = (@as(u32, 1) << index); const value = if (enabled) mask else 0; setup(&@ptrCast([*]volatile u32, &lpc.pincon.PINMODE_OD0)[port], mask, value); // P0.0 } fn configure(port: u32, pin: u32, func: Function, mode: Mode, open_drain: bool) callconv(.Inline) void { selectFunction(port, pin, func); setMode(port, pin, mode); setOpenDrain(port, pin, open_drain); } }; const Serial = struct { const port = lpc.uart2; const Error = error{}; const SyncWriter = std.io.Writer(void, Error, writeSync); fn syncWriter() SyncWriter { return SyncWriter{ .context = {} }; } const SyncReader = std.io.Reader(void, Error, readSync); fn syncReader() SyncReader { return SyncReader{ .context = {} }; } const AsyncWriter = std.io.Writer(void, Error, writeAsync); fn writer() AsyncWriter { return AsyncWriter{ .context = {} }; } const AsyncReader = std.io.Reader(void, Error, readAsync); fn reader() AsyncReader { return AsyncReader{ .context = {} }; } fn init(comptime baudrate: u32) void { lpc.sc.setPeripherialPower(.uart2, .on); lpc.sc.PCLKSEL0 &= ~@as(u32, 0xC0); lpc.sc.PCLKSEL0 |= @as(u32, 0x00); // UART0 PCLK = SysClock / 4 port.LCR = 0x83; // enable DLAB, 8N1 port.unnamed_2.FCR = 0x00; // disable any fifoing const pclk = F_CPU / 4; const regval = (pclk / (16 * baudrate)); port.unnamed_0.DLL = @truncate(u8, regval >> 0x00); port.unnamed_1.DLM = @truncate(u8, regval >> 0x08); port.LCR &= ~@as(u8, 0x80); // disable DLAB } fn tx(ch: u8) void { while ((port.LSR & (1 << 5)) == 0) {} // Wait for Previous transmission port.unnamed_0.THR = ch; // Load the data to be transmitted } fn available() bool { return (port.LSR & (1 << 0)) != 0; } fn rx() u8 { while ((port.LSR & (1 << 0)) == 0) {} // Wait till the data is received return @truncate(u8, port.unnamed_0.RBR); // Read received data } fn writeSync(context: void, data: []const u8) Error!usize { for (data) |c| { tx(c); } return data.len; } fn readSync(context: void, data: []u8) Error!usize { for (data) |*c| { c.* = rx(); } return data.len; } fn writeAsync(context: void, data: []const u8) Error!usize { for (data) |c| { EventLoop.waitForRegister(u8, &port.LSR, (1 << 5), (1 << 5)); std.debug.assert((port.LSR & (1 << 5)) != 0); port.unnamed_0.THR = c; // Load the data to be transmitted } return data.len; } fn readAsync(context: void, data: []u8) Error!usize { for (data) |*c| { EventLoop.waitForRegister(u8, &port.LSR, (1 << 0), (1 << 0)); std.debug.assert((port.LSR & (1 << 0)) != 0); c.* = @truncate(u8, port.unnamed_0.RBR); // Read received data } return data.len; } }; const SysTick = struct { var counter: u32 = 0; fn init(comptime freq: u32) void { lpc.NVIC_SetHandler(.SysTick, SysTickHandler); lpc.SysTick_Config(F_CPU / freq) catch unreachable; } fn get() u32 { return @atomicLoad(u32, &SysTick.counter, .SeqCst); } fn SysTickHandler() callconv(.C) void { _ = @atomicRmw(u32, &counter, .Add, 1, .SeqCst); } }; const EventLoop = struct { const Fairness = enum { prefer_current, prefer_others, }; const fairness: Fairness = .prefer_current; const SuspendedTask = struct { frame: anyframe, condition: WaitCondition, }; const WaitCondition = union(enum) { register8: Register(u8), register16: Register(u16), register32: Register(u32), time: u32, fn Register(comptime T: type) type { return struct { register: *volatile T, mask: T, value: T, }; } fn isMet(cond: @This()) bool { return switch (cond) { .register8 => |reg| (reg.register.* & reg.mask) == reg.value, .register16 => |reg| (reg.register.* & reg.mask) == reg.value, .register32 => |reg| (reg.register.* & reg.mask) == reg.value, .time => |time| SysTick.get() >= time, }; } }; var tasks: [64]SuspendedTask = undefined; var task_count: usize = 0; fn waitFor(condition: WaitCondition) void { // don't suspend if we already meet the condition if (fairness == .prefer_current) { if (condition.isMet()) return; } std.debug.assert(task_count < tasks.len); var offset = task_count; tasks[offset] = SuspendedTask{ .frame = @frame(), .condition = condition, }; task_count += 1; suspend; } fn waitForRegister(comptime Type: type, register: *volatile Type, mask: Type, value: Type) void { std.debug.assert((mask & value) == value); var reg = WaitCondition.Register(Type){ .register = register, .mask = mask, .value = value, }; waitFor(switch (Type) { u8 => WaitCondition{ .register8 = reg, }, u16 => WaitCondition{ .register16 = reg, }, u32 => WaitCondition{ .register32 = reg, }, else => @compileError("Type must be u8, u16 or u32!"), }); } fn waitForMillis(delta: u32) void { waitFor(WaitCondition{ .time = SysTick.get() + delta, }); } fn init() void { task_count = 0; } fn run() void { while (task_count > 0) { std.debug.assert(task_count <= tasks.len); var i: usize = 0; while (i < task_count) : (i += 1) { if (tasks[i].condition.isMet()) { var frame = tasks[i].frame; if (i < (task_count - 1)) { std.mem.swap(SuspendedTask, &tasks[i], &tasks[task_count - 1]); } task_count -= 1; LED3.set(); resume frame; LED3.clear(); break; } } } } }; const SPI = struct { const Mode = enum { @"async", sync, fast, }; const mode: Mode = .@"async"; const TFE = (1 << 0); const TNF = (1 << 1); const RNE = (1 << 2); const RFF = (1 << 3); const BSY = (1 << 4); fn init() void { lpc.sc.setPeripherialPower(.ssp0, .on); // SSP0 prescaler = 1 (CCLK) // lpc.sc.PCLKSEL1 &= ~@as(u32, 3 << 10); // lpc.sc.PCLKSEL1 |= @as(u32, 1 << 10); lpc.ssp0.CR0 = 0x0007; // kein SPI-CLK Teiler, CPHA=0, CPOL=0, SPI, 8 bit lpc.ssp0.CR1 = 0x02; // SSP0 an Bus aktiv setPrescaler(2); } fn xmit(value: u16) u16 { switch (mode) { .@"async" => EventLoop.waitForRegister(u32, &lpc.ssp0.SR, BSY, 0), .sync => while ((lpc.ssp0.SR & BSY) != 0) {}, // while not transmit fifo empty .fast => {}, } lpc.ssp0.DR = value & 0x1FF; switch (mode) { .@"async" => EventLoop.waitForRegister(u32, &lpc.ssp0.SR, BSY, 0), .sync => while ((lpc.ssp0.SR & BSY) != 0) {}, // while not transmit fifo empty .fast => {}, } return @intCast(u16, lpc.ssp0.DR); } fn write(value: u16) void { switch (mode) { .@"async" => EventLoop.waitForRegister(u32, &lpc.ssp0.SR, TNF, TNF), .@"sync" => while ((lpc.ssp0.SR & TNF) == 0) {}, // while transmit fifo is full .fast => {}, } lpc.ssp0.DR = value & 0x1FF; } fn setPrescaler(prescaler: u32) void { lpc.ssp0.CPSR = prescaler; } }; const Color = packed struct { b: u5, g: u6, r: u5, pub const red = Color{ .r = 0x1F, .g = 0x00, .b = 0x00 }; pub const green = Color{ .r = 0x00, .g = 0x3F, .b = 0x00 }; pub const blue = Color{ .r = 0x00, .g = 0x00, .b = 0x1F }; pub const yellow = Color{ .r = 0x1F, .g = 0x3F, .b = 0x00 }; pub const magenta = Color{ .r = 0x1F, .g = 0x00, .b = 0x1F }; pub const cyan = Color{ .r = 0x00, .g = 0x3F, .b = 0x1F }; pub const black = Color{ .r = 0x00, .g = 0x00, .b = 0x00 }; pub const white = Color{ .r = 0x1F, .g = 0x3F, .b = 0x1F }; }; comptime { std.debug.assert(@sizeOf(Color) == 2); } const Display = struct { const width = 320; const height = 240; const MajorIncrement = enum { column_major, row_major, }; const IncrementDirection = enum { decrement, increment, }; const GCTRL_RAMWR = 0x22; // Set or get GRAM data const GCTRL_RAMRD = 0x22; // Set or get GRAM data const GCTRL_DISP_CTRL = 0x07; const GCTRL_DEVICE_CODE = 0x00; // rd only const GCTRL_V_WIN_ADR = 0x44; // Vertical range address end,begin const GCTRL_H_WIN_ADR_STRT = 0x45; // begin const GCTRL_H_WIN_ADR_END = 0x46; // end const GCTRL_RAM_ADR_X = 0x4E; // Set GRAM address x const GCTRL_RAM_ADR_Y = 0x4F; // Set GRAM address y // GCTRL_DISP_CTRL */ const GDISP_ON = 0x0033; const GDISP_OFF = 0x0030; const GDISP_WRITE_PIXEL = 0x22; const DisplayCommand = struct { index: u8, value: u16, fn init(index: u8, value: u16) DisplayCommand { return DisplayCommand{ .index = index, .value = value, }; } }; // Array of configuration descriptors, the registers are initialized in the order given in the table const init_commands = [_]DisplayCommand{ // DLC-Parameter START DisplayCommand.init(0x28, 0x0006), // set SS and SM bit DisplayCommand.init(0x00, 0x0001), // start oscillator DisplayCommand.init(0x10, 0x0000), // sleep mode = 0 DisplayCommand.init(0x07, 0x0033), // Resize register DisplayCommand.init(0x02, 0x0600), // RGB interface setting DisplayCommand.init(0x03, 0xaaae), // Frame marker Position 0x686a DisplayCommand.init(0x01, 0x30F0), // RGB interface polarity 70ef, setup BGR // *************Power On sequence **************** DisplayCommand.init(0x0f, 0x0000), // SAP, BT[3:0], AP, DSTB, SLP, STB DisplayCommand.init(0x0b, 0x5208), // VREG1OUT voltage 0x5408 DisplayCommand.init(0x0c, 0x0004), // VDV[4:0] for VCOM amplitude DisplayCommand.init(0x2a, 0x09d5), DisplayCommand.init(0x0d, 0x000e), // SAP, BT[3:0], AP, DSTB, SLP, STB DisplayCommand.init(0x0e, 0x2700), // DC1[2:0], DC0[2:0], VC[2:0] 0X3200 DisplayCommand.init(0x1e, 0x00ad), // Internal reference voltage= Vci; ac //set window DisplayCommand.init(0x44, 0xef00), // Set VDV[4:0] for VCOM amplitude DisplayCommand.init(0x45, 0x0000), // Set VCM[5:0] for VCOMH DisplayCommand.init(0x46, 0x013f), // Set Frame Rate DisplayCommand.init(0x4e, 0x0000), DisplayCommand.init(0x4f, 0x0000), //--------------- Gamma control---------------// DisplayCommand.init(0x30, 0x0100), // GRAM horizontal Address DisplayCommand.init(0x31, 0x0000), // GRAM Vertical Address DisplayCommand.init(0x32, 0x0106), DisplayCommand.init(0x33, 0x0000), DisplayCommand.init(0x34, 0x0000), DisplayCommand.init(0x35, 0x0403), DisplayCommand.init(0x36, 0x0000), DisplayCommand.init(0x37, 0x0000), DisplayCommand.init(0x3a, 0x1100), DisplayCommand.init(0x3b, 0x0009), DisplayCommand.init(0x25, 0xf000), // DC1[2:0], DC0[2:0], VC[2:0] e000 DisplayCommand.init(0x26, 0x3800), //18 30 // DLC-Parameter ENDE // {GCTRL_DISP_CTRL, 0, GDISP_ON} /* Reg 0x0007, turn disp on, to ease debug */ DisplayCommand.init(GCTRL_DISP_CTRL, GDISP_OFF), // Reg 0x0007, turn dispoff during ram clear }; var cursor_x: u16 = 0; var cursor_y: u16 = 0; var cursor_dx: IncrementDirection = undefined; var cursor_dy: IncrementDirection = undefined; var horiz_incr: bool = false; pub fn init() void { IO_DISP_RST.setDirection(.out); IO_DISP_OE.setDirection(.out); enable(false); EventLoop.waitForMillis(100); reset(); EventLoop.waitForMillis(100); enable(true); for (init_commands) |cmd| { exec(cmd.index, cmd.value); } set_entry_mode(.row_major, .increment, .increment); on(); write_cmd(GDISP_WRITE_PIXEL); force_move(0, 0); } pub fn reset() void { IO_DISP_RST.clear(); EventLoop.waitForMillis(1); IO_DISP_RST.set(); } pub fn on() callconv(.Inline) void { exec(GCTRL_DISP_CTRL, GDISP_ON); } pub fn off() callconv(.Inline) void { exec(GCTRL_DISP_CTRL, GDISP_OFF); } pub fn enable(enabled: bool) void { IO_DISP_OE.setTo(enabled); } const ColorCmd = struct { lower: u9, upper: u9, fn writeToDisplay(self: @This()) void { SPI.write(self.upper); SPI.write(self.lower); } }; fn decodeColor(color: Color) callconv(.Inline) ColorCmd { const bits = @bitCast(u16, color); return ColorCmd{ .upper = 0x100 | @as(u9, @truncate(u8, bits >> 8)), .lower = 0x100 | @as(u9, @truncate(u8, bits)), }; } pub fn fill(color: Color) void { const cmd = decodeColor(color); write_cmd(GDISP_WRITE_PIXEL); var i: usize = 0; while (i < width * height) : (i += 1) { cmd.writeToDisplay(); } } pub fn set(x: u16, y: u16, color: Color) void { if (move(x, y)) write_cmd(GDISP_WRITE_PIXEL); decodeColor(color).writeToDisplay(); } /// Moves the draw cursor to (x,y). /// This function lazily moves the cursor and only updates /// Returns `true` when the display received pub fn move(x: u16, y: u16) bool { force_move(x, y); return true; // // rotate 180° // // x = Display::width - x - 1; // // y = Display::height - y - 1; // if((x != cursor_x) or (y != cursor_y)) // { // force_move(x, y); // if(horiz_incr) // { // cursor_x = switch(cursor_dx) { // .decrement => if(cursor_x == 0) width - 1 else cursor_x - 1, // .increment => if(cursor_x == width - 1) 0 else cursor_x + 1, // else => unreachable, // } // if(cursor_x < 0 || cursor_x >= width) // cursor_y += cursor_dy; // } // else // { // cursor_y += cursor_dy; // if(cursor_x < 0 || cursor_x >= width) // cursor_x += cursor_dx; // } // cursor_x = (cursor_x + width) % width; // cursor_y = (cursor_y + height) % height; // return true; // } // else // { // return false; // } } pub fn set_entry_mode(major_increment: MajorIncrement, horizontal_dir: IncrementDirection, vertical_dir: IncrementDirection) void { // set entry mode, use vertical writing when COLUMN_MAJOR var cmd = DisplayCommand{ .index = 0x11, .value = 0x6200, }; if (major_increment == .column_major) cmd.value |= (1 << 3); // vertical first, horizontal second if (horizontal_dir == .increment) cmd.value |= (1 << 4); // inc x if (vertical_dir == .increment) cmd.value |= (1 << 5); exec(cmd.index, cmd.value); cursor_dx = horizontal_dir; cursor_dy = vertical_dir; horiz_incr = major_increment == .column_major; } /// Moves the display cursor. This will not use auto-increment buffering, /// but will always issue a command to the display. pub fn force_move(x: u16, y: u16) void { exec(GCTRL_RAM_ADR_X, x); exec(GCTRL_RAM_ADR_Y, y); cursor_x = x; cursor_y = y; } /// Low level display API: /// Writes a "write pixel data" command, but without pixel data. pub fn begin_put() void { write_cmd(GDISP_WRITE_PIXEL); } /// Low level display API: /// Writes raw pixel data to the display. Make sure the display /// is in "write pixel data" mode! pub fn put(color: Color) void { decodeColor(color).writeToDisplay(); } fn write_cmd(value: u8) callconv(.Inline) void { SPI.write(value); } fn write_data(value: u8) callconv(.Inline) void { SPI.write(0x100 | @as(u16, value)); } fn exec(cmd: u8, value: u16) callconv(.Inline) void { write_cmd(cmd); write_data(@truncate(u8, value >> 8)); write_data(@truncate(u8, value & 0xFF)); } };
const std = @import("std"); pub fn build(b: *std.build.Builder) void { const exe = b.addExecutable("async-lpc", "src/main.zig"); exe.addPackage(std.build.Pkg{ .name = "lpc1768", .path = "libs/lpc1768/lpc1768.zig", }); exe.setTarget(std.zig.CrossTarget{ .cpu_arch = .thumb, .cpu_model = .{ .explicit = &std.Target.arm.cpu.cortex_m3, }, .os_tag = .freestanding, .abi = .eabi, }); exe.strip = true; exe.setBuildMode(.ReleaseSmall); exe.install(); exe.setLinkerScriptPath("./src/linker.ld"); const create_hex = b.addSystemCommand(&[_][]const u8{ "arm-none-eabi-objcopy", "-R", "stack", "-R", ".data", "-R", ".bss", "-R", ".debug_abbrev", "-O", "ihex", // "zig-cache/bin/async-lpc", // "async-lpc.hex", }); create_hex.addArtifactArg(exe); create_hex.addArg("firmware.hex"); const hex_step = b.step("hex", "Creates a flashable ihex file"); hex_step.dependOn(&create_hex.step); const create_bin = b.addSystemCommand(&[_][]const u8{ "arm-none-eabi-objcopy", "-I", "ihex", "-O", "binary", "firmware.hex", "firmware.bin", }); create_bin.step.dependOn(&create_hex.step); const bin_step = b.step("bin", "Creates a flashable binary file"); bin_step.dependOn(&create_bin.step); const flash_step = b.step("flash", "Creates a hex file and flashes it."); if (b.option([]const u8, "flash-drive", "If given, the file is deployed via mtools/fat32")) |file_name| { const copy_flash = b.addSystemCommand(&[_][]const u8{ "mcopy", "-D", "o", // override the file without asking "firmware.bin", // from firmware.bin "::firmware.bin", // to D:\firmware.bin "-i", // MUST BE LAST }); copy_flash.addArg(file_name); copy_flash.step.dependOn(&create_bin.step); flash_step.dependOn(&copy_flash.step); } else { // This is 100% machine dependant const run_flash = b.addSystemCommand(&[_][]const u8{ "flash-magic", "COM(5, 115200)", "DEVICE(LPC1768, 0.000000, 0)", "HARDWARE(BOOTEXEC, 50, 100)", "ERASEUSED(Z:\\home\\felix\\projects\\lowlevel\\async-lpc\\async-lpc.hex, PROTECTISP)", "HEXFILE(Z:\\home\\felix\\projects\\lowlevel\\async-lpc\\async-lpc.hex, NOCHECKSUMS, NOFILL, PROTECTISP)", }); run_flash.step.dependOn(&create_hex.step); flash_step.dependOn(&run_flash.step); } const run_term = b.addSystemCommand(&[_][]const u8{ "picocom", "--baud", "19200", "--lower-rts", // Disable programmer "--lower-dtr", // Disable reset "/dev/ttyUSB0", }); const term_step = b.step("terminal", "Starts picocom on the correct port"); term_step.dependOn(&run_term.step); }
const std = @import("std"); const builtin = @import("builtin"); const argsParser = @import("args"); const ihex = @import("ihex"); const spu = @import("spu-mk2"); const common = @import("shared.zig"); extern "kernel32" fn SetConsoleMode(hConsoleHandle: std.os.windows.HANDLE, dwMode: std.os.windows.DWORD) callconv(.Stdcall) std.os.windows.BOOL; pub fn dumpState(emu: *spu.SpuMk2(common.WasmDemoMachine)) !void { const stdout = std.io.getStdOut().writer(); try stdout.print( "\r\nstate: IP={X:0>4} SP={X:0>4} BP={X:0>4} FR={X:0>4}\r\n", .{ emu.ip, emu.sp, emu.bp, @bitCast(u16, emu.fr), // emu.bus_addr, // @tagName(emu.stage), }, ); try stdout.writeAll("stack:\r\n"); var offset: i8 = -6; while (offset <= 6) : (offset += 1) { const msg: []const u8 = if (offset == 0) " <-" else ""; // workaround for tuple bug const addr = if (offset < 0) emu.sp -% @intCast(u8, -2 * offset) else emu.sp +% @intCast(u8, 2 * offset); const msg_2: []const u8 = if (addr == emu.bp) " (BASE)" else ""; const value = emu.readWord(addr) catch @as(u16, 0xAAAA); try stdout.print(" {X:0>4}: [SP{:0>2}]={X:0>4}{s}{s}\r\n", .{ addr, offset, value, msg, msg_2, }); } } var termios_bak: std.os.termios = undefined; fn outputErrorMsg(emu: *spu.SpuMk2(common.WasmDemoMachine), err: anyerror) !u8 { const stdin = std.io.getStdIn(); // reset terminal before outputting error messages if (builtin.os.tag == .linux) { try std.os.tcsetattr(stdin.handle, .NOW, termios_bak); } // const time = timer.read(); try std.io.getStdOut().writer().print("\nerror: {s}\n", .{ @errorName(err), }); try dumpState(emu); switch (err) { error.BusError, error.UserBreak => return 1, else => return err, } unreachable; } pub fn main() !u8 { const cli_args = argsParser.parseForCurrentProcess(struct { help: bool = false, @"entry-point": u16 = 0x0000, trace: bool = false, @"memory-dump": ?[]const u8 = null, pub const shorthands = .{ .h = "help", .e = "entry-point", }; }, std.heap.page_allocator, .print) catch return 1; defer cli_args.deinit(); if (cli_args.options.help or cli_args.positionals.len == 0) { try std.io.getStdOut().writer().writeAll( \\emulator [--help] initialization.hex […] \\Emulates the Ashet Home Computer, based on the SPU Mark II. \\Each file passed as an argument will be loaded into the memory \\and provides an initialization for ROM and RAM. \\ \\-h, --help Displays this help text. \\ ); return if (cli_args.options.help) @as(u8, 0) else @as(u8, 1); } var debugger = Debugger{}; var emu = spu.SpuMk2(common.WasmDemoMachine).init(.{}); const memory = &emu.memory; if (cli_args.options.trace) { emu.debug_interface = &debugger.interface; } const hexParseMode = ihex.ParseMode{ .pedantic = true }; for (cli_args.positionals) |path| { var file = try std.fs.cwd().openFile(path, .{ .read = true, .write = false }); defer file.close(); // Emulator will always start at address 0x0000 or CLI given entry point. _ = try ihex.parseData(file.reader(), hexParseMode, memory, common.WasmDemoMachine.LoaderError, common.WasmDemoMachine.loadHexRecord); } emu.ip = cli_args.options.@"entry-point"; const stdin = std.io.getStdIn(); if (builtin.os.tag == .linux) { const original = try std.os.tcgetattr(stdin.handle); var modified_raw = original; const IGNBRK = 0o0000001; const BRKINT = 0o0000002; const PARMRK = 0o0000010; const ISTRIP = 0o0000040; const INLCR = 0o0000100; const IGNCR = 0o0000200; const ICRNL = 0o0000400; const IXON = 0o0002000; const OPOST = 0o0000001; const ECHO = 0o0000010; const ECHONL = 0o0000100; const ICANON = 0o0000002; const ISIG = 0o0000001; const IEXTEN = 0o0100000; const CSIZE = 0o0000060; const PARENB = 0o0000400; const CS8 = 0o0000060; // Note that this will also disable break signals! _ = 0; _ = 0; _ = 0 | ISIG; modified_raw.iflag &= ~@as(std.os.linux.tcflag_t, BRKINT | IGNBRK | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON); modified_raw.oflag &= ~@as(std.os.linux.tcflag_t, OPOST); modified_raw.lflag &= ~@as(std.os.linux.tcflag_t, ECHO | ECHONL | ICANON | IEXTEN); modified_raw.cflag &= ~@as(std.os.linux.tcflag_t, CSIZE | PARENB); modified_raw.cflag |= CS8; try std.os.tcsetattr(stdin.handle, .NOW, modified_raw); termios_bak = original; } defer if (builtin.os.tag == .linux) { std.os.tcsetattr(stdin.handle, .NOW, termios_bak) catch { std.log.err("Failed to reset stdin. Please call stty sane to get back a proper terminal experience!", .{}); }; }; if (builtin.os.tag == .windows) { if (SetConsoleMode(stdin.handle, 0) == 0) return error.FailedToSetConsole; } // defer std.debug.warn("Executed {} instructions!\n", .{emu.count}); main_loop: while (true) { emu.runBatch(10_000) catch |err| switch (err) { error.CpuHalted => break :main_loop, error.DebugBreak => try dumpState(&emu), else => |e| return try outputErrorMsg(&emu, e), }; } if (cli_args.options.@"memory-dump") |file_name| { try std.fs.cwd().writeFile(file_name, &emu.memory.memory); } return 0; } const Debugger = struct { interface: spu.DebugInterface = .{ .traceInstructionFn = traceInstruction, .traceAddressFn = traceAddress, }, fn traceInstruction(interface: *spu.DebugInterface, ip: u16, instruction: spu.Instruction, input0: u16, input1: u16, output: u16) void { const self = @fieldParentPtr(Debugger, "interface", interface); _ = self; const stdout = std.io.getStdOut().writer(); stdout.print("offset={X:0>4} instr={}\tinput0={X:0>4}\tinput1={X:0>4}\toutput={X:0>4}\r\n", .{ ip, instruction, input0, input1, output, }) catch {}; } fn traceAddress(interface: *spu.DebugInterface, virt: u16) spu.DebugInterface.TraceError!void { const self = @fieldParentPtr(Debugger, "interface", interface); _ = self; _ = virt; // } }; pub const SerialEmulator = struct { pub fn read() !u16 { const stdin = std.io.getStdIn(); if (builtin.os.tag == .linux) { var fds = [1]std.os.pollfd{ .{ .fd = stdin.handle, .events = std.os.POLL.IN, .revents = 0, }, }; _ = try std.os.poll(&fds, 0); if ((fds[0].revents & std.os.POLL.IN) != 0) { const val = @as(u16, try stdin.reader().readByte()); if (val == 0x03) // CTRL_C return error.UserBreak; return val; } } if (builtin.os.tag == .windows) { std.os.windows.WaitForSingleObject(stdin.handle, 0) catch |err| switch (err) { error.WaitTimeOut => return 0xFFFF, else => return err, }; const val = @as(u16, try stdin.reader().readByte()); if (val == 0x03) // CTRL_C return error.UserBreak; return val; } return 0xFFFF; } pub fn write(value: u16) !void { try std.io.getStdOut().writer().print("{c}", .{@truncate(u8, value)}); // std.time.sleep(50 * std.time.millisecond); } };
const std = @import("std"); const argsParser = @import("args"); const ihex = @import("ihex"); const spu = @import("spu-mk2"); const FileFormat = enum { ihex, binary }; const DisasmError = error{EndOfStream} || std.os.WriteError || std.io.FixedBufferStream([]const u8).ReadError; fn processRecord(out: *const std.io.Writer(std.fs.File, std.os.WriteError, std.fs.File.write), base: u32, data: []const u8) DisasmError!void { const in = std.io.fixedBufferStream(data).reader(); var offset = base; while (true) { try out.print("{X:0>4} ", .{offset}); offset += 2; if (in.readIntLittle(u16)) |instr_int| { const instr = @bitCast(spu.Instruction, instr_int); try out.print("{}", .{instr}); if (instr.input0 == .immediate) { offset += 2; const val = in.readIntLittle(u16) catch |err| switch (err) { error.EndOfStream => { try out.writeAll(" | ????\n"); return; }, else => return err, }; try out.print(" | {X:0>4}", .{val}); } if (instr.input1 == .immediate) { offset += 2; const val = in.readIntLittle(u16) catch |err| switch (err) { error.EndOfStream => { try out.writeAll(" | ????\n"); return; }, else => return err, }; try out.print(" | {X:0>4}", .{val}); } try out.writeAll("\n"); } else |err| { switch (err) { error.EndOfStream => break, else => return err, } } } } pub fn main() !u8 { const cli_args = argsParser.parseForCurrentProcess(struct { help: bool = false, format: ?FileFormat = null, offset: ?u16 = null, pub const shorthands = .{ .h = "help", .f = "format", }; }, std.heap.page_allocator, .print) catch return 1; defer cli_args.deinit(); const out = std.io.getStdOut().writer(); if (cli_args.options.help or cli_args.positionals.len == 0) { try out.writeAll( \\disassembler --help [--format ihex|binary] [--offset XXXX] fileA fileB \\Disassembles code for the SPU Mark II platform. \\ \\-h, --help Displays this help text. \\-f, --format Selects the input format (binary or ihex). \\ If not given, the file extension will be used \\ to guess the format. \\--offset XXXX Defines the disassembly offset for binary files. \\ ); return if (cli_args.options.help) @as(u8, 0) else @as(u8, 1); } var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const hexParseMode = ihex.ParseMode{ .pedantic = true }; for (cli_args.positionals) |path| { var file = try std.fs.cwd().openFile(path, .{ .read = true, .write = false }); defer file.close(); if (std.mem.endsWith(u8, path, ".hex")) { // Emulator will always start at address 0x0000 or CLI given entry point. _ = try ihex.parseData(file.reader(), hexParseMode, &out, DisasmError, processRecord); } else { const buffer = try file.reader().readAllAlloc(arena.allocator(), 65536); defer arena.allocator().free(buffer); try processRecord(&out, cli_args.options.offset orelse 0x0000, buffer); } } return 0; }
<filename>tools/emulator/web-main.zig const std = @import("std"); const spu = @import("spu-mk2"); const common = @import("shared.zig"); var emulator: spu.SpuMk2(common.WasmDemoMachine) = undefined; const bootrom = @embedFile("../../zig-out/firmware/wasm.bin"); pub fn dumpState(emu: *spu.SpuMk2) !void { _ = emu; } pub fn dumpTrace(emu: *spu.SpuMk2, ip: u16, instruction: spu.Instruction, input0: u16, input1: u16, output: u16) !void { _ = emu; _ = ip; _ = instruction; _ = input0; _ = input1; _ = output; } export fn init() void { // serialWrite("a", 1); emulator = spu.SpuMk2(common.WasmDemoMachine).init(.{}); // serialWrite("b", 1); std.mem.copy(u8, &emulator.memory.memory, bootrom[0..std.math.min(emulator.memory.memory.len, bootrom.len)]); // serialWrite("c", 1); } export fn run(steps: u32) u32 { emulator.runBatch(steps) catch |err| { // halting is similar to debugging if (err != error.CpuHalted) emulator.reset(); switch (err) { error.BadInstruction => return 1, error.UnalignedAccess => return 2, error.BusError => return 3, error.DebugBreak => return 4, error.CpuHalted => return 5, } }; return 0; } export fn resetCpu() void { emulator.triggerInterrupt(.reset); } export fn invokeNmi() void { emulator.triggerInterrupt(.nmi); } export fn getMemoryPtr() [*]u8 { return &emulator.memory.memory; } extern fn invokeJsPanic() noreturn; extern fn serialRead(data: [*]u8, len: u32) u32; extern fn serialWrite(data: [*]const u8, len: u32) void; pub const SerialEmulator = struct { pub fn read() !u16 { var value: [1]u8 = undefined; if (serialRead(&value, 1) == 1) { return @as(u16, value[0]); } else { return 0xFFFF; } } pub fn write(value: u16) !void { serialWrite(&[_]u8{@truncate(u8, value)}, 1); } }; pub fn panic(message: []const u8, stackTrace: ?*std.builtin.StackTrace) noreturn { serialWrite(message.ptr, message.len); _ = stackTrace; invokeJsPanic(); } pub fn log(level: anytype, comptime fmt: []const u8, args: anytype) void { _ = level; _ = fmt; _ = args; // }
const root = @import("root"); const std = @import("std"); extern var _ftext: u8; extern var _etext: u8; extern var _frodata: u8 align(4); extern var _erodata: u8 align(4); extern var _fdata: u8 align(4); extern var _gp: u8 align(16); extern var _edata: u8 align(16); extern var _fbss: u8 align(4); extern var _ebss: u8 align(4); extern var _end: u8; extern var _fstack: u8; export fn _start() linksection(".text.start") callconv(.Naked) noreturn { asm volatile ( \\ j over_magic \\ .word 0xb469075a // Magic value for config flags \\ .word 0x00000020 // USB_NO_RESET flag so we can attach the debugger \\over_magic: ); // set the stack pointer to `&_fstack` asm volatile ( \\ la sp, _fstack + 4 ); // zero out bss asm ( \\ la a0, %[fbss] \\ la a1, %[ebss] \\bss_loop: \\ beq a0, a1, bss_done \\ sw zero, 0(a0) \\ add a0, a0,4 \\ j bss_loop \\bss_done: : [ret] "=" (-> void) : [fbss] "m" (&_fbss), [ebss] "m" (&_ebss) ); // copy data from data rom (which is after rodata) to data asm ( \\ la t0, %[erodata] \\ la t1, %[fdata] \\ la t2, %[edata] \\data_loop: \\ lw t3, 0(t0) \\ sw t3, 0(t1) \\ addi t0, t0, 4 \\ addi t1, t1, 4 \\ bltu t1, t2, data_loop : [ret] "=" (-> void) : [erodata] "m" (&_erodata), [fdata] "m" (&_fdata), [edata] "m" (&_edata) ); // call user's main root.main(); }
/// https://rm.fomu.im/reboot.html pub const REBOOT = struct { const base = 0xe0006000; /// Provides support for rebooting the FPGA. /// You can select which of the four images to reboot to. pub const CTRL = @intToPtr(*volatile packed struct { /// Which image to reboot to. SB_WARMBOOT supports four images that are configured at FPGA startup. /// The bootloader is image 0, so set these bits to 0 to reboot back into the bootloader. image: u2, /// A reboot key used to prevent accidental reboots when writing to random areas of memory. /// To initiate a reboot, set this to 0b101011. key: u6, }, base + 0x0); /// This sets the reset vector for the VexRiscv. /// This address will be used whenever the CPU is reset, for example /// through a debug bridge. You should update this address whenever /// you load a new program, to enable the debugger to run `mon reset` pub const ADDR = @intToPtr(*volatile u32, base + 0x4); };
<reponame>Freax13/fomu-workshop<gh_stars>100-1000 /// Provides a generic Timer core. /// /// The Timer is implemented as a countdown timer that can be used in various modes: /// - Polling: Returns current countdown value to software. /// - One-Shot: Loads itself and stops when value reaches 0. /// - Periodic: (Re-)Loads itself when value reaches 0. /// /// *en* register allows the user to enable/disable the Timer. When the Timer /// is enabled, it is automatically loaded with the value of load register. /// /// When the Timer reaches 0, it is automatically reloaded with value of reload register. /// /// The user can latch the current countdown value by writing to update_value /// register, it will update value register with current countdown value. /// /// To use the Timer in One-Shot mode, the user needs to: /// - Disable the timer. /// - Set the load register to the expected duration. /// - (Re-)Enable the Timer. /// /// To use the Timer in Periodic mode, the user needs to: /// - Disable the Timer. /// - Set the load register to 0. /// - Set the reload register to the expected period. /// - Enable the Timer. /// /// For both modes, the CPU can be advertised by an IRQ that the /// duration/period has elapsed. (The CPU can also do software polling with /// update_value and value to know the elapsed duration) pub const TIMER0 = struct { const base = 0xe0002800; pub const LOAD3 = @intToPtr(*volatile u8, base + 0x0); pub const LOAD2 = @intToPtr(*volatile u8, base + 0x4); pub const LOAD1 = @intToPtr(*volatile u8, base + 0x8); pub const LOAD0 = @intToPtr(*volatile u8, base + 0xc); /// Load value when Timer is (re-)enabled. /// In One-Shot mode, the value written to this register specify the /// Timer’s duration in clock cycles. pub fn load(x: u32) void { LOAD3.* = @truncate(u8, x >> 24); LOAD2.* = @truncate(u8, x >> 16); LOAD1.* = @truncate(u8, x >> 8); LOAD0.* = @truncate(u8, x); } pub const RELOAD3 = @intToPtr(*volatile u8, base + 0x10); pub const RELOAD2 = @intToPtr(*volatile u8, base + 0x14); pub const RELOAD1 = @intToPtr(*volatile u8, base + 0x18); pub const RELOAD0 = @intToPtr(*volatile u8, base + 0x1c); /// Reload value when Timer reaches 0. /// In Periodic mode, the value written to this register specify the /// Timer’s period in clock cycles. pub fn reload(x: u32) void { RELOAD3.* = @truncate(u8, x >> 24); RELOAD2.* = @truncate(u8, x >> 16); RELOAD1.* = @truncate(u8, x >> 8); RELOAD0.* = @truncate(u8, x); } /// Enable of the Timer. /// Set if to 1 to enable/start the Timer and 0 to disable the Timer pub const EN = @intToPtr(*volatile bool, base + 0x20); pub fn start() void { EN.* = true; } pub fn stop() void { EN.* = false; } /// Update of the current countdown value. /// A write to this register latches the current countdown value to value /// register. pub const UPDATE_VALUE = @intToPtr(*volatile bool, base + 0x24); pub const VALUE3 = @intToPtr(*volatile u8, base + 0x28); pub const VALUE2 = @intToPtr(*volatile u8, base + 0x2c); pub const VALUE1 = @intToPtr(*volatile u8, base + 0x30); pub const VALUE0 = @intToPtr(*volatile u8, base + 0x34); pub fn latchedValue() u32 { return (@as(u32, VALUE3.*) << 24) | (@as(u32, VALUE2.*) << 16) | (@as(u32, VALUE1.*) << 8) | (@as(u32, VALUE0.*)); } pub fn value() u32 { UPDATE_VALUE.* = true; return latchedValue(); } /// This register contains the current raw level of the Event trigger. /// Writes to this register have no effect. pub const EV_STATUS = @intToPtr(*volatile bool, base + 0x38); /// When an Event occurs, the corresponding bit will be set in this /// register. To clear the Event, set the corresponding bit in this /// register. pub const EV_PENDING = @intToPtr(*volatile bool, base + 0x3c); /// This register enables the corresponding Events. Write a 0 to this /// register to disable individual events. pub const EV_ENABLE = @intToPtr(*volatile bool, base + 0x40); };
const std = @import("std"); const io = std.io; const mem = std.mem; pub fn main() %void { var stdout = try io.getStdOut(); try stdout.write(source); var lines = mem.split(source, "\n"); var line: ?[]const u8 = lines.next(); while (line != null) { try stdout.write("\n \\\\"); try stdout.write(??line); line = lines.next(); } try stdout.write("\n;\n"); } const source = \\const std = @import("std"); \\const io = std.io; \\const mem = std.mem; \\pub fn main() %void { \\ var stdout = try io.getStdOut(); \\ try stdout.write(source); \\ var lines = mem.split(source, "\n"); \\ var line: ?[]const u8 = lines.next(); \\ while (line != null) { \\ try stdout.write("\n \\\\"); \\ try stdout.write(??line); \\ line = lines.next(); \\ } \\ try stdout.write("\n;\n"); \\} \\const source = ;
/// Messible: An Ansible for Messages /// https://rm.fomu.im/messible.html /// /// An Ansible is a system for instant communication across vast distances, /// from a small portable device to a huge terminal far away. A Messible is /// a message- passing system from embedded devices to a host system. You can /// use it to get very simple printf()-style support over a debug channel. /// /// The Messible assumes the host has a way to peek into the device’s memory /// space. This is the case with the Wishbone bridge, which allows both the /// device and the host to access the same memory. /// /// At its core, a Messible is a FIFO. As long as the STATUS.FULL bit is 0, /// the device can write data into the Messible by writing into the IN. /// However, if this value is 1, you need to decide if you want to wait for it /// to empty (if the other side is just slow), or if you want to drop the /// message. From the host side, you need to read STATUS.HAVE to see if there /// is data in the FIFO. If there is, read OUT to get the most recent byte, /// which automatically advances the READ pointer. pub const MESSIBLE = struct { const base = 0xe0008000; /// Write half of the FIFO to send data out the Messible. Writing to this register advances the write pointer automatically. pub const IN = @intToPtr(*volatile u8, base + 0x0); /// Read half of the FIFO to receive data on the Messible. Reading from this register advances the read pointer automatically. pub const OUT = @intToPtr(*volatile u8, base + 0x4); pub const STATUS = @intToPtr(*volatile packed struct { /// if more data can fit into the IN FIFO. FULL: bool, /// if data can be read from the OUT FIFO. HAVE: bool, }, base + 0x8); pub fn write(data: []const u8) usize { for (data) |c, i| { if (STATUS.*.FULL) return i; IN.* = c; } return data.len; } pub fn read(dst: []u8) usize { for (dst) |*c, i| { if (!STATUS.*.HAVE) return i; c.* = OUT.*; } return dst.len; } };
const std = @import("std"); const spu = @import("spu-mk2"); const SerialEmulator = @import("root").SerialEmulator; pub const WasmDemoMachine = struct { const Self = @This(); memory: [65536]u8 = undefined, // lower half is ROM, upper half is RAM pub const LoaderError = error{InvalidAddress}; pub fn loadHexRecord(self: *Self, base: u32, data: []const u8) LoaderError!void { // std.debug.warn("load {}+{}: {X}\n", .{ base, data.len, data }); for (data) |byte, offset| { const address = base + offset; switch (address) { 0x0000...0xFFFF => |a| self.memory[a] = byte, else => return error.InvalidAddress, } } } pub fn read8(self: *Self, address: u16) !u8 { return switch (address) { 0x7FFE...0x7FFF => return error.BusError, else => self.memory[address], }; } pub fn write8(self: *Self, address: u16, value: u8) !void { switch (address) { 0x0000...0x7FFD => return error.BusError, 0x7FFE...0x7FFF => return error.BusError, 0x8000...0xFFFF => self.memory[address] = value, } } pub fn read16(self: *Self, address: u16) !u16 { return switch (address) { 0x7FFE...0x7FFF => try SerialEmulator.read(), else => std.mem.readIntLittle(u16, self.memory[address..][0..2]), }; } pub fn write16(self: *Self, address: u16, value: u16) !void { return switch (address) { 0x0000...0x7FFD => return error.BusError, 0x7FFE...0x7FFF => try SerialEmulator.write(value), 0x8000...0xFFFF => std.mem.writeIntLittle(u16, self.memory[address..][0..2], value), }; } };
const debug = @import("std").debug; pub fn main() void { while (true) debug.warn("a", .{}); }
<gh_stars>10-100 // Result from translate-c: const std = @import("std"); test "" { std.meta.refAllDecls(@This()); } pub inline fn __enable_irq() void { asm volatile ("cpsie i"); } pub inline fn __disable_irq() void { asm volatile ("cpsid i"); } pub inline fn __enable_fault_irq() void { asm volatile ("cpsie f"); } pub inline fn __disable_fault_irq() void { asm volatile ("cpsid f"); } pub inline fn __NOP() void { asm volatile ("nop"); } pub inline fn __WFI() void { asm volatile ("wfi"); } pub inline fn __WFE() void { asm volatile ("wfe"); } pub inline fn __SEV() void { asm volatile ("sev"); } pub inline fn __ISB() void { asm volatile ("isb"); } pub inline fn __DSB() void { asm volatile ("dsb"); } pub inline fn __DMB() void { asm volatile ("dmb"); } pub inline fn __CLREX() void { asm volatile ("clrex"); } pub const NonMaskableInt_IRQn = @enumToInt(IRQn.NonMaskableInt); pub const MemoryManagement_IRQn = @enumToInt(IRQn.MemoryManagement); pub const BusFault_IRQn = @enumToInt(IRQn.BusFault); pub const UsageFault_IRQn = @enumToInt(IRQn.UsageFault); pub const SVCall_IRQn = @enumToInt(IRQn.SVCall); pub const DebugMonitor_IRQn = @enumToInt(IRQn.DebugMonitor); pub const PendSV_IRQn = @enumToInt(IRQn.PendSV); pub const SysTick_IRQn = @enumToInt(IRQn.SysTick); pub const WDT_IRQn = @enumToInt(IRQn.WDT); pub const TIMER0_IRQn = @enumToInt(IRQn.TIMER0); pub const TIMER1_IRQn = @enumToInt(IRQn.TIMER1); pub const TIMER2_IRQn = @enumToInt(IRQn.TIMER2); pub const TIMER3_IRQn = @enumToInt(IRQn.TIMER3); pub const UART0_IRQn = @enumToInt(IRQn.UART0); pub const UART1_IRQn = @enumToInt(IRQn.UART1); pub const UART2_IRQn = @enumToInt(IRQn.UART2); pub const UART3_IRQn = @enumToInt(IRQn.UART3); pub const PWM1_IRQn = @enumToInt(IRQn.PWM1); pub const I2C0_IRQn = @enumToInt(IRQn.I2C0); pub const I2C1_IRQn = @enumToInt(IRQn.I2C1); pub const I2C2_IRQn = @enumToInt(IRQn.I2C2); pub const SPI_IRQn = @enumToInt(IRQn.SPI); pub const SSP0_IRQn = @enumToInt(IRQn.SSP0); pub const SSP1_IRQn = @enumToInt(IRQn.SSP1); pub const PLL0_IRQn = @enumToInt(IRQn.PLL0); pub const RTC_IRQn = @enumToInt(IRQn.RTC); pub const EINT0_IRQn = @enumToInt(IRQn.EINT0); pub const EINT1_IRQn = @enumToInt(IRQn.EINT1); pub const EINT2_IRQn = @enumToInt(IRQn.EINT2); pub const EINT3_IRQn = @enumToInt(IRQn.EINT3); pub const ADC_IRQn = @enumToInt(IRQn.ADC); pub const BOD_IRQn = @enumToInt(IRQn.BOD); pub const USB_IRQn = @enumToInt(IRQn.USB); pub const CAN_IRQn = @enumToInt(IRQn.CAN); pub const DMA_IRQn = @enumToInt(IRQn.DMA); pub const I2S_IRQn = @enumToInt(IRQn.I2S); pub const ENET_IRQn = @enumToInt(IRQn.ENET); pub const RIT_IRQn = @enumToInt(IRQn.RIT); pub const MCPWM_IRQn = @enumToInt(IRQn.MCPWM); pub const QEI_IRQn = @enumToInt(IRQn.QEI); pub const PLL1_IRQn = @enumToInt(IRQn.PLL1); pub const IRQn = extern enum(isize) { NonMaskableInt = -14, MemoryManagement = -12, BusFault = -11, UsageFault = -10, SVCall = -5, DebugMonitor = -4, PendSV = -2, SysTick = -1, WDT = 0, TIMER0 = 1, TIMER1 = 2, TIMER2 = 3, TIMER3 = 4, UART0 = 5, UART1 = 6, UART2 = 7, UART3 = 8, PWM1 = 9, I2C0 = 10, I2C1 = 11, I2C2 = 12, SPI = 13, SSP0 = 14, SSP1 = 15, PLL0 = 16, RTC = 17, EINT0 = 18, EINT1 = 19, EINT2 = 20, EINT3 = 21, ADC = 22, BOD = 23, USB = 24, CAN = 25, DMA = 26, I2S = 27, ENET = 28, RIT = 29, MCPWM = 30, QEI = 31, PLL1 = 32, _, }; pub const NVIC_Type = extern struct { ISER: [8]u32, RESERVED0: [24]u32, ICER: [8]u32, RSERVED1: [24]u32, ISPR: [8]u32, RESERVED2: [24]u32, ICPR: [8]u32, RESERVED3: [24]u32, IABR: [8]u32, RESERVED4: [56]u32, IP: [240]u8, RESERVED5: [644]u32, STIR: u32, }; pub const SCB_Type = extern struct { CPUID: u32, ICSR: u32, VTOR: u32, AIRCR: u32, SCR: u32, CCR: u32, SHP: [12]u8, SHCSR: u32, CFSR: u32, HFSR: u32, DFSR: u32, MMFAR: u32, BFAR: u32, AFSR: u32, PFR: [2]u32, DFR: u32, ADR: u32, MMFR: [4]u32, ISAR: [5]u32, }; pub const SysTick_Type = extern struct { CTRL: u32, LOAD: u32, VAL: u32, CALIB: u32, }; const union_unnamed_5 = extern union { u8: u8, u16: u16, u32: u32, }; pub const ITM_Type = extern struct { PORT: [32]union_unnamed_5, RESERVED0: [864]u32, TER: u32, RESERVED1: [15]u32, TPR: u32, RESERVED2: [15]u32, TCR: u32, RESERVED3: [29]u32, IWR: u32, IRR: u32, IMCR: u32, RESERVED4: [43]u32, LAR: u32, LSR: u32, RESERVED5: [6]u32, PID4: u32, PID5: u32, PID6: u32, PID7: u32, PID0: u32, PID1: u32, PID2: u32, PID3: u32, CID0: u32, CID1: u32, CID2: u32, CID3: u32, }; pub const InterruptType_Type = extern struct { RESERVED0: u32, ICTR: u32, RESERVED1: u32, }; pub const MPU_Type = extern struct { TYPE: u32, CTRL: u32, RNR: u32, RBAR: u32, RASR: u32, RBAR_A1: u32, RASR_A1: u32, RBAR_A2: u32, RASR_A2: u32, RBAR_A3: u32, RASR_A3: u32, }; pub const CoreDebug_Type = extern struct { DHCSR: u32, DCRSR: u32, DCRDR: u32, DEMCR: u32, }; pub extern fn __get_PSP() u32; pub extern fn __set_PSP(topOfProcStack: u32) void; pub extern fn __get_MSP() u32; pub extern fn __set_MSP(topOfMainStack: u32) void; pub extern fn __get_BASEPRI() u32; pub extern fn __set_BASEPRI(basePri: u32) void; pub extern fn __get_PRIMASK() u32; pub extern fn __set_PRIMASK(priMask: u32) void; pub extern fn __get_FAULTMASK() u32; pub extern fn __set_FAULTMASK(faultMask: u32) void; pub extern fn __get_CONTROL() u32; pub extern fn __set_CONTROL(control: u32) void; pub extern fn __REV(value: u32) u32; pub extern fn __REV16(value: u16) u32; pub extern fn __REVSH(value: i16) i32; pub extern fn __RBIT(value: u32) u32; pub extern fn __LDREXB(addr: [*c]u8) u8; pub extern fn __LDREXH(addr: [*c]u16) u16; pub extern fn __LDREXW(addr: [*c]u32) u32; pub extern fn __STREXB(value: u8, addr: [*c]u8) u32; pub extern fn __STREXH(value: u16, addr: [*c]u16) u32; pub extern fn __STREXW(value: u32, addr: [*c]u32) u32; pub inline fn NVIC_SetPriorityGrouping(PriorityGroup: u32) void { const PriorityGroupTmp = (PriorityGroup & 0x07); // only values 0..7 are used var reg_value = SCB.AIRCR; // read old register configuration reg_value &= ~((0xFFFF << 16) | (0x0F << 8)); // clear bits to change reg_value = ((reg_value | NVIC_AIRCR_VECTKEY | (PriorityGroupTmp << 8))); // Insert write key and priorty group SCB.AIRCR = reg_value; } // pub fn NVIC_GetPriorityGrouping() callconv(.C) u32 { // return (((@intToPtr([*c]SCB_Type, ((@as(c_uint, 3758153728)) +% @bitCast(c_uint, @as(c_int, 3328))))).*.AIRCR >> @intCast(u5, 8)) & @bitCast(c_uint, @as(c_int, 7))); // } pub inline fn NVIC_SetHandler(irq: IRQn, handler: *allowzero const c_void) void { const base = @intToPtr([*]u32, SCB.VTOR); const offset = @intCast(usize, 16 + @enumToInt(irq)); base[offset] = @bitCast(u32, @ptrToInt(handler)); } // pub fn NVIC_EnableIRQ(arg_IRQn_1: IRQn) callconv(.C) void { // var IRQn_1 = arg_IRQn_1; // (@intToPtr([*c]NVIC_Type, ((@as(c_uint, 3758153728)) +% @bitCast(c_uint, @as(c_int, 256))))).*.ISER[(@enumToInt((IRQn_1)) >> @intCast(u5, 5))] = @bitCast(u32, (@as(c_int, 1) << @intCast(std.math.Log2Int(c_int), (@enumToInt((IRQn_1)) & @bitCast(c_uint, @as(c_int, 31)))))); // } // pub fn NVIC_DisableIRQ(arg_IRQn_1: IRQn) callconv(.C) void { // var IRQn_1 = arg_IRQn_1; // (@intToPtr([*c]NVIC_Type, ((@as(c_uint, 3758153728)) +% @bitCast(c_uint, @as(c_int, 256))))).*.ICER[(@enumToInt((IRQn_1)) >> @intCast(u5, 5))] = @bitCast(u32, (@as(c_int, 1) << @intCast(std.math.Log2Int(c_int), (@enumToInt((IRQn_1)) & @bitCast(c_uint, @as(c_int, 31)))))); // } // pub fn NVIC_GetPendingIRQ(arg_IRQn_1: IRQn) callconv(.C) u32 { // var IRQn_1 = arg_IRQn_1; // return (@bitCast(u32, (if (((@intToPtr([*c]NVIC_Type, ((@as(c_uint, 3758153728)) +% @bitCast(c_uint, @as(c_int, 256))))).*.ISPR[@enumToInt((IRQn_1)) >> @intCast(u5, 5)] & @bitCast(c_uint, (@as(c_int, 1) << @intCast(std.math.Log2Int(c_int), (@enumToInt((IRQn_1)) & @bitCast(c_uint, @as(c_int, 31))))))) != 0) @as(c_int, 1) else @as(c_int, 0)))); // } // pub fn NVIC_SetPendingIRQ(arg_IRQn_1: IRQn) callconv(.C) void { // var IRQn_1 = arg_IRQn_1; // (@intToPtr([*c]NVIC_Type, ((@as(c_uint, 3758153728)) +% @bitCast(c_uint, @as(c_int, 256))))).*.ISPR[(@enumToInt((IRQn_1)) >> @intCast(u5, 5))] = @bitCast(u32, (@as(c_int, 1) << @intCast(std.math.Log2Int(c_int), (@enumToInt((IRQn_1)) & @bitCast(c_uint, @as(c_int, 31)))))); // } // pub fn NVIC_ClearPendingIRQ(arg_IRQn_1: IRQn) callconv(.C) void { // var IRQn_1 = arg_IRQn_1; // (@intToPtr([*c]NVIC_Type, ((@as(c_uint, 3758153728)) +% @bitCast(c_uint, @as(c_int, 256))))).*.ICPR[(@enumToInt((IRQn_1)) >> @intCast(u5, 5))] = @bitCast(u32, (@as(c_int, 1) << @intCast(std.math.Log2Int(c_int), (@enumToInt((IRQn_1)) & @bitCast(c_uint, @as(c_int, 31)))))); // } // pub fn NVIC_GetActive(arg_IRQn_1: IRQn) callconv(.C) u32 { // var IRQn_1 = arg_IRQn_1; // return (@bitCast(u32, (if (((@intToPtr([*c]NVIC_Type, ((@as(c_uint, 3758153728)) +% @bitCast(c_uint, @as(c_int, 256))))).*.IABR[@enumToInt((IRQn_1)) >> @intCast(u5, 5)] & @bitCast(c_uint, (@as(c_int, 1) << @intCast(std.math.Log2Int(c_int), (@enumToInt((IRQn_1)) & @bitCast(c_uint, @as(c_int, 31))))))) != 0) @as(c_int, 1) else @as(c_int, 0)))); // } const __MPU_PRESENT = 1; const __NVIC_PRIO_BITS = 5; const __Vendor_SysTickConfig = 0; pub inline fn NVIC_SetPriority(irq: IRQn, priority: u32) void { const irq_number = @enumToInt(irq); if (irq_number < 0) { // set Priority for Cortex-M3 System Interrupts SCB.SHP[@intCast(u32, irq_number & 0xF) - 4] = @truncate(u8, priority << (8 - __NVIC_PRIO_BITS)); } else { // set Priority for device specific Interrupts NVIC.IP[@intCast(u32, irq_number)] = @truncate(u8, priority << (8 - __NVIC_PRIO_BITS)); } } // pub fn NVIC_GetPriority(arg_IRQn_1: IRQn) callconv(.C) u32 { // var IRQn_1 = arg_IRQn_1; // if (@enumToInt(IRQn_1) < @as(c_int, 0)) { // return (@bitCast(u32, (@bitCast(c_int, @as(c_uint, (@intToPtr([*c]SCB_Type, ((@as(c_uint, 3758153728)) +% @bitCast(c_uint, @as(c_int, 3328))))).*.SHP[((@enumToInt((IRQn_1)) & @bitCast(c_uint, @as(c_int, 15))) -% @bitCast(c_uint, @as(c_int, 4)))])) >> @intCast(std.math.Log2Int(c_int), (@as(c_int, 8) - @as(c_int, 5)))))); // } else { // return (@bitCast(u32, (@bitCast(c_int, @as(c_uint, (@intToPtr([*c]NVIC_Type, ((@as(c_uint, 3758153728)) +% @bitCast(c_uint, @as(c_int, 256))))).*.IP[@enumToInt((IRQn_1))])) >> @intCast(std.math.Log2Int(c_int), (@as(c_int, 8) - @as(c_int, 5)))))); // } // return 0; // } // pub fn NVIC_EncodePriority(arg_PriorityGroup: u32, arg_PreemptPriority: u32, arg_SubPriority: u32) callconv(.C) u32 { // var PriorityGroup = arg_PriorityGroup; // var PreemptPriority = arg_PreemptPriority; // var SubPriority = arg_SubPriority; // var PriorityGroupTmp: u32 = (PriorityGroup & @bitCast(c_uint, @as(c_int, 7))); // var PreemptPriorityBits: u32 = undefined; // var SubPriorityBits: u32 = undefined; // PreemptPriorityBits = if ((@bitCast(c_uint, @as(c_int, 7)) -% PriorityGroupTmp) > @bitCast(c_uint, @as(c_int, 5))) @bitCast(c_uint, @as(c_int, 5)) else (@bitCast(c_uint, @as(c_int, 7)) -% PriorityGroupTmp); // SubPriorityBits = if ((PriorityGroupTmp +% @bitCast(c_uint, @as(c_int, 5))) < @bitCast(c_uint, @as(c_int, 7))) @bitCast(c_uint, @as(c_int, 0)) else ((PriorityGroupTmp -% @bitCast(c_uint, @as(c_int, 7))) +% @bitCast(c_uint, @as(c_int, 5))); // return (((PreemptPriority & @bitCast(c_uint, ((@as(c_int, 1) << @intCast(std.math.Log2Int(c_int), (PreemptPriorityBits))) - @as(c_int, 1)))) << @intCast(std.math.Log2Int(c_uint), SubPriorityBits)) | (SubPriority & @bitCast(c_uint, ((@as(c_int, 1) << @intCast(std.math.Log2Int(c_int), (SubPriorityBits))) - @as(c_int, 1))))); // } // pub fn NVIC_DecodePriority(arg_Priority: u32, arg_PriorityGroup: u32, arg_pPreemptPriority: [*c]u32, arg_pSubPriority: [*c]u32) callconv(.C) void { // var Priority = arg_Priority; // var PriorityGroup = arg_PriorityGroup; // var pPreemptPriority = arg_pPreemptPriority; // var pSubPriority = arg_pSubPriority; // var PriorityGroupTmp: u32 = (PriorityGroup & @bitCast(c_uint, @as(c_int, 7))); // var PreemptPriorityBits: u32 = undefined; // var SubPriorityBits: u32 = undefined; // PreemptPriorityBits = if ((@bitCast(c_uint, @as(c_int, 7)) -% PriorityGroupTmp) > @bitCast(c_uint, @as(c_int, 5))) @bitCast(c_uint, @as(c_int, 5)) else (@bitCast(c_uint, @as(c_int, 7)) -% PriorityGroupTmp); // SubPriorityBits = if ((PriorityGroupTmp +% @bitCast(c_uint, @as(c_int, 5))) < @bitCast(c_uint, @as(c_int, 7))) @bitCast(c_uint, @as(c_int, 0)) else ((PriorityGroupTmp -% @bitCast(c_uint, @as(c_int, 7))) +% @bitCast(c_uint, @as(c_int, 5))); // pPreemptPriority.?.* = ((Priority >> @intCast(u5, SubPriorityBits)) & @bitCast(c_uint, ((@as(c_int, 1) << @intCast(std.math.Log2Int(c_int), (PreemptPriorityBits))) - @as(c_int, 1)))); // pSubPriority.?.* = ((Priority) & @bitCast(c_uint, ((@as(c_int, 1) << @intCast(std.math.Log2Int(c_int), (SubPriorityBits))) - @as(c_int, 1)))); // } pub inline fn SysTick_Config(ticks: u24) !void { if (ticks > SYSTICK_MAXCOUNT) // Reload value impossible return error.OutOfRange; SysTick.LOAD = (ticks & SYSTICK_MAXCOUNT) - 1; // set reload register NVIC_SetPriority(.SysTick, (1 << __NVIC_PRIO_BITS) - 1); // set Priority for Cortex-M0 System Interrupts SysTick.VAL = 0x00; // Load the SysTick Counter Value SysTick.CTRL = (1 << SYSTICK_CLKSOURCE) | (1 << SYSTICK_ENABLE) | (1 << SYSTICK_TICKINT); // Enable SysTick IRQ and SysTick Timer } // pub fn NVIC_SystemReset() callconv(.C) void { // (@intToPtr([*c]SCB_Type, ((@as(c_uint, 3758153728)) +% @bitCast(c_uint, @as(c_int, 3328))))).*.AIRCR = ((@bitCast(c_uint, (@as(c_int, 1530) << @intCast(std.math.Log2Int(c_int), 16))) | ((@intToPtr([*c]SCB_Type, ((@as(c_uint, 3758153728)) +% @bitCast(c_uint, @as(c_int, 3328))))).*.AIRCR & @bitCast(c_uint, (@as(c_int, 1792))))) | @bitCast(c_uint, (@as(c_int, 1) << @intCast(std.math.Log2Int(c_int), 2)))); // __DSB(); // while (true) {} // } // pub fn ITM_SendChar(arg_ch: u32) callconv(.C) u32 { // var ch = arg_ch; // if (ch == @bitCast(c_uint, @as(c_int, '\n'))) _ = ITM_SendChar(@bitCast(u32, @as(c_int, '\r'))); // if (((((@intToPtr([*c]CoreDebug_Type, (@as(c_uint, 3758157296)))).*.DEMCR & @bitCast(c_uint, (@as(c_int, 1) << @intCast(std.math.Log2Int(c_int), 24)))) != 0) and (((@intToPtr([*c]ITM_Type, (@as(c_uint, 3758096384)))).*.TCR & @bitCast(c_uint, @as(c_int, 1))) != 0)) and ((@bitCast(c_ulong, @as(c_ulong, (@intToPtr([*c]ITM_Type, (@as(c_uint, 3758096384)))).*.TER)) & (@as(c_ulong, 1) << @intCast(std.math.Log2Int(c_ulong), 0))) != 0)) { // while ((@intToPtr([*c]ITM_Type, (@as(c_uint, 3758096384)))).*.PORT[@intCast(c_uint, @as(c_int, 0))].u32 == @bitCast(c_uint, @as(c_int, 0))) {} // (@intToPtr([*c]ITM_Type, (@as(c_uint, 3758096384)))).*.PORT[@intCast(c_uint, @as(c_int, 0))].u8 = @bitCast(u8, @truncate(u8, ch)); // } // return (ch); // } pub const LPC_SC_TypeDef = extern struct { const Self = @This(); pub const Peripherial = enum(u5) { tim0 = 1, tim1 = 2, uart0 = 3, uart1 = 4, pwm1 = 6, i2c0 = 7, spi = 8, rtc = 9, ssp1 = 10, adc = 12, can1 = 13, can2 = 14, gpio = 15, rit = 16, mcpwm = 17, qei = 18, i2c1 = 19, ssp0 = 21, tim2 = 22, tim3 = 23, uart2 = 24, uart3 = 25, i2c2 = 26, i2s = 27, gpdma = 29, enet = 30, usb = 31, }; pub const Power = packed enum(u1) { off = 0, on = 1 }; pub fn setPeripherialPower(self: *volatile Self, peripherial: Peripherial, power: Power) void { switch (power) { .on => self.PCONP |= (@as(u32, 1) << @enumToInt(peripherial)), .off => self.PCONP &= ~(@as(u32, 1) << @enumToInt(peripherial)), } } FLASHCFG: u32, RESERVED0: [31]u32, PLL0CON: u32, PLL0CFG: u32, PLL0STAT: u32, PLL0FEED: u32, RESERVED1: [4]u32, PLL1CON: u32, PLL1CFG: u32, PLL1STAT: u32, PLL1FEED: u32, RESERVED2: [4]u32, PCON: u32, PCONP: u32, RESERVED3: [15]u32, CCLKCFG: u32, USBCLKCFG: u32, CLKSRCSEL: u32, RESERVED4: [12]u32, EXTINT: u32, RESERVED5: u32, EXTMODE: u32, EXTPOLAR: u32, RESERVED6: [12]u32, RSID: u32, RESERVED7: [7]u32, SCS: u32, IRCTRIM: u32, PCLKSEL0: u32, PCLKSEL1: u32, RESERVED8: [4]u32, USBIntSt: u32, RESERVED9: u32, CLKOUTCFG: u32, }; pub const LPC_PINCON_TypeDef = extern struct { PINSEL: [10]u32, RESERVED0: [5]u32, PINMODE: [10]u32, PINMODE_OD: [5]u32, I2CPADCFG: u32, }; pub const LPC_GPIO_TypeDef = extern struct { FIODIR: u32, RESERVED0: [3]u32, FIOMASK: u32, FIOPIN: u32, FIOSET: u32, FIOCLR: u32, }; pub const LPC_GPIOINT_TypeDef = extern struct { IntStatus: u32, IO0IntStatR: u32, IO0IntStatF: u32, IO0IntClr: u32, IO0IntEnR: u32, IO0IntEnF: u32, RESERVED0: [3]u32, IO2IntStatR: u32, IO2IntStatF: u32, IO2IntClr: u32, IO2IntEnR: u32, IO2IntEnF: u32, }; pub const LPC_TIM_TypeDef = extern struct { IR: u32, TCR: u32, TC: u32, PR: u32, PC: u32, MCR: u32, MR0: u32, MR1: u32, MR2: u32, MR3: u32, CCR: u32, CR0: u32, CR1: u32, RESERVED0: [2]u32, EMR: u32, RESERVED1: [12]u32, CTCR: u32, }; pub const LPC_PWM_TypeDef = extern struct { IR: u32, TCR: u32, TC: u32, PR: u32, PC: u32, MCR: u32, MR0: u32, MR1: u32, MR2: u32, MR3: u32, CCR: u32, CR0: u32, CR1: u32, CR2: u32, CR3: u32, RESERVED0: u32, MR4: u32, MR5: u32, MR6: u32, PCR: u32, LER: u32, RESERVED1: [7]u32, CTCR: u32, }; pub const LPC_UART_TypeDef = extern struct { unnamed_0: extern union { RBR: u8, THR: u8, DLL: u8, RESERVED0: u32, }, unnamed_1: extern union { DLM: u8, IER: u32, }, unnamed_2: extern union { IIR: u32, FCR: u8, }, LCR: u8, RESERVED1: [7]u8, LSR: u8, RESERVED2: [7]u8, SCR: u8, RESERVED3: [3]u8, ACR: u32, ICR: u8, RESERVED4: [3]u8, FDR: u8, RESERVED5: [7]u8, TER: u8, RESERVED6: [39]u8, FIFOLVL: u8, }; pub const LPC_UART0_TypeDef = extern struct { uart: LPC_UART_TypeDef, RESERVED7: [363]u8, DMAREQSEL: u32, }; pub const LPC_UART1_TypeDef = extern struct { unnamed_0: extern union { RBR: u8, THR: u8, DLL: u8, RESERVED0: u32, }, unnamed_1: extern union { DLM: u8, IER: u32, }, unnamed_2: extern union { IIR: u32, FCR: u8, }, LCR: u8, RESERVED1: [3]u8, MCR: u8, RESERVED2: [3]u8, LSR: u8, RESERVED3: [3]u8, MSR: u8, RESERVED4: [3]u8, SCR: u8, RESERVED5: [3]u8, ACR: u32, RESERVED6: u32, FDR: u32, RESERVED7: u32, TER: u8, RESERVED8: [27]u8, RS485CTRL: u8, RESERVED9: [3]u8, ADRMATCH: u8, RESERVED10: [3]u8, RS485DLY: u8, RESERVED11: [3]u8, FIFOLVL: u8, }; pub const LPC_SPI_TypeDef = extern struct { SPCR: u32, SPSR: u32, SPDR: u32, SPCCR: u32, RESERVED0: [3]u32, SPINT: u32, }; pub const LPC_SSP_TypeDef = extern struct { CR0: u32, CR1: u32, DR: u32, SR: u32, CPSR: u32, IMSC: u32, RIS: u32, MIS: u32, ICR: u32, DMACR: u32, }; pub const LPC_I2C_TypeDef = extern struct { I2CONSET: u32, I2STAT: u32, I2DAT: u32, I2ADR0: u32, I2SCLH: u32, I2SCLL: u32, I2CONCLR: u32, MMCTRL: u32, I2ADR1: u32, I2ADR2: u32, I2ADR3: u32, I2DATA_BUFFER: u32, I2MASK0: u32, I2MASK1: u32, I2MASK2: u32, I2MASK3: u32, }; pub const LPC_I2S_TypeDef = extern struct { I2SDAO: u32, I2SDAI: u32, I2STXFIFO: u32, I2SRXFIFO: u32, I2SSTATE: u32, I2SDMA1: u32, I2SDMA2: u32, I2SIRQ: u32, I2STXRATE: u32, I2SRXRATE: u32, I2STXBITRATE: u32, I2SRXBITRATE: u32, I2STXMODE: u32, I2SRXMODE: u32, }; pub const LPC_RIT_TypeDef = extern struct { RICOMPVAL: u32, RIMASK: u32, RICTRL: u8, RESERVED0: [3]u8, RICOUNTER: u32, }; pub const LPC_RTC_TypeDef = extern struct { ILR: u8, RESERVED0: [7]u8, CCR: u8, RESERVED1: [3]u8, CIIR: u8, RESERVED2: [3]u8, AMR: u8, RESERVED3: [3]u8, CTIME0: u32, CTIME1: u32, CTIME2: u32, SEC: u8, RESERVED4: [3]u8, MIN: u8, RESERVED5: [3]u8, HOUR: u8, RESERVED6: [3]u8, DOM: u8, RESERVED7: [3]u8, DOW: u8, RESERVED8: [3]u8, DOY: u16, RESERVED9: u16, MONTH: u8, RESERVED10: [3]u8, YEAR: u16, RESERVED11: u16, CALIBRATION: u32, GPREG0: u32, GPREG1: u32, GPREG2: u32, GPREG3: u32, GPREG4: u32, RTC_AUXEN: u8, RESERVED12: [3]u8, RTC_AUX: u8, RESERVED13: [3]u8, ALSEC: u8, RESERVED14: [3]u8, ALMIN: u8, RESERVED15: [3]u8, ALHOUR: u8, RESERVED16: [3]u8, ALDOM: u8, RESERVED17: [3]u8, ALDOW: u8, RESERVED18: [3]u8, ALDOY: u16, RESERVED19: u16, ALMON: u8, RESERVED20: [3]u8, ALYEAR: u16, RESERVED21: u16, }; pub const LPC_WDT_TypeDef = extern struct { WDMOD: u8, RESERVED0: [3]u8, WDTC: u32, WDFEED: u8, RESERVED1: [3]u8, WDTV: u32, WDCLKSEL: u32, }; pub const LPC_ADC_TypeDef = extern struct { ADCR: u32, ADGDR: u32, RESERVED0: u32, ADINTEN: u32, ADDR0: u32, ADDR1: u32, ADDR2: u32, ADDR3: u32, ADDR4: u32, ADDR5: u32, ADDR6: u32, ADDR7: u32, ADSTAT: u32, ADTRM: u32, }; pub const LPC_DAC_TypeDef = extern struct { DACR: u32, DACCTRL: u32, DACCNTVAL: u16, }; pub const LPC_MCPWM_TypeDef = extern struct { MCCON: u32, MCCON_SET: u32, MCCON_CLR: u32, MCCAPCON: u32, MCCAPCON_SET: u32, MCCAPCON_CLR: u32, MCTIM0: u32, MCTIM1: u32, MCTIM2: u32, MCPER0: u32, MCPER1: u32, MCPER2: u32, MCPW0: u32, MCPW1: u32, MCPW2: u32, MCDEADTIME: u32, MCCCP: u32, MCCR0: u32, MCCR1: u32, MCCR2: u32, MCINTEN: u32, MCINTEN_SET: u32, MCINTEN_CLR: u32, MCCNTCON: u32, MCCNTCON_SET: u32, MCCNTCON_CLR: u32, MCINTFLAG: u32, MCINTFLAG_SET: u32, MCINTFLAG_CLR: u32, MCCAP_CLR: u32, }; pub const LPC_QEI_TypeDef = extern struct { QEICON: u32, QEISTAT: u32, QEICONF: u32, QEIPOS: u32, QEIMAXPOS: u32, CMPOS0: u32, CMPOS1: u32, CMPOS2: u32, INXCNT: u32, INXCMP: u32, QEILOAD: u32, QEITIME: u32, QEIVEL: u32, QEICAP: u32, VELCOMP: u32, FILTER: u32, RESERVED0: [998]u32, QEIIEC: u32, QEIIES: u32, QEIINTSTAT: u32, QEIIE: u32, QEICLR: u32, QEISET: u32, }; pub const LPC_CANAF_RAM_TypeDef = extern struct { mask: [512]u32, }; pub const LPC_CANAF_TypeDef = extern struct { AFMR: u32, SFF_sa: u32, SFF_GRP_sa: u32, EFF_sa: u32, EFF_GRP_sa: u32, ENDofTable: u32, LUTerrAd: u32, LUTerr: u32, FCANIE: u32, FCANIC0: u32, FCANIC1: u32, }; pub const LPC_CANCR_TypeDef = extern struct { CANTxSR: u32, CANRxSR: u32, CANMSR: u32, }; pub const LPC_CAN_TypeDef = extern struct { MOD: u32, CMR: u32, GSR: u32, ICR: u32, IER: u32, BTR: u32, EWL: u32, SR: u32, RFS: u32, RID: u32, RDA: u32, RDB: u32, TFI1: u32, TID1: u32, TDA1: u32, TDB1: u32, TFI2: u32, TID2: u32, TDA2: u32, TDB2: u32, TFI3: u32, TID3: u32, TDA3: u32, TDB3: u32, }; pub const LPC_GPDMA_TypeDef = extern struct { DMACIntStat: u32, DMACIntTCStat: u32, DMACIntTCClear: u32, DMACIntErrStat: u32, DMACIntErrClr: u32, DMACRawIntTCStat: u32, DMACRawIntErrStat: u32, DMACEnbldChns: u32, DMACSoftBReq: u32, DMACSoftSReq: u32, DMACSoftLBReq: u32, DMACSoftLSReq: u32, DMACConfig: u32, DMACSync: u32, }; pub const LPC_GPDMACH_TypeDef = extern struct { DMACCSrcAddr: u32, DMACCDestAddr: u32, DMACCLLI: u32, DMACCControl: u32, DMACCConfig: u32, }; const union_unnamed_45 = extern union { USBClkCtrl: u32, OTGClkCtrl: u32, }; const union_unnamed_46 = extern union { USBClkSt: u32, OTGClkSt: u32, }; pub const LPC_USB_TypeDef = extern struct { HcRevision: u32, HcControl: u32, HcCommandStatus: u32, HcInterruptStatus: u32, HcInterruptEnable: u32, HcInterruptDisable: u32, HcHCCA: u32, HcPeriodCurrentED: u32, HcControlHeadED: u32, HcControlCurrentED: u32, HcBulkHeadED: u32, HcBulkCurrentED: u32, HcDoneHead: u32, HcFmInterval: u32, HcFmRemaining: u32, HcFmNumber: u32, HcPeriodicStart: u32, HcLSTreshold: u32, HcRhDescriptorA: u32, HcRhDescriptorB: u32, HcRhStatus: u32, HcRhPortStatus1: u32, HcRhPortStatus2: u32, RESERVED0: [40]u32, Module_ID: u32, OTGIntSt: u32, OTGIntEn: u32, OTGIntSet: u32, OTGIntClr: u32, OTGStCtrl: u32, OTGTmr: u32, RESERVED1: [58]u32, USBDevIntSt: u32, USBDevIntEn: u32, USBDevIntClr: u32, USBDevIntSet: u32, USBCmdCode: u32, USBCmdData: u32, USBRxData: u32, USBTxData: u32, USBRxPLen: u32, USBTxPLen: u32, USBCtrl: u32, USBDevIntPri: u32, USBEpIntSt: u32, USBEpIntEn: u32, USBEpIntClr: u32, USBEpIntSet: u32, USBEpIntPri: u32, USBReEp: u32, USBEpInd: u32, USBMaxPSize: u32, USBDMARSt: u32, USBDMARClr: u32, USBDMARSet: u32, RESERVED2: [9]u32, USBUDCAH: u32, USBEpDMASt: u32, USBEpDMAEn: u32, USBEpDMADis: u32, USBDMAIntSt: u32, USBDMAIntEn: u32, RESERVED3: [2]u32, USBEoTIntSt: u32, USBEoTIntClr: u32, USBEoTIntSet: u32, USBNDDRIntSt: u32, USBNDDRIntClr: u32, USBNDDRIntSet: u32, USBSysErrIntSt: u32, USBSysErrIntClr: u32, USBSysErrIntSet: u32, RESERVED4: [15]u32, I2C_RX: u32, I2C_WO: u32, I2C_STS: u32, I2C_CTL: u32, I2C_CLKHI: u32, I2C_CLKLO: u32, RESERVED5: [823]u32, unnamed_0: union_unnamed_45, unnamed_1: union_unnamed_46, }; pub const LPC_EMAC_TypeDef = extern struct { MAC1: u32, MAC2: u32, IPGT: u32, IPGR: u32, CLRT: u32, MAXF: u32, SUPP: u32, TEST: u32, MCFG: u32, MCMD: u32, MADR: u32, MWTD: u32, MRDD: u32, MIND: u32, RESERVED0: [2]u32, SA0: u32, SA1: u32, SA2: u32, RESERVED1: [45]u32, Command: u32, Status: u32, RxDescriptor: u32, RxStatus: u32, RxDescriptorNumber: u32, RxProduceIndex: u32, RxConsumeIndex: u32, TxDescriptor: u32, TxStatus: u32, TxDescriptorNumber: u32, TxProduceIndex: u32, TxConsumeIndex: u32, RESERVED2: [10]u32, TSV0: u32, TSV1: u32, RSV: u32, RESERVED3: [3]u32, FlowControlCounter: u32, FlowControlStatus: u32, RESERVED4: [34]u32, RxFilterCtrl: u32, RxFilterWoLStatus: u32, RxFilterWoLClear: u32, RESERVED5: u32, HashFilterL: u32, HashFilterH: u32, RESERVED6: [882]u32, IntStatus: u32, IntEnable: u32, IntClear: u32, IntSet: u32, RESERVED7: u32, PowerDown: u32, RESERVED8: u32, Module_ID: u32, }; pub const NVIC_VECTRESET = 0; pub const NVIC_SYSRESETREQ = 2; pub const NVIC_AIRCR_VECTKEY = 0x5FA << 16; pub const NVIC_AIRCR_ENDIANESS = 15; pub const CoreDebug_DEMCR_TRCENA = 1 << 24; pub const ITM_TCR_ITMENA = 1; pub const SCS_BASE = 0xE000E000; pub const ITM_BASE = 0xE0000000; pub const CoreDebug_BASE = 0xE000EDF0; pub const SysTick_BASE = SCS_BASE + 0x0010; pub const NVIC_BASE = SCS_BASE + 0x0100; pub const SCB_BASE = SCS_BASE + 0x0D00; pub const InterruptType = @intToPtr(*volatile InterruptType_Type, SCS_BASE); pub const SCB = @intToPtr(*volatile SCB_Type, SCB_BASE); pub const SysTick = @intToPtr(*volatile SysTick_Type, SysTick_BASE); pub const NVIC = @intToPtr(*volatile NVIC_Type, NVIC_BASE); pub const ITM = @intToPtr(*volatile ITM_Type, ITM_BASE); pub const CoreDebug = @intToPtr(*volatile CoreDebug_Type, CoreDebug_BASE); pub const MPU_BASE = SCS_BASE + 0x0D90; pub const MPU = @intToPtr(*volatile MPU_Type, MPU_BASE); pub const SYSTICK_ENABLE = 0; pub const SYSTICK_TICKINT = 1; pub const SYSTICK_CLKSOURCE = 2; pub const SYSTICK_MAXCOUNT = (1 << 24) - 1; pub const FLASH_BASE = 0x00000000; pub const RAM_BASE = 0x10000000; pub const GPIO_BASE = 0x2009C000; pub const APB0_BASE = 0x40000000; pub const APB1_BASE = 0x40080000; pub const AHB_BASE = 0x50000000; pub const CM3_BASE = 0xE0000000; pub const WDT_BASE = APB0_BASE + 0x00000; pub const TIM0_BASE = APB0_BASE + 0x04000; pub const TIM1_BASE = APB0_BASE + 0x08000; pub const UART0_BASE = APB0_BASE + 0x0C000; pub const UART1_BASE = APB0_BASE + 0x10000; pub const PWM1_BASE = APB0_BASE + 0x18000; pub const I2C0_BASE = APB0_BASE + 0x1C000; pub const SPI_BASE = APB0_BASE + 0x20000; pub const RTC_BASE = APB0_BASE + 0x24000; pub const GPIOINT_BASE = APB0_BASE + 0x28080; pub const PINCON_BASE = APB0_BASE + 0x2C000; pub const SSP1_BASE = APB0_BASE + 0x30000; pub const ADC_BASE = APB0_BASE + 0x34000; pub const CANAF_RAM_BASE = APB0_BASE + 0x38000; pub const CANAF_BASE = APB0_BASE + 0x3C000; pub const CANCR_BASE = APB0_BASE + 0x40000; pub const CAN1_BASE = APB0_BASE + 0x44000; pub const CAN2_BASE = APB0_BASE + 0x48000; pub const I2C1_BASE = APB0_BASE + 0x5C000; pub const SSP0_BASE = APB1_BASE + 0x08000; pub const DAC_BASE = APB1_BASE + 0x0C000; pub const TIM2_BASE = APB1_BASE + 0x10000; pub const TIM3_BASE = APB1_BASE + 0x14000; pub const UART2_BASE = APB1_BASE + 0x18000; pub const UART3_BASE = APB1_BASE + 0x1C000; pub const I2C2_BASE = APB1_BASE + 0x20000; pub const I2S_BASE = APB1_BASE + 0x28000; pub const RIT_BASE = APB1_BASE + 0x30000; pub const MCPWM_BASE = PB1_BASE + 0x38000; pub const QEI_BASE = APB1_BASE + 0x3C000; pub const SC_BASE = APB1_BASE + 0x7C000; pub const EMAC_BASE = AHB_BASE + 0x00000; pub const GPDMA_BASE = AHB_BASE + 0x04000; pub const GPDMACH0_BASE = AHB_BASE + 0x04100; pub const GPDMACH1_BASE = AHB_BASE + 0x04120; pub const GPDMACH2_BASE = AHB_BASE + 0x04140; pub const GPDMACH3_BASE = AHB_BASE + 0x04160; pub const GPDMACH4_BASE = AHB_BASE + 0x04180; pub const GPDMACH5_BASE = AHB_BASE + 0x041A0; pub const GPDMACH6_BASE = AHB_BASE + 0x041C0; pub const GPDMACH7_BASE = AHB_BASE + 0x041E0; pub const USB_BASE = AHB_BASE + 0x0C000; pub const GPIO0_BASE = GPIO_BASE + 0x00000; pub const GPIO1_BASE = GPIO_BASE + 0x00020; pub const GPIO2_BASE = GPIO_BASE + 0x00040; pub const GPIO3_BASE = GPIO_BASE + 0x00060; pub const GPIO4_BASE = GPIO_BASE + 0x00080; pub inline fn __LPC_MODULE(comptime _Type: type, comptime _Base: u32) *volatile _Type { return @intToPtr(*volatile _Type, _Base); } pub const sc = __LPC_MODULE(LPC_SC_TypeDef, SC_BASE); pub const gpio0 = __LPC_MODULE(LPC_GPIO_TypeDef, GPIO0_BASE); pub const gpio1 = __LPC_MODULE(LPC_GPIO_TypeDef, GPIO1_BASE); pub const gpio2 = __LPC_MODULE(LPC_GPIO_TypeDef, GPIO2_BASE); pub const gpio3 = __LPC_MODULE(LPC_GPIO_TypeDef, GPIO3_BASE); pub const gpio4 = __LPC_MODULE(LPC_GPIO_TypeDef, GPIO4_BASE); pub const wdt = __LPC_MODULE(LPC_WDT_TypeDef, WDT_BASE); pub const tim0 = __LPC_MODULE(LPC_TIM_TypeDef, TIM0_BASE); pub const tim1 = __LPC_MODULE(LPC_TIM_TypeDef, TIM1_BASE); pub const tim2 = __LPC_MODULE(LPC_TIM_TypeDef, TIM2_BASE); pub const tim3 = __LPC_MODULE(LPC_TIM_TypeDef, TIM3_BASE); pub const rit = __LPC_MODULE(LPC_RIT_TypeDef, RIT_BASE); pub const uart0 = __LPC_MODULE(LPC_UART0_TypeDef, UART0_BASE); pub const uart1 = __LPC_MODULE(LPC_UART1_TypeDef, UART1_BASE); pub const uart2 = __LPC_MODULE(LPC_UART_TypeDef, UART2_BASE); pub const uart3 = __LPC_MODULE(LPC_UART_TypeDef, UART3_BASE); pub const pwm1 = __LPC_MODULE(LPC_PWM_TypeDef, PWM1_BASE); pub const i2c0 = __LPC_MODULE(LPC_I2C_TypeDef, I2C0_BASE); pub const i2c1 = __LPC_MODULE(LPC_I2C_TypeDef, I2C1_BASE); pub const i2c2 = __LPC_MODULE(LPC_I2C_TypeDef, I2C2_BASE); pub const i2s = __LPC_MODULE(LPC_I2S_TypeDef, I2S_BASE); pub const spi = __LPC_MODULE(LPC_SPI_TypeDef, SPI_BASE); pub const rtc = __LPC_MODULE(LPC_RTC_TypeDef, RTC_BASE); pub const gpioint = __LPC_MODULE(LPC_GPIOINT_TypeDef, GPIOINT_BASE); pub const pincon = __LPC_MODULE(LPC_PINCON_TypeDef, PINCON_BASE); pub const ssp0 = __LPC_MODULE(LPC_SSP_TypeDef, SSP0_BASE); pub const ssp1 = __LPC_MODULE(LPC_SSP_TypeDef, SSP1_BASE); pub const adc = __LPC_MODULE(LPC_ADC_TypeDef, ADC_BASE); pub const dac = __LPC_MODULE(LPC_DAC_TypeDef, DAC_BASE); pub const canaf_ram = __LPC_MODULE(LPC_CANAF_RAM_TypeDef, CANAF_RAM_BASE); pub const canaf = __LPC_MODULE(LPC_CANAF_TypeDef, CANAF_BASE); pub const cancr = __LPC_MODULE(LPC_CANCR_TypeDef, CANCR_BASE); pub const can1 = __LPC_MODULE(LPC_CAN_TypeDef, CAN1_BASE); pub const can2 = __LPC_MODULE(LPC_CAN_TypeDef, CAN2_BASE); pub const mcpwm = __LPC_MODULE(LPC_MCPWM_TypeDef, MCPWM_BASE); pub const qei = __LPC_MODULE(LPC_QEI_TypeDef, QEI_BASE); pub const emac = __LPC_MODULE(LPC_EMAC_TypeDef, EMAC_BASE); pub const gpdma = __LPC_MODULE(LPC_GPDMA_TypeDef, GPDMA_BASE); pub const gpdmach0 = __LPC_MODULE(LPC_GPDMACH_TypeDef, GPDMACH0_BASE); pub const gpdmach1 = __LPC_MODULE(LPC_GPDMACH_TypeDef, GPDMACH1_BASE); pub const gpdmach2 = __LPC_MODULE(LPC_GPDMACH_TypeDef, GPDMACH2_BASE); pub const gpdmach3 = __LPC_MODULE(LPC_GPDMACH_TypeDef, GPDMACH3_BASE); pub const gpdmach4 = __LPC_MODULE(LPC_GPDMACH_TypeDef, GPDMACH4_BASE); pub const gpdmach5 = __LPC_MODULE(LPC_GPDMACH_TypeDef, GPDMACH5_BASE); pub const gpdmach6 = __LPC_MODULE(LPC_GPDMACH_TypeDef, GPDMACH6_BASE); pub const gpdmach7 = __LPC_MODULE(LPC_GPDMACH_TypeDef, GPDMACH7_BASE); pub const usb = __LPC_MODULE(LPC_USB_TypeDef, USB_BASE);