Merge: Do not display test suite modules in Nitdoc
[nit.git] / src / compiler / pnacl_platform.nit
1 # This file is part of NIT ( http://www.nitlanguage.org )
2 #
3 # Copyright 2014 Johan Kayser <kayser.johan@gmail.com>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Compile program for the PNaCl platform
18 module pnacl_platform
19
20 import platform
21 import abstract_compiler
22
23 redef class ToolContext
24 redef fun platform_from_name(name)
25 do
26 if name == "pnacl" then return new PnaclPlatform
27 return super
28 end
29 end
30
31 class PnaclPlatform
32 super Platform
33
34 redef fun supports_libunwind do return false
35
36 redef fun no_main do return true
37
38 redef fun toolchain(toolcontext) do return new PnaclToolchain(toolcontext)
39 end
40
41 class PnaclToolchain
42 super MakefileToolchain
43
44 redef fun write_files(compiler, compile_dir, cfiles)
45 do
46 var app_name = compiler.mainmodule.name
47
48 # create compile_dir
49 var dir = compile_dir
50 if not dir.file_exists then dir.mkdir
51
52 # compile normal C files
53 super(compiler, compile_dir, cfiles)
54
55 # Gather extra C files generated elsewhere than in super
56 for f in compiler.extern_bodies do
57 if f isa ExternCFile then cfiles.add(f.filename.basename(""))
58 end
59
60 # Outname
61 var outname = toolcontext.opt_output.value
62 if outname == null then outname = "{compiler.mainmodule.name}"
63
64 var ofiles = new Array[String]
65 for cfile in cfiles do ofiles.add(cfile.substring(0, cfile.length-2) + ".o")
66
67 ## Generate makefile
68 var file = "{dir}/Makefile"
69 """
70 # This file was generated by Nit, any modification will be lost.
71
72 # Get pepper directory for toolchain and includes.
73 #
74 # If NACL_SDK_ROOT is not set, then assume it can be found five directories up.
75 #
76 THIS_MAKEFILE := $(abspath $(lastword $(MAKEFILE_LIST)))
77 NACL_SDK_ROOT ?= $(abspath $(dir $(THIS_MAKEFILE))../../../..)
78
79 # Project Build flags
80 WARNINGS := -Wno-long-long -Wno-unused-value -Wno-unused-label -Wno-duplicate-decl-specifier -Wno-switch -Wno-embedded-directive
81 CXXFLAGS := -pthread $(WARNINGS)
82
83 CXXFLAGS += -g -O0 # Debug
84 # CXXFLAGS += -O3 # Release
85
86 #
87 # Compute tool paths
88 #
89 GETOS := python $(NACL_SDK_ROOT)/tools/getos.py
90 OSHELPERS = python $(NACL_SDK_ROOT)/tools/oshelpers.py
91 OSNAME := $(shell $(GETOS))
92
93 PNACL_TC_PATH := $(abspath $(NACL_SDK_ROOT)/toolchain/$(OSNAME)_pnacl)
94 PNACL_CXX := $(PNACL_TC_PATH)/bin/pnacl-clang
95 PNACL_FINALIZE := $(PNACL_TC_PATH)/bin/pnacl-finalize
96 CXXFLAGS += -I$(NACL_SDK_ROOT)/include -I$(NACL_SDK_ROOT)/include/pnacl
97 LDFLAGS := -L$(NACL_SDK_ROOT)/lib/pnacl/Release -lppapi_cpp -lppapi -lm
98
99 #
100 # Disable DOS PATH warning when using Cygwin based tools Windows
101 #
102 CYGWIN ?= nodosfilewarning
103 export CYGWIN
104
105 # Declare the ALL target first, to make the 'all' target the default build
106 all: ../{{{outname}}}/{{{app_name}}}.pexe
107
108 .c.o:
109 $(PNACL_CXX) -c $< -g -O0 $(CXXFLAGS)
110
111 {{{app_name}}}.pexe: {{{ofiles.join(" ")}}}
112 $(PNACL_CXX) -o $@ $^ $(LDFLAGS)
113
114 ../{{{outname}}}/{{{app_name}}}.pexe: {{{app_name}}}.pexe
115 $(PNACL_FINALIZE) -o $@ $<
116 """.write_to_file(file)
117
118 ### generate the minimal index.html
119 if not outname.file_exists then outname.mkdir
120 file = "{outname}/index.html"
121
122 if not file.file_exists then """
123 <!DOCTYPE html>
124 <html>
125 <!--
126 This file was generated by Nit, any modification will be lost.
127 -->
128 <head>
129 <title>{{{app_name}}}</title>
130 <script src="js/pnacl_js.js"></script>
131 </head>
132 <body onload="pageDidLoad()">
133 <h1>PNaCl : Minimal HTML for {{{app_name}}}</h1>
134 <p>
135 <!--
136 Load the published pexe.
137 Note: Since this module does not use any real-estate in the browser, its
138 width and height are set to 0.
139
140 Note: The <embed> element is wrapped inside a <div>, which has both a 'load'
141 and a 'message' event listener attached. This wrapping method is used
142 instead of attaching the event listeners directly to the <embed> element to
143 ensure that the listeners are active before the NaCl module 'load' event
144 fires. This also allows you to use PPB_Messaging.PostMessage() (in C) or
145 pp::Instance.PostMessage() (in C++) from within the initialization code in
146 your module.
147 -->
148 <div id="listener">
149 <script type="text/javascript">
150 var listener = document.getElementById('listener');
151 listener.addEventListener('load', moduleDidLoad, true);
152 listener.addEventListener('message', handleMessage, true);
153 </script>
154
155 <embed id="{{{app_name}}}"
156 width=0 height=0
157 src="{{{app_name}}}.nmf"
158 type="application/x-pnacl" />
159 </div>
160 </p>
161 <h2>Status <code id="statusField">NO-STATUS</code></h2>
162 </body>
163 </html>
164 """.write_to_file(file)
165
166 ### generate pnacl_js.js in a folder named 'js'
167 dir = "{outname}/js/"
168 if not dir.file_exists then dir.mkdir
169 file = "{dir}/pnacl_js.js"
170 if not file.file_exists then """
171 // This file was generated by Nit, any modification will be lost.
172
173 {{{app_name}}}Module = null; // Global application object.
174 statusText = 'NO-STATUS';
175
176 // Indicate load success.
177 function moduleDidLoad() {
178 {{{app_name}}}Module = document.getElementById('{{{app_name}}}');
179 updateStatus('SUCCESS');
180 // Send a message to the Native Client module like that
181 //{{{app_name}}}Module.postMessage('Hello World');
182 }
183
184 // The 'message' event handler. This handler is fired when the NaCl module
185 // posts a message to the browser by calling PPB_Messaging.PostMessage()
186 // (in C) or pp::Instance.PostMessage() (in C++). This implementation
187 // simply displays the content of the message in an alert panel.
188 function handleMessage(message_event) {
189 console.log(message_event.data);
190 }
191
192 // If the page loads before the Native Client module loads, then set the
193 // status message indicating that the module is still loading. Otherwise,
194 // do not change the status message.
195 function pageDidLoad() {
196 if ({{{app_name}}}Module == null) {
197 updateStatus('LOADING...');
198 } else {
199 // It's possible that the Native Client module onload event fired
200 // before the page's onload event. In this case, the status message
201 // will reflect 'SUCCESS', but won't be displayed. This call will
202 // display the current message.
203 updateStatus();
204 }
205 }
206
207 // Set the global status message. If the element with id 'statusField'
208 // exists, then set its HTML to the status message as well.
209 // opt_message The message test. If this is null or undefined, then
210 // attempt to set the element with id 'statusField' to the value of
211 // |statusText|.
212 function updateStatus(opt_message) {
213 if (opt_message)
214 statusText = opt_message;
215 var statusField = document.getElementById('statusField');
216 if (statusField) {
217 statusField.innerHTML = statusText;
218 }
219 }
220 """.write_to_file(file)
221
222 ### generate the manifest file : app_name.nmf
223 # used to point the HTML to the Native Client module
224 # and optionally provide additional commands to the PNaCl translator in Chrome
225 file = "{outname}/{app_name}.nmf"
226 """
227 {
228 "program": {
229 "portable": {
230 "pnacl-translate": {
231 "url": "{{{app_name}}}.pexe"
232 }
233 }
234 }
235 }
236 """.write_to_file(file)
237 end
238
239 redef fun write_makefile(compiler, compile_dir, cfiles)
240 do
241 # Do nothing, already done in `write_files`
242 end
243
244 redef fun compile_c_code(compiler, compile_dir)
245 do
246 # Generate the pexe
247 toolcontext.exec_and_check(["make", "-C", compile_dir, "-j", "4"], "PNaCl project error")
248 end
249 end