Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/xmake/xmake/core | repos/xmake/xmake/core/ui/event.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file event.lua
--
-- load modules
local log = require("ui/log")
local object = require("ui/object")
-- define module
local event = event or object { _init = {"type", "command", "extra"} }
-- register event types
function event:register(tag, ...)
local base = self[tag] or 0
local enums = {...}
local n = #enums
for i = 1, n do
self[enums[i]] = i + base
end
self[tag] = base + n
end
-- is key?
function event:is_key(key_name)
return self.type == event.ev_keyboard and self.key_name == key_name
end
-- is command event: cm_xxx?
function event:is_command(command)
return self.type == event.ev_command and self.command == command
end
-- dump event
function event:dump()
if self.type == event.ev_keyboard then
log:print("event(key): %s %s ..", self.key_name, self.key_code)
elseif self.type == event.ev_command then
log:print("event(cmd): %s ..", self.command)
else
log:print("event(%s): ..", self.type)
end
end
-- register event types, event.ev_keyboard = 1, event.ev_mouse = 2, ... , event.ev_idle = 5, event.ev_max = 5
event:register("ev_max", "ev_keyboard", "ev_mouse", "ev_command", "ev_text", "ev_idle")
-- register command event types (ev_command)
event:register("cm_max", "cm_quit", "cm_exit", "cm_enter")
-- define keyboard event
--
-- keyname = key name
-- keycode = key code
-- keymeta = ALT key was pressed
--
event.keyboard = object {_init = { "key_code", "key_name", "key_meta" }, type = event.ev_keyboard}
-- define mouse event
--
-- btn_name = button number and event type
-- btn_code = mouse event code
-- x, y = coordinates
--
event.mouse = object {_init = { "btn_code", "x", "y", "btn_name" }, type = event.ev_mouse}
-- define command event
event.command = object {_init = { "command", "extra" }, type = event.ev_command}
-- define idle event
event.idle = object {_init = {}, type = event.ev_idle}
-- return module
return event
|
0 | repos/xmake/xmake/core | repos/xmake/xmake/core/ui/program.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file program.lua
--
-- load modules
local log = require("ui/log")
local rect = require("ui/rect")
local point = require("ui/point")
local panel = require("ui/panel")
local event = require("ui/event")
local curses = require("ui/curses")
local action = require("ui/action")
-- define module
local program = program or panel()
-- init program
function program:init(name, argv)
-- init main window
local main_window = self:main_window()
-- disable echo
curses.echo(false)
-- disable input cache
curses.cbreak(true)
-- disable newline
curses.nl(false)
-- init mouse support
if curses.has_mouse() then
-- curses.ALL_MOUSE_EVENTS may be set to mask unused events
curses.mousemask(curses.ALL_MOUSE_EVENTS)
end
-- init colors
if (curses.has_colors()) then
curses.start_color()
end
-- disable main window cursor
main_window:leaveok(false)
-- enable special key map
main_window:keypad(true)
-- non-block for getch()
main_window:nodelay(true)
-- get 8-bits character for getch()
main_window:meta(true)
-- save the current arguments
self._ARGV = argv
-- init panel
panel.init(self, name, rect {0, 0, curses.columns(), curses.lines()})
-- init state
self:state_set("focused", true)
self:state_set("selected", true)
end
-- exit program
function program:exit()
-- exit panel
panel.exit(self)
-- (attempt to) make sure the screen will be cleared
-- if not restored by the curses driver
self:main_window():clear()
self:main_window():noutrefresh()
curses.doupdate()
-- exit curses
assert(not curses.isdone())
curses.done()
end
-- get the main window
function program:main_window()
-- init main window if not exists
local main_window = self._MAIN_WINDOW
if not main_window then
-- init main window
main_window = curses.init()
assert(main_window, "cannot init main window!")
-- save main window
self._MAIN_WINDOW = main_window
end
return main_window
end
-- get the command arguments
function program:argv()
return self._ARGV
end
-- get the current event
function program:event()
-- get event from the event queue first
local event_queue = self._EVENT_QUEUE
if event_queue then
local e = event_queue[1]
if e then
table.remove(event_queue, 1)
return e
end
end
-- get input key
local key_code, key_name, key_meta = self:_input_key()
if key_code then
if curses.KEY_MOUSE and key_code == curses.KEY_MOUSE then
local code, x, y = curses.getmouse()
local name = self:_mouse_map()[code]
return event.mouse{code, x, y, name}
end
return event.keyboard{key_code, key_name, key_meta}
end
end
-- on event
function program:on_event(e)
-- get the top focused view
local focused_view = self
while focused_view:type() == "panel" and focused_view:current() do
focused_view = focused_view:current()
end
-- do event for focused views
while focused_view and focused_view ~= self do
local parent = focused_view:parent()
if focused_view:on_event(e) then
return true
end
focused_view = parent
end
-- do event
if e.type == event.ev_keyboard then
-- resize?
if e.key_name == "Resize" then
self:bounds_set(rect {0, 0, curses.columns(), curses.lines()})
return true
-- refresh?
elseif e.key_name == "Refresh" then
self:invalidate()
return true
-- ctrl+c? quit program
elseif e.key_name == "CtrlC" then
self:send("cm_exit")
return true
end
-- quit program?
elseif event.is_command(e, "cm_exit") then
self:quit()
return true
-- mouse events
elseif e.type == event.ev_mouse and curses.has_mouse() and self:option("mouseable") then
if e.btn_name == "BUTTON1_CLICKED" or e.btn_name == "BUTTON1_DOUBLE_CLICKED" then
self:action_on(action.ac_on_clicked, e.x, e.y)
end
end
end
-- put an event to view
function program:put_event(e)
-- init event queue
self._EVENT_QUEUE = self._EVENT_QUEUE or {}
-- put event to queue
table.insert(self._EVENT_QUEUE, e)
end
-- send command
function program:send(command, extra)
self:put_event(event.command {command, extra})
end
-- quit program
function program:quit()
self:send("cm_quit")
end
-- run program loop
function program:loop(argv)
-- do message loop
local e = nil
local sleep = true
while true do
-- get the current event
e = self:event()
-- do event
if e then
event.dump(e)
self:on_event(e)
sleep = false
else
-- do idle event
self:on_event(event.idle())
sleep = true
end
-- quit?
if e and event.is_command(e, "cm_quit") then
break
end
-- resize views
if self:state("resize") then
self:on_resize()
end
-- draw views
self:on_draw()
-- refresh views
if self:state("refresh") then
self:on_refresh()
end
-- wait some time, 50ms
if sleep then
curses.napms(50)
end
end
end
-- refresh program
function program:on_refresh()
-- refresh views
panel.on_refresh(self)
-- trace
log:print("%s: refresh ..", self)
-- get main window
local main_window = curses.main_window()
-- refresh main window
self:window():copy(main_window, 0, 0, 0, 0, self:height() - 1, self:width() - 1)
-- refresh cursor
self:_refresh_cursor()
-- mark as refresh
main_window:noutrefresh()
-- do update
curses.doupdate()
end
-- get key map
function program:_key_map()
if not self._KEYMAP then
self._KEYMAP =
{
[ 1] = "CtrlA", [ 2] = "CtrlB", [ 3] = "CtrlC",
[ 4] = "CtrlD", [ 5] = "CtrlE", [ 6] = "CtrlF",
[ 7] = "CtrlG", [ 8] = "CtrlH", [ 9] = "CtrlI",
[10] = "CtrlJ", [11] = "CtrlK", [12] = "CtrlL",
[13] = "CtrlM", [14] = "CtrlN", [15] = "CtrlO",
[16] = "CtrlP", [17] = "CtrlQ", [18] = "CtrlR",
[19] = "CtrlS", [20] = "CtrlT", [21] = "CtrlU",
[22] = "CtrlV", [23] = "CtrlW", [24] = "CtrlX",
[25] = "CtrlY", [26] = "CtrlZ",
[ 8] = "Backspace",
[ 9] = "Tab",
[ 10] = "Enter",
[ 13] = "Enter",
[ 27] = "Esc",
[ 31] = "CtrlBackspace",
[127] = "Backspace",
[curses.KEY_DOWN ] = "Down",
[curses.KEY_UP ] = "Up",
[curses.KEY_LEFT ] = "Left",
[curses.KEY_RIGHT ] = "Right",
[curses.KEY_HOME ] = "Home",
[curses.KEY_END ] = "End",
[curses.KEY_NPAGE ] = "PageDown",
[curses.KEY_PPAGE ] = "PageUp",
[curses.KEY_IC ] = "Insert",
[curses.KEY_DC ] = "Delete",
[curses.KEY_BACKSPACE ] = "Backspace",
[curses.KEY_F1 ] = "F1",
[curses.KEY_F2 ] = "F2",
[curses.KEY_F3 ] = "F3",
[curses.KEY_F4 ] = "F4",
[curses.KEY_F5 ] = "F5",
[curses.KEY_F6 ] = "F6",
[curses.KEY_F7 ] = "F7",
[curses.KEY_F8 ] = "F8",
[curses.KEY_F9 ] = "F9",
[curses.KEY_F10 ] = "F10",
[curses.KEY_F11 ] = "F11",
[curses.KEY_F12 ] = "F12",
[curses.KEY_RESIZE ] = "Resize",
[curses.KEY_REFRESH ] = "Refresh",
[curses.KEY_BTAB ] = "ShiftTab",
[curses.KEY_SDC ] = "ShiftDelete",
[curses.KEY_SIC ] = "ShiftInsert",
[curses.KEY_SEND ] = "ShiftEnd",
[curses.KEY_SHOME ] = "ShiftHome",
[curses.KEY_SLEFT ] = "ShiftLeft",
[curses.KEY_SRIGHT ] = "ShiftRight",
-- register virtual keys
--
-- @see https://github.com/xmake-io/xmake/issues/1610
-- https://github.com/wmcbrine/PDCurses/blob/HEAD/curses.h#L766-L774
[curses.KEY_C2 or -1 ] = "Down",
[curses.KEY_A2 or -1 ] = "Up",
[curses.KEY_B1 or -1 ] = "Left",
[curses.KEY_B3 or -1 ] = "Right"
}
end
return self._KEYMAP
end
-- get mouse map
function program:_mouse_map()
if not self._MOUSEMAP then
-- must be defined dynamically since it depends
-- on curses implementation
self._MOUSEMAP = {}
for n, v in pairs(curses) do
if (n:match('MOUSE') and n ~= 'KEY_MOUSE') or n:match('BUTTON') then
self._MOUSEMAP[v] = n
end
end
end
return self._MOUSEMAP
end
-- get input key
function program:_input_key()
-- get main window
local main_window = self:main_window()
-- get input character
local ch = main_window:getch()
if not ch then
return
end
-- this is the time limit in ms within Esc-key sequences are detected as
-- Alt-letter sequences. useful when we can't generate Alt-letter sequences
-- directly. sometimes this pause may be longer than expected since the
-- curses driver may also pause waiting for another key (ncurses-5.3)
local esc_delay = 400
-- get key map
local key_map = self:_key_map()
-- is alt?
local alt = ch == 27
if alt then
-- get the next input character
ch = main_window:getch()
if not ch then
-- since there is no way to know the time with millisecond precision
-- we pause the the program until we get a key or the time limit
-- is reached
local t = 0
while true do
ch = main_window:getch()
if ch or t >= esc_delay then
break
end
-- wait some time, 50ms
curses.napms(50)
t = t + 50
end
-- nothing was typed... return Esc
if not ch then
return 27, "Esc", false
end
end
if ch > 96 and ch < 123 then
ch = ch - 32
end
end
-- map character to key
local key = key_map[ch]
local key_name = nil
if key then
key_name = alt and "Alt".. key or key
elseif (ch < 256) then
key_name = alt and "Alt".. string.char(ch) or string.char(ch)
else
return ch, '(noname)', alt
end
-- return key info
return ch, key_name, alt
end
-- refresh cursor
function program:_refresh_cursor()
-- get the top focused view
local focused_view = self
while focused_view:type() == "panel" and focused_view:current() do
focused_view = focused_view:current()
end
-- get the cursor state of the top focused view
local cursor_state = 0
if focused_view and focused_view:state("cursor_visible") then
cursor_state = focused_view:state("block_cursor") and 2 or 1
end
-- get the cursor position
local cursor = focused_view and focused_view:cursor()() or point{0, 0}
if cursor_state ~= 0 then
local v = focused_view
while v:parent() do
-- update the cursor position
cursor:addxy(v:bounds().sx, v:bounds().sy)
-- is cursor visible?
if cursor.x < 0 or cursor.y < 0 or cursor.x >= v:parent():width() or cursor.y >= v:parent():height() then
cursor_state = 0
break
end
-- get the parent view
v = v:parent()
end
end
-- update the cursor state
curses.cursor_set(cursor_state)
-- get main window
local main_window = curses.main_window()
-- trace
log:print("cursor(%s): %s, %d", focused_view, cursor, cursor_state)
-- move cursor position
if cursor_state ~= 0 then
main_window:move(cursor.y, cursor.x)
else
main_window:move(self:height() - 1, self:width() - 1)
end
end
-- return module
return program
|
0 | repos/xmake/xmake/rules/plugin | repos/xmake/xmake/rules/plugin/compile_commands/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- update compile_commandss.json automatically
--
-- @code
-- add_rules("plugin.compile_commands.autoupdate", {outputdir = ".vscode", lsp = "clangd"})
-- target("test")
-- set_kind("binary")
-- add_files("src/*.c")
-- @endcode
--
rule("plugin.compile_commands.autoupdate")
set_kind("project")
after_build(function (opt)
-- imports
import("core.project.config")
import("core.project.depend")
import("core.project.project")
import("core.base.task")
-- we should not update it if we are installing xmake package
if os.getenv("XMAKE_IN_XREPO") then
return
end
-- run only once for all xmake process
local tmpfile = path.join(config.buildir(), ".gens", "rules", "plugin.compile_commands.autoupdate")
local dependfile = tmpfile .. ".d"
local lockfile = io.openlock(tmpfile .. ".lock")
if lockfile:trylock() then
local outputdir
local lsp
local sourcefiles = {}
for _, target in pairs(project.targets()) do
table.join2(sourcefiles, target:sourcefiles(), (target:headerfiles()))
local extraconf = target:extraconf("rules", "plugin.compile_commands.autoupdate")
if extraconf then
outputdir = extraconf.outputdir
lsp = extraconf.lsp
end
end
table.sort(sourcefiles)
depend.on_changed(function ()
-- we use task instead of os.exec("xmake") to avoid the project lock
local filename = "compile_commands.json"
local filepath = outputdir and path.join(outputdir, filename) or filename
task.run("project", {kind = "compile_commands", outputdir = outputdir, lsp = lsp})
print("compile_commands.json updated!")
end, {dependfile = dependfile,
files = table.join(project.allfiles(), config.filepath()),
values = sourcefiles})
lockfile:close()
end
end)
|
0 | repos/xmake/xmake/rules/plugin | repos/xmake/xmake/rules/plugin/vsxmake/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- update vsxmake project automatically
--
-- @code
-- add_rules("plugin.vsxmake.autoupdate")
-- target("test")
-- set_kind("binary")
-- add_files("src/*.c")
-- @endcode
--
rule("plugin.vsxmake.autoupdate")
set_kind("project")
after_build(function (opt)
-- imports
import("core.project.config")
import("core.project.depend")
import("core.project.project")
import("core.cache.localcache")
import("core.base.task")
-- run only once for all xmake process in vs
local tmpfile = path.join(config.buildir(), ".gens", "rules", "plugin.vsxmake.autoupdate")
local dependfile = tmpfile .. ".d"
local lockfile = io.openlock(tmpfile .. ".lock")
local kind = localcache.get("vsxmake", "kind")
local modes = localcache.get("vsxmake", "modes")
local archs = localcache.get("vsxmake", "archs")
local outputdir = localcache.get("vsxmake", "outputdir")
if lockfile:trylock() then
if os.getenv("XMAKE_IN_VSTUDIO") and not os.getenv("XMAKE_IN_XREPO") then
local sourcefiles = {}
for _, target in pairs(project.targets()) do
table.join2(sourcefiles, target:sourcefiles(), (target:headerfiles()))
end
table.sort(sourcefiles)
depend.on_changed(function ()
-- we use task instead of os.exec("xmake") to avoid the project lock
print("update vsxmake project -k %s %s ..", kind or "vsxmake", outputdir or "")
task.run("project", {kind = kind or "vsxmake", modes = modes, archs = archs, outputdir = outputdir})
print("update vsxmake project ok")
end, {dependfile = dependfile,
files = project.allfiles(),
values = sourcefiles})
end
lockfile:close()
end
end)
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/module/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
rule("module.binary")
on_load(function (target)
import("core.project.config")
target:set("kind", "binary")
target:set("basename", "module_" .. target:name())
target:set("targetdir", config.buildir())
end)
rule("module.shared")
add_deps("utils.symbols.export_all")
on_load(function (target)
import("core.project.config")
target:set("kind", "shared")
target:set("basename", "module_" .. target:name())
target:set("targetdir", config.buildir())
target:set("strip", "none")
target:add("includedirs", path.join(os.programdir(), "scripts", "module"))
target:add("includedirs", path.join(os.programdir(), "scripts", "module", "luawrap"))
if xmake.luajit() then
target:add("defines", "XMI_USE_LUAJIT")
end
end)
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/nim/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: nim.build
rule("nim.build")
set_sourcekinds("nc")
on_load(function (target)
local cachedir = path.join(target:autogendir(), "nimcache")
target:add("ncflags", "--nimcache:" .. cachedir, {force = true})
end)
on_build("build.target")
-- define rule: nim
rule("nim")
-- add build rules
add_deps("nim.build")
-- inherit links and linkdirs of all dependent targets by default
add_deps("utils.inherit.links")
|
0 | repos/xmake/xmake/rules/nim | repos/xmake/xmake/rules/nim/build/target.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file target.lua
--
-- imports
import("core.base.option")
import("core.base.hashset")
import("core.tool.compiler")
import("core.project.depend")
import("utils.progress")
-- build the source files
function build_sourcefiles(target, sourcebatch, opt)
-- get the target file
local targetfile = target:targetfile()
-- get source files and kind
local sourcefiles = sourcebatch.sourcefiles
local sourcekind = sourcebatch.sourcekind
-- get depend file
local dependfile = target:dependfile(targetfile)
-- load compiler
local compinst = compiler.load(sourcekind, {target = target})
-- get compile flags
local compflags = compinst:compflags({target = target})
-- load dependent info
local dependinfo = option.get("rebuild") and {} or (depend.load(dependfile) or {})
-- need build this object?
local depvalues = {compinst:program(), compflags}
if not depend.is_changed(dependinfo, {lastmtime = os.mtime(targetfile), values = depvalues}) then
return
end
-- trace progress into
progress.show(opt.progress, "${color.build.target}linking.$(mode) %s", path.filename(targetfile))
-- trace verbose info
vprint(compinst:buildcmd(sourcefiles, targetfile, {target = target, compflags = compflags}))
-- flush io buffer to update progress info
io.flush()
-- compile it
dependinfo.files = {}
assert(compinst:build(sourcefiles, targetfile, {target = target, dependinfo = dependinfo, compflags = compflags}))
-- update files and values to the dependent file
dependinfo.values = depvalues
table.join2(dependinfo.files, sourcefiles)
depend.save(dependinfo, dependfile)
end
-- build target
function main(target, opt)
-- @note only support one source kind!
local sourcebatches = target:sourcebatches()
if sourcebatches then
local sourcebatch = sourcebatches["nim.build"]
if sourcebatch then
build_sourcefiles(target, sourcebatch, opt)
end
end
end
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/xmake_cli/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: xmake cli program
rule("xmake.cli")
on_load(function (target)
target:set("kind", "binary")
assert(target:pkg("libxmake"), 'please add_packages("libxmake") to target(%s) first!', target:name())
end)
after_install(function (target)
-- get lua script directory
local scriptdir = path.join(target:scriptdir(), "src")
if not os.isfile(path.join(scriptdir, "lua", "main.lua")) then
import("lib.detect.find_path")
scriptdir = find_path("lua/main.lua", path.join(target:scriptdir(), "**"))
end
-- install xmake-core lua scripts first
local libxmake = target:pkg("libxmake")
local programdir = path.join(libxmake:installdir(), "share", "xmake")
local installdir = path.join(target:installdir(), "share", target:name())
assert(os.isdir(programdir), "%s not found!", programdir)
if not os.isdir(installdir) then
os.mkdir(installdir)
end
if scriptdir then
os.mkdir(path.join(installdir, "plugins"))
os.vcp(path.join(programdir, "core"), installdir)
os.vcp(path.join(programdir, "modules"), installdir)
os.vcp(path.join(programdir, "themes"), installdir)
os.vcp(path.join(programdir, "plugins", "lua"), path.join(installdir, "plugins"))
os.vcp(path.join(programdir, "actions", "build", "xmake.lua"), path.join(installdir, "actions", "build", "xmake.lua"))
else
os.vcp(path.join(programdir, "*"), installdir)
end
-- install xmake/cli lua scripts
--
-- - bin
-- - hello
-- - share
-- - hello
-- - modules
-- - lua
-- - main.lua
--
if scriptdir then
os.vcp(path.join(scriptdir, "lua"), path.join(installdir, "modules"))
end
end)
before_run(function (target)
local scriptdir = path.join(target:scriptdir(), "src")
if not os.isfile(path.join(scriptdir, "lua", "main.lua")) then
import("lib.detect.find_path")
scriptdir = find_path("lua/main.lua", path.join(target:scriptdir(), "**"))
end
if scriptdir then
os.setenv("XMAKE_MODULES_DIR", scriptdir)
end
local libxmake = target:pkg("libxmake")
local programdir = path.join(libxmake:installdir(), "share", "xmake")
assert(os.isdir(programdir), "%s not found!", programdir)
os.setenv("XMAKE_PROGRAM_DIR", programdir)
end)
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/pascal/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: pascal.build
rule("pascal.build")
set_sourcekinds("pc")
on_build("build.target")
-- define rule: pascal
rule("pascal")
-- add build rules
add_deps("pascal.build")
-- inherit links and linkdirs of all dependent targets by default
add_deps("utils.inherit.links")
|
0 | repos/xmake/xmake/rules/pascal | repos/xmake/xmake/rules/pascal/build/target.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file target.lua
--
-- imports
import("core.base.option")
import("core.base.hashset")
import("core.theme.theme")
import("core.tool.compiler")
import("core.project.depend")
import("utils.progress")
-- build the source files
function build_sourcefiles(target, sourcebatch, opt)
-- is verbose?
local verbose = option.get("verbose")
-- get the target file
local targetfile = target:targetfile()
-- get source files and kind
local sourcefiles = sourcebatch.sourcefiles
local sourcekind = sourcebatch.sourcekind
-- get depend file
local dependfile = target:dependfile(targetfile)
-- load compiler
local compinst = compiler.load(sourcekind, {target = target})
-- get compile flags
local compflags = compinst:compflags({target = target})
-- load dependent info
local dependinfo = option.get("rebuild") and {} or (depend.load(dependfile) or {})
-- need build this object?
local depvalues = {compinst:program(), compflags}
if not depend.is_changed(dependinfo, {lastmtime = os.mtime(targetfile), values = depvalues}) then
return
end
-- trace progress into
progress.show(opt.progress, "${color.build.target}linking.$(mode) %s", path.filename(targetfile))
-- trace verbose info
if verbose then
print(compinst:buildcmd(sourcefiles, targetfile, {target = target, compflags = compflags}))
end
-- compile it
dependinfo.files = {}
assert(compinst:build(sourcefiles, targetfile, {target = target, dependinfo = dependinfo, compflags = compflags}))
-- update files and values to the dependent file
dependinfo.values = depvalues
table.join2(dependinfo.files, sourcefiles)
depend.save(dependinfo, dependfile)
end
-- build target
function main(target, opt)
-- @note only support one source kind!
for _, sourcebatch in pairs(target:sourcebatches()) do
if sourcebatch.sourcekind == "pc" then
build_sourcefiles(target, sourcebatch, opt)
break
end
end
end
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/cuda/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: cuda.build
rule("cuda.build")
set_sourcekinds("cu")
add_deps("cuda.build.devlink")
on_build_files("private.action.build.object", {batch = true})
on_config(function (target)
-- https://github.com/xmake-io/xmake/issues/4755
local cu_ccbin = target:tool("cu-ccbin")
if cu_ccbin then
target:add("cuflags", "-ccbin=" .. os.args(cu_ccbin), {force = true})
target:add("culdflags", "-ccbin=" .. os.args(cu_ccbin), {force = true})
end
end)
-- define rule: cuda
rule("cuda")
-- add build rules
add_deps("cuda.build", "cuda.gencodes")
-- inherit links and linkdirs of all dependent targets by default
add_deps("utils.inherit.links")
|
0 | repos/xmake/xmake/rules/cuda | repos/xmake/xmake/rules/cuda/env/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
rule("cuda.env")
on_load(function (target)
import("detect.sdks.find_cuda")
local cuda = assert(find_cuda(nil, {verbose = true}), "Cuda SDK not found!")
if cuda then
target:data_set("cuda", cuda)
end
end)
after_load(function (target)
import("core.platform.platform")
-- get cuda sdk
local cuda = assert(target:data("cuda"), "Cuda SDK not found!")
-- add arch
if target:is_arch("i386", "x86") then
target:add("cuflags", "-m32", {force = true})
target:add("culdflags", "-m32", {force = true})
else
target:add("cuflags", "-m64", {force = true})
target:add("culdflags", "-m64", {force = true})
end
-- add rdc, @see https://github.com/xmake-io/xmake/issues/1975
if target:values("cuda.rdc") ~= false then
target:add("cuflags", "-rdc=true")
end
-- add links
target:add("syslinks", "cudadevrt")
local cudart = false
for _, link in ipairs(table.join(target:get("links") or {}, target:get("syslinks"))) do
if link == "cudart" or link == "cudart_static" then
cudart = true
break
end
end
if not cudart then
target:add("syslinks", "cudart_static")
end
if target:is_plat("linux") then
target:add("syslinks", "rt", "pthread", "dl")
end
target:add("linkdirs", cuda.linkdirs)
target:add("rpathdirs", cuda.linkdirs)
-- add includedirs
target:add("includedirs", cuda.includedirs)
end)
before_run(function (target)
import("core.project.config")
import("lib.detect.find_tool")
local debugger = config.get("debugger")
if not debugger then
local cudagdb = find_tool("cudagdb")
if cudagdb then
config.set("debugger", cudagdb.program)
end
end
end)
|
0 | repos/xmake/xmake/rules/cuda | repos/xmake/xmake/rules/cuda/devlink/devlink.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file devlink.lua
--
-- imports
import("core.base.option")
import("core.theme.theme")
import("core.project.config")
import("core.project.depend")
import("core.tool.linker")
import("core.platform.platform")
import("utils.progress")
-- @see https://devblogs.nvidia.com/separate-compilation-linking-cuda-device-code/
function main(target, opt)
-- disable devlink?
--
-- @note cuda.build.devlink value will be deprecated
--
local devlink = target:policy("build.cuda.devlink") or target:values("cuda.build.devlink")
if devlink == false then
return
end
-- only for binary/shared by default
-- https://github.com/xmake-io/xmake/issues/1976
if not (devlink == true or target:is_binary() or target:is_shared()) then
return
end
-- load linker instance
local linkinst = linker.load("gpucode", "cu", {target = target})
-- init culdflags
local culdflags = {"-dlink"}
-- add shared flag
if target:is_shared() then
table.insert(culdflags, "-shared")
end
-- get link flags
local linkflags = linkinst:linkflags({target = target, configs = {force = {culdflags = culdflags}}})
-- get target file
local targetfile = target:objectfile(path.join("rules", "cuda", "devlink", target:basename() .. "_gpucode.cu"))
-- get object files
local objectfiles = nil
for _, sourcebatch in pairs(target:sourcebatches()) do
if sourcebatch.sourcekind == "cu" then
objectfiles = sourcebatch.objectfiles
end
end
if not objectfiles then
return
end
-- insert gpucode.o to the object files
table.insert(target:objectfiles(), targetfile)
-- need build this target?
local depfiles = objectfiles
for _, dep in ipairs(target:orderdeps()) do
if dep:kind() == "static" then
if depfiles == objectfiles then
depfiles = table.copy(objectfiles)
end
table.insert(depfiles, dep:targetfile())
end
end
local dryrun = option.get("dry-run")
local depvalues = {linkinst:program(), linkflags}
depend.on_changed(function ()
-- is verbose?
local verbose = option.get("verbose")
-- trace progress info
progress.show(opt.progress, "${color.build.target}devlinking.$(mode) %s", path.filename(targetfile))
-- trace verbose info
if verbose then
-- show the full link command with raw arguments, it will expand @xxx.args for msvc/link on windows
print(linkinst:linkcmd(objectfiles, targetfile, {linkflags = linkflags, rawargs = true}))
end
-- link it
if not dryrun then
assert(linkinst:link(objectfiles, targetfile, {linkflags = linkflags}))
end
end, {dependfile = target:dependfile(targetfile),
lastmtime = os.mtime(targetfile),
changed = target:is_rebuilt(),
values = depvalues, files = depfiles, dryrun = dryrun})
end
|
0 | repos/xmake/xmake/rules/cuda | repos/xmake/xmake/rules/cuda/devlink/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- device link
-- @see https://devblogs.nvidia.com/separate-compilation-linking-cuda-device-code/
rule("cuda.build.devlink")
add_deps("cuda.env")
before_link("devlink")
|
0 | repos/xmake/xmake/rules/cuda | repos/xmake/xmake/rules/cuda/gencodes/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: gencodes
rule("cuda.gencodes")
-- add cuda `-gencode` flags to target
--
-- the gpu arch format syntax
-- - compute_xx --> `-gencode arch=compute_xx,code=compute_xx`
-- - sm_xx --> `-gencode arch=compute_xx,code=sm_xx`
-- - sm_xx,sm_yy --> `-gencode arch=compute_xx,code=[sm_xx,sm_yy]`
-- - compute_xx,sm_yy --> `-gencode arch=compute_xx,code=sm_yy`
-- - compute_xx,sm_yy,sm_zz --> `-gencode arch=compute_xx,code=[sm_yy,sm_zz]`
-- - native --> match the fastest cuda device on current host,
-- eg. for a Tesla P100, `-gencode arch=compute_60,code=sm_60` will be added,
-- if no available device is found, no `-gencode` flags will be added
-- @seealso xmake/modules/lib/detect/find_cudadevices
--
on_config(function (target)
-- imports
import("core.platform.platform")
import("lib.detect.find_cudadevices")
import("core.base.hashset")
-- sm_20 and compute_20 is supported until CUDA 8
-- sm_30 and compute_30 is supported until CUDA 10
local known_v_archs = hashset.of(20, 30, 32, 35, 37, 50, 52, 53, 60, 61, 62, 70, 72, 75, 80, 86, 87, 89, 90)
local known_r_archs = hashset.of(20, 30, 32, 35, 37, 50, 52, 53, 60, 61, 62, 70, 72, 75, 80, 86, 87, 89, 90)
local function nf_cugencode(archs)
if type(archs) ~= "string" then
return nil
end
archs = archs:trim():lower()
if archs == "native" then
local cuda_envs
for _, toolchain_inst in ipairs(target:toolchains()) do
if toolchain_inst:name() == "cuda" then
cuda_envs = toolchain_inst:runenvs()
break
end
end
local device = find_cudadevices({skip_compute_mode_prohibited = true, order_by_flops = true, envs = cuda_envs, plat = target:plat(), arch = target:arch()})[1]
if device then
return nf_cugencode("sm_" .. device.major .. device.minor)
end
return nil
end
local v_arch = nil
local r_archs = {}
local function parse_arch(value, prefix, know_list)
if not value:startswith(prefix) then
return nil
end
local arch = tonumber(value:sub(#prefix + 1)) or tonumber(value:sub(#prefix + 2))
if arch == nil then
raise("unknown architecture: " .. value)
end
if not know_list:has(arch) then
if arch <= table.maxn(know_list:data()) then
raise("unknown architecture: " .. prefix .. "_" .. arch)
else
utils.warning("unknown architecture: " .. prefix .. "_" .. arch)
end
end
return arch
end
for _, v in ipairs(archs:split(',')) do
local arch = v:trim()
local temp_r_arch = parse_arch(arch, "sm", known_r_archs)
if temp_r_arch then
table.insert(r_archs, temp_r_arch)
end
local temp_v_arch = parse_arch(arch, "compute", known_v_archs)
if temp_v_arch then
if v_arch ~= nil then
raise("more than one virtual architecture is defined in one gpu gencode option: compute_" .. v_arch .. " and compute_" .. temp_v_arch)
end
v_arch = temp_v_arch
end
if not (temp_r_arch or temp_v_arch) then
raise("unknown architecture: " .. arch)
end
end
if v_arch == nil and #r_archs == 0 then
return nil
end
if #r_archs == 0 then
return {
clang = "--cuda-gpu-arch=sm_" .. v_arch,
nvcc = "-gencode arch=compute_" .. v_arch .. ",code=compute_" .. v_arch
}
end
if v_arch then
table.insert(r_archs, v_arch)
else
v_arch = math.min(table.unpack(r_archs))
end
r_archs = table.unique(r_archs)
local clang_flags = {}
for _, r_arch in ipairs(r_archs) do
table.insert(clang_flags, "--cuda-gpu-arch=sm_" .. r_arch)
end
local nvcc_flags = nil
if #r_archs == 1 then
nvcc_flags = "-gencode arch=compute_" .. v_arch .. ",code=sm_" .. r_archs[1]
else
nvcc_flags = "-gencode arch=compute_" .. v_arch .. ",code=[sm_" .. table.concat(r_archs, ",sm_") .. "]"
end
return { clang = clang_flags, nvcc = nvcc_flags }
end
local cugencodes = table.wrap(target:get("cugencodes"))
for _, opt in ipairs(target:orderopts()) do
table.join2(cugencodes, opt:get("cugencodes"))
end
for _, v in ipairs(cugencodes) do
local flag = nf_cugencode(v)
if flag then
if target:has_tool("cu", "nvcc") then
target:add("cuflags", flag.nvcc)
else
target:add("cuflags", flag.clang)
end
target:add("culdflags", flag.nvcc)
end
end
end)
rule_end()
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/asm/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: asm.build
rule("asm.build")
set_sourcekinds("as")
on_build_files("private.action.build.object", {batch = true})
-- define rule: asm
rule("asm")
-- add build rules
add_deps("asm.build")
-- inherit links and linkdirs of all dependent targets by default
add_deps("utils.inherit.links")
-- support `add_files("src/*.o")` and `add_files("src/*.a")` to merge object and archive files to target
add_deps("utils.merge.object", "utils.merge.archive")
-- we attempt to extract symbols to the independent file and
-- strip self-target binary if `set_symbols("debug")` and `set_strip("all")` are enabled
add_deps("utils.symbols.extract")
-- add platform rules
add_deps("platform.windows")
-- add linker rules
add_deps("linker")
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/gnu-rm/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author Jacob
-- @file xmake.lua
--
rule("gnu-rm.binary")
on_load(function (target)
-- we disable checking flags for cross toolchain automatically
target:set("policy", "check.auto_ignore_flags", false)
target:set("policy", "check.auto_map_flags", false)
-- set default output binary
target:set("kind", "binary")
if not target:get("extension") then
target:set("extension", ".elf")
end
end)
rule("gnu-rm.static")
on_load(function (target)
-- we disable checking flags for cross toolchain automatically
target:set("policy", "check.auto_ignore_flags", false)
target:set("policy", "check.auto_map_flags", false)
-- set default output binary
target:set("kind", "static")
end)
rule("gnu-rm.shared")
on_load(function (target)
-- we disable checking flags for cross toolchain automatically
target:set("policy", "check.auto_ignore_flags", false)
target:set("policy", "check.auto_map_flags", false)
-- set default output binary
target:set("kind", "shared")
end)
rule("gnu-rm.object")
on_load(function (target)
-- we disable checking flags for cross toolchain automatically
target:set("policy", "check.auto_ignore_flags", false)
target:set("policy", "check.auto_map_flags", false)
-- set default output binary
target:set("kind", "object")
end)
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/swift/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: swift.build
rule("swift.build")
set_sourcekinds("sc")
on_build_files("private.action.build.object", {batch = true})
on_config(function (target)
-- we use swift-frontend to support multiple modules
-- @see https://github.com/xmake-io/xmake/issues/3916
if target:has_tool("sc", "swift_frontend") then
target:add("scflags", "-module-name", target:name(), {force = true})
local sourcebatch = target:sourcebatches()["swift.build"]
if sourcebatch then
for _, sourcefile in ipairs(sourcebatch.sourcefiles) do
target:add("scflags", sourcefile, {force = true})
end
end
end
end)
-- define rule: swift
rule("swift")
-- add build rules
add_deps("swift.build")
-- support `add_files("src/*.o")` to merge object files to target
add_deps("utils.merge.object")
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/capnproto/capnp.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author wsw0108
-- @file capnp.lua
--
-- imports
import("lib.detect.find_tool")
-- get capnp
function _get_capnp(target)
-- find capnp
local capnp = target:data("capnproto.capnp")
if not capnp then
capnp = find_tool("capnp")
if capnp and capnp.program then
target:data_set("capnproto.capnp", capnp.program)
end
end
-- get capnp
return assert(target:data("capnproto.capnp"), "capnp not found!")
end
-- generate build commands
function buildcmd(target, batchcmds, sourcefile_capnp, opt)
-- get capnp
local capnp = _get_capnp(target)
-- get c/c++ source file for capnproto
local prefixdir
local public
local fileconfig = target:fileconfig(sourcefile_capnp)
if fileconfig then
public = fileconfig.capnp_public
prefixdir = fileconfig.capnp_rootdir
end
local rootdir = path.join(target:autogendir(), "rules", "capnproto")
local filename = path.basename(sourcefile_capnp) .. ".capnp.c++"
local sourcefile_cx = target:autogenfile(sourcefile_capnp, {rootdir = rootdir, filename = filename})
local sourcefile_dir = prefixdir and path.join(rootdir, prefixdir) or path.directory(sourcefile_cx)
-- add includedirs
target:add("includedirs", sourcefile_dir, {public = public})
-- add objectfile
local objectfile = target:objectfile(sourcefile_cx)
table.insert(target:objectfiles(), objectfile)
-- add commands
batchcmds:mkdir(sourcefile_dir)
batchcmds:show_progress(opt.progress, "${color.build.object}compiling.capnp %s", sourcefile_capnp)
local capnproto = target:pkg("capnproto")
local includes = capnproto:get("sysincludedirs")
local argv = {"compile"}
for _, value in ipairs(includes) do
table.insert(argv, path(value, function (p) return "-I" .. p end))
end
table.insert(argv, path(prefixdir and prefixdir or path.directory(sourcefile_capnp), function (p) return "-I" .. p end))
if prefixdir then
table.insert(argv, path(prefixdir, function (p) return "--src-prefix=" .. p end))
end
table.insert(argv, "-o")
table.insert(argv, path(sourcefile_dir, function (p) return "c++:" .. p end))
table.insert(argv, path(sourcefile_capnp))
batchcmds:vrunv(capnp, argv)
local configs = {includedirs = sourcefile_dir, languages = "c++14"}
if target:is_plat("windows") then
configs.cxflags = "/TP"
end
batchcmds:compile(sourcefile_cx, objectfile, {sourcekind = "cxx", configs = configs})
-- add deps
batchcmds:add_depfiles(sourcefile_capnp)
batchcmds:set_depmtime(os.mtime(objectfile))
batchcmds:set_depcache(target:dependfile(objectfile))
end
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/capnproto/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author wsw0108
-- @file xmake.lua
--
-- define rule: capnproto.cpp
rule("capnproto.cpp")
set_extensions(".capnp")
before_buildcmd_file(function (target, batchcmds, sourcefile_capnp, opt)
return import("capnp").buildcmd(target, batchcmds, sourcefile_capnp, opt)
end)
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/verilator/verilator.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file verilator.lua
--
-- imports
import("utils.progress")
import("core.base.hashset")
import("core.project.depend")
import("private.action.build.object", {alias = "build_objectfiles"})
-- parse sourcefiles from cmakefile
function _get_sourcefiles_from_cmake(target, cmakefile)
local global_classes = {}
local classefiles_slow = {}
local classefiles_fast = {}
local supportfiles_slow = {}
local supportfiles_fast = {}
local targetname = target:name()
local verilator_root = assert(target:data("verilator.root"), "no verilator_root!")
io.gsub(cmakefile, "set%((%S-) (.-)%)", function (key, values)
if key == targetname .. "_GLOBAL" then
-- get global class source files
-- set(hello_GLOBAL "${VERILATOR_ROOT}/include/verilated.cpp" "${VERILATOR_ROOT}/include/verilated_threads.cpp")
for classfile in values:gmatch("\"(.-)\"") do
classfile = classfile:gsub("%${VERILATOR_ROOT}", verilator_root)
if os.isfile(classfile) then
table.insert(global_classes, classfile)
end
end
elseif key == targetname .. "_CLASSES_SLOW" then
for classfile in values:gmatch("\"(.-)\"") do
table.insert(classefiles_slow, classfile)
end
elseif key == targetname .. "_CLASSES_FAST" then
for classfile in values:gmatch("\"(.-)\"") do
table.insert(classefiles_fast, classfile)
end
elseif key == targetname .. "_SUPPORT_SLOW" then
for classfile in values:gmatch("\"(.-)\"") do
table.insert(supportfiles_slow, classfile)
end
elseif key == targetname .. "_SUPPORT_FAST" then
for classfile in values:gmatch("\"(.-)\"") do
table.insert(supportfiles_fast, classfile)
end
end
end)
-- get compiled source files
local sourcefiles = table.join(global_classes, classefiles_slow, classefiles_fast, supportfiles_slow, supportfiles_fast)
return sourcefiles
end
-- get languages
--
-- Select the Verilog language generation to support in the compiler.
-- This selects between v1364-1995, v1364-2001, v1364-2005, v1800-2005, v1800-2009, v1800-2012.
--
function _get_lanuage_flags(target)
local language_v
local languages = target:get("languages")
if languages then
for _, language in ipairs(languages) do
if language:startswith("v") then
language_v = language
break
end
end
end
if language_v then
local maps = {
-- Verilog
["v1364-1995"] = "+1364-1995ext+v",
["v1364-2001"] = "+1364-2001ext+v",
["v1364-2005"] = "+1364-2005ext+v",
-- SystemVerilog
["v1800-2005"] = "+1800-2005ext+v",
["v1800-2009"] = "+1800-2009ext+v",
["v1800-2012"] = "+1800-2012ext+v",
["v1800-2017"] = "+1800-2017ext+v",
}
local flag = maps[language_v]
if flag then
return flag
else
assert("unknown language(%s) for verilator!", language_v)
end
end
end
function config(target)
local toolchain = assert(target:toolchain("verilator"), 'we need to set_toolchains("verilator") in target("%s")', target:name())
local verilator = assert(toolchain:config("verilator"), "verilator not found!")
local autogendir = path.join(target:autogendir(), "rules", "verilator")
local tmpdir = os.tmpfile() .. ".dir"
local cmakefile = path.join(tmpdir, "test.cmake")
local sourcefile = path.join(tmpdir, "main.v")
local argv = {"--cc", "--make", "cmake", "--prefix", "test", "--Mdir", tmpdir, "main.v"}
local flags = target:values("verilator.flags")
local switches_flags = hashset.of( "sc", "coverage", "timing", "trace", "trace-fst", "threads")
if flags then
for idx, flag in ipairs(flags) do
if flag:startswith("--") and switches_flags:has(flag:sub(3)) then
table.insert(argv, flag)
if flag:startswith("--threads") then
table.insert(argv, flags[idx + 1])
end
end
end
end
io.writefile(sourcefile, [[
module hello;
initial begin
$display("hello world!");
$finish ;
end
endmodule]])
os.mkdir(tmpdir)
-- we just pass relative sourcefile path to solve this issue on windows.
-- @see https://github.com/verilator/verilator/issues/3873
os.runv(verilator, argv, {curdir = tmpdir, envs = toolchain:runenvs()})
-- parse some configurations from cmakefile
local verilator_root
local switches = {}
local targetname = target:name()
io.gsub(cmakefile, "set%((%S-) (.-)%)", function (key, values)
if key == "VERILATOR_ROOT" then
verilator_root = values:match("\"(.-)\" CACHE PATH")
if not verilator_root then
verilator_root = values:match("(.-) CACHE PATH")
end
elseif key == "test_SC" then
-- SystemC output mode? 0/1 (from --sc)
switches.SC = values:trim()
elseif key == "test_COVERAGE" then
-- Coverage output mode? 0/1 (from --coverage)
switches.COVERAGE = values:trim()
elseif key == "test_TIMING" then
-- Timing mode? 0/1 (from --timing)
switches.TIMING = values:trim()
elseif key == "test_THREADS" then
-- Threaded output mode? 1/N threads (from --threads)
switches.THREADS = values:trim()
elseif key == "test_TRACE_VCD" then
-- VCD Tracing output mode? 0/1 (from --trace)
switches.TRACE_VCD = values:trim()
elseif key == "test_TRACE_FST" then
-- FST Tracing output mode? 0/1 (from --trace-fst)
switches.TRACE_FST = values:trim()
end
end)
assert(verilator_root, "the verilator root directory not found!")
target:data_set("verilator.root", verilator_root)
-- add includedirs
if not os.isfile(autogendir) then
os.mkdir(autogendir)
end
target:add("includedirs", autogendir, {public = true})
target:add("includedirs", path.join(verilator_root, "include"), {public = true})
target:add("includedirs", path.join(verilator_root, "include", "vltstd"), {public = true})
-- set languages
local languages = target:get("languages")
local cxxlang = false
for _, lang in ipairs(languages) do
if lang:startswith("xx") or lang:startswith("++") then
cxxlang = true
break
end
end
if not cxxlang then
target:add("languages", "c++20", {public = true})
end
-- add definitions for switches
for k, v in table.orderpairs(switches) do
target:add("defines", "VM_" .. k .. "=" .. v, {public = true})
end
-- add syslinks
if target:is_plat("linux", "macosx") and switches.THREADS == "1" then
target:add("syslinks", "pthread")
end
if target:is_plat("linux", "macosx") and switches.TRACE_FST == "1" then
target:add("syslinks", "z")
end
os.rm(tmpdir)
end
function build_cppfiles(target, batchjobs, sourcebatch, opt)
local toolchain = assert(target:toolchain("verilator"), 'we need to set_toolchains("verilator") in target("%s")', target:name())
local verilator = assert(toolchain:config("verilator"), "verilator not found!")
local autogendir = path.join(target:autogendir(), "rules", "verilator")
local targetname = target:name()
local cmakefile = path.join(autogendir, targetname .. ".cmake")
-- build verilog files
depend.on_changed(function()
local argv = {"--cc", "--make", "cmake", "--prefix", targetname, "--Mdir", autogendir}
local flags = target:values("verilator.flags")
if flags then
table.join2(argv, flags)
end
local language_flags = _get_lanuage_flags(target)
if language_flags then
table.join2(argv, language_flags)
end
local sourcefiles = sourcebatch.sourcefiles
for _, sourcefile in ipairs(sourcefiles) do
progress.show(opt.progress or 0, "${color.build.object}compiling.verilog %s", sourcefile)
-- we need to use slashes to fix it on windows
-- @see https://github.com/verilator/verilator/issues/3873
if is_host("windows") then
sourcefile = sourcefile:gsub("\\", "/")
end
table.insert(argv, sourcefile)
end
-- generate c++ sourcefiles
os.vrunv(verilator, argv, {envs = toolchain:runenvs()})
end, {dependfile = cmakefile .. ".d",
files = sourcebatch.sourcefiles,
changed = target:is_rebuilt(),
lastmtime = os.mtime(cmakefile)})
-- get compiled source files
local sourcefiles = _get_sourcefiles_from_cmake(target, cmakefile)
-- do build
local sourcebatch_cpp = {
rulename = "c++.build",
sourcekind = "cxx",
sourcefiles = sourcefiles,
objectfiles = {},
dependfiles = {}}
for _, sourcefile in ipairs(sourcefiles) do
local objectfile = target:objectfile(sourcefile)
local dependfile = target:objectfile(objectfile)
table.insert(target:objectfiles(), objectfile)
table.insert(sourcebatch_cpp.objectfiles, objectfile)
table.insert(sourcebatch_cpp.dependfiles, dependfile)
end
build_objectfiles(target, batchjobs, sourcebatch_cpp, opt)
end
function buildcmd_vfiles(target, batchcmds, sourcebatch, opt)
local toolchain = assert(target:toolchain("verilator"), 'we need to set_toolchains("verilator") in target("%s")', target:name())
local verilator = assert(toolchain:config("verilator"), "verilator not found!")
local autogendir = path.join(target:autogendir(), "rules", "verilator")
local targetname = target:name()
local cmakefile = path.join(autogendir, targetname .. ".cmake")
local dependfile = cmakefile .. ".d"
local argv = {"--cc", "--make", "cmake", "--prefix", targetname, "--Mdir", path(autogendir)}
local flags = target:values("verilator.flags")
if flags then
table.join2(argv, flags)
end
local language_flags = _get_lanuage_flags(target)
if language_flags then
table.join2(argv, language_flags)
end
local sourcefiles = sourcebatch.sourcefiles
for _, sourcefile in ipairs(sourcefiles) do
batchcmds:show_progress(opt.progress, "${color.build.object}compiling.verilog %s", sourcefile)
table.insert(argv, path(sourcefile, function (v)
-- we need to use slashes to fix it on windows
-- @see https://github.com/verilator/verilator/issues/3873
if is_host("windows") then
v = v:gsub("\\", "/")
end
return v
end))
end
-- generate c++ sourcefiles
batchcmds:vrunv(verilator, argv, {envs = toolchain:runenvs()})
batchcmds:add_depfiles(sourcefiles)
batchcmds:set_depmtime(os.mtime(cmakefile))
batchcmds:set_depcache(dependfile)
end
function buildcmd_cppfiles(target, batchcmds, sourcebatch, opt)
local toolchain = assert(target:toolchain("verilator"), 'we need set_toolchains("verilator") in target("%s")', target:name())
local verilator = assert(toolchain:config("verilator"), "verilator not found!")
local autogendir = path.join(target:autogendir(), "rules", "verilator")
local targetname = target:name()
local cmakefile = path.join(autogendir, targetname .. ".cmake")
local dependfile = path.join(autogendir, targetname .. ".build.d")
-- get compiled source files
local sourcefiles = _get_sourcefiles_from_cmake(target, cmakefile)
-- do build
for _, sourcefile in ipairs(sourcefiles) do
local objectfile = target:objectfile(sourcefile)
batchcmds:show_progress(opt.progress, "${color.build.object}compiling.$(mode) %s", path.filename(sourcefile))
batchcmds:compile(sourcefile, objectfile)
table.insert(target:objectfiles(), objectfile)
end
batchcmds:add_depfiles(sourcefiles)
batchcmds:set_depmtime(os.mtime(dependfile))
batchcmds:set_depcache(dependfile)
end
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/verilator/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- @see https://github.com/xmake-io/xmake/issues/3257
rule("verilator.binary")
add_deps("c++")
set_extensions(".v", ".sv")
on_load(function (target)
target:set("kind", "binary")
end)
on_config(function (target)
import("verilator").config(target)
end)
before_build_files(function (target, sourcebatch)
-- Just to avoid before_buildcmd_files being executed at build time
end)
on_build_files(function (target, batchjobs, sourcebatch, opt)
import("verilator").build_cppfiles(target, batchjobs, sourcebatch, opt)
end, {batch = true, distcc = true})
before_buildcmd_files(function(target, batchcmds, sourcebatch, opt)
import("verilator").buildcmd_vfiles(target, batchcmds, sourcebatch, opt)
end)
on_buildcmd_files(function (target, batchcmds, sourcebatch, opt)
import("verilator").buildcmd_cppfiles(target, batchcmds, sourcebatch, opt)
end)
rule("verilator.static")
add_deps("c++")
set_extensions(".v", ".sv")
on_load(function (target)
target:set("kind", "static")
end)
on_config(function (target)
import("verilator").config(target)
end)
before_build_files(function (target, sourcebatch)
-- Just to avoid before_buildcmd_files being executed at build time
end)
on_build_files(function (target, batchjobs, sourcebatch, opt)
import("verilator").build_cppfiles(target, batchjobs, sourcebatch, opt)
end, {batch = true, distcc = true})
before_buildcmd_files(function(target, batchcmds, sourcebatch, opt)
import("verilator").buildcmd_vfiles(target, batchcmds, sourcebatch, opt)
end)
on_buildcmd_files(function (target, batchcmds, sourcebatch, opt)
import("verilator").buildcmd_cppfiles(target, batchcmds, sourcebatch, opt)
end)
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/wdk/load.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file load.lua
--
-- imports
import("core.project.config")
import("os.winver", {alias = "os_winver"})
-- load for umdf driver
function driver_umdf(target)
-- set kind
target:set("kind", "shared")
-- add links
target:add("links", "ntdll", "OneCoreUAP", "mincore", "ucrt")
target:add("shflags", "-NODEFAULTLIB:kernel32.lib", "-NODEFAULTLIB:user32.lib", "-NODEFAULTLIB:libucrt.lib", {force = true})
-- add subsystem
local winver = target:values("wdk.env.winver") or config.get("wdk_winver")
target:add("shflags", "-subsystem:windows," .. os_winver.subsystem(winver), {force = true})
-- set default driver entry if does not exist
local entry = false
for _, ldflag in ipairs(target:get("shflags")) do
ldflag = ldflag:lower()
if ldflag:find("[/%-]entry:") then
entry = true
break
end
end
if not entry then
target:add("links", "WdfDriverStubUm")
end
end
-- load for kmdf driver
function driver_kmdf(target)
-- set kind
target:set("kind", "binary")
-- set filename: xxx.sys
target:set("filename", target:basename() .. ".sys")
-- add links
local winver = target:values("wdk.env.winver") or config.get("wdk_winver")
if winver and os_winver.version(winver) >= os_winver.version("win8") then
target:add("links", "BufferOverflowFastFailK")
else
target:add("links", "BufferOverflowK")
end
target:add("links", "ntoskrnl", "hal", "wmilib", "WdfLdr", "ntstrsafe", "wdmsec")
-- compile as kernel driver
target:add("cxflags", "-kernel", {force = true})
target:add("ldflags", "-kernel", "-driver", {force = true})
target:add("ldflags", "-nodefaultlib", {force = true})
-- add subsystem
target:add("ldflags", "-subsystem:native," .. os_winver.subsystem(winver), {force = true})
-- set default driver entry if does not exist
local entry = false
for _, ldflag in ipairs(target:get("ldflags")) do
if type(ldflag) == "string" then
ldflag = ldflag:lower()
if ldflag:find("[/%-]entry:") then
entry = true
break
end
end
end
if not entry then
target:add("links", "WdfDriverEntry")
target:add("ldflags", "-entry:FxDriverEntry" .. (is_arch("x86") and "@8" or ""), {force = true})
end
end
-- load for wdm driver
function driver_wdm(target)
-- set kind
target:set("kind", "binary")
-- set filename: xxx.sys
target:set("filename", target:basename() .. ".sys")
-- add links
local winver = target:values("wdk.env.winver") or config.get("wdk_winver")
if winver and os_winver.version(winver) >= os_winver.version("win8") then
target:add("links", "BufferOverflowFastFailK")
else
target:add("links", "BufferOverflowK")
end
target:add("links", "ntoskrnl", "hal", "wmilib", "ntstrsafe")
-- compile as kernel driver
target:add("cxflags", "-kernel", {force = true})
target:add("ldflags", "-kernel", "-driver", {force = true})
target:add("ldflags", "-nodefaultlib", {force = true})
-- add subsystem
target:add("ldflags", "-subsystem:native," .. os_winver.subsystem(winver), {force = true})
-- set default driver entry if does not exist
local entry = false
for _, ldflag in ipairs(target:get("ldflags")) do
if type(ldflag) == "string" then
ldflag = ldflag:lower()
if ldflag:find("[/%-]entry:") then
entry = true
break
end
end
end
if not entry then
target:add("ldflags", "-entry:GsDriverEntry" .. (is_arch("x86") and "@8" or ""), {force = true})
end
end
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/wdk/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: driver
rule("wdk.driver")
-- add rules
add_deps("wdk.inf", "wdk.man", "wdk.mc", "wdk.mof", "wdk.tracewpp", "wdk.sign", "wdk.package.cab")
-- after load
after_load(function (target)
-- load environment
if target:rule("wdk.env.umdf") then
import("load").driver_umdf(target)
end
if target:rule("wdk.env.kmdf") then
import("load").driver_kmdf(target)
end
if target:rule("wdk.env.wdm") then
import("load").driver_wdm(target)
end
end)
-- after build
after_build(function (target)
-- imports
import("core.project.config")
-- copy redist files for kmdf
if target:rule("wdk.env.kmdf") then
-- get wdk
local wdk = target:data("wdk")
-- copy wdf redist dll libraries (WdfCoInstaller01011.dll, ..) to the target directory
os.cp(path.join(wdk.sdkdir, "Redist", "wdf", config.arch(), "*.dll"), target:targetdir())
end
end)
-- define rule: binary
rule("wdk.binary")
-- add rules
add_deps("wdk.inf", "wdk.man", "wdk.mc", "wdk.mof", "wdk.tracewpp")
-- after load
after_load(function (target)
-- set kind
target:set("kind", "binary")
-- add links
target:add("links", "kernel32", "user32", "gdi32", "winspool", "comdlg32")
target:add("links", "advapi32", "shell32", "ole32", "oleaut32", "uuid", "odbc32", "odbccp32", "setupapi")
end)
-- define rule: static
rule("wdk.static")
-- add rules
add_deps("wdk.inf", "wdk.man", "wdk.mc", "wdk.mof", "wdk.tracewpp")
-- after load
after_load(function (target)
-- set kind
target:set("kind", "static")
-- for kernel driver
if target:rule("wdk.env.kmdf") or target:rule("wdk.env.wdm") then
-- compile as kernel driver
target:add("cxflags", "-kernel", {force = true})
end
end)
-- define rule: shared
rule("wdk.shared")
-- add rules
add_deps("wdk.inf", "wdk.man", "wdk.mc", "wdk.mof", "wdk.tracewpp")
-- after load
after_load(function (target)
-- set kind
target:set("kind", "shared")
-- add links
target:add("links", "kernel32", "user32", "gdi32", "winspool", "comdlg32")
target:add("links", "advapi32", "shell32", "ole32", "oleaut32", "uuid", "odbc32", "odbccp32", "setupapi")
end)
|
0 | repos/xmake/xmake/rules/wdk | repos/xmake/xmake/rules/wdk/man/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: *.man
rule("wdk.man")
-- add rule: wdk environment
add_deps("wdk.env")
-- set extensions
set_extensions(".man")
-- before load
on_load(function (target)
-- imports
import("core.project.config")
-- get arch
local arch = assert(config.arch(), "arch not found!")
-- get wdk
local wdk = target:data("wdk")
-- get ctrpp
local ctrpp = path.join(wdk.bindir, arch, "ctrpp.exe")
if not os.isexec(ctrpp) then
ctrpp = path.join(wdk.bindir, wdk.sdkver, arch, "ctrpp.exe")
end
assert(os.isexec(ctrpp), "ctrpp not found!")
-- save ctrpp
target:data_set("wdk.ctrpp", ctrpp)
end)
-- before build file
before_build_file(function (target, sourcefile, opt)
-- imports
import("core.base.option")
import("core.theme.theme")
import("core.project.depend")
import("utils.progress")
-- get ctrpp
local ctrpp = target:data("wdk.ctrpp")
-- get output directory
local outputdir = path.join(target:autogendir(), "rules", "wdk", "man")
-- init args
local args = {sourcefile}
local flags = target:values("wdk.man.flags", sourcefile)
if flags then
table.join2(args, flags)
end
-- add includedirs
target:add("includedirs", outputdir)
-- add header file
local header = target:values("wdk.man.header", sourcefile)
local headerfile = header and path.join(outputdir, header) or nil
if headerfile then
table.insert(args, "-o")
table.insert(args, headerfile)
else
raise("please call `set_values(\"wdk.man.header\", \"header.h\")` to set the provider header file name!")
end
-- add prefix
local prefix = target:values("wdk.man.prefix", sourcefile)
if prefix then
table.insert(args, "-prefix")
table.insert(args, prefix)
end
-- add counter header file
local counter_header = target:values("wdk.man.counter_header", sourcefile)
local counter_headerfile = counter_header and path.join(outputdir, counter_header) or nil
if counter_headerfile then
table.insert(args, "-ch")
table.insert(args, counter_headerfile)
end
-- add resource file
local resource = target:values("wdk.man.resource", sourcefile)
local resourcefile = resource and path.join(outputdir, resource) or nil
if resourcefile then
table.insert(args, "-rc")
table.insert(args, resourcefile)
end
-- need build this object?
local dependfile = target:dependfile(headerfile)
local dependinfo = target:is_rebuilt() and {} or (depend.load(dependfile) or {})
if not depend.is_changed(dependinfo, {lastmtime = os.mtime(headerfile), values = args}) then
return
end
-- trace progress info
progress.show(opt.progress, "${color.build.object}compiling.wdk.man %s", sourcefile)
-- generate header and resource file
if not os.isdir(outputdir) then
os.mkdir(outputdir)
end
os.vrunv(ctrpp, args)
-- update files and values to the dependent file
dependinfo.files = {sourcefile}
dependinfo.values = args
depend.save(dependinfo, dependfile)
end)
|
0 | repos/xmake/xmake/rules/wdk | repos/xmake/xmake/rules/wdk/env/load.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file load.lua
--
-- imports
import("core.project.config")
-- get version of the library sub-directory
function _winver_libdir(winver)
-- ignore the subname with '_xxx'
winver = (winver or ""):split('_')[1]
-- make defined values
local vervals =
{
win81 = "winv6.3"
, winblue = "winv6.3"
, win8 = "win8"
, win7 = "win7"
}
return vervals[winver]
end
-- load for umdf environment
function umdf(target)
-- get wdk
local wdk = target:data("wdk")
-- get arch
local arch = config.arch()
-- add definitions
local umdfver = wdk.umdfver:split('%.')
if arch == "x64" then
target:add("defines", "_WIN64", "_AMD64_", "AMD64")
else
target:add("defines", "_X86_=1", "i386=1")
target:add("defines", "DEPRECATE_DDK_FUNCTIONS=1", "MSC_NOOPT", "_ATL_NO_WIN_SUPPORT")
target:add("defines", "STD_CALL")
target:add("cxflags", "-Gz", {force = true})
end
target:add("defines", "UMDF_VERSION_MAJOR=" .. umdfver[1], "UMDF_VERSION_MINOR=" .. umdfver[2], "UMDF_USING_NTSTATUS")
target:add("defines", "WIN32_LEAN_AND_MEAN=1", "WINNT=1", "_WINDLL")
-- add include directories
target:add("includedirs", path.join(wdk.includedir, wdk.sdkver, "um"))
target:add("includedirs", path.join(wdk.includedir, "wdf", "umdf", wdk.umdfver))
-- add link directories
target:add("linkdirs", path.join(wdk.libdir, wdk.sdkver, "um", arch))
target:add("linkdirs", path.join(wdk.libdir, "wdf", "umdf", arch, wdk.umdfver))
end
-- load for kmdf environment
function kmdf(target)
-- get wdk
local wdk = target:data("wdk")
-- get arch
local arch = config.arch()
-- add definitions
local winver = target:values("wdk.env.winver") or config.get("wdk_winver")
local kmdfver = wdk.kmdfver:split('%.')
if arch == "x64" then
target:add("defines", "_WIN64", "_AMD64_", "AMD64")
else
target:add("defines", "_X86_=1", "i386=1")
target:add("defines", "DEPRECATE_DDK_FUNCTIONS=1", "MSC_NOOPT", "_ATL_NO_WIN_SUPPORT")
target:add("defines", "STD_CALL")
target:add("cxflags", "-Gz", {force = true})
end
target:add("defines", "KMDF_VERSION_MAJOR=" .. kmdfver[1], "KMDF_VERSION_MINOR=" .. kmdfver[2], "KMDF_USING_NTSTATUS")
target:add("defines", "WIN32_LEAN_AND_MEAN=1", "WINNT=1", "_WINDLL")
-- add include directories
target:add("includedirs", path.join(wdk.includedir, wdk.sdkver, "km"))
if target:rule("wdk.driver") then
target:add("includedirs", path.join(wdk.includedir, wdk.sdkver, "km", "crt"))
end
target:add("includedirs", path.join(wdk.includedir, "wdf", "kmdf", wdk.kmdfver))
-- add link directories
local libdirver = _winver_libdir(winver)
if libdirver then
target:add("linkdirs", path.join(wdk.libdir, libdirver, "km", arch))
end
target:add("linkdirs", path.join(wdk.libdir, wdk.sdkver, "km", arch))
target:add("linkdirs", path.join(wdk.libdir, "wdf", "kmdf", arch, wdk.kmdfver))
end
-- load for wdm environment
function wdm(target)
-- get wdk
local wdk = target:data("wdk")
-- get arch
local arch = config.arch()
-- add definitions
local winver = target:values("wdk.env.winver") or config.get("wdk_winver")
local kmdfver = wdk.kmdfver:split('%.')
if arch == "x64" then
target:add("defines", "_WIN64", "_AMD64_", "AMD64")
else
target:add("defines", "_X86_=1", "i386=1")
target:add("defines", "DEPRECATE_DDK_FUNCTIONS=1", "MSC_NOOPT", "_ATL_NO_WIN_SUPPORT")
target:add("defines", "STD_CALL")
target:add("cxflags", "-Gz", {force = true})
end
target:add("defines", "KMDF_VERSION_MAJOR=" .. kmdfver[1], "KMDF_VERSION_MINOR=" .. kmdfver[2], "KMDF_USING_NTSTATUS")
target:add("defines", "WIN32_LEAN_AND_MEAN=1", "WINNT=1", "_WINDLL")
-- add include directories
target:add("includedirs", path.join(wdk.includedir, wdk.sdkver, "km"))
if target:rule("wdk.driver") then
target:add("includedirs", path.join(wdk.includedir, wdk.sdkver, "km", "crt"))
end
target:add("includedirs", path.join(wdk.includedir, "wdf", "kmdf", wdk.kmdfver))
-- add link directories
local libdirver = _winver_libdir(winver)
if libdirver then
target:add("linkdirs", path.join(wdk.libdir, libdirver, "km", arch))
end
target:add("linkdirs", path.join(wdk.libdir, wdk.sdkver, "km", arch))
target:add("linkdirs", path.join(wdk.libdir, "wdf", "kmdf", arch, wdk.kmdfver))
end
|
0 | repos/xmake/xmake/rules/wdk | repos/xmake/xmake/rules/wdk/env/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: environment
rule("wdk.env")
-- before load
on_load(function (target)
-- imports
import("os.winver", {alias = "os_winver"})
import("core.project.config")
import("detect.sdks.find_wdk")
-- load wdk environment
if not target:data("wdk") then
-- find wdk
local wdk = assert(find_wdk(nil, {verbose = true}), "WDK not found!")
-- update the umdf sdk version from the xmake.lua
local umdfver = target:values("wdk.umdf.sdkver")
if umdfver then
wdk.umdfver = umdfver
end
-- update the kmdf sdk version from the xmake.lua
local kmdfver = target:values("wdk.kmdf.sdkver")
if kmdfver then
wdk.kmdfver = kmdfver
end
-- add definitions for debug
if is_mode("debug") then
target:add("defines", "DBG=1")
end
-- get winver name
local winver = target:values("wdk.env.winver") or config.get("wdk_winver")
-- get winver version
local winver_version = os_winver.version(winver or "") or "0x0A00"
-- get target version
local target_version = os_winver.target_version(winver or "") or "0x0A00"
-- get winnt version
local winnt_version = os_winver.winnt_version(winver or "") or "0x0A00"
-- get ntddi version
local ntddi_version = os_winver.ntddi_version(winver or "") or "0x0A000000"
-- add definitions for winver
target:add("defines", "_WIN32_WINNT=" .. winnt_version, "WINVER=" .. winver_version, "NTDDI_VERSION=" .. ntddi_version, "_NT_TARGET_VERSION=" .. target_version)
-- set builtin version values
target:values_set("wdk.env.winnt_version", winnt_version)
target:values_set("wdk.env.ntddi_version", ntddi_version)
target:values_set("wdk.env.winver_version", winver_version)
target:values_set("wdk.env.target_version", target_version)
-- save wdk
target:data_set("wdk", wdk)
end
end)
-- define rule: umdf
rule("wdk.env.umdf")
-- add rules
add_deps("wdk.env")
-- after load
after_load(function (target)
import("load").umdf(target)
end)
-- define rule: kmdf
rule("wdk.env.kmdf")
-- add rules
add_deps("wdk.env")
-- after load
after_load(function (target)
import("load").kmdf(target)
end)
-- define rule: wdm
rule("wdk.env.wdm")
-- add rules
add_deps("wdk.env")
-- after load
after_load(function (target)
import("load").wdm(target)
end)
|
0 | repos/xmake/xmake/rules/wdk | repos/xmake/xmake/rules/wdk/mof/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: *.mof
rule("wdk.mof")
-- add rule: wdk environment
add_deps("wdk.env")
-- set extensions
set_extensions(".mof")
-- before load
on_load(function (target)
-- imports
import("core.project.config")
import("lib.detect.find_program")
-- get arch
local arch = assert(config.arch(), "arch not found!")
-- get wdk
local wdk = target:data("wdk")
-- get mofcomp
local mofcomp = find_program("mofcomp", {check = function (program)
local tmpmof = os.tmpfile()
io.writefile(tmpmof, "")
os.run("%s %s", program, tmpmof)
os.tryrm(tmpmof)
end})
assert(mofcomp, "mofcomp not found!")
-- get wmimofck
local wmimofck = nil
if arch == "x64" then
wmimofck = path.join(wdk.bindir, wdk.sdkver, "x64", "wmimofck.exe")
if not os.isexec(wmimofck) then
wmimofck = path.join(wdk.bindir, wdk.sdkver, "x86", "x64", "wmimofck.exe")
end
else
wmimofck = path.join(wdk.bindir, wdk.sdkver, "x86", "wmimofck.exe")
end
assert(wmimofck and os.isexec(wmimofck), "wmimofck not found!")
-- save mofcomp and wmimofck
target:data_set("wdk.mofcomp", mofcomp)
target:data_set("wdk.wmimofck", wmimofck)
end)
-- before build file
before_build_file(function (target, sourcefile, opt)
-- imports
import("core.base.option")
import("core.theme.theme")
import("core.project.depend")
import("utils.progress")
-- get mofcomp
local mofcomp = target:data("wdk.mofcomp")
-- get wmimofck
local wmimofck = target:data("wdk.wmimofck")
-- get output directory
local outputdir = path.join(target:autogendir(), "rules", "wdk", "mof")
-- add includedirs
target:add("includedirs", outputdir)
-- get header file
local header = target:values("wdk.mof.header", sourcefile)
local headerfile = path.join(outputdir, header and header or (path.basename(sourcefile) .. ".h"))
-- get some temporary file
local sourcefile_mof = path.join(outputdir, path.filename(sourcefile))
local targetfile_mfl = path.join(outputdir, "." .. path.basename(sourcefile) .. ".mfl")
local targetfile_mof = path.join(outputdir, "." .. path.basename(sourcefile) .. ".mof")
local targetfile_mfl_mof = path.join(outputdir, "." .. path.basename(sourcefile) .. ".mfl.mof")
local targetfile_bmf = path.join(outputdir, path.basename(sourcefile) .. ".bmf")
local outputdir_htm = path.join(outputdir, "htm")
local targetfile_vbs = path.join(outputdir, path.basename(sourcefile) .. ".vbs")
-- need build this object?
local dependfile = target:dependfile(headerfile)
local dependinfo = target:is_rebuilt() and {} or (depend.load(dependfile) or {})
if not depend.is_changed(dependinfo, {lastmtime = os.mtime(headerfile), values = args}) then
return
end
-- trace progress info
progress.show(opt.progress, "${color.build.object}compiling.wdk.mof %s", sourcefile)
-- ensure the output directory
if not os.isdir(outputdir) then
os.mkdir(outputdir)
end
-- copy *.mof to output directory
os.cp(sourcefile, sourcefile_mof)
-- do mofcomp
os.vrunv(mofcomp, {"-Amendment:ms_409", "-MFL:" .. targetfile_mfl, "-MOF:" .. targetfile_mof, sourcefile_mof})
-- do wmimofck
os.vrunv(wmimofck, {"-y" .. targetfile_mof, "-z" .. targetfile_mfl, targetfile_mfl_mof})
-- do mofcomp to generate *.bmf
os.vrunv(mofcomp, {"-B:" .. targetfile_bmf, targetfile_mfl_mof})
-- do wmimofck to generate *.h
os.vrunv(wmimofck, {"-h" .. headerfile, "-w" .. outputdir_htm, "-m", "-t" .. targetfile_vbs, targetfile_bmf})
-- update files and values to the dependent file
dependinfo.files = {sourcefile}
dependinfo.values = args
depend.save(dependinfo, dependfile)
end)
|
0 | repos/xmake/xmake/rules/wdk | repos/xmake/xmake/rules/wdk/sign/sign.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file sign.lua
--
-- imports
import("core.base.option")
import("core.base.global")
import("core.project.config")
-- get tool
function _get_tool(target, name)
-- init cache
_g.tools = _g.tools or {}
-- get it from the cache
local tool = _g.tools[name]
if not tool then
-- get wdk
local wdk = target:data("wdk")
-- get arch
local arch = assert(config.arch(), "arch not found!")
-- get tool
tool = path.join(wdk.bindir, arch, name .. ".exe")
if not os.isexec(tool) then
tool = path.join(wdk.bindir, wdk.sdkver, arch, name .. ".exe")
end
assert(os.isexec(tool), name .. " not found!")
_g.tools[name] = tool
end
return tool
end
-- do sign
function main(target, filepath, mode)
-- get signtool
local signtool = _get_tool(target, "signtool")
-- init arguments
local argv = {"sign", "/v"}
local timestamp = target:values("wdk.sign.timestamp")
if timestamp then
table.insert(argv, "/t")
table.insert(argv, timestamp)
end
local company = target:values("wdk.sign.company")
if company then
table.insert(argv, "/n")
table.insert(argv, company)
end
local certfile = target:values("wdk.sign.certfile")
if certfile then
table.insert(argv, "/ac")
table.insert(argv, certfile)
end
local thumbprint = target:values("wdk.sign.thumbprint")
if thumbprint then
table.insert(argv, "/sha1")
table.insert(argv, thumbprint)
end
local store = target:values("wdk.sign.store")
if store then
table.insert(argv, "/a")
table.insert(argv, "/s")
table.insert(argv, store)
end
local digest_algorithm = target:values("wdk.sign.digest_algorithm")
if digest_algorithm then
table.insert(argv, "/fd")
table.insert(argv, digest_algorithm)
end
-- uses the default test certificate
if mode == "test" and (not certfile and not thumbprint and not store) then
table.insert(argv, "/a")
table.insert(argv, "/n")
table.insert(argv, "tboox.org(test)")
table.insert(argv, "/s")
table.insert(argv, "PrivateCertStore")
end
-- add target file
table.insert(argv, filepath)
-- do sign
os.vrunv(signtool, argv)
end
|
0 | repos/xmake/xmake/rules/wdk | repos/xmake/xmake/rules/wdk/sign/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: sign
--
-- values:
-- - wdk.sign.mode: nosign/test/release (default: nosign)
-- - wdk.sign.store: PrivateCertStore
-- - wdk.sign.thumbprint: 032122545DCAA6167B1ADBE5F7FDF07AE2234AAA
-- - wdk.sign.company: tboox.org
-- - wdk.sign.certfile: signcert.cer
-- - wdk.sign.timestamp: http://timestamp.verisign.com/scripts/timstamp.dll
--
rule("wdk.sign")
-- add rule: wdk environment
add_deps("wdk.env")
-- before load
on_load(function (target)
-- imports
import("core.project.config")
import("utils.wdk.testcert")
-- get wdk
local wdk = target:data("wdk")
-- get arch
local arch = assert(config.arch(), "arch not found!")
-- get inf2cat
local inf2cat = path.join(wdk.bindir, arch, "inf2cat.exe")
if not os.isexec(inf2cat) then
inf2cat = path.join(wdk.bindir, wdk.sdkver, arch, "inf2cat.exe")
end
if not os.isexec(inf2cat) then
inf2cat = path.join(wdk.bindir, wdk.sdkver, "x86", "inf2cat.exe")
end
assert(os.isexec(inf2cat), "inf2cat not found!")
target:data_set("wdk.sign.inf2cat", inf2cat)
-- check
local mode = target:values("wdk.sign.mode")
local store = target:values("wdk.sign.store")
local certfile = target:values("wdk.sign.certfile")
local thumbprint = target:values("wdk.sign.thumbprint")
if mode and (not certfile and not thumbprint and not store) then
if mode == "test" then
-- attempt to install test certificate first
local ok = try
{
function ()
testcert("install")
return true
end
}
if not ok then
raise([[please first select one following step for signing:
1. run `$xmake l utils.wdk.testcert install` as admin in console (only once) or
2. add set_values(\"wdk.sign.[certfile|store|thumbprint]\", ...) in xmake.lua]], mode)
end
else
raise("please add set_values(\"wdk.sign.[certfile|store|thumbprint]\", ...) for %s signing!", mode)
end
end
end)
-- after build
after_build(function (target, opt)
-- imports
import("sign")
import("core.base.option")
import("core.theme.theme")
import("core.project.config")
import("core.project.depend")
import("lib.detect.find_file")
import("utils.progress")
-- need build this object?
local tempfile = os.tmpfile(target:targetfile())
local dependfile = tempfile .. ".d"
local dependinfo = target:is_rebuilt() and {} or (depend.load(dependfile) or {})
if not depend.is_changed(dependinfo, {lastmtime = os.mtime(tempfile)}) then
return
end
-- get sign mode
local signmode = target:values("wdk.sign.mode")
if not signmode then
return
end
-- trace progress info
progress.show(opt.progress, "${color.build.target}signing.%s %s", signmode, path.filename(target:targetfile()))
-- get arch
local arch = assert(config.arch(), "arch not found!")
-- get inf2cat
local inf2cat = target:data("wdk.sign.inf2cat")
-- sign the target file
sign(target, target:targetfile(), signmode)
-- get inf file
local infile = target:data("wdk.sign.inf")
if infile and os.isfile(infile) then
-- do inf2cat
local inf2cat_dir = path.directory(target:targetfile())
local inf2cat_argv = {"/driver:" .. inf2cat_dir}
local inf2cat_os = target:values("wdk.inf2cat.os") or {"XP_" .. arch, "7_" .. arch, "8_" .. arch, "10_" .. arch}
table.insert(inf2cat_argv, "/os:" .. table.concat(table.wrap(inf2cat_os), ','))
os.vrunv(inf2cat, inf2cat_argv)
-- get *.cat file path from the output directory
local catfile = find_file("*.cat", inf2cat_dir)
assert(catfile, "*.cat not found!")
-- sign *.cat file
sign(target, catfile, signmode)
else
-- trace
vprint("Inf2Cat task was skipped as there were no inf files to process")
end
-- update files and values to the dependent file
dependinfo.files = {target:targetfile()}
depend.save(dependinfo, dependfile)
io.writefile(tempfile, "")
end)
-- after package
after_package(function (target)
-- imports
import("sign")
import("core.base.option")
-- get signtool
local signtool = target:data("wdk.sign.signtool")
-- get package file
local packagefile = target:data("wdk.sign.cab")
assert(packagefile and os.isfile(packagefile), "the driver package file(.cab) not found!")
-- get sign mode
local signmode = target:values("wdk.sign.mode") or "test"
-- trace progress info
if option.get("verbose") then
cprint("${dim magenta}signing.%s %s", signmode, path.filename(packagefile))
else
cprint("${magenta}signing.%s %s", signmode, path.filename(packagefile))
end
-- sign package file
sign(target, packagefile, signmode)
end)
|
0 | repos/xmake/xmake/rules/wdk | repos/xmake/xmake/rules/wdk/tracewpp/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: tracewpp
rule("wdk.tracewpp")
-- add rule: wdk environment
add_deps("wdk.env")
-- before load
on_load(function (target)
-- imports
import("core.project.config")
-- get wdk
local wdk = target:data("wdk")
-- get arch
local arch = assert(config.arch(), "arch not found!")
-- get tracewpp
local tracewpp = path.join(wdk.bindir, arch, is_host("windows") and "tracewpp.exe" or "tracewpp")
if not os.isexec(tracewpp) then
tracewpp = path.join(wdk.bindir, wdk.sdkver, arch, is_host("windows") and "tracewpp.exe" or "tracewpp")
end
assert(os.isexec(tracewpp), "tracewpp not found!")
-- save tracewpp
target:data_set("wdk.tracewpp", tracewpp)
-- save config directory
target:data_set("wdk.tracewpp.configdir", path.join(wdk.bindir, wdk.sdkver, "WppConfig", "Rev1"))
end)
-- before build file
before_build_file(function (target, sourcefile, opt)
-- imports
import("core.base.option")
import("core.theme.theme")
import("core.project.depend")
import("utils.progress")
-- get tracewpp
local tracewpp = target:data("wdk.tracewpp")
-- get outputdir
local outputdir = path.join(target:autogendir(), "rules", "wdk", "wpp")
-- get configdir
local configdir = target:data("wdk.tracewpp.configdir")
-- init args
local args = {}
if target:rule("wdk.driver") and (target:rule("wdk.env.kmdf") or target:rule("wdk.env.wdm")) then
table.insert(args, "-km")
table.insert(args, "-gen:{km-WdfDefault.tpl}*.tmh")
end
local flags = target:values("wdk.tracewpp.flags", sourcefile)
if flags then
table.join2(args, flags)
end
table.insert(args, "-cfgdir:" .. configdir)
table.insert(args, "-odir:" .. outputdir)
table.insert(args, sourcefile)
-- add includedirs
target:add("includedirs", outputdir)
-- need build this object?
local targetfile = path.join(outputdir, path.basename(sourcefile) .. ".tmh")
local dependfile = target:dependfile(targetfile)
local dependinfo = target:is_rebuilt() and {} or (depend.load(dependfile) or {})
if not depend.is_changed(dependinfo, {lastmtime = os.mtime(targetfile), values = args}) then
return
end
-- trace progress info
progress.show(opt.progress, "${color.build.object}compiling.wdk.tracewpp %s", sourcefile)
-- ensure the output directory
if not os.isdir(outputdir) then
os.mkdir(outputdir)
end
-- remove the previous target file first
os.tryrm(targetfile)
-- generate the *.tmh file
os.vrunv(tracewpp, args)
-- update files and values to the dependent file
dependinfo.files = {sourcefile}
dependinfo.values = args
depend.save(dependinfo, dependfile)
end)
|
0 | repos/xmake/xmake/rules/wdk | repos/xmake/xmake/rules/wdk/inf/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: *.inf
rule("wdk.inf")
-- add rule: wdk environment
add_deps("wdk.env")
-- set extensions
set_extensions(".inf", ".inx")
-- before load
on_load(function (target)
-- imports
import("core.project.config")
-- get arch
local arch = assert(config.arch(), "arch not found!")
-- get wdk
local wdk = target:data("wdk")
-- get stampinf
local stampinf = path.join(wdk.bindir, wdk.sdkver, arch, is_host("windows") and "stampinf.exe" or "stampinf")
assert(stampinf and os.isexec(stampinf), "stampinf not found!")
-- save uic
target:data_set("wdk.stampinf", stampinf)
end)
-- on build file
on_build_file(function (target, sourcefile, opt)
-- imports
import("core.base.option")
import("core.theme.theme")
import("core.project.depend")
import("utils.progress")
-- the target file
local targetfile = path.join(target:targetdir(), path.basename(sourcefile) .. ".inf")
-- save this target file for signing (wdk.sign.*, wdk.package.* rules)
target:data_set("wdk.sign.inf", targetfile)
-- init args
local args = {"-d", "*", "-a", is_arch("x64") and "amd64" or "x86", "-v", "*"}
local flags = target:values("wdk.inf.flags", sourcefile)
if flags then
table.join2(args, flags)
end
local wdk = target:data("wdk")
if wdk then
if wdk.kmdfver and (target:rule("wdk.env.wdm") or target:rule("wdk.env.kmdf")) then
table.insert(args, "-k")
table.insert(args, wdk.kmdfver)
elseif wdk.umdfver then
table.insert(args, "-u")
table.insert(args, wdk.umdfver .. ".0")
end
end
table.insert(args, "-f")
table.insert(args, targetfile)
-- need build this object?
local dependfile = target:dependfile(targetfile)
local dependinfo = target:is_rebuilt() and {} or (depend.load(dependfile) or {})
if not depend.is_changed(dependinfo, {lastmtime = os.mtime(targetfile), values = args}) then
return
end
-- trace progress info
progress.show(opt.progress, "${color.build.object}compiling.wdk.inf %s", sourcefile)
-- get stampinf
local stampinf = target:data("wdk.stampinf")
-- update the timestamp
os.cp(sourcefile, targetfile)
os.vrunv(stampinf, args)
-- update files and values to the dependent file
dependinfo.files = {sourcefile}
dependinfo.values = args
depend.save(dependinfo, dependfile)
end)
|
0 | repos/xmake/xmake/rules/wdk | repos/xmake/xmake/rules/wdk/mc/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: *.mc
rule("wdk.mc")
-- add rule: wdk environment
add_deps("wdk.env")
-- set extensions
set_extensions(".mc")
-- before load
on_load(function (target)
-- imports
import("core.project.config")
-- get arch
local arch = assert(config.arch(), "arch not found!")
-- get wdk
local wdk = target:data("wdk")
-- get mc
local mc = path.join(wdk.bindir, arch, is_host("windows") and "mc.exe" or "mc")
if not os.isexec(mc) then
mc = path.join(wdk.bindir, wdk.sdkver, arch, is_host("windows") and "mc.exe" or "mc")
end
assert(os.isexec(mc), "mc not found!")
-- save mc
target:data_set("wdk.mc", mc)
end)
-- before build file
before_build_file(function (target, sourcefile, opt)
-- imports
import("core.base.option")
import("core.theme.theme")
import("core.project.depend")
import("utils.progress")
-- get mc
local mc = target:data("wdk.mc")
-- get output directory
local outputdir = path.join(target:autogendir(), "rules", "wdk", "mc")
-- init args
local args = {}
local flags = target:values("wdk.mc.flags", sourcefile)
if flags then
table.join2(args, flags)
end
table.insert(args, "-h")
table.insert(args, outputdir)
table.insert(args, "-r")
table.insert(args, outputdir)
table.insert(args, sourcefile)
-- add includedirs
target:add("includedirs", outputdir)
-- add header file
local header = target:values("wdk.mc.header", sourcefile)
local headerfile = header and path.join(outputdir, header) or nil
if headerfile then
table.insert(args, "-z")
table.insert(args, path.basename(headerfile))
else
headerfile = path.join(outputdir, path.basename(sourcefile) .. ".h")
end
-- need build this object?
local dependfile = target:dependfile(headerfile)
local dependinfo = target:is_rebuilt() and {} or (depend.load(dependfile) or {})
if not depend.is_changed(dependinfo, {lastmtime = os.mtime(headerfile), values = args}) then
return
end
-- trace progress info
progress.show(opt.progress, "${color.build.object}compiling.wdk.mc %s", sourcefile)
-- do message compile
if not os.isdir(outputdir) then
os.mkdir(outputdir)
end
os.vrunv(mc, args)
-- update files and values to the dependent file
dependinfo.files = {sourcefile}
dependinfo.values = args
depend.save(dependinfo, dependfile)
end)
|
0 | repos/xmake/xmake/rules/wdk | repos/xmake/xmake/rules/wdk/package/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: package *.cab
rule("wdk.package.cab")
-- on package
on_package(function (target)
-- imports
import("core.base.option")
import("core.project.config")
import("lib.detect.find_program")
-- the output directory
local outputdir = path.join(option.get("outputdir") or config.buildir(), "drivers", target:name())
local mode = config.mode()
if mode then
outputdir = path.join(outputdir, mode)
end
local arch = config.arch()
if arch then
outputdir = path.join(outputdir, arch)
end
-- the package file
local packagefile = path.join(outputdir, target:name() .. ".cab")
-- the .ddf file
local ddfile = os.tmpfile(target:targetfile()) .. ".ddf"
-- trace progress info
if option.get("verbose") then
cprint("${dim magenta}packaging %s", packagefile)
else
cprint("${magenta}packaging %s", packagefile)
end
-- get makecab
local makecab = find_program("makecab", {check = "/?"})
assert(makecab, "makecab not found!")
-- make .ddf file
local file = io.open(ddfile, "w")
if file then
file:print("; %s.ddf", target:name())
file:print(";")
file:print(".OPTION EXPLICIT ; Generate errors")
file:print(".Set CabinetFileCountThreshold=0")
file:print(".Set FolderFileCountThreshold=0")
file:print(".Set FolderSizeThreshold=0")
file:print(".Set MaxCabinetSize=0")
file:print(".Set MaxDiskFileCount=0")
file:print(".Set MaxDiskSize=0")
file:print(".Set CompressionType=MSZIP")
file:print(".Set Cabinet=on")
file:print(".Set Compress=on")
file:print(";Specify file name for new cab file")
file:print(".Set CabinetNameTemplate=%s.cab", target:name())
file:print("; Specify the subdirectory for the files. ")
file:print("; Your cab file should not have files at the root level,")
file:print("; and each driver package must be in a separate subfolder.")
file:print(".Set DiskDirectoryTemplate=%s", outputdir)
file:print(";Specify files to be included in cab file")
local infile = target:data("wdk.sign.inf")
if infile and os.isfile(infile) then
file:print(path.absolute(infile))
end
file:print(path.absolute(target:targetfile()))
file:close()
end
-- make .cab
os.vrunv(makecab, {"/f", ddfile})
-- save this package file for signing (wdk.sign.* rules)
target:data_set("wdk.sign.cab", packagefile)
end)
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/dlang/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
rule("dlang.build")
set_sourcekinds("dc")
add_deps("dlang.build.optimization")
on_build_files("private.action.build.object", {batch = true})
on_load(function (target)
local toolchains = target:get("toolchains") or get_config("toolchain")
if not toolchains or not table.contains(table.wrap(toolchains), "dlang", "dmd", "ldc", "gdc") then
target:add("toolchains", "dlang")
end
end)
rule("dlang")
-- add build rules
add_deps("dlang.build")
-- inherit links and linkdirs of all dependent targets by default
add_deps("utils.inherit.links")
-- support `add_files("src/*.o")` and `add_files("src/*.a")` to merge object and archive files to target
add_deps("utils.merge.object", "utils.merge.archive")
-- we attempt to extract symbols to the independent file and
-- strip self-target binary if `set_symbols("debug")` and `set_strip("all")` are enabled
add_deps("utils.symbols.extract")
-- add linker rules
add_deps("linker")
|
0 | repos/xmake/xmake/rules/dlang | repos/xmake/xmake/rules/dlang/build_optimization/config.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file config.lua
--
-- imports
import("core.tool.compiler")
import("core.project.project")
-- add lto optimization
function _add_lto_optimization(target)
if target:has_tool("dc", "ldc2") and target:has_tool("dcld", "ldc2") then
target:add("dcflags", "-flto=thin", {force = true})
target:add("ldflags", "-flto=thin", "-defaultlib=phobos2-ldc-lto,druntime-ldc-lto", {force = true})
target:add("shflags", "-flto=thin", "-defaultlib=phobos2-ldc-lto,druntime-ldc-lto", {force = true})
-- to use the link-time optimizer, lto and optimization options should be specified at compile time and during the final link.
-- @see https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
local optimize = target:get("optimize")
if optimize then
local optimize_flags = compiler.map_flags("d", "optimize", optimize)
target:add("ldflags", optimize_flags)
target:add("shflags", optimize_flags)
end
end
end
function main(target)
if target:policy("build.optimization.lto") or
project.policy("build.optimization.lto") then
_add_lto_optimization(target)
end
end
|
0 | repos/xmake/xmake/rules/dlang | repos/xmake/xmake/rules/dlang/build_optimization/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: dlang.build.optimization
rule("dlang.build.optimization")
on_config("config")
|
0 | repos/xmake/xmake/rules/xcode | repos/xmake/xmake/rules/xcode/framework/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: xcode framework
rule("xcode.framework")
-- support add_files("Info.plist")
add_deps("xcode.info_plist")
-- we must set kind before target.on_load(), may we will use target in on_load()
on_load(function (target)
-- get framework directory
local targetdir = target:targetdir()
local bundledir = path.join(targetdir, target:basename() .. ".framework")
target:data_set("xcode.bundle.rootdir", bundledir)
-- get contents and resources directory
local contentsdir = target:is_plat("macosx") and path.join(bundledir, "Versions", "A") or bundledir
local resourcesdir = path.join(contentsdir, "Resources")
target:data_set("xcode.bundle.contentsdir", contentsdir)
target:data_set("xcode.bundle.resourcesdir", resourcesdir)
-- set target info for framework
if not target:get("kind") then
target:set("kind", "shared")
end
target:set("filename", target:basename())
-- export frameworks for `add_deps()`
target:data_set("inherit.links", false) -- disable to inherit links, @see rule("utils.inherit.links")
target:add("frameworks", target:basename(), {interface = true})
target:add("frameworkdirs", targetdir, {interface = true})
target:add("includedirs", path.join(contentsdir, "Headers.tmp"), {interface = true})
-- register clean files for `xmake clean`
target:add("cleanfiles", bundledir)
end)
before_build(function (target)
-- get framework directory
local bundledir = path.absolute(target:data("xcode.bundle.rootdir"))
local contentsdir = path.absolute(target:data("xcode.bundle.contentsdir"))
local headersdir = path.join(contentsdir, "Headers.tmp", target:basename())
-- copy header files to the framework directory
local srcheaders, dstheaders = target:headerfiles(headersdir)
if srcheaders and dstheaders then
local i = 1
for _, srcheader in ipairs(srcheaders) do
local dstheader = dstheaders[i]
if dstheader then
os.vcp(srcheader, dstheader)
end
i = i + 1
end
end
if not os.isdir(headersdir) then
os.mkdir(headersdir)
end
end)
after_build(function (target, opt)
-- imports
import("core.base.option")
import("core.theme.theme")
import("core.project.depend")
import("private.tools.codesign")
import("utils.progress")
-- get framework directory
local bundledir = path.absolute(target:data("xcode.bundle.rootdir"))
local contentsdir = target:data("xcode.bundle.contentsdir")
local resourcesdir = target:data("xcode.bundle.resourcesdir")
local headersdir = path.join(contentsdir, "Headers")
-- do build if changed
depend.on_changed(function ()
-- trace progress info
progress.show(opt.progress, "${color.build.target}generating.xcode.$(mode) %s", path.filename(bundledir))
-- copy target file
if not os.isdir(contentsdir) then
os.mkdir(contentsdir)
end
os.vcp(target:targetfile(), contentsdir)
if target:is_shared() then
-- change rpath
-- @see https://github.com/xmake-io/xmake/issues/2679#issuecomment-1221839215
local filename = path.filename(target:targetfile())
local targetfile = path.join(contentsdir, filename)
local rpath = path.relative(contentsdir, path.directory(bundledir))
os.vrunv("install_name_tool", {"-id", path.join("@rpath", rpath, filename), targetfile})
end
-- move header files
os.tryrm(headersdir)
os.mv(path.join(contentsdir, "Headers.tmp", target:basename()), headersdir)
os.rm(path.join(contentsdir, "Headers.tmp"))
-- copy resource files
local srcfiles, dstfiles = target:installfiles(resourcesdir)
if srcfiles and dstfiles then
local i = 1
for _, srcfile in ipairs(srcfiles) do
local dstfile = dstfiles[i]
if dstfile then
os.vcp(srcfile, dstfile)
end
i = i + 1
end
end
-- link Versions/Current -> Versions/A
-- only for macos, @see https://github.com/xmake-io/xmake/issues/2765
if target:is_plat("macosx") then
local oldir = os.cd(path.join(bundledir, "Versions"))
os.tryrm("Current")
os.ln("A", "Current")
-- link bundledir/* -> Versions/Current/*
local target_filename = path.filename(target:targetfile())
os.cd(bundledir)
os.tryrm("Headers")
os.tryrm("Resources")
os.tryrm(target_filename)
os.tryrm("Info.plist")
os.ln("Versions/Current/Headers", "Headers")
if os.isdir(resourcesdir) then
os.ln("Versions/Current/Resources", "Resources")
end
os.ln(path.join("Versions/Current", target_filename), target_filename)
os.cd(oldir)
end
-- do codesign, only for dynamic library
if target:is_shared() then
local codesign_identity = target:values("xcode.codesign_identity") or get_config("xcode_codesign_identity")
if target:is_plat("macosx") or (target:is_plat("iphoneos") and target:is_arch("x86_64", "i386")) then
codesign_identity = nil
end
codesign(contentsdir, codesign_identity)
end
end, {dependfile = target:dependfile(bundledir), files = {bundledir, target:targetfile()}, changed = target:is_rebuilt()})
end)
on_install(function (target)
import("xcode.application.build", {alias = "appbuild", rootdir = path.join(os.programdir(), "rules")})
local bundledir = path.absolute(target:data("xcode.bundle.rootdir"))
local installdir = target:installdir()
if installdir then
if not os.isdir(installdir) then
os.mkdir(installdir)
end
os.vcp(bundledir, installdir, {symlink = true})
end
end)
on_uninstall(function (target)
local bundledir = path.absolute(target:data("xcode.bundle.rootdir"))
local installdir = target:installdir()
os.tryrm(path.join(installdir, path.filename(bundledir)))
end)
-- disable package
on_package(function (target) end)
|
0 | repos/xmake/xmake/rules/xcode | repos/xmake/xmake/rules/xcode/info_plist/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule
rule("xcode.info_plist")
-- support add_files("Info.plist")
set_extensions(".plist")
-- build Info.plist
on_build_file(function (target, sourcefile, opt)
-- imports
import("core.base.option")
import("core.theme.theme")
import("core.project.depend")
import("core.tool.toolchain")
import("utils.progress")
-- check
assert(path.filename(sourcefile) == "Info.plist", "we only support Info.plist file!")
-- get contents and resources directory
local contentsdir = assert(target:data("xcode.bundle.contentsdir"), "contents directory not found!")
local resourcesdir = assert(target:data("xcode.bundle.resourcesdir"), "resources directory not found!")
-- need re-compile it?
local dependfile = target:dependfile(sourcefile)
local dependinfo = target:is_rebuilt() and {} or (depend.load(dependfile) or {})
if not depend.is_changed(dependinfo, {lastmtime = os.mtime(dependfile)}) then
return
end
-- trace progress info
progress.show(opt.progress, "${color.build.object}processing.xcode.$(mode) %s", sourcefile)
-- process and generate Info.plist
-- https://github.com/xmake-io/xmake/issues/2765#issuecomment-1251738622
local info_plist_file
if target:rule("xcode.framework") and target:is_plat("macosx") then
info_plist_file = path.join(resourcesdir, path.filename(sourcefile))
else
info_plist_file = path.join(contentsdir, path.filename(sourcefile))
end
local maps =
{
DEVELOPMENT_LANGUAGE = "en",
EXECUTABLE_NAME = target:basename(),
PRODUCT_BUNDLE_IDENTIFIER = target:values("xcode.bundle_identifier") or get_config("xcode_bundle_identifier") or "io.xmake." .. target:name(),
PRODUCT_NAME = target:name(),
PRODUCT_DISPLAY_NAME = target:name(),
CURRENT_PROJECT_VERSION = target:version() and tostring(target:version()) or "1.0",
}
if target:is_plat("macosx") then
local toolchain_xcode = toolchain.load("xcode", {plat = target:plat(), arch = target:arch()})
if toolchain_xcode then
maps.MACOSX_DEPLOYMENT_TARGET = toolchain_xcode:config("target_minver")
end
end
if target:rule("xcode.bundle") then
maps.PRODUCT_BUNDLE_PACKAGE_TYPE = "BNDL"
elseif target:rule("xcode.framework") then
maps.PRODUCT_BUNDLE_PACKAGE_TYPE = "FMWK"
elseif target:rule("xcode.application") then
maps.PRODUCT_BUNDLE_PACKAGE_TYPE = "APPL"
end
os.vcp(sourcefile, info_plist_file)
io.gsub(info_plist_file, "(%$%((.-)%))", function (_, variable)
return maps[variable]
end)
-- patch some entries for mac catalyst
local xcode = target:toolchain("xcode")
if xcode and xcode:config("appledev") == "catalyst" then
-- remove entry for "LSRequiresIPhoneOS" - not supported on macOS
--
-- <key>LSRequiresIPhoneOS</key>
-- <true/>
io.replace(info_plist_file, "<key>LSRequiresIPhoneOS</key>.-<true/>", "")
end
-- update files and values to the dependent file
dependinfo.files = {sourcefile}
depend.save(dependinfo, dependfile)
end)
|
0 | repos/xmake/xmake/rules/xcode | repos/xmake/xmake/rules/xcode/metal/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- build metal files
--
-- @see https://developer.apple.com/documentation/metal/libraries/building_a_library_with_metal_s_command-line_tools
--
rule("xcode.metal")
set_extensions(".metal")
-- build *.metal to *.air
on_buildcmd_file(function (target, batchcmds, sourcefile, opt)
-- get metal
import("lib.detect.find_tool")
local xcode = assert(target:toolchain("xcode"), "xcode not fount!")
local metal = assert(find_tool("metal", {program = path.join(xcode:bindir(), "metal")}), "metal command not found!")
-- get xcode toolchain
local target_minver = xcode:config("target_minver")
local xcode_sysroot = xcode:config("xcode_sysroot")
-- init metal arguments
local objectfile = target:objectfile(sourcefile) .. ".air"
local argv = {"-c", "-ffast-math", "-gline-tables-only"}
if target_minver then
table.insert(argv, "-target")
local airarch = target:is_arch("x86_64", "arm64") and "air64" or "air32"
if target:is_plat("macosx") then
table.insert(argv, airarch .. "-apple-macos" .. target_minver)
elseif target:is_plat("iphoneos") then
local airtarget = airarch .. "-apple-ios" .. target_minver
if target:is_arch("x86_64", "i386") then
airtarget = airtarget .. "-simulator"
end
table.insert(argv, airtarget)
elseif target:is_plat("watchos") then
local airtarget = airarch .. "-apple-watchos" .. target_minver
if target:is_arch("x86_64", "i386") then
airtarget = airtarget .. "-simulator"
end
table.insert(argv, airtarget)
elseif target:is_plat("appletvos") then
local airtarget = airarch .. "-apple-tvos" .. target_minver
if target:is_arch("x86_64", "i386") then
airtarget = airtarget .. "-simulator"
end
table.insert(argv, airtarget)
end
end
if xcode_sysroot then
table.insert(argv, "-isysroot")
table.insert(argv, path(xcode_sysroot))
end
table.insert(argv, "-o")
table.insert(argv, path(objectfile))
table.insert(argv, path(sourcefile))
-- add commands
batchcmds:show_progress(opt.progress, "${color.build.object}compiling.metal %s", sourcefile)
batchcmds:mkdir(path.directory(objectfile))
batchcmds:vrunv(metal.program, argv)
-- add deps
batchcmds:add_depfiles(sourcefile)
batchcmds:set_depmtime(os.mtime(objectfile))
batchcmds:set_depcache(target:dependfile(objectfile))
end)
-- link *.air to *.metallib
before_linkcmd(function (target, batchcmds, opt)
-- get objectfiles
local objectfiles = {}
local objectfiles_wrap = {}
for rulename, sourcebatch in pairs(target:sourcebatches()) do
if rulename == "xcode.metal" then
for _, sourcefile in ipairs(sourcebatch.sourcefiles) do
table.insert(objectfiles, target:objectfile(sourcefile) .. ".air")
table.insert(objectfiles_wrap, path(target:objectfile(sourcefile) .. ".air"))
end
break
end
end
if #objectfiles == 0 then
return
end
-- get metallib
import("lib.detect.find_tool")
local xcode = assert(target:toolchain("xcode"), "xcode not fount!")
local metallib = assert(find_tool("metallib", {program = path.join(xcode:bindir(), "metallib")}), "metallib command not found!")
-- get xcode toolchain
local xcode_sysroot = xcode:config("xcode_sysroot")
-- add commands
local resourcesdir = path.absolute(target:data("xcode.bundle.resourcesdir"))
local libraryfile = resourcesdir and path.join(resourcesdir, "default.metallib") or (target:targetfile() .. ".metallib")
batchcmds:show_progress(opt.progress, "${color.build.target}linking.metal %s", path.filename(libraryfile))
batchcmds:mkdir(path.directory(libraryfile))
batchcmds:vrunv(metallib.program, table.join({"-o", path(libraryfile)}, objectfiles_wrap), {envs = {SDKROOT = xcode_sysroot}})
-- add deps
batchcmds:add_depfiles(objectfiles)
batchcmds:set_depmtime(os.mtime(libraryfile))
batchcmds:set_depcache(target:dependfile(libraryfile))
end)
|
0 | repos/xmake/xmake/rules/xcode | repos/xmake/xmake/rules/xcode/application/uninstall.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file uninstall.lua
--
-- imports
import("lib.detect.find_tool")
-- uninstall for ios
function _uninstall_for_ios(target)
-- TODO
end
-- uninstall for macosx
function _uninstall_for_macosx(target)
-- get app directory
local appdir = target:data("xcode.bundle.rootdir")
-- do uninstall
os.rm(path.join(target:installdir() or "/Applications", path.filename(appdir)))
end
-- main entry
function main (target)
if target:is_plat("iphoneos") then
_uninstall_for_ios(target)
elseif target:is_plat("macosx") then
_uninstall_for_macosx(target)
end
end
|
0 | repos/xmake/xmake/rules/xcode | repos/xmake/xmake/rules/xcode/application/build.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file build.lua
--
-- imports
import("core.base.option")
import("core.theme.theme")
import("core.project.depend")
import("private.tools.codesign")
import("utils.progress")
-- main entry
function main (target, opt)
-- get app and resources directory
local bundledir = path.absolute(target:data("xcode.bundle.rootdir"))
local contentsdir = path.absolute(target:data("xcode.bundle.contentsdir"))
local resourcesdir = path.absolute(target:data("xcode.bundle.resourcesdir"))
local frameworksdir = path.join(contentsdir, "Frameworks")
-- do build if changed
depend.on_changed(function ()
-- trace progress info
progress.show(opt.progress, "${color.build.target}generating.xcode.$(mode) %s", path.filename(bundledir))
-- copy target file
local binarydir = contentsdir
if target:is_plat("macosx") then
binarydir = path.join(contentsdir, "MacOS")
end
os.vcp(target:targetfile(), path.join(binarydir, path.filename(target:targetfile())))
-- change rpath
-- @see https://github.com/xmake-io/xmake/issues/2679#issuecomment-1221839215
local targetfile = path.join(binarydir, path.filename(target:targetfile()))
try { function () os.vrunv("install_name_tool", {"-delete_rpath", "@loader_path", targetfile}) end }
os.vrunv("install_name_tool", {"-add_rpath", "@executable_path/../Frameworks", targetfile})
-- copy dependent dynamic libraries and frameworks
for _, dep in ipairs(target:orderdeps()) do
if dep:kind() == "shared" then
if not os.isdir(frameworksdir) then
os.mkdir(frameworksdir)
end
local frameworkdir = dep:data("xcode.bundle.rootdir")
if dep:rule("xcode.framework") and frameworkdir then
os.cp(frameworkdir, frameworksdir, {symlink = true})
else
os.vcp(dep:targetfile(), frameworksdir)
end
end
end
-- copy PkgInfo to the contents directory
os.mkdir(resourcesdir)
os.vcp(path.join(os.programdir(), "scripts", "PkgInfo"), resourcesdir)
-- copy resource files to the resources directory
local srcfiles, dstfiles = target:installfiles(resourcesdir)
if srcfiles and dstfiles then
local i = 1
for _, srcfile in ipairs(srcfiles) do
local dstfile = dstfiles[i]
if dstfile then
os.vcp(srcfile, dstfile)
end
i = i + 1
end
end
-- generate embedded.mobileprovision to *.app/embedded.mobileprovision
local mobile_provision_embedded = path.join(bundledir, "embedded.mobileprovision")
local mobile_provision = target:values("xcode.mobile_provision") or get_config("xcode_mobile_provision")
if mobile_provision and target:is_plat("iphoneos") then
os.tryrm(mobile_provision_embedded)
local provisions = codesign.mobile_provisions()
if provisions then
local mobile_provision_data = provisions[mobile_provision]
if mobile_provision_data then
io.writefile(mobile_provision_embedded, mobile_provision_data)
end
end
end
-- do codesign
local codesign_identity = target:values("xcode.codesign_identity") or get_config("xcode_codesign_identity")
if target:is_plat("macosx") or (target:is_plat("iphoneos") and target:is_arch("x86_64", "i386")) then
codesign_identity = nil
end
codesign(bundledir, codesign_identity, mobile_provision, {deep = true})
end, {dependfile = target:dependfile(bundledir), files = {bundledir, target:targetfile()}, changed = target:is_rebuilt()})
end
|
0 | repos/xmake/xmake/rules/xcode | repos/xmake/xmake/rules/xcode/application/run.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file run.lua
--
-- imports
import("core.base.option")
import("devel.debugger")
import("private.action.run.runenvs")
-- run on macosx
function _run_on_macosx(target, opt)
-- get the runable target file
local contentsdir = path.absolute(target:data("xcode.bundle.contentsdir"))
local binarydir = path.join(contentsdir, "MacOS")
local targetfile = path.join(binarydir, path.filename(target:targetfile()))
-- get the run directory of target
local rundir = target:rundir()
-- enter the run directory
local oldir = os.cd(rundir)
-- add run environments
local addrunenvs, setrunenvs = runenvs.make(target)
-- debugging?
if option.get("debug") then
debugger.run(targetfile, option.get("arguments"), {addrunenvs = addrunenvs, setrunenvs = setrunenvs})
else
os.execv(targetfile, option.get("arguments"), {envs = runenvs.join(addrunenvs, setrunenvs)})
end
-- restore the previous directory
os.cd(oldir)
end
-- run on simulator
function _run_on_simulator(target, opt)
-- get devices list
local list = try { function () return os.iorun("xcrun simctl list") end}
assert(list, "simulator devices not found!")
-- find the booted devices
local name, deviceid
for _, line in ipairs(list:split('\n', {plain = true})) do
if line:find("(Booted)", 1, true) then
line = line:trim()
name, deviceid = line:match("(.-)%s+%(([%w%-]+)%)")
if name and deviceid then
break
end
end
end
assert(name and deviceid, "booted simulator devices not found!")
-- do launch on first simulator device
local bundle_identifier = target:values("xcode.bundle_identifier") or get_config("xcode_bundle_identifier") or "io.xmake." .. target:name()
if bundle_identifier then
print("running %s application on %s (%s) ..", target:name(), name, deviceid)
os.execv("xcrun", {"simctl", "launch", "--console", deviceid, bundle_identifier})
end
end
-- main entry
function main (target, opt)
if target:is_plat("macosx") then
_run_on_macosx(target, opt)
elseif target:is_plat("iphoneos") and target:is_arch("x86_64", "i386") then
_run_on_simulator(target, opt)
else
raise("we can only run application on macOS or simulator!")
end
end
|
0 | repos/xmake/xmake/rules/xcode | repos/xmake/xmake/rules/xcode/application/install.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file install.lua
--
-- imports
import("core.base.task")
import("lib.detect.find_tool")
import("utils.ipa.install", {alias = "install_ipa"})
-- install for ios
function _install_for_ios(target)
-- get app directory
local appdir = target:data("xcode.bundle.rootdir")
-- get *.ipa file
local ipafile = path.join(path.directory(appdir), path.basename(appdir) .. ".ipa")
if not os.isfile(ipafile) or os.mtime(target:targetfile()) > os.mtime(ipafile) then
task.run("package", {target = target:name()})
end
assert(os.isfile(ipafile), "please run `xmake package` first!")
-- do install
install_ipa(ipafile)
end
-- install for ios simulator
function _install_for_ios_simulator(target)
-- get app directory
local appdir = target:data("xcode.bundle.rootdir")
-- do install
os.vrunv("xcrun", {"simctl", "install", "booted", appdir})
end
-- install for macosx
function _install_for_macosx(target)
-- get app directory
local appdir = target:data("xcode.bundle.rootdir")
-- do install
os.vcp(appdir, target:installdir() or "/Applications/")
end
-- main entry
function main (target)
if target:is_plat("iphoneos") then
if target:is_arch("x86_64", "i386") then
_install_for_ios_simulator(target)
else
_install_for_ios(target)
end
elseif target:is_plat("macosx") then
_install_for_macosx(target)
end
end
|
0 | repos/xmake/xmake/rules/xcode | repos/xmake/xmake/rules/xcode/application/load.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file load.lua
--
-- main entry
function main (target)
-- get bundle directory
local targetdir = target:targetdir()
local bundledir = path.join(targetdir, target:basename() .. ".app")
target:data_set("xcode.bundle.rootdir", bundledir)
-- get contents and resources directory
local contentsdir = bundledir
local resourcesdir = bundledir
if target:is_plat("macosx") then
contentsdir = path.join(bundledir, "Contents")
resourcesdir = path.join(bundledir, "Contents", "Resources")
end
target:data_set("xcode.bundle.contentsdir", contentsdir)
target:data_set("xcode.bundle.resourcesdir", resourcesdir)
-- set target directory for app
target:set("kind", "binary")
target:set("filename", target:basename())
-- set install directory
if target:is_plat("macosx") and not target:get("installdir") then
target:set("installdir", "/Applications")
end
-- add frameworks
if target:is_plat("macosx") then
local xcode = target:toolchain("xcode")
if xcode and xcode:config("appledev") == "catalyst" then
target:add("frameworks", "UIKit")
else
target:add("frameworks", "AppKit")
end
else
target:add("frameworks", "UIKit")
end
-- register clean files for `xmake clean`
target:add("cleanfiles", bundledir)
end
|
0 | repos/xmake/xmake/rules/xcode | repos/xmake/xmake/rules/xcode/application/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: xcode application
rule("xcode.application")
-- support add_files("Info.plist", "*.storyboard", "*.xcassets", "*.metal")
add_deps("xcode.info_plist", "xcode.storyboard", "xcode.xcassets", "xcode.metal")
-- we must set kind before target.on_load(), may we will use target in on_load()
on_load("load")
-- depend xcode.framework? we need to disable `build.across_targets_in_parallel` policy
after_load(function (target)
local across_targets_in_parallel
for _, dep in ipairs(target:orderdeps()) do
if dep:rule("xcode.framework") then
across_targets_in_parallel = false
end
end
if across_targets_in_parallel ~= nil then
target:set("policy", "build.across_targets_in_parallel", across_targets_in_parallel)
end
end)
-- build *.app
after_build("build")
-- package *.app to *.ipa (iphoneos) or *.dmg (macosx)
on_package("package")
-- install application
on_install("install")
-- uninstall application
on_uninstall("uninstall")
-- run application
on_run("run")
|
0 | repos/xmake/xmake/rules/xcode | repos/xmake/xmake/rules/xcode/application/package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file package.lua
--
-- imports
import("utils.ipa.package", {alias = "ipagen"})
-- package for ios
function _package_for_ios(target)
-- get app directory
local appdir = target:data("xcode.bundle.rootdir")
-- get *.ipa file
local ipafile = path.join(path.directory(appdir), path.basename(appdir) .. ".ipa")
-- generate *.ipa file
ipagen(appdir, ipafile)
-- trace
cprint("output: ${bright}%s", ipafile)
cprint("${color.success}package ok!")
end
-- main entry
function main (target, opt)
if target:is_plat("iphoneos") then
_package_for_ios(target)
end
end
|
0 | repos/xmake/xmake/rules/xcode | repos/xmake/xmake/rules/xcode/storyboard/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
rule("xcode.storyboard")
-- support add_files("*.storyboard")
set_extensions(".storyboard")
-- build *.storyboard
on_build_file(function (target, sourcefile, opt)
-- imports
import("core.base.option")
import("core.theme.theme")
import("core.project.depend")
import("core.tool.toolchain")
import("utils.progress")
-- get xcode sdk directory
local xcode_sdkdir = assert(get_config("xcode"), "xcode not found!")
local xcode_usrdir = path.join(xcode_sdkdir, "Contents", "Developer", "usr")
-- get base.lproj
local base_lproj = path.join(target:autogendir(), "rules", "xcode", "storyboard", "Base.lproj")
-- get resources directory
local resourcesdir = assert(target:data("xcode.bundle.resourcesdir"), "resources directory not found!")
-- need re-compile it?
local dependfile = target:dependfile(sourcefile)
local dependinfo = target:is_rebuilt() and {} or (depend.load(dependfile) or {})
if not depend.is_changed(dependinfo, {lastmtime = os.mtime(dependfile)}) then
return
end
-- trace progress info
progress.show(opt.progress, "${color.build.object}compiling.xcode.$(mode) %s", sourcefile)
-- clear Base.lproj first
os.tryrm(base_lproj)
os.mkdir(base_lproj)
-- do compile
local target_minver = nil
local toolchain_xcode = toolchain.load("xcode", {plat = target:plat(), arch = target:arch()})
if toolchain_xcode then
target_minver = toolchain_xcode:config("target_minver")
end
local argv = {"--errors", "--warnings", "--notices", "--auto-activate-custom-fonts", "--output-format", "human-readable-text"}
if target:is_plat("macosx") then
local xcode = target:toolchain("xcode")
if xcode and xcode:config("appledev") == "catalyst" then
table.insert(argv, "--platform")
table.insert(argv, "macosx")
table.insert(argv, "--target-device")
table.insert(argv, "ipad")
else
table.insert(argv, "--target-device")
table.insert(argv, "mac")
end
elseif target:is_plat("iphoneos") then
table.insert(argv, "--target-device")
table.insert(argv, "iphone")
table.insert(argv, "--target-device")
table.insert(argv, "ipad")
else
assert("unknown device!")
end
if target_minver then
table.insert(argv, "--minimum-deployment-target")
table.insert(argv, target_minver)
end
table.insert(argv, "--compilation-directory")
table.insert(argv, base_lproj)
table.insert(argv, sourcefile)
os.vrunv(path.join(xcode_usrdir, "bin", "ibtool"), argv, {envs = {XCODE_DEVELOPER_USR_PATH = xcode_usrdir}})
-- do link
argv = {"--errors", "--warnings", "--notices", "--auto-activate-custom-fonts", "--output-format", "human-readable-text"}
if target:is_plat("macosx") then
table.insert(argv, "--target-device")
table.insert(argv, "mac")
end
if target_minver then
table.insert(argv, "--minimum-deployment-target")
table.insert(argv, target_minver)
end
table.insert(argv, "--link")
table.insert(argv, resourcesdir)
table.insert(argv, path.join(base_lproj, path.filename(sourcefile) .. "c"))
os.vrunv(path.join(xcode_usrdir, "bin", "ibtool"), argv, {envs = {XCODE_DEVELOPER_USR_PATH = xcode_usrdir}})
-- update files and values to the dependent file
dependinfo.files = {sourcefile}
depend.save(dependinfo, dependfile)
end)
|
0 | repos/xmake/xmake/rules/xcode | repos/xmake/xmake/rules/xcode/xcassets/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule
rule("xcode.xcassets")
-- support add_files("*.xcassets")
set_extensions(".xcassets")
-- build *.xcassets
on_build_file(function (target, sourcefile, opt)
-- imports
import("core.base.option")
import("core.theme.theme")
import("core.project.depend")
import("core.tool.toolchain")
import("utils.progress")
-- get xcode sdk directory
local xcode_sdkdir = assert(get_config("xcode"), "xcode not found!")
local xcode_usrdir = path.join(xcode_sdkdir, "Contents", "Developer", "usr")
-- get resources directory
local resourcesdir = assert(target:data("xcode.bundle.resourcesdir"), "resources directory not found!")
-- need re-compile it?
local dependfile = target:dependfile(sourcefile)
local dependinfo = target:is_rebuilt() and {} or (depend.load(dependfile) or {})
if not depend.is_changed(dependinfo, {lastmtime = os.mtime(dependfile)}) then
return
end
-- ensure resources directory exists
if not os.isdir(resourcesdir) then
os.mkdir(resourcesdir)
end
-- trace progress info
progress.show(opt.progress, "${color.build.object}compiling.xcode.$(mode) %s", sourcefile)
-- get assetcatalog_generated_info.plist
local assetcatalog_generated_info_plist = path.join(target:autogendir(), "rules", "xcode", "xcassets", "assetcatalog_generated_info.plist")
io.writefile(assetcatalog_generated_info_plist, "")
-- do compile
local target_minver = nil
local toolchain_xcode = toolchain.load("xcode", {plat = target:plat(), arch = target:arch()})
if toolchain_xcode then
target_minver = toolchain_xcode:config("target_minver")
end
local argv = {"--warnings", "--notices", "--output-format", "human-readable-text"}
if target:is_plat("macosx") then
table.insert(argv, "--target-device")
table.insert(argv, "mac")
table.insert(argv, "--platform")
table.insert(argv, "macosx")
elseif target:is_plat("iphoneos") then
table.insert(argv, "--target-device")
table.insert(argv, "iphone")
table.insert(argv, "--target-device")
table.insert(argv, "ipad")
table.insert(argv, "--platform")
table.insert(argv, "iphoneos")
else
assert("unknown device!")
end
if target_minver then
table.insert(argv, "--minimum-deployment-target")
table.insert(argv, target_minver)
end
table.insert(argv, "--app-icon")
table.insert(argv, "AppIcon")
if target:is_plat("iphoneos") then
table.insert(argv, "--enable-on-demand-resources")
table.insert(argv, "YES")
table.insert(argv, "--compress-pngs")
else
table.insert(argv, "--enable-on-demand-resources")
table.insert(argv, "NO")
end
table.insert(argv, "--output-partial-info-plist")
table.insert(argv, assetcatalog_generated_info_plist)
table.insert(argv, "--development-region")
table.insert(argv, "en")
table.insert(argv, "--product-type")
table.insert(argv, "com.apple.product-type.application")
table.insert(argv, "--compile")
table.insert(argv, resourcesdir)
table.insert(argv, sourcefile)
os.vrunv(path.join(xcode_usrdir, "bin", "actool"), argv)
-- update files and values to the dependent file
dependinfo.files = {sourcefile}
depend.save(dependinfo, dependfile)
end)
|
0 | repos/xmake/xmake/rules/xcode | repos/xmake/xmake/rules/xcode/bundle/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: xcode bundle
rule("xcode.bundle")
-- support add_files("Info.plist")
add_deps("xcode.info_plist")
-- we must set kind before target.on_load(), may we will use target in on_load()
on_load(function (target)
-- get bundle directory
local targetdir = target:targetdir()
local bundledir = path.join(targetdir, target:basename() .. ".bundle")
target:data_set("xcode.bundle.rootdir", bundledir)
-- get contents and resources directory
local contentsdir = bundledir
local resourcesdir = bundledir
if target:is_plat("macosx") then
contentsdir = path.join(bundledir, "Contents")
resourcesdir = path.join(bundledir, "Contents", "Resources")
end
target:data_set("xcode.bundle.contentsdir", contentsdir)
target:data_set("xcode.bundle.resourcesdir", resourcesdir)
-- register clean files for `xmake clean`
target:add("cleanfiles", bundledir)
-- generate binary as bundle, we cannot set `-shared` or `-dynamiclib`
target:set("kind", "binary")
-- set target info for bundle
target:set("filename", target:basename())
end)
on_config(function (target)
-- add bundle flags
local linker = target:linker():name()
if linker == "swiftc" then
target:add("ldflags", "-Xlinker -bundle", {force = true})
else
target:add("ldflags", "-bundle", {force = true})
end
end)
after_build(function (target, opt)
-- imports
import("core.base.option")
import("core.theme.theme")
import("core.project.depend")
import("private.tools.codesign")
import("utils.progress")
-- get bundle and resources directory
local bundledir = path.absolute(target:data("xcode.bundle.rootdir"))
local contentsdir = path.absolute(target:data("xcode.bundle.contentsdir"))
local resourcesdir = path.absolute(target:data("xcode.bundle.resourcesdir"))
-- do build if changed
depend.on_changed(function ()
-- trace progress info
progress.show(opt.progress, "${color.build.target}generating.xcode.$(mode) %s", path.filename(bundledir))
-- copy target file
if target:is_plat("macosx") then
os.vcp(target:targetfile(), path.join(contentsdir, "MacOS", path.filename(target:targetfile())))
else
os.vcp(target:targetfile(), path.join(contentsdir, path.filename(target:targetfile())))
end
-- copy resource files
local srcfiles, dstfiles = target:installfiles(resourcesdir)
if srcfiles and dstfiles then
local i = 1
for _, srcfile in ipairs(srcfiles) do
local dstfile = dstfiles[i]
if dstfile then
os.vcp(srcfile, dstfile)
end
i = i + 1
end
end
-- do codesign
local codesign_identity = target:values("xcode.codesign_identity") or get_config("xcode_codesign_identity")
if target:is_plat("macosx") or (target:is_plat("iphoneos") and target:is_arch("x86_64", "i386")) then
codesign_identity = nil
end
codesign(bundledir, codesign_identity)
end, {dependfile = target:dependfile(bundledir), files = {bundledir, target:targetfile()}, changed = target:is_rebuilt()})
end)
on_install(function (target)
local bundledir = path.absolute(target:data("xcode.bundle.rootdir"))
local installdir = target:installdir()
if installdir then
if not os.isdir(installdir) then
os.mkdir(installdir)
end
os.vcp(bundledir, installdir)
end
end)
on_uninstall(function (target)
local bundledir = path.absolute(target:data("xcode.bundle.rootdir"))
local installdir = target:installdir()
os.tryrm(path.join(installdir, path.filename(bundledir)))
end)
-- disable package
on_package(function (target) end)
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/c++/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
rule("c.build")
set_sourcekinds("cc")
add_deps("c.build.pcheader", "c.build.optimization", "c.build.sanitizer")
on_build_files("private.action.build.object", {batch = true, distcc = true})
on_config(function (target)
-- https://github.com/xmake-io/xmake/issues/4621
if target:is_plat("windows") and target:is_static() and target:has_tool("cc", "tcc") then
target:set("extension", ".a")
target:set("prefixname", "lib")
end
end)
rule("c++.build")
set_sourcekinds("cxx")
add_deps("c++.build.pcheader", "c++.build.modules", "c++.build.optimization", "c++.build.sanitizer")
on_build_files("private.action.build.object", {batch = true, distcc = true})
on_config(function (target)
-- we enable c++ exceptions by default
if target:is_plat("windows") and not target:get("exceptions") then
target:set("exceptions", "cxx")
end
-- https://github.com/xmake-io/xmake/issues/4621
if target:is_plat("windows") and target:is_static() and target:has_tool("cxx", "tcc") then
target:set("extension", ".a")
target:set("prefixname", "lib")
end
end)
rule("c")
-- add build rules
add_deps("c.build")
-- set compiler runtime, e.g. vs runtime
add_deps("utils.compiler.runtime")
-- inherit links and linkdirs of all dependent targets by default
add_deps("utils.inherit.links")
-- support `add_files("src/*.o")` and `add_files("src/*.a")` to merge object and archive files to target
add_deps("utils.merge.object", "utils.merge.archive")
-- we attempt to extract symbols to the independent file and
-- strip self-target binary if `set_symbols("debug")` and `set_strip("all")` are enabled
add_deps("utils.symbols.extract")
-- add platform rules
add_deps("platform.wasm")
add_deps("platform.windows")
-- add linker rules
add_deps("linker")
rule("c++")
-- add build rules
add_deps("c++.build")
-- set compiler runtime, e.g. vs runtime
add_deps("utils.compiler.runtime")
-- inherit links and linkdirs of all dependent targets by default
add_deps("utils.inherit.links")
-- support `add_files("src/*.o")` and `add_files("src/*.a")` to merge object and archive files to target
add_deps("utils.merge.object", "utils.merge.archive")
-- we attempt to extract symbols to the independent file and
-- strip self-target binary if `set_symbols("debug")` and `set_strip("all")` are enabled
add_deps("utils.symbols.extract")
-- add platform rules
add_deps("platform.wasm")
add_deps("platform.windows")
-- add linker rules
add_deps("linker")
|
0 | repos/xmake/xmake/rules/c++ | repos/xmake/xmake/rules/c++/modules/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki, Arthapz
-- @file xmake.lua
--
-- define rule: c++.build.modules
rule("c++.build.modules")
-- @note common.contains_modules() need it
set_extensions(".cppm", ".ccm", ".cxxm", ".c++m", ".mpp", ".mxx", ".ixx")
add_deps("c++.build.modules.builder")
add_deps("c++.build.modules.install")
on_config(function (target)
import("modules_support.compiler_support")
-- we disable to build across targets in parallel, because the source files may depend on other target modules
-- @see https://github.com/xmake-io/xmake/issues/1858
if compiler_support.contains_modules(target) then
-- @note this will cause cross-parallel builds to be disabled for all sub-dependent targets,
-- even if some sub-targets do not contain C++ modules.
--
-- maybe we will have a more fine-grained configuration strategy to disable it in the future.
target:set("policy", "build.across_targets_in_parallel", false)
-- disable ccache for this target
--
-- Caching can affect incremental compilation, for example
-- by interfering with the results of depfile generation for msvc.
--
-- @see https://github.com/xmake-io/xmake/issues/3000
target:set("policy", "build.ccache", false)
-- load compiler support
compiler_support.load(target)
-- mark this target with modules
target:data_set("cxx.has_modules", true)
-- moduleonly modules are implicitly public
if target:is_moduleonly() then
local sourcebatch = target:sourcebatches()["c++.build.modules.builder"]
for _, sourcefile in ipairs(sourcebatch.sourcefiles) do
target:fileconfig_add(sourcefile, {public = true})
end
end
end
end)
-- build modules
rule("c++.build.modules.builder")
set_sourcekinds("cxx")
set_extensions(".mpp", ".mxx", ".cppm", ".ixx")
-- parallel build support to accelerate `xmake build` to build modules
before_build_files(function(target, batchjobs, sourcebatch, opt)
if target:data("cxx.has_modules") then
import("modules_support.compiler_support")
import("modules_support.dependency_scanner")
import("modules_support.builder")
-- add target deps modules
if target:orderdeps() then
local deps_sourcefiles = dependency_scanner.get_targetdeps_modules(target)
if deps_sourcefiles then
table.join2(sourcebatch.sourcefiles, deps_sourcefiles)
end
end
-- append std module
local std_modules = compiler_support.get_stdmodules(target)
if std_modules then
table.join2(sourcebatch.sourcefiles, std_modules)
end
-- extract packages modules dependencies
local package_modules_data = dependency_scanner.get_all_packages_modules(target, opt)
if package_modules_data then
-- append to sourcebatch
for _, package_module_data in table.orderpairs(package_modules_data) do
table.insert(sourcebatch.sourcefiles, package_module_data.file)
target:fileconfig_set(package_module_data.file, {external = package_module_data.external, defines = package_module_data.metadata.defines})
end
end
opt = opt or {}
opt.batchjobs = true
compiler_support.patch_sourcebatch(target, sourcebatch, opt)
local modules = dependency_scanner.get_module_dependencies(target, sourcebatch, opt)
if not target:is_moduleonly() then
-- avoid building non referenced modules
local build_objectfiles, link_objectfiles = dependency_scanner.sort_modules_by_dependencies(target, sourcebatch.objectfiles, modules)
sourcebatch.objectfiles = build_objectfiles
-- build modules
builder.build_modules_for_batchjobs(target, batchjobs, sourcebatch, modules, opt)
-- build headerunits and we need to do it before building modules
builder.build_headerunits_for_batchjobs(target, batchjobs, sourcebatch, modules, opt)
sourcebatch.objectfiles = link_objectfiles
else
sourcebatch.objectfiles = {}
end
compiler_support.localcache():set2(target:name(), "c++.modules", modules)
compiler_support.localcache():save()
else
-- avoid duplicate linking of object files of non-module programs
sourcebatch.objectfiles = {}
end
end, {batch = true})
-- serial compilation only, usually used to support project generator
before_buildcmd_files(function(target, batchcmds, sourcebatch, opt)
if target:data("cxx.has_modules") then
import("modules_support.compiler_support")
import("modules_support.dependency_scanner")
import("modules_support.builder")
-- add target deps modules
if target:orderdeps() then
local deps_sourcefiles = dependency_scanner.get_targetdeps_modules(target)
if deps_sourcefiles then
table.join2(sourcebatch.sourcefiles, deps_sourcefiles)
end
end
-- append std module
local std_modules = compiler_support.get_stdmodules(target)
if std_modules then
table.join2(sourcebatch.sourcefiles, std_modules)
end
-- extract packages modules dependencies
local package_modules_data = dependency_scanner.get_all_packages_modules(target, opt)
if package_modules_data then
-- append to sourcebatch
for _, package_module_data in table.orderpairs(package_modules_data) do
table.insert(sourcebatch.sourcefiles, package_module_data.file)
target:fileconfig_set(package_module_data.file, {external = package_module_data.external, defines = package_module_data.metadata.defines})
end
end
opt = opt or {}
opt.batchjobs = false
compiler_support.patch_sourcebatch(target, sourcebatch, opt)
local modules = dependency_scanner.get_module_dependencies(target, sourcebatch, opt)
if not target:is_moduleonly() then
-- avoid building non referenced modules
local build_objectfiles, link_objectfiles = dependency_scanner.sort_modules_by_dependencies(target, sourcebatch.objectfiles, modules)
sourcebatch.objectfiles = build_objectfiles
-- build headerunits
builder.build_headerunits_for_batchcmds(target, batchcmds, sourcebatch, modules, opt)
-- build modules
builder.build_modules_for_batchcmds(target, batchcmds, sourcebatch, modules, opt)
sourcebatch.objectfiles = link_objectfiles
else
-- avoid duplicate linking of object files of non-module programs
sourcebatch.objectfiles = {}
end
compiler_support.localcache():set2(target:name(), "c++.modules", modules)
compiler_support.localcache():save()
else
sourcebatch.sourcefiles = {}
sourcebatch.objectfiles = {}
sourcebatch.dependfiles = {}
end
end)
after_clean(function (target)
import("core.base.option")
import("modules_support.compiler_support")
import("private.action.clean.remove_files")
-- we cannot use target:data("cxx.has_modules"),
-- because on_config will be not called when cleaning targets
if compiler_support.contains_modules(target) then
remove_files(compiler_support.modules_cachedir(target))
if option.get("all") then
remove_files(compiler_support.stlmodules_cachedir(target))
compiler_support.localcache():clear()
compiler_support.localcache():save()
end
end
end)
-- install modules
rule("c++.build.modules.install")
set_extensions(".mpp", ".mxx", ".cppm", ".ixx")
before_install(function (target)
import("modules_support.compiler_support")
import("modules_support.builder")
-- we cannot use target:data("cxx.has_modules"),
-- because on_config will be not called when installing targets
if compiler_support.contains_modules(target) then
local modules = compiler_support.localcache():get2(target:name(), "c++.modules")
builder.generate_metadata(target, modules)
compiler_support.add_installfiles_for_modules(target)
end
end)
before_uninstall(function (target)
import("modules_support.compiler_support")
if compiler_support.contains_modules(target) then
compiler_support.add_installfiles_for_modules(target)
end
end)
|
0 | repos/xmake/xmake/rules/c++/modules | repos/xmake/xmake/rules/c++/modules/modules_support/builder.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki, Arthapz
-- @file common.lua
--
-- imports
import("core.base.json")
import("core.base.option")
import("async.runjobs")
import("private.async.buildjobs")
import("core.tool.compiler")
import("core.project.config")
import("core.project.depend")
import("utils.progress")
import("compiler_support")
import("dependency_scanner")
-- build target modules
function _build_modules(target, sourcebatch, modules, opt)
local objectfiles = sourcebatch.objectfiles
for _, objectfile in ipairs(objectfiles) do
local module = modules[objectfile]
if not module then
goto continue
end
local name, _, cppfile = compiler_support.get_provided_module(module)
cppfile = cppfile or module.cppfile
local deps = {}
for _, dep in ipairs(table.keys(module.requires or {})) do
table.insert(deps, opt.batchjobs and target:name() .. dep or dep)
end
opt.build_module(deps, module, name, objectfile, cppfile)
::continue::
end
end
-- build target headerunits
function _build_headerunits(target, headerunits, opt)
local outputdir = compiler_support.headerunits_cachedir(target, {mkdir = true})
if opt.stl_headerunit then
outputdir = path.join(outputdir, "stl")
end
for _, headerunit in ipairs(headerunits) do
local outputdir = outputdir
if opt.stl_headerunit and headerunit.name:startswith("experimental/") then
outputdir = path.join(outputdir, "experimental")
end
local bmifile = path.join(outputdir, path.filename(headerunit.name) .. compiler_support.get_bmi_extension(target))
local key = path.normalize(headerunit.path)
local build = should_build(target, headerunit.path, bmifile, {key = key, headerunit = true})
if build then
mark_build(target, key)
end
opt.build_headerunit(headerunit, key, bmifile, outputdir, build)
end
end
-- check if flags are compatible for module reuse
function _are_flags_compatible(target, other, cppfile)
local compinst1 = target:compiler("cxx")
local flags1 = compinst1:compflags({sourcefile = cppfile, target = target})
local compinst2 = other:compiler("cxx")
local flags2 = compinst2:compflags({sourcefile = cppfile, target = other})
-- strip unrelevent flags
flags1 = compiler_support.strip_flags(target, flags1)
flags2 = compiler_support.strip_flags(target, flags2)
if #flags1 ~= #flags2 then
return false
end
table.sort(flags1)
table.sort(flags2)
for i = 1, #flags1 do
if flags1[i] ~= flags2[i] then
return false
end
end
return true
end
-- try to reuse modules from other target
function _try_reuse_modules(target, modules)
for _, module in pairs(modules) do
local name, provide, cppfile = compiler_support.get_provided_module(module)
if not provide then
goto continue
end
cppfile = cppfile or module.cppfile
local fileconfig = target:fileconfig(cppfile)
local public = fileconfig and (fileconfig.public or fileconfig.external)
if not public then
goto continue
end
for _, dep in ipairs(target:orderdeps()) do
if not _are_flags_compatible(target, dep, cppfile) then
goto nextdep
end
local mapped = get_from_target_mapper(dep, name)
if mapped then
compiler_support.memcache():set2(target:name() .. name, "reuse", true)
add_module_to_target_mapper(target, mapped.name, mapped.sourcefile, mapped.bmi, table.join(mapped.opt or {}, {target = dep}))
break
end
::nextdep::
end
::continue::
end
return modules
end
-- should we build this module or headerunit ?
function should_build(target, sourcefile, bmifile, opt)
opt = opt or {}
local objectfile = opt.objectfile
local compinst = compiler.load("cxx", {target = target})
local compflags = compinst:compflags({sourcefile = sourcefile, target = target})
local dependfile = target:dependfile(bmifile or objectfile)
local dependinfo = target:is_rebuilt() and {} or (depend.load(dependfile) or {})
local depvalues = {compinst:program(), compflags}
-- force rebuild a module if any of its module dependency is rebuilt
local requires = opt.requires
if requires then
for required, _ in table.orderpairs(requires) do
local m = get_from_target_mapper(target, required)
if m then
local rebuild = (m.opt and m.opt.target) and compiler_support.memcache():get2("should_build_in_" .. m.opt.target:name(), m.key)
or compiler_support.memcache():get2("should_build_in_" .. target:name(), m.key)
if rebuild then
dependinfo.files = {}
table.insert(dependinfo.files, sourcefile)
dependinfo.values = depvalues
return true, dependinfo
end
end
end
end
-- reused
if opt.name then
local m = get_from_target_mapper(target, opt.name)
if m and m.opt and m.opt.target then
local rebuild = compiler_support.memcache():get2("should_build_in_" .. m.opt.target:name(), m.key)
if rebuild then
dependinfo.files = {}
table.insert(dependinfo.files, sourcefile)
dependinfo.values = depvalues
end
return rebuild, dependinfo
end
end
-- need build this object?
local dryrun = option.get("dry-run")
local lastmtime = os.isfile(bmifile or objectfile) and os.mtime(dependfile) or 0
if dryrun or depend.is_changed(dependinfo, {lastmtime = lastmtime, values = depvalues}) then
dependinfo.files = {}
table.insert(dependinfo.files, sourcefile)
dependinfo.values = depvalues
return true, dependinfo
end
return false
end
-- generate meta module informations for package / other buildsystems import
--
-- e.g
-- {
-- "defines": ["FOO=BAR"]
-- "imports": ["std", "bar"]
-- "name": "foo"
-- "file": "foo.cppm"
-- }
function _generate_meta_module_info(target, name, sourcefile, requires)
local modulehash = compiler_support.get_modulehash(target, sourcefile)
local module_metadata = {name = name, file = path.join(modulehash, path.filename(sourcefile))}
-- add definitions
module_metadata.defines = _builder(target).get_module_required_defines(target, sourcefile)
-- add imports
if requires then
for _name, _ in table.orderpairs(requires) do
module_metadata.imports = module_metadata.imports or {}
table.append(module_metadata.imports, _name)
end
end
return module_metadata
end
function _target_module_map_cachekey(target)
local mode = config.mode()
return target:name() .. "module_mapper" .. (mode or "")
end
function _is_duplicated_headerunit(target, key)
local _, mapper_keys = get_target_module_mapper(target)
return mapper_keys[key]
end
function _builder(target)
local cachekey = tostring(target)
local builder = compiler_support.memcache():get2("builder", cachekey)
if builder == nil then
if target:has_tool("cxx", "clang", "clangxx") then
builder = import("clang.builder", {anonymous = true})
elseif target:has_tool("cxx", "gcc", "gxx") then
builder = import("gcc.builder", {anonymous = true})
elseif target:has_tool("cxx", "cl") then
builder = import("msvc.builder", {anonymous = true})
else
local _, toolname = target:tool("cxx")
raise("compiler(%s): does not support c++ module!", toolname)
end
compiler_support.memcache():set2("builder", cachekey, builder)
end
return builder
end
function mark_build(target, name)
compiler_support.memcache():set2("should_build_in_" .. target:name(), name, true)
end
-- build batchjobs for modules
function build_batchjobs_for_modules(modules, batchjobs, rootjob)
return buildjobs(modules, batchjobs, rootjob)
end
-- build modules for batchjobs
function build_modules_for_batchjobs(target, batchjobs, sourcebatch, modules, opt)
opt.rootjob = batchjobs:group_leave() or opt.rootjob
batchjobs:group_enter(target:name() .. "/build_modules", {rootjob = opt.rootjob})
-- add populate module job
local modulesjobs = {}
local populate_jobname = target:name() .. "_populate_module_map"
modulesjobs[populate_jobname] = {
name = populate_jobname,
job = batchjobs:newjob(populate_jobname, function(_, _)
_try_reuse_modules(target, modules)
_builder(target).populate_module_map(target, modules)
end)
}
-- add module jobs
_build_modules(target, sourcebatch, modules, table.join(opt, {
build_module = function(deps, module, name, objectfile, cppfile)
local job_name = name and target:name() .. name or cppfile
modulesjobs[job_name] = _builder(target).make_module_buildjobs(target, batchjobs, job_name, deps,
{module = module, objectfile = objectfile, cppfile = cppfile})
end
}))
-- build batchjobs for modules
build_batchjobs_for_modules(modulesjobs, batchjobs, opt.rootjob)
end
-- build modules for batchcmds
function build_modules_for_batchcmds(target, batchcmds, sourcebatch, modules, opt)
local depmtime = 0
opt.progress = opt.progress or 0
_try_reuse_modules(target, modules)
_builder(target).populate_module_map(target, modules)
-- build modules
_build_modules(target, sourcebatch, modules, table.join(opt, {
build_module = function(_, module, _, objectfile, cppfile)
depmtime = math.max(depmtime, _builder(target).make_module_buildcmds(target, batchcmds, {module = module, cppfile = cppfile, objectfile = objectfile, progress = opt.progress}))
end
}))
batchcmds:set_depmtime(depmtime)
end
-- generate headerunits for batchjobs
function build_headerunits_for_batchjobs(target, batchjobs, sourcebatch, modules, opt)
local user_headerunits, stl_headerunits = dependency_scanner.get_headerunits(target, sourcebatch, modules)
if not user_headerunits and not stl_headerunits then
return
end
-- we need new group(headerunits)
-- e.g. group(build_modules) -> group(headerunits)
opt.rootjob = batchjobs:group_leave() or opt.rootjob
batchjobs:group_enter(target:name() .. "/build_headerunits", {rootjob = opt.rootjob})
local build_headerunits = function(headerunits)
local modulesjobs = {}
_build_headerunits(target, headerunits, table.join(opt, {
build_headerunit = function(headerunit, key, bmifile, outputdir, build)
local job_name = target:name() .. key
local job = _builder(target).make_headerunit_buildjobs(target, job_name, batchjobs, headerunit, bmifile, outputdir, table.join(opt, {build = build}))
if job then
modulesjobs[job_name] = job
end
end
}))
build_batchjobs_for_modules(modulesjobs, batchjobs, opt.rootjob)
end
-- build stl header units first as other headerunits may need them
if stl_headerunits then
opt.stl_headerunit = true
build_headerunits(stl_headerunits)
end
if user_headerunits then
opt.stl_headerunit = false
build_headerunits(user_headerunits)
end
end
-- generate headerunits for batchcmds
function build_headerunits_for_batchcmds(target, batchcmds, sourcebatch, modules, opt)
local user_headerunits, stl_headerunits = dependency_scanner.get_headerunits(target, sourcebatch, modules)
if not user_headerunits and not stl_headerunits then
return
end
local build_headerunits = function(headerunits)
local depmtime = 0
_build_headerunits(target, headerunits, table.join(opt, {
build_headerunit = function(headerunit, _, bmifile, outputdir, build)
depmtime = math.max(depmtime, _builder(target).make_headerunit_buildcmds(target, batchcmds, headerunit, bmifile, outputdir, table.join({build = build}, opt)))
end
}))
batchcmds:set_depmtime(depmtime)
end
-- build stl header units first as other headerunits may need them
if stl_headerunits then
opt.stl_headerunit = true
build_headerunits(stl_headerunits)
end
if user_headerunits then
opt.stl_headerunit = false
build_headerunits(user_headerunits)
end
end
function generate_metadata(target, modules)
local public_modules
for _, module in table.orderpairs(modules) do
local _, _, cppfile = compiler_support.get_provided_module(module)
local fileconfig = target:fileconfig(cppfile)
local public = fileconfig and fileconfig.public
if public then
public_modules = public_modules or {}
table.insert(public_modules, module)
end
end
if not public_modules then
return
end
local jobs = option.get("jobs") or os.default_njob()
runjobs(target:name() .. "_install_modules", function(index, total, jobopt)
local module = public_modules[index]
local name, _, cppfile = compiler_support.get_provided_module(module)
local metafilepath = compiler_support.get_metafile(target, cppfile)
progress.show(jobopt.progress, "${color.build.target}<%s> generating.module.metadata %s", target:name(), name)
local metadata = _generate_meta_module_info(target, name, cppfile, module.requires)
json.savefile(metafilepath, metadata)
end, {comax = jobs, total = #public_modules})
end
-- flush target module mapper keys
function flush_target_module_mapper_keys(target)
local memcache = compiler_support.memcache()
memcache:set2(target:name(), "module_mapper_keys", nil)
end
-- get or create a target module mapper
function get_target_module_mapper(target)
local memcache = compiler_support.memcache()
local mapper = memcache:get2(target:name(), "module_mapper")
if not mapper then
mapper = {}
memcache:set2(target:name(), "module_mapper", mapper)
end
-- we generate the keys map to optimise the efficiency of _is_duplicated_headerunit
local mapper_keys = memcache:get2(target:name(), "module_mapper_keys")
if not mapper_keys then
mapper_keys = {}
for _, item in pairs(mapper) do
if item.key then
mapper_keys[item.key] = item
end
end
memcache:set2(target:name(), "module_mapper_keys", mapper_keys)
end
return mapper, mapper_keys
end
-- get a module or headerunit from target mapper
function get_from_target_mapper(target, name)
local mapper = get_target_module_mapper(target)
if mapper[name] then
return mapper[name]
end
end
-- add a module to target mapper
function add_module_to_target_mapper(target, name, sourcefile, bmifile, opt)
local mapper = get_target_module_mapper(target)
if not mapper[name] then
mapper[name] = {name = name, key = name, bmi = bmifile, sourcefile = sourcefile, opt = opt}
end
flush_target_module_mapper_keys(target)
end
-- add a headerunit to target mapper
function add_headerunit_to_target_mapper(target, headerunit, bmifile)
local mapper = get_target_module_mapper(target)
local key = hash.uuid(path.normalize(headerunit.path))
local deduplicated = _is_duplicated_headerunit(target, key)
if deduplicated then
mapper[headerunit.name] = {name = headerunit.name, key = key, aliasof = deduplicated.name, headerunit = headerunit}
else
mapper[headerunit.name] = {name = headerunit.name, key = key, headerunit = headerunit, bmi = bmifile}
end
flush_target_module_mapper_keys(target)
return deduplicated and true or false
end
|
0 | repos/xmake/xmake/rules/c++/modules | repos/xmake/xmake/rules/c++/modules/modules_support/dependency_scanner.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki, Arthapz
-- @file dependency_scanner.lua
--
-- imports
import("core.base.json")
import("core.base.hashset")
import("core.base.graph")
import("core.base.option")
import("async.runjobs")
import("compiler_support")
import("stl_headers")
function _dependency_scanner(target)
local cachekey = tostring(target)
local dependency_scanner = compiler_support.memcache():get2("dependency_scanner", cachekey)
if dependency_scanner == nil then
if target:has_tool("cxx", "clang", "clangxx") then
dependency_scanner = import("clang.dependency_scanner", {anonymous = true})
elseif target:has_tool("cxx", "gcc", "gxx") then
dependency_scanner = import("gcc.dependency_scanner", {anonymous = true})
elseif target:has_tool("cxx", "cl") then
dependency_scanner = import("msvc.dependency_scanner", {anonymous = true})
else
local _, toolname = target:tool("cxx")
raise("compiler(%s): does not support c++ module!", toolname)
end
compiler_support.memcache():set2("dependency_scanner", cachekey, dependency_scanner)
end
return dependency_scanner
end
function _parse_meta_info(target, metafile)
local metadata = json.loadfile(metafile)
if metadata.file and metadata.name then
return metadata.file, metadata.name, metadata
end
local filename = path.basename(metafile)
local metadir = path.directory(metafile)
for _, ext in ipairs({".mpp", ".mxx", ".cppm", ".ixx"}) do
if os.isfile(path.join(metadir, filename .. ext)) then
filename = filename .. ext
break
end
end
local sourcecode = io.readfile(path.join(path.directory(metafile), filename))
sourcecode = sourcecode:gsub("//.-\n", "\n")
sourcecode = sourcecode:gsub("/%*.-%*/", "")
local name
for _, line in ipairs(sourcecode:split("\n", {plain = true})) do
name = line:match("export%s+module%s+(.+)%s*;") or line:match("export%s+__preprocessed_module%s+(.+)%s*;")
if name then
break
end
end
return filename, name, metadata
end
-- parse module dependency data
--[[
{
"build/.objs/stl_headerunit/linux/x86_64/release/src/hello.mpp.o" = {
requires = {
iostream = {
method = "include-angle",
unique = true,
path = "/usr/include/c++/11/iostream"
}
},
provides = {
hello = {
bmi = "build/.gens/stl_headerunit/linux/x86_64/release/rules/modules/cache/hello.gcm",
sourcefile = "src/hello.mpp"
}
}
},
"build/.objs/stl_headerunit/linux/x86_64/release/src/main.cpp.o" = {
requires = {
hello = {
method = "by-name",
unique = false,
path = "build/.gens/stl_headerunit/linux/x86_64/release/rules/modules/cache/hello.gcm"
}
}
}
}]]
function _parse_dependencies_data(target, moduleinfos)
local modules
for _, moduleinfo in ipairs(moduleinfos) do
assert(moduleinfo.version <= 1)
for _, rule in ipairs(moduleinfo.rules) do
modules = modules or {}
local m = {}
if rule.provides then
for _, provide in ipairs(rule.provides) do
m.provides = m.provides or {}
assert(provide["logical-name"])
local bmifile = provide["compiled-module-path"]
-- try to find the compiled module path in outputs filed (MSVC doesn't generate compiled-module-path)
if not bmifile then
for _, output in ipairs(rule.outputs) do
if output:endswith(compiler_support.get_bmi_extension(target)) then
bmifile = output
break
end
end
-- we didn't found the compiled module path, so we assume it
if not bmifile then
local name = provide["logical-name"] .. compiler_support.get_bmi_extension(target)
-- partition ":" character is invalid path character on windows
-- @see https://github.com/xmake-io/xmake/issues/2954
name = name:replace(":", "-")
bmifile = path.join(compiler_support.get_outputdir(target, name), name)
end
end
m.provides[provide["logical-name"]] = {
bmi = bmifile,
sourcefile = moduleinfo.sourcefile,
interface = provide["is-interface"]
}
end
else
m.cppfile = moduleinfo.sourcefile
end
assert(rule["primary-output"])
modules[path.translate(rule["primary-output"])] = m
end
end
for _, moduleinfo in ipairs(moduleinfos) do
for _, rule in ipairs(moduleinfo.rules) do
local m = modules[path.translate(rule["primary-output"])]
for _, r in ipairs(rule.requires) do
m.requires = m.requires or {}
local p = r["source-path"]
if not p then
for _, dependency in pairs(modules) do
if dependency.provides and dependency.provides[r["logical-name"]] then
p = dependency.provides[r["logical-name"]].bmi
break
end
end
end
m.requires[r["logical-name"]] = {
method = r["lookup-method"] or "by-name",
path = p and path.translate(p) or nil,
unique = r["unique-on-source-path"] or false
}
end
end
end
return modules
end
-- generate edges for DAG
function _get_edges(nodes, modules)
local edges = {}
local module_names = {}
local name_filemap = {}
local named_module_names = hashset.new()
for _, node in ipairs(table.unique(nodes)) do
local module = modules[node]
local module_name, _, cppfile = compiler_support.get_provided_module(module)
if module_name then
if named_module_names:has(module_name) then
raise("duplicate module name detected \"" .. module_name .. "\"\n -> " .. cppfile .. "\n -> " .. name_filemap[module_name])
end
named_module_names:insert(module_name)
name_filemap[module_name] = cppfile
end
if module.requires then
for required_name, _ in table.orderpairs(module.requires) do
for _, required_node in ipairs(nodes) do
local name, _, _ = compiler_support.get_provided_module(modules[required_node])
if name and name == required_name then
table.insert(edges, {required_node, node})
end
end
end
end
end
return edges
end
function _get_package_modules(target, package, opt)
local package_modules
local modulesdir = path.join(package:installdir(), "modules")
local metafiles = os.files(path.join(modulesdir, "*", "*.meta-info"))
for _, metafile in ipairs(metafiles) do
package_modules = package_modules or {}
local modulefile, name, metadata = _parse_meta_info(target, metafile)
local moduleonly = not package:libraryfiles()
package_modules[name] = {file = path.join(modulesdir, modulefile), metadata = metadata, external = {moduleonly = moduleonly}}
end
return package_modules
end
-- generate dependency files
function _generate_dependencies(target, sourcebatch, opt)
local changed = false
if opt.batchjobs then
local jobs = option.get("jobs") or os.default_njob()
runjobs(target:name() .. "_module_dependency_scanner", function(index)
local sourcefile = sourcebatch.sourcefiles[index]
changed = _dependency_scanner(target).generate_dependency_for(target, sourcefile, opt) or changed
end, {comax = jobs, total = #sourcebatch.sourcefiles})
else
for _, sourcefile in ipairs(sourcebatch.sourcefiles) do
changed = _dependency_scanner(target).generate_dependency_for(target, sourcefile, opt) or changed
end
end
return changed
end
-- get module dependencies
function get_module_dependencies(target, sourcebatch, opt)
local cachekey = target:name() .. "/" .. sourcebatch.rulename
local modules = compiler_support.memcache():get2("modules", cachekey)
if modules == nil or opt.regenerate then
modules = compiler_support.localcache():get2("modules", cachekey)
opt.progress = opt.progress or 0
local changed = _generate_dependencies(target, sourcebatch, opt)
if changed or modules == nil then
local moduleinfos = compiler_support.load_moduleinfos(target, sourcebatch)
modules = _parse_dependencies_data(target, moduleinfos)
compiler_support.localcache():set2("modules", cachekey, modules)
compiler_support.localcache():save()
end
compiler_support.memcache():set2("modules", cachekey, modules)
end
return modules
end
-- get headerunits info
function get_headerunits(target, sourcebatch, modules)
local headerunits
local stl_headerunits
for _, objectfile in ipairs(sourcebatch.objectfiles) do
local m = modules[objectfile]
if m then
for name, r in pairs(m.requires) do
if r.method ~= "by-name" then
local unittype = r.method == "include-angle" and ":angle" or ":quote"
if stl_headers.is_stl_header(name) then
stl_headerunits = stl_headerunits or {}
if not table.find_if(stl_headerunits, function(i, v) return v.name == name end) then
table.insert(stl_headerunits, {name = name, path = r.path, type = unittype, unique = r.unique})
end
else
headerunits = headerunits or {}
if not table.find_if(headerunits, function(i, v) return v.name == name end) then
table.insert(headerunits, {name = name, path = r.path, type = unittype, unique = r.unique})
end
end
end
end
end
end
return headerunits, stl_headerunits
end
-- https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p1689r5.html
--[[
{
"version": 1,
"revision": 0,
"rules": [
{
"primary-output": "use-header.mpp.o",
"requires": [
{
"logical-name": "<header.hpp>",
"source-path": "/path/to/found/header.hpp",
"unique-on-source-path": true,
"lookup-method": "include-angle"
}
]
},
{
"primary-output": "header.hpp.bmi",
"provides": [
{
"logical-name": "header.hpp",
"source-path": "/path/to/found/header.hpp",
"unique-on-source-path": true,
}
]
}
]
}]]
function fallback_generate_dependencies(target, jsonfile, sourcefile, preprocess_file)
local output = {version = 1, revision = 0, rules = {}}
local rule = {outputs = {jsonfile}}
rule["primary-output"] = target:objectfile(sourcefile)
local module_name_export
local module_name_private
local module_deps = {}
local module_deps_set = hashset.new()
local sourcecode = preprocess_file(sourcefile) or io.readfile(sourcefile)
local internal = false
sourcecode = sourcecode:gsub("//.-\n", "\n")
sourcecode = sourcecode:gsub("/%*.-%*/", "")
for _, line in ipairs(sourcecode:split("\n", {plain = true})) do
if line:match("#") then
goto continue
end
if not module_name_export then
module_name_export = line:match("export%s+module%s+(.+)%s*;") or line:match("export%s+__preprocessed_module%s+(.+)%s*;")
end
if not module_name_private then
module_name_private = line:match("module%s+(.+)%s*;") or line:match("__preprocessed_module%s+(.+)%s*;")
if module_name_private then
internal = module_name_private:find(":")
end
end
local module_depname = line:match("import%s+(.+)%s*;")
-- we need to parse module interface dep in cxx/impl_unit.cpp, e.g. hello.mpp and hello_impl.cpp
-- @see https://github.com/xmake-io/xmake/pull/2664#issuecomment-1213167314
if not module_depname and not compiler_support.has_module_extension(sourcefile) then
module_depname = module_name_private
end
if module_depname and not module_deps_set:has(module_depname) then
local module_dep = {}
-- partition? import :xxx;
if module_depname:startswith(":") then
local module_name = (module_name_export or module_name_private or "")
module_name = module_name:split(":")[1]
module_dep["unique-on-source-path"] = true
module_depname = module_name .. module_depname
elseif module_depname:startswith("\"") then
module_depname = module_depname:sub(2, -2)
module_dep["lookup-method"] = "include-quote"
module_dep["unique-on-source-path"] = true
module_dep["source-path"] = compiler_support.find_quote_header_file(target, sourcefile, module_depname)
elseif module_depname:startswith("<") then
module_depname = module_depname:sub(2, -2)
module_dep["lookup-method"] = "include-angle"
module_dep["unique-on-source-path"] = true
module_dep["source-path"] = compiler_support.find_angle_header_file(target, module_depname)
end
module_dep["logical-name"] = module_depname
table.insert(module_deps, module_dep)
module_deps_set:insert(module_depname)
end
::continue::
end
if module_name_export or internal then
local outputdir = compiler_support.get_outputdir(target, sourcefile)
local provide = {}
provide["logical-name"] = module_name_export or module_name_private
provide["source-path"] = sourcefile
provide["is-interface"] = not internal
provide["compiled-module-path"] = path.join(outputdir, (module_name_export or module_name_private) .. compiler_support.get_bmi_extension(target))
rule.provides = {}
table.insert(rule.provides, provide)
end
rule.requires = module_deps
table.insert(output.rules, rule)
local jsondata = json.encode(output)
io.writefile(jsonfile, jsondata)
end
-- extract packages modules dependencies
function get_all_packages_modules(target, opt)
-- parse all meta-info and append their informations to the package store
local packages = target:pkgs() or {}
for _, deps in ipairs(target:orderdeps()) do
table.join2(packages, deps:pkgs())
end
local packages_modules
for _, package in table.orderpairs(packages) do
local package_modules = _get_package_modules(target, package, opt)
if package_modules then
packages_modules = packages_modules or {}
table.join2(packages_modules, package_modules)
end
end
return packages_modules
end
-- topological sort
function sort_modules_by_dependencies(target, objectfiles, modules, opt)
local build_objectfiles = {}
local link_objectfiles = {}
local edges = _get_edges(objectfiles, modules)
local dag = graph.new(true)
for _, e in ipairs(edges) do
dag:add_edge(e[1], e[2])
end
local cycle = dag:find_cycle()
if cycle then
local names = {}
for _, objectfile in ipairs(cycle) do
local name, _, cppfile = compiler_support.get_provided_module(modules[objectfile])
table.insert(names, name or cppfile)
end
local name, _, cppfile = compiler_support.get_provided_module(modules[cycle[1]])
table.insert(names, name or cppfile)
raise("circular modules dependency detected!\n%s", table.concat(names, "\n -> import "))
end
local objectfiles_sorted = table.reverse(dag:topological_sort())
local objectfiles_sorted_set = hashset.from(objectfiles_sorted)
for _, objectfile in ipairs(objectfiles) do
if not objectfiles_sorted_set:has(objectfile) then
table.insert(objectfiles_sorted, objectfile)
objectfiles_sorted_set:insert(objectfile)
end
end
local culleds
for _, objectfile in ipairs(objectfiles_sorted) do
local name, provide, cppfile = compiler_support.get_provided_module(modules[objectfile])
local fileconfig = target:fileconfig(cppfile)
local public
local external
local can_cull = true
if fileconfig then
public = fileconfig.public
external = fileconfig.external
can_cull = fileconfig.cull == nil and true or fileconfig.cull
end
can_cull = can_cull and target:policy("build.c++.modules.culling")
local insert = true
if provide then
insert = public or (not external or external.moduleonly)
if insert and not public and can_cull then
insert = false
local edges = dag:adjacent_edges(objectfile)
local public = fileconfig and fileconfig.public
if edges then
for _, edge in ipairs(edges) do
if edge:to() ~= objectfile and objectfiles_sorted_set:has(edge:to()) then
insert = true
break
end
end
end
end
end
if insert then
table.insert(build_objectfiles, objectfile)
table.insert(link_objectfiles, objectfile)
elseif external and not external.from_moduleonly then
table.insert(build_objectfiles, objectfile)
else
objectfiles_sorted_set:remove(objectfile)
if name ~= "std" and name ~= "std.compat" then
culleds = culleds or {}
culleds[target:name()] = culleds[target:name()] or {}
table.insert(culleds[target:name()], format("%s -> %s", name, cppfile))
end
end
end
if culleds then
if option.get("verbose") then
local culled_strs = {}
for target_name, m in pairs(culleds) do
table.insert(culled_strs, format("%s:\n %s", target_name, table.concat(m, "\n ")))
end
wprint("some modules have got culled, because it is not consumed by its target nor flagged as a public module with add_files(\"xxx.mpp\", {public = true})\n %s",
table.concat(culled_strs, "\n "))
else
wprint("some modules have got culled, use verbose (-v) mode to more informations")
end
end
return build_objectfiles, link_objectfiles
end
-- get source modulefile for external target deps
function get_targetdeps_modules(target)
local sourcefiles
for _, dep in ipairs(target:orderdeps()) do
local sourcebatch = dep:sourcebatches()["c++.build.modules.builder"]
if sourcebatch and sourcebatch.sourcefiles then
for _, sourcefile in ipairs(sourcebatch.sourcefiles) do
local fileconfig = dep:fileconfig(sourcefile)
local public = (fileconfig and fileconfig.public and not fileconfig.external) or false
if public then
sourcefiles = sourcefiles or {}
table.insert(sourcefiles, sourcefile)
target:fileconfig_add(sourcefile, {external = {moduleonly = dep:is_moduleonly()}})
end
end
end
end
return sourcefiles
end
|
0 | repos/xmake/xmake/rules/c++/modules | repos/xmake/xmake/rules/c++/modules/modules_support/compiler_support.lua | -- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki, Arthapz
-- @file compiler_support.lua
--
-- imports
import("core.base.json")
import("core.base.hashset")
import("core.cache.memcache", {alias = "_memcache"})
import("core.cache.localcache", {alias = "_localcache"})
import("lib.detect.find_file")
import("core.project.project")
import("core.project.config")
function _compiler_support(target)
local cachekey = tostring(target)
local compiler_support = memcache():get2("compiler_support", cachekey)
if compiler_support == nil then
if target:has_tool("cxx", "clang", "clangxx") then
compiler_support = import("clang.compiler_support", {anonymous = true})
elseif target:has_tool("cxx", "gcc", "gxx") then
compiler_support = import("gcc.compiler_support", {anonymous = true})
elseif target:has_tool("cxx", "cl") then
compiler_support = import("msvc.compiler_support", {anonymous = true})
else
local _, toolname = target:tool("cxx")
raise("compiler(%s): does not support c++ module!", toolname)
end
memcache():set2("compiler_support", cachekey, compiler_support)
end
return compiler_support
end
-- load module support for the current target
function load(target)
-- At least std c++20 is required, and we should call `set_languages("c++20")` to set it
local languages = target:get("languages")
local cxxlang = false
for _, lang in ipairs(languages) do
if lang:find("cxx", 1, true) or lang:find("c++", 1, true) or lang:find("gnuxx", 1, true) or lang:find("gnu++", 1, true) then
cxxlang = true
break
end
end
if not cxxlang then
target:add("languages", "c++20")
end
-- load module support for the specific compiler
_compiler_support(target).load(target)
end
-- strip flags not relevent for module reuse
function strip_flags(target, flags)
return _compiler_support(target).strip_flags(target, flags)
end
-- patch sourcebatch
function patch_sourcebatch(target, sourcebatch)
sourcebatch.sourcekind = "cxx"
sourcebatch.objectfiles = {}
sourcebatch.dependfiles = {}
for _, sourcefile in ipairs(sourcebatch.sourcefiles) do
local objectfile = target:objectfile(sourcefile)
table.insert(sourcebatch.objectfiles, objectfile)
local dependfile = target:dependfile(sourcefile or objectfile)
table.insert(sourcebatch.dependfiles, dependfile)
end
end
-- get bmi extension
function get_bmi_extension(target)
return _compiler_support(target).get_bmi_extension()
end
-- get bmi path
-- @see https://github.com/xmake-io/xmake/issues/4063
function get_bmi_path(bmifile)
bmifile = bmifile:gsub(":", "_PARTITION_")
return path.normalize(bmifile)
end
-- has module extension? e.g. *.mpp, ...
function has_module_extension(sourcefile)
local modulexts = _g.modulexts
if modulexts == nil then
modulexts = hashset.of(".mpp", ".mxx", ".cppm", ".ixx")
_g.modulexts = modulexts
end
local extension = path.extension(sourcefile)
return modulexts:has(extension:lower())
end
-- this target contains module files?
function contains_modules(target)
-- we can not use `"c++.build.builder"`, because it contains sourcekind/cxx.
local target_with_modules = target:sourcebatches()["c++.build.modules"] and true or false
if not target_with_modules then
target_with_modules = target:policy("build.c++.modules")
end
if not target_with_modules then
for _, dep in ipairs(target:orderdeps()) do
local sourcebatches = dep:sourcebatches()
if sourcebatches["c++.build.modules"] then
target_with_modules = true
break
end
end
end
return target_with_modules
end
-- load module infos
function load_moduleinfos(target, sourcebatch)
local moduleinfos
for _, sourcefile in ipairs(sourcebatch.sourcefiles) do
local dependfile = target:dependfile(sourcefile)
if os.isfile(dependfile) then
local data = io.load(dependfile)
if data then
moduleinfos = moduleinfos or {}
local moduleinfo = json.decode(data.moduleinfo)
moduleinfo.sourcefile = sourcefile
if moduleinfo then
table.insert(moduleinfos, moduleinfo)
end
end
end
end
return moduleinfos
end
function find_quote_header_file(target, sourcefile, file)
local p = path.join(path.directory(path.absolute(sourcefile, project.directory())), file)
assert(os.isfile(p))
return p
end
function find_angle_header_file(target, file)
local headerpaths = _compiler_support(target).toolchain_includedirs(target)
for _, dep in ipairs(target:orderdeps()) do
local includedirs = table.join(dep:get("sysincludedirs") or {}, dep:get("includedirs") or {})
table.join2(headerpaths, includedirs)
end
for _, pkg in ipairs(target:orderpkgs()) do
local includedirs = table.join(pkg:get("sysincludedirs") or {}, pkg:get("includedirs") or {})
table.join2(headerpaths, includedirs)
end
table.join2(headerpaths, target:get("includedirs"))
local p = find_file(file, headerpaths)
assert(p, "find <%s> not found!", file)
return p
end
-- get stdmodules
function get_stdmodules(target)
return _compiler_support(target).get_stdmodules(target)
end
-- get memcache
function memcache()
return _memcache.cache("cxxmodules")
end
-- get localcache
function localcache()
return _localcache.cache("cxxmodules")
end
-- get stl headerunits cache directory
function stlheaderunits_cachedir(target, opt)
opt = opt or {}
local stlcachedir = path.join(target:autogendir(), "rules", "bmi", "cache", "stl-headerunits")
if opt.mkdir and not os.isdir(stlcachedir) then
os.mkdir(stlcachedir)
os.mkdir(path.join(stlcachedir, "experimental"))
end
return stlcachedir
end
-- get stl modules cache directory
function stlmodules_cachedir(target, opt)
opt = opt or {}
local stlcachedir = path.join(target:autogendir(), "rules", "bmi", "cache", "stl-modules")
if opt.mkdir and not os.isdir(stlcachedir) then
os.mkdir(stlcachedir)
end
return stlcachedir
end
-- get headerunits cache directory
function headerunits_cachedir(target, opt)
opt = opt or {}
local cachedir = path.join(target:autogendir(), "rules", "bmi", "cache", "headerunits")
if opt.mkdir and not os.isdir(cachedir) then
os.mkdir(cachedir)
end
return cachedir
end
-- get modules cache directory
function modules_cachedir(target, opt)
opt = opt or {}
local cachedir = path.join(target:autogendir(), "rules", "bmi", "cache", "modules")
if opt.mkdir and not os.isdir(cachedir) then
os.mkdir(cachedir)
end
return cachedir
end
function get_modulehash(target, modulepath)
local key = path.directory(modulepath) .. target:name()
return hash.uuid(key):split("-", {plain = true})[1]:lower()
end
function get_metafile(target, modulefile)
local outputdir = get_outputdir(target, modulefile)
return path.join(outputdir, path.filename(modulefile) .. ".meta-info")
end
function get_outputdir(target, module)
local cachedir = module and modules_cachedir(target) or headerunits_cachedir(target)
local modulehash = get_modulehash(target, module.path or module)
local outputdir = path.join(cachedir, modulehash)
if not os.exists(outputdir) then
os.mkdir(outputdir)
end
return outputdir
end
-- get name provide info and cpp sourcefile of a module
function get_provided_module(module)
local name, provide, cppfile
if module.provides then
-- assume there that provides is only one, until we encounter the cases
-- "Some compiler may choose to implement the :private module partition as a separate module for lookup purposes, and if so, it should be indicated as a separate provides entry."
local length = 0
for k, v in pairs(module.provides) do
length = length + 1
name = k
provide = v
cppfile = provide.sourcefile
if length > 1 then
raise("multiple provides are not supported now!")
end
break
end
end
return name, provide, cppfile
end
function add_installfiles_for_modules(target)
local sourcebatch = target:sourcebatches()["c++.build.modules.install"]
if sourcebatch and sourcebatch.sourcefiles then
for _, sourcefile in ipairs(sourcebatch.sourcefiles) do
local fileconfig = target:fileconfig(sourcefile)
local install = fileconfig and fileconfig.public or false
if install then
local modulehash = get_modulehash(target, sourcefile)
local prefixdir = path.join("modules", modulehash)
target:add("installfiles", sourcefile, {prefixdir = prefixdir})
local metafile = get_metafile(target, sourcefile)
if os.exists(metafile) then
target:add("installfiles", metafile, {prefixdir = prefixdir})
end
end
end
end
end
|
0 | repos/xmake/xmake/rules/c++/modules | repos/xmake/xmake/rules/c++/modules/modules_support/stl_headers.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki, Arthapz
-- @file stl_headers.lua
--
-- imports
import("core.base.hashset")
-- the stl headers list
function _stl_headers()
return {
"algorithm",
"forward_list",
"numbers",
"stop_token",
"any",
"fstream",
"numeric",
"streambuf",
"array",
"functional",
"optional",
"string",
"atomic",
"future",
"ostream",
"string_view",
"barrier",
"initializer_list",
"queue",
"bit",
"iomanip",
"random",
"syncstream",
"bitset",
"ios",
"ranges",
"system_error",
"charconv",
"iosfwd",
"ratio",
"thread",
"chrono",
"iostream",
"regex",
"tuple",
"codecvt",
"istream",
"scoped_allocator",
"typeindex",
"compare",
"iterator",
"semaphore",
"typeinfo",
"complex",
"latch",
"set",
"type_traits",
"concepts",
"limits",
"shared_mutex",
"unordered_map",
"condition_variable",
"list",
"source_location",
"stacktrace",
"unordered_set",
"coroutine",
"locale",
"span",
"utility",
"deque",
"map",
"spanstream",
"valarray",
"exception",
"memory",
"sstream",
"variant",
"execution",
"memory_resource",
"stack",
"vector",
"filesystem",
"mutex",
"version",
"format",
"new",
"type_traits",
"string_view",
"stdexcept",
"condition_variable",
"print",
"flat_map",
"flat_set",
"mdspan",
"stdfloat",
"generator",
"csetjmp",
"csignal",
"cstdarg",
"cstddef",
"cstdlib",
"cfloat",
"cinttypes",
"climits",
"cstdint",
"cassert",
"cerrno",
"cctype",
"cstring",
"cuchar",
"cwchar",
"cwctype",
"cfenv",
"cmath",
"ctime",
"clocale",
"expected",
"cstdio"}
end
-- get all stl headers
function get_stl_headers()
local stl_headers = _g.stl_headers
if stl_headers == nil then
stl_headers = hashset.from(_stl_headers())
_g.stl_headers = stl_headers or false
end
return stl_headers or nil
end
-- is stl header?
function is_stl_header(header)
if header:startswith("experimental/") then
header = header:sub(14, -1)
end
return get_stl_headers():has(header)
end
|
0 | repos/xmake/xmake/rules/c++/modules/modules_support | repos/xmake/xmake/rules/c++/modules/modules_support/gcc/builder.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki, Arthapz
-- @file gcc/builder.lua
--
-- imports
import("core.base.json")
import("core.base.option")
import("core.base.semver")
import("utils.progress")
import("private.action.build.object", {alias = "objectbuilder"})
import("core.tool.compiler")
import("core.project.config")
import("core.project.depend")
import("compiler_support")
import(".builder", {inherit = true})
-- get flags for building a headerunit
function _make_headerunitflags(target, headerunit, headerunit_mapper)
local module_headerflag = compiler_support.get_moduleheaderflag(target)
local module_onlyflag = compiler_support.get_moduleonlyflag(target)
local module_mapperflag = compiler_support.get_modulemapperflag(target)
assert(module_headerflag and module_onlyflag, "compiler(gcc): does not support c++ header units!")
local local_directory = (headerunit.type == ":quote") and {"-I" .. path.directory(path.normalize(headerunit.path))} or {}
local headertype = (headerunit.type == ":angle") and "system" or "user"
local flags = table.join(local_directory, {module_mapperflag .. headerunit_mapper,
module_headerflag .. headertype,
module_onlyflag,
"-xc++-header"})
return flags
end
-- do compile
function _compile(target, flags, sourcefile, outputfile)
local dryrun = option.get("dry-run")
local compinst = target:compiler("cxx")
local compflags = compinst:compflags({sourcefile = sourcefile, target = target})
local flags = table.join(compflags or {}, flags)
-- trace
if option.get("verbose") then
print(compinst:compcmd(sourcefile, outputfile, {target = target, compflags = flags, rawargs = true}))
end
-- do compile
if not dryrun then
assert(compinst:compile(sourcefile, outputfile, {target = target, compflags = flags}))
end
end
-- do compile for batchcmds
-- @note we need to use batchcmds:compilev to translate paths in compflags for generator, e.g. -Ixx
function _batchcmds_compile(batchcmds, target, flags, sourcefile, outputfile)
local compinst = target:compiler("cxx")
local compflags = compinst:compflags({sourcefile = sourcefile, target = target})
local flags = table.join("-c", compflags or {}, flags, {"-o", outputfile, sourcefile})
batchcmds:compilev(flags, {compiler = compinst, sourcekind = "cxx"})
end
function _module_map_cachekey(target)
local mode = config.mode()
return target:name() .. "module_mapper" .. (mode or "")
end
-- generate a module mapper file for build a headerunit
function _generate_headerunit_modulemapper_file(module)
local mapper_path = os.tmpfile()
local mapper_file = io.open(mapper_path, "wb")
mapper_file:write("root " .. path.unix(os.projectdir()))
mapper_file:write("\n")
mapper_file:write(mapper_file, path.unix(module.name) .. " " .. path.unix(module.bmifile))
mapper_file:write("\n")
mapper_file:close()
return mapper_path
end
function _get_maplines(target, module)
local maplines = {}
local m_name, m, _ = compiler_support.get_provided_module(module)
if m then
table.insert(maplines, m_name .. " " .. compiler_support.get_bmi_path(m.bmi))
end
for required, _ in table.orderpairs(module.requires) do
local dep_module = get_from_target_mapper(target, required)
assert(dep_module, "module dependency %s required for %s not found", required, m_name or module.cppfile)
local bmifile = dep_module.bmi
local mapline
-- aliased headerunit
if dep_module.aliasof then
local aliased = get_from_target_mapper(target, dep_module.aliasof)
bmifile = aliased.bmi
mapline = path.unix(dep_module.headerunit.path) .. " " .. path.unix(bmifile)
-- headerunit
elseif dep_module.headerunit then
mapline = path.unix(dep_module.headerunit.path) .. " " .. path.unix(bmifile)
-- named module
else
mapline = required .. " " .. path.unix(bmifile)
end
table.insert(maplines, mapline)
-- append deps
if dep_module.opt and dep_module.opt.deps then
local deps = _get_maplines(target, {name = dep_module.name, bmi = bmifile, requires = dep_module.opt.deps})
table.join2(maplines, deps)
end
end
-- remove duplicates
return table.unique(maplines)
end
-- generate a module mapper file for build a module
-- e.g
-- /usr/include/c++/11/iostream build/.gens/stl_headerunit/linux/x86_64/release/stlmodules/cache/iostream.gcm
-- hello build/.gens/stl_headerunit/linux/x86_64/release/rules/modules/cache/hello.gcm
--
function _generate_modulemapper_file(target, module, cppfile)
local maplines = _get_maplines(target, module)
local mapper_path = path.join(os.tmpdir(), target:name():replace(" ", "_"), name or cppfile:replace(" ", "_"))
local mapper_content = {}
table.insert(mapper_content, "root " .. path.unix(os.projectdir()))
for _, mapline in ipairs(maplines) do
table.insert(mapper_content, mapline)
end
mapper_content = table.concat(mapper_content, "\n") .. "\n"
if not os.isfile(mapper_path) or io.readfile(mapper_path, {encoding = "binary"}) ~= mapper_content then
io.writefile(mapper_path, mapper_content, {encoding = "binary"})
end
return mapper_path
end
-- populate module map
function populate_module_map(target, modules)
for _, module in pairs(modules) do
local name, provide = compiler_support.get_provided_module(module)
if provide then
local bmifile = compiler_support.get_bmi_path(provide.bmi)
add_module_to_target_mapper(target, name, provide.sourcefile, bmifile, {deps = module.requires})
end
end
end
-- get defines for a module
function get_module_required_defines(target, sourcefile)
local compinst = compiler.load("cxx", {target = target})
local compflags = compinst:compflags({sourcefile = sourcefile, target = target})
local defines
for _, flag in ipairs(compflags) do
if flag:startswith("-D") then
defines = defines or {}
table.insert(defines, flag:sub(3))
end
end
return defines
end
-- build module file for batchjobs
function make_module_buildjobs(target, batchjobs, job_name, deps, opt)
local name, provide, _ = compiler_support.get_provided_module(opt.module)
local bmifile = provide and compiler_support.get_bmi_path(provide.bmi)
local module_mapperflag = compiler_support.get_modulemapperflag(target)
return {
name = job_name,
deps = table.join(target:name() .. "_populate_module_map", deps),
sourcefile = opt.cppfile,
job = batchjobs:newjob(name or opt.cppfile, function(index, total, jobopt)
local mapped_bmi
if provide and compiler_support.memcache():get2(target:name() .. name, "reuse") then
mapped_bmi = get_from_target_mapper(target, name).bmi
end
-- generate and append module mapper file
local module_mapper
if provide or opt.module.requires then
module_mapper = _generate_modulemapper_file(target, opt.module, opt.cppfile)
target:fileconfig_add(opt.cppfile, {force = {cxxflags = {module_mapperflag .. module_mapper}}})
end
local dependfile = target:dependfile(bmifile or opt.objectfile)
local build, dependinfo = should_build(target, opt.cppfile, bmifile, {name = name, objectfile = opt.objectfile, requires = opt.module.requires})
-- needed to detect rebuild of dependencies
if provide and build then
mark_build(target, name)
end
if build then
-- compile if it's a named module
if provide or compiler_support.has_module_extension(opt.cppfile) then
local fileconfig = target:fileconfig(opt.cppfile)
local public = fileconfig and fileconfig.public
local external = fileconfig and fileconfig.external
local from_moduleonly = external and external.moduleonly
local bmifile = mapped_bmi or bmifile
local flags = {"-x", "c++"}
local sourcefile
if external and not from_moduleonly then
if not mapped_bmi then
progress.show(jobopt.progress, "${color.build.target}<%s> ${clear}${color.build.object}compiling.bmi.$(mode) %s", target:name(), name or opt.cppfile)
local module_onlyflag = compiler_support.get_moduleonlyflag(target)
table.insert(flags, module_onlyflag)
sourcefile = opt.cppfile
end
else
progress.show(jobopt.progress, "${color.build.target}<%s> ${clear}${color.build.object}compiling.module.$(mode) %s", target:name(), name or opt.cppfile)
sourcefile = opt.cppfile
end
if option.get("diagnosis") then
print("mapper file --------\n%s--------", io.readfile(module_mapper))
end
if sourcefile then
_compile(target, flags, sourcefile, opt.objectfile)
end
os.tryrm(module_mapper)
else
os.tryrm(opt.objectfile) -- force rebuild for .cpp files
end
depend.save(dependinfo, dependfile)
end
end)}
end
-- build module file for batchcmds
function make_module_buildcmds(target, batchcmds, opt)
local name, provide, _ = compiler_support.get_provided_module(opt.module)
local bmifile = provide and compiler_support.get_bmi_path(provide.bmi)
local module_mapperflag = compiler_support.get_modulemapperflag(target)
local mapped_bmi
if provide and compiler_support.memcache():get2(target:name() .. name, "reuse") then
mapped_bmi = get_from_target_mapper(target, name).bmi
end
-- generate and append module mapper file
local module_mapper
if provide or opt.module.requires then
module_mapper = _generate_modulemapper_file(target, opt.module, opt.cppfile)
target:fileconfig_add(opt.cppfile, {force = {cxxflags = {module_mapperflag .. module_mapper}}})
end
-- compile if it's a named module
if provide or compiler_support.has_module_extension(opt.cppfile) then
batchcmds:mkdir(path.directory(opt.objectfile))
local fileconfig = target:fileconfig(opt.cppfile)
local public = fileconfig and fileconfig.public
local external = fileconfig and fileconfig.external
local from_moduleonly = external and external.moduleonly
local bmifile = mapped_bmi or bmifile
local flags = {"-x", "c++"}
local sourcefile
if external and not from_moduleonly then
if not mapped_bmi then
batchcmds:show_progress(opt.progress, "${color.build.target}<%s> ${clear}${color.build.object}compiling.bmi.$(mode) %s", target:name(), name or opt.cppfile)
local module_onlyflag = compiler_support.get_moduleonlyflag(target)
table.insert(flags, module_onlyflag)
sourcefile = opt.cppfile
end
else
batchcmds:show_progress(opt.progress, "${color.build.target}<%s> ${clear}${color.build.object}compiling.module.$(mode) %s", target:name(), name or opt.cppfile)
sourcefile = opt.cppfile
end
if option.get("diagnosis") then
batchcmds:print("mapper file: %s", io.readfile(module_mapper))
end
if sourcefile then
_batchcmds_compile(batchcmds, target, flags, sourcefile, opt.objectfile)
end
batchcmds:rm(module_mapper)
else
batchcmds:rm(opt.objectfile) -- force rebuild for .cpp files
end
batchcmds:add_depfiles(opt.cppfile)
return os.mtime(opt.objectfile)
end
-- build headerunit file for batchjobs
function make_headerunit_buildjobs(target, job_name, batchjobs, headerunit, bmifile, outputdir, opt)
local _headerunit = headerunit
_headerunit.path = headerunit.type == ":quote" and "./" .. path.relative(headerunit.path) or headerunit.path
local already_exists = add_headerunit_to_target_mapper(target, _headerunit, bmifile)
if not already_exists then
return {
name = job_name,
sourcefile = headerunit.path,
job = batchjobs:newjob(job_name, function(index, total, jobopt)
if not os.isdir(outputdir) then
os.mkdir(outputdir)
end
local compinst = compiler.load("cxx", {target = target})
local compflags = compinst:compflags({sourcefile = headerunit.path, target = target})
local dependfile = target:dependfile(bmifile)
local dependinfo = depend.load(dependfile) or {}
dependinfo.files = {}
local depvalues = {compinst:program(), compflags}
if opt.build then
local headerunit_mapper = _generate_headerunit_modulemapper_file({name = path.normalize(headerunit.path), bmifile = bmifile})
progress.show(jobopt.progress, "${color.build.target}<%s> ${clear}${color.build.object}compiling.headerunit.$(mode) %s", target:name(), headerunit.name)
if option.get("diagnosis") then
print("mapper file:\n%s", io.readfile(headerunit_mapper))
end
_compile(target,
_make_headerunitflags(target, headerunit, headerunit_mapper, opt),
path.translate(path.filename(headerunit.name)), bmifile)
os.tryrm(headerunit_mapper)
end
table.insert(dependinfo.files, headerunit.path)
dependinfo.values = depvalues
depend.save(dependinfo, dependfile)
end)}
end
end
-- build headerunit file for batchcmds
function make_headerunit_buildcmds(target, batchcmds, headerunit, bmifile, outputdir, opt)
local headerunit_mapper = _generate_headerunit_modulemapper_file({name = path.normalize(headerunit.path), bmifile = bmifile})
batchcmds:mkdir(outputdir)
local _headerunit = headerunit
_headerunit.path = headerunit.type == ":quote" and "./" .. path.relative(headerunit.path) or headerunit.path
add_headerunit_to_target_mapper(target, _headerunit, bmifile)
if opt.build then
local name = headerunit.unique and headerunit.name or headerunit.path
batchcmds:show_progress(opt.progress, "${color.build.target}<%s> ${clear}${color.build.object}compiling.headerunit.$(mode) %s", target:name(), name)
if option.get("diagnosis") then
batchcmds:print("mapper file:\n%s", io.readfile(headerunit_mapper))
end
_batchcmds_compile(batchcmds, target, _make_headerunitflags(target, headerunit, headerunit_mapper), bmifile)
end
batchcmds:rm(headerunit_mapper)
batchcmds:add_depfiles(headerunit.path)
return os.mtime(bmifile)
end
|
0 | repos/xmake/xmake/rules/c++/modules/modules_support | repos/xmake/xmake/rules/c++/modules/modules_support/gcc/dependency_scanner.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki, Arthapz
-- @file gcc/dependency_scanner.lua
--
-- imports
import("core.base.json")
import("core.base.semver")
import("core.project.depend")
import("utils.progress")
import("compiler_support")
import("builder")
import(".dependency_scanner", {inherit = true})
-- generate dependency files
function generate_dependency_for(target, sourcefile, opt)
local compinst = target:compiler("cxx")
local baselineflags = {"-E", "-x", "c++"}
local depsformatflag = compiler_support.get_depsflag(target, "p1689r5")
local depsfileflag = compiler_support.get_depsfileflag(target)
local depstargetflag = compiler_support.get_depstargetflag(target)
local dependfile = target:dependfile(sourcefile)
local changed = false
depend.on_changed(function()
if opt.progress then
progress.show(opt.progress, "${color.build.target}<%s> generating.module.deps %s", target:name(), sourcefile)
end
local outputdir = compiler_support.get_outputdir(target, sourcefile)
local jsonfile = path.translate(path.join(outputdir, path.filename(sourcefile) .. ".json"))
local has_depsflags = depsformatflag and depsfileflag and depstargetflag
if has_depsflags and not target:policy("build.c++.gcc.fallbackscanner") then
local ifile = path.translate(path.join(outputdir, path.filename(sourcefile) .. ".i"))
local dfile = path.translate(path.join(outputdir, path.filename(sourcefile) .. ".d"))
local compflags = compinst:compflags({sourcefile = sourcefile, target = target})
local flags = table.join(compflags or {}, baselineflags, {sourcefile, "-MT", jsonfile, "-MD", "-MF", dfile, depsformatflag, depsfileflag .. jsonfile, depstargetflag .. target:objectfile(sourcefile), "-o", ifile})
os.vrunv(compinst:program(), flags)
os.rm(ifile)
os.rm(dfile)
else
if not has_depsflags then
wprint("GCC doesn't support module scanning ! using fallback scanner")
end
fallback_generate_dependencies(target, jsonfile, sourcefile, function(file)
local compflags = compinst:compflags({sourcefile = file, target = target})
-- exclude -fmodule* flags because, when they are set gcc try to find bmi of imported modules but they don't exists a this point of compilation
table.remove_if(compflags, function(_, flag) return flag:startswith("-fmodule") end)
local ifile = path.translate(path.join(outputdir, path.filename(file) .. ".i"))
local flags = table.join(baselineflags, compflags or {}, {file, "-o", ifile})
os.vrunv(compinst:program(), flags)
local content = io.readfile(ifile)
os.rm(ifile)
return content
end)
end
changed = true
local dependinfo = io.readfile(jsonfile)
return { moduleinfo = dependinfo }
end, {dependfile = dependfile, files = {sourcefile}, changed = target:is_rebuilt()})
return changed
end
|
0 | repos/xmake/xmake/rules/c++/modules/modules_support | repos/xmake/xmake/rules/c++/modules/modules_support/gcc/compiler_support.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki, Arthapz
-- @file gcc/compiler_support.lua
--
-- imports
import("core.base.semver")
import("core.project.config")
import("lib.detect.find_tool")
import(".compiler_support", {inherit = true})
-- get includedirs for stl headers
--
-- $ echo '#include <vector>' | gcc -x c++ -E - | grep '/vector"'
-- # 1 "/usr/include/c++/11/vector" 1 3
-- # 58 "/usr/include/c++/11/vector" 3
-- # 59 "/usr/include/c++/11/vector" 3
--
function _get_toolchain_includedirs_for_stlheaders(includedirs, gcc)
local tmpfile = os.tmpfile() .. ".cc"
io.writefile(tmpfile, "#include <vector>")
local result = try {function () return os.iorunv(gcc, {"-E", "-x", "c++", tmpfile}) end}
if result then
for _, line in ipairs(result:split("\n", {plain = true})) do
line = line:trim()
if line:startswith("#") and line:find("/vector\"", 1, true) then
local includedir = line:match("\"(.+)/vector\"")
if includedir and os.isdir(includedir) then
table.insert(includedirs, path.normalize(includedir))
break
end
end
end
end
os.tryrm(tmpfile)
end
-- load module support for the current target
function load(target)
local modulesflag = get_modulesflag(target)
target:add("cxxflags", modulesflag, {force = true, expand = false})
-- fix cxxabi issue
-- @see https://github.com/xmake-io/xmake/issues/2716#issuecomment-1225057760
-- https://github.com/xmake-io/xmake/issues/3855
if target:policy("build.c++.gcc.modules.cxx11abi") then
target:add("cxxflags", "-D_GLIBCXX_USE_CXX11_ABI=1")
else
target:add("cxxflags", "-D_GLIBCXX_USE_CXX11_ABI=0")
end
end
-- strip flags that doesn't affect bmi generation
function strip_flags(target, flags)
-- speculative list as there is no resource that list flags that prevent reusability, this list will likely be improve over time
local strippable_flags = {
"-I",
"-isystem",
"-g",
"-O",
"-W",
"-w",
"-cxx-isystem",
"-Q",
"-fmodule-mapper",
}
if not target:policy("build.c++.modules.tryreuse.discriminate_on_defines") then
table.join2(strippable_flags, {"-D", "-U"})
end
local output = {}
local last_flag_I = false
for _, flag in ipairs(flags) do
local strip = false
for _, _flag in ipairs(strippable_flags) do
if flag:startswith(_flag) or last_flag_I then
last_flag_I = _flag == "-I"
strip = true
break
end
end
if not strip then
table.insert(output, flag)
end
end
return output
end
-- provide toolchain include directories for stl headerunit when p1689 is not supported
function toolchain_includedirs(target)
local includedirs = _g.includedirs
if includedirs == nil then
includedirs = {}
local gcc, toolname = target:tool("cxx")
assert(toolname == "gcc" or toolname == "gxx")
_get_toolchain_includedirs_for_stlheaders(includedirs, gcc)
local _, result = try {function () return os.iorunv(gcc, {"-E", "-Wp,-v", "-xc", os.nuldev()}) end}
if result then
for _, line in ipairs(result:split("\n", {plain = true})) do
line = line:trim()
if os.isdir(line) then
table.insert(includedirs, path.normalize(line))
elseif line:startswith("End") then
break
end
end
end
_g.includedirs = includedirs
end
return includedirs
end
function get_target_module_mapperpath(target)
local path = path.join(modules_cachedir(target, {mkdir = true}), "..", "mapper.txt")
if not os.isfile(path) then
io.writefile(path, "")
end
return path
end
-- not supported atm
function get_stdmodules(target)
end
function get_bmi_extension()
return ".gcm"
end
function get_modulesflag(target)
local modulesflag = _g.modulesflag
if modulesflag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags("-fmodules-ts", "cxxflags", {flagskey = "gcc_modules_ts"}) then
modulesflag = "-fmodules-ts"
end
assert(modulesflag, "compiler(gcc): does not support c++ module!")
_g.modulesflag = modulesflag or false
end
return modulesflag or nil
end
function get_moduleheaderflag(target)
local moduleheaderflag = _g.moduleheaderflag
if moduleheaderflag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags("-fmodule-header", "cxxflags", {flagskey = "gcc_module_header"}) then
moduleheaderflag = "-fmodule-header="
end
_g.moduleheaderflag = moduleheaderflag or false
end
return moduleheaderflag or nil
end
function get_moduleonlyflag(target)
local moduleonlyflag = _g.moduleonlyflag
if moduleonlyflag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags("-fmodule-only", "cxxflags", {flagskey = "gcc_module_only"}) then
moduleonlyflag = "-fmodule-only"
end
_g.moduleonlyflag = moduleonlyflag or false
end
return moduleonlyflag or nil
end
function get_modulemapperflag(target)
local modulemapperflag = _g.modulemapperflag
if modulemapperflag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags("-fmodule-mapper=" .. os.tmpfile(), "cxxflags", {flagskey = "gcc_module_mapper"}) then
modulemapperflag = "-fmodule-mapper="
end
assert(modulemapperflag, "compiler(gcc): does not support c++ module!")
_g.modulemapperflag = modulemapperflag or false
end
return modulemapperflag or nil
end
function get_depsflag(target)
local depflag = _g.depflag
if depflag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags("-fdeps-format=p1689r5", "cxxflags", {flagskey = "gcc_deps_format",
on_check = function (ok, errors)
if errors:find("-M") then
ok = true
end
return ok, errors
end}) then
depflag = "-fdeps-format=p1689r5"
end
_g.depflag = depflag or false
end
return depflag or nil
end
function get_depsfileflag(target)
local depfileflag = _g.depfileflag
if depfileflag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags("-fdeps-file=" .. os.tmpfile(), "cxxflags", {flagskey = "gcc_deps_file",
on_check = function (ok, errors)
if errors:find("-M") then
ok = true
end
return ok, errors
end}) then
depfileflag = "-fdeps-file="
end
_g.depfileflag = depfileflag or false
end
return depfileflag or nil
end
function get_depstargetflag(target)
local depoutputflag = _g.depoutputflag
if depoutputflag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags("-fdeps-target=" .. os.tmpfile() .. ".o", "cxxflags", {flagskey = "gcc_deps_output",
on_check = function (ok, errors)
if errors:find("-M") then
ok = true
end
return ok, errors
end}) then
depoutputflag = "-fdeps-target="
end
_g.depoutputflag = depoutputflag or false
end
return depoutputflag or nil
end
function get_cppversionflag(target)
local cppversionflag = _g.cppversionflag
if cppversionflag == nil then
local compinst = target:compiler("cxx")
local flags = compinst:compflags({target = target})
cppversionflag = table.find_if(flags, function(v) string.startswith(v, "-std=c++") end) or "-std=c++20"
_g.cppversionflag = cppversionflag
end
return cppversionflag or nil
end
|
0 | repos/xmake/xmake/rules/c++/modules/modules_support | repos/xmake/xmake/rules/c++/modules/modules_support/msvc/builder.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki, Arthapz
-- @file msvc/builder.lua
--
-- imports
import("core.base.json")
import("core.base.option")
import("core.base.semver")
import("utils.progress")
import("private.action.build.object", {alias = "objectbuilder"})
import("core.tool.compiler")
import("core.project.config")
import("core.project.depend")
import("private.tools.vstool")
import("compiler_support")
import(".builder", {inherit = true})
-- get flags for building a module
function _make_modulebuildflags(target, provide, bmifile, opt)
local ifcoutputflag = compiler_support.get_ifcoutputflag(target)
local ifconlyflag = compiler_support.get_ifconlyflag(target)
local interfaceflag = compiler_support.get_interfaceflag(target)
local internalpartitionflag = compiler_support.get_internalpartitionflag(target)
local ifconly = (not opt.build_objectfile and ifconlyflag)
local flags
if provide then -- named module
flags = table.join({"-TP", ifcoutputflag, path(bmifile), provide.interface and interfaceflag or internalpartitionflag}, ifconly or {})
else
flags = {"-TP"}
end
return flags
end
function _compile_one_step(target, bmifile, sourcefile, objectfile, provide, opt)
local ifcoutputflag = compiler_support.get_ifcoutputflag(target)
local interfaceflag = compiler_support.get_interfaceflag(target)
local internalpartitionflag = compiler_support.get_internalpartitionflag(target)
-- get flags
local flags = {"-TP"}
if provide then
table.join2(flags, ifcoutputflag, path(bmifile), provide.interface and interfaceflag or internalpartitionflag)
end
if opt and opt.batchcmds then
_batchcmds_compile(opt.batchcmds, target, flags, sourcefile, objectfile)
else
_compile(target, flags, sourcefile, objectfile)
end
end
function _compile_bmi_step(target, bmifile, sourcefile, objectfile, provide, opt)
local ifcoutputflag = compiler_support.get_ifcoutputflag(target)
local interfaceflag = compiler_support.get_interfaceflag(target)
local ifconlyflag = compiler_support.get_ifconlyflag(target)
if not ifconlyflag then
_compile_one_step(target, bmifile, sourcefile, objectfile, provide, opt)
else
local flags = {"-TP", ifcoutputflag, path(bmifile), interfaceflag, ifconlyflag}
if opt and opt.batchcmds then
_batchcmds_compile(opt.batchcmds, target, flags, sourcefile, bmifile)
else
_compile(target, flags, sourcefile, bmifile)
end
end
end
function _compile_objectfile_step(target, bmifile, sourcefile, objectfile, provide, opt)
local ifconlyflag = compiler_support.get_ifconlyflag(target)
local interfaceflag = compiler_support.get_interfaceflag(target)
local internalpartitionflag = compiler_support.get_internalpartitionflag(target)
local flags = {"-TP", (provide and provide.interface) and interfaceflag or internalpartitionflag}
if not ifconlyflag then
_compile_one_step(target, bmifile, sourcefile, objectfile, provide, opt)
else
if opt and opt.batchcmds then
_batchcmds_compile(opt.batchcmds, target, flags, sourcefile, objectfile)
else
_compile(target, flags, sourcefile, objectfile)
end
end
end
-- get flags for building a headerunit
function _make_headerunitflags(target, headerunit, bmifile)
-- get flags
local exportheaderflag = compiler_support.get_exportheaderflag(target)
local headernameflag = compiler_support.get_headernameflag(target)
local ifcoutputflag = compiler_support.get_ifcoutputflag(target)
local ifconlyflag = compiler_support.get_ifconlyflag(target)
assert(headernameflag and exportheaderflag, "compiler(msvc): does not support c++ header units!")
local local_directory = (headerunit.type == ":quote") and {"-I" .. path.directory(headerunit.path)} or {}
local flags = table.join(local_directory, {"-TP",
exportheaderflag,
headernameflag .. headerunit.type,
headerunit.type == ":angle" and headerunit.name or headerunit.path,
ifcoutputflag,
bmifile}, ifconlyflag or {})
return flags
end
-- do compile
function _compile(target, flags, sourcefile, outputfile, headerunit)
local dryrun = option.get("dry-run")
local compinst = target:compiler("cxx")
local compflags = compinst:compflags({sourcefile = sourcefile, target = target})
local flags = table.join(compflags or {}, flags)
-- trace
if option.get("verbose") then
if headerunit then
print(os.args(compinst:program(), flags))
else
print(compinst:compcmd(sourcefile, outputfile, {target = target, compflags = flags, rawargs = true}))
end
end
-- do compile
if not dryrun then
if headerunit then
local msvc = target:toolchain("msvc")
os.vrunv(compinst:program(), flags, {envs = msvc:runenvs()})
else
assert(compinst:compile(sourcefile, outputfile, {target = target, compflags = flags}))
end
end
end
-- do compile for batchcmds
-- @note we need to use batchcmds:compilev to translate paths in compflags for generator, e.g. -Ixx
function _batchcmds_compile(batchcmds, target, flags, sourcefile, outputfile)
opt = opt or {}
local compinst = target:compiler("cxx")
local compflags = compinst:compflags({sourcefile = sourcefile, target = target})
flags = table.join(compflags or {}, flags)
batchcmds:compile(sourcefile, outputfile, {sourcekind = "cxx", compflags = flags})
end
-- get module requires flags
-- e.g
-- /reference Foo=build/.gens/Foo/rules/modules/cache/Foo.ifc
-- /headerUnit:angle glm/mat4x4.hpp=Users\arthu\AppData\Local\.xmake\packages\g\glm\0.9.9+8\91454f3ee0be416cb9c7452970a2300f\include\glm\mat4x4.hpp.ifc
--
function _get_requiresflags(target, module, opt)
local referenceflag = compiler_support.get_referenceflag(target)
local headerunitflag = compiler_support.get_headerunitflag(target)
local name = module.name
local cachekey = target:name() .. name
local requiresflags = compiler_support.memcache():get2(cachekey, "requiresflags")
or compiler_support.localcache():get2(cachekey, "requiresflags")
if not requiresflags or (opt and opt.regenerate) then
local deps_flags = {}
for required, _ in table.orderpairs(module.requires) do
local dep_module = get_from_target_mapper(target, required)
assert(dep_module, "module dependency %s required for %s not found <%s>", required, name, target:name())
local mapflag
local bmifile = dep_module.bmi
-- aliased headerunit
if dep_module.aliasof then
local aliased = get_from_target_mapper(target, dep_module.aliasof)
bmifile = aliased.bmi
mapflag = {headerunitflag .. aliased.headerunit.type, required .. "=" .. bmifile}
-- headerunit
elseif dep_module.headerunit then
mapflag = {headerunitflag .. dep_module.headerunit.type, required .. "=" .. bmifile}
-- named module
else
mapflag = {referenceflag, required .. "=" .. bmifile}
end
table.insert(deps_flags, mapflag)
-- append deps
if dep_module.opt and dep_module.opt.deps then
local deps = _get_requiresflags(target, { name = dep_module.name or dep_module.sourcefile, bmi = bmifile, requires = dep_module.opt.deps })
table.join2(deps_flags, deps)
end
end
-- remove duplicates
requiresflags = {}
local contains = {}
for _, map in ipairs(deps_flags) do
local name, _ = map[2]:split("=")[1], map[2]:split("=")[2]
if not contains[name] then
table.insert(requiresflags, map)
contains[name] = true
end
end
compiler_support.memcache():set2(cachekey, "requiresflags", requiresflags)
compiler_support.localcache():set2(cachekey, "requiresflags", requiresflags)
end
return requiresflags
end
function _append_requires_flags(target, module, name, cppfile, bmifile, opt)
local cxxflags = {}
local requiresflags = _get_requiresflags(target, {name = (name or cppfile), bmi = bmifile, requires = module.requires}, {regenerate = opt.build})
for _, flag in ipairs(requiresflags) do
-- we need to wrap flag to support flag with space
if type(flag) == "string" and flag:find(" ", 1, true) then
table.insert(cxxflags, {flag})
else
table.insert(cxxflags, flag)
end
end
target:fileconfig_add(cppfile, {force = {cxxflags = cxxflags}})
end
-- populate module map
function populate_module_map(target, modules)
for _, module in pairs(modules) do
local name, provide, cppfile = compiler_support.get_provided_module(module)
if provide then
local bmifile = compiler_support.get_bmi_path(provide.bmi)
add_module_to_target_mapper(target, name, cppfile, bmifile, {deps = module.requires})
end
end
end
-- get defines for a module
function get_module_required_defines(target, sourcefile)
local compinst = compiler.load("cxx", {target = target})
local compflags = compinst:compflags({sourcefile = sourcefile, target = target})
local defines
for _, flag in ipairs(compflags) do
if flag:startswith("-D") or flag:startswith("/D") then
defines = defines or {}
table.insert(defines, flag:sub(3))
end
end
return defines
end
-- build module file for batchjobs
function make_module_buildjobs(target, batchjobs, job_name, deps, opt)
local name, provide, _ = compiler_support.get_provided_module(opt.module)
local bmifile = provide and compiler_support.get_bmi_path(provide.bmi)
local dryrun = option.get("dry-run")
return {
name = job_name,
deps = table.join(target:name() .. "_populate_module_map", deps),
sourcefile = opt.cppfile,
job = batchjobs:newjob(name or opt.cppfile, function(index, total, jobopt)
local mapped_bmi
if provide and compiler_support.memcache():get2(target:name() .. name, "reuse") then
mapped_bmi = get_from_target_mapper(target, name).bmi
end
local build, dependinfo
local dependfile = target:dependfile(bmifile or opt.objectfile)
if provide or compiler_support.has_module_extension(opt.cppfile) then
build, dependinfo = should_build(target, opt.cppfile, bmifile, {name = name, objectfile = opt.objectfile, requires = opt.module.requires})
-- needed to detect rebuild of dependencies
if provide and build then
mark_build(target, name)
end
end
-- append requires flags
if opt.module.requires then
_append_requires_flags(target, opt.module, name, opt.cppfile, bmifile, opt)
end
-- for cpp file we need to check after appendings the flags
if build == nil then
build, dependinfo = should_build(target, opt.cppfile, bmifile, {name = name, objectfile = opt.objectfile, requires = opt.module.requires})
end
if build then
-- compile if it's a named module
if provide or compiler_support.has_module_extension(opt.cppfile) then
if not dryrun then
local objectdir = path.directory(opt.objectfile)
if not os.isdir(objectdir) then
os.mkdir(objectdir)
end
end
local fileconfig = target:fileconfig(opt.cppfile)
local public = fileconfig and fileconfig.public
local external = fileconfig and fileconfig.external
local from_moduleonly = external and external.moduleonly
local bmifile = mapped_bmi or bmifile
if external and not from_moduleonly then
if not mapped_bmi then
progress.show(jobopt.progress, "${color.build.target}<%s> ${clear}${color.build.object}compiling.bmi.$(mode) %s", target:name(), name or opt.cppfile)
_compile_bmi_step(target, bmifile, opt.cppfile, opt.objectfile, provide)
end
else
progress.show(jobopt.progress, "${color.build.target}<%s> ${clear}${color.build.object}compiling.module.$(mode) %s", target:name(), name or opt.cppfile)
_compile_one_step(target, bmifile, opt.cppfile, opt.objectfile, provide)
end
else
os.tryrm(opt.objectfile) -- force rebuild for .cpp files
end
depend.save(dependinfo, dependfile)
end
end)}
end
-- build module file for batchcmds
function make_module_buildcmds(target, batchcmds, opt)
local name, provide, _ = compiler_support.get_provided_module(opt.module)
local bmifile = provide and compiler_support.get_bmi_path(provide.bmi)
local mapped_bmi
if provide and compiler_support.memcache():get2(target:name() .. name, "reuse") then
mapped_bmi = get_from_target_mapper(target, name).bmi
end
-- append requires flags
if opt.module.requires then
_append_requires_flags(target, opt.module, name, opt.cppfile, bmifile, opt)
end
-- compile if it's a named module
if provide or compiler_support.has_module_extension(opt.cppfile) then
batchcmds:mkdir(path.directory(opt.objectfile))
local fileconfig = target:fileconfig(opt.cppfile)
local public = fileconfig and fileconfig.public
local external = fileconfig and fileconfig.external
local from_moduleonly = external and external.moduleonly
local bmifile = mapped_bmi or bmifile
if external and not from_moduleonly then
if not mapped_bmi then
batchcmds:show_progress(opt.progress, "${color.build.target}<%s> ${clear}${color.build.object}compiling.bmi.$(mode) %s", target:name(), name or opt.cppfile)
_compile_bmi_step(target, bmifile, opt.cppfile, provide, {batchcmds = batchcmds})
end
else
batchcmds:show_progress(opt.progress, "${color.build.target}<%s> ${clear}${color.build.object}compiling.module.$(mode) %s", target:name(), name or opt.cppfile)
_compile_one_step(target, bmifile, opt.cppfile, opt.objectfile, provide, {batchcmds = batchcmds})
end
else
batchcmds:rm(opt.objectfile) -- force rebuild for .cpp files
end
batchcmds:add_depfiles(opt.cppfile)
return os.mtime(opt.objectfile)
end
-- build headerunit file for batchjobs
function make_headerunit_buildjobs(target, job_name, batchjobs, headerunit, bmifile, outputdir, opt)
local already_exists = add_headerunit_to_target_mapper(target, headerunit, bmifile)
if not already_exists then
return {
name = job_name,
sourcefile = headerunit.path,
job = batchjobs:newjob(job_name, function(index, total, jobopt)
if not os.isdir(outputdir) then
os.mkdir(outputdir)
end
local compinst = compiler.load("cxx", {target = target})
local compflags = compinst:compflags({sourcefile = headerunit.path, target = target})
local dependfile = target:dependfile(bmifile)
local dependinfo = depend.load(dependfile) or {}
dependinfo.files = {}
local depvalues = {compinst:program(), compflags}
local name = headerunit.unique and headerunit.name or headerunit.path
if opt.build then
progress.show(jobopt.progress, "${color.build.target}<%s> ${clear}${color.build.object}compiling.headerunit.$(mode) %s", target:name(), headerunit.name)
_compile(target, _make_headerunitflags(target, headerunit, bmifile), name, target:objectfile(headerunit.path), true)
end
table.insert(dependinfo.files, headerunit.path)
dependinfo.values = depvalues
depend.save(dependinfo, dependfile)
end)}
end
end
-- build headerunit file for batchcmds
function make_headerunit_buildcmds(target, batchcmds, headerunit, bmifile, outputdir, opt)
batchcmds:mkdir(outputdir)
add_headerunit_to_target_mapper(target, headerunit, bmifile)
if opt.build then
local name = headerunit.unique and headerunit.name or headerunit.path
batchcmds:show_progress(opt.progress, "${color.build.target}<%s> ${clear}${color.build.object}compiling.headerunit.$(mode) %s", target:name(), name)
_batchcmds_compile(batchcmds, target, _make_headerunitflags(target, headerunit, bmifile), target:objectfile(headerunit.path))
end
batchcmds:add_depfiles(headerunit.path)
return os.mtime(bmifile)
end
|
0 | repos/xmake/xmake/rules/c++/modules/modules_support | repos/xmake/xmake/rules/c++/modules/modules_support/msvc/dependency_scanner.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki, Arthapz
-- @file msvc/dependency_scanner.lua
--
-- imports
import("core.base.json")
import("core.base.semver")
import("core.project.depend")
import("private.tools.vstool")
import("utils.progress")
import("compiler_support")
import("builder")
import(".dependency_scanner", {inherit = true})
-- generate dependency files
function generate_dependency_for(target, sourcefile, opt)
local msvc = target:toolchain("msvc")
local scandependenciesflag = compiler_support.get_scandependenciesflag(target)
local ifcoutputflag = compiler_support.get_ifcoutputflag(target)
local common_flags = {"-TP", scandependenciesflag}
local dependfile = target:dependfile(sourcefile)
local changed = false
depend.on_changed(function ()
progress.show(opt.progress, "${color.build.target}<%s> generating.module.deps %s", target:name(), sourcefile)
local outputdir = compiler_support.get_outputdir(target, sourcefile)
local jsonfile = path.join(outputdir, path.filename(sourcefile) .. ".module.json")
if scandependenciesflag and not target:policy("build.c++.msvc.fallbackscanner") then
local flags = {jsonfile, sourcefile, ifcoutputflag, outputdir, "-Fo" .. target:objectfile(sourcefile)}
local compinst = target:compiler("cxx")
local compflags = table.join(compinst:compflags({sourcefile = sourcefile, target = target}) or {}, common_flags, flags)
os.vrunv(compinst:program(), winos.cmdargv(compflags), {envs = msvc:runenvs()})
else
fallback_generate_dependencies(target, jsonfile, sourcefile, function(file)
local compinst = target:compiler("cxx")
local compflags = compinst:compflags({sourcefile = file, target = target})
local ifile = path.translate(path.join(outputdir, path.filename(file) .. ".i"))
os.vrunv(compinst:program(), table.join(compflags,
{"/P", "-TP", file, "/Fi" .. ifile}), {envs = msvc:runenvs()})
local content = io.readfile(ifile)
os.rm(ifile)
return content
end)
end
changed = true
local dependinfo = io.readfile(jsonfile)
return { moduleinfo = dependinfo }
end, {dependfile = dependfile, files = {sourcefile}, changed = target:is_rebuilt()})
return changed
end
|
0 | repos/xmake/xmake/rules/c++/modules/modules_support | repos/xmake/xmake/rules/c++/modules/modules_support/msvc/compiler_support.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki, Arthapz
-- @file msvc/compiler_support.lua
--
-- imports
import("core.base.semver")
import("core.project.config")
import("lib.detect.find_tool")
import(".compiler_support", {inherit = true})
-- load module support for the current target
function load(target)
local msvc = target:toolchain("msvc")
local vcvars = msvc:config("vcvars")
-- enable std modules if c++23 by defaults
if target:data("c++.msvc.enable_std_import") == nil and target:policy("build.c++.modules.std") then
local languages = target:get("languages")
local isatleastcpp23 = false
for _, language in ipairs(languages) do
if language:startswith("c++") or language:startswith("cxx") then
isatleastcpp23 = true
local version = tonumber(language:match("%d+"))
if (not version or version <= 20) and not language:match("latest") then
isatleastcpp23 = false
break
end
end
end
local stdmodulesdir
local msvc = target:toolchain("msvc")
if msvc then
local vcvars = msvc:config("vcvars")
if vcvars.VCInstallDir and vcvars.VCToolsVersion and semver.compare(vcvars.VCToolsVersion, "14.35") > 0 then
stdmodulesdir = path.join(vcvars.VCInstallDir, "Tools", "MSVC", vcvars.VCToolsVersion, "modules")
end
end
target:data_set("c++.msvc.enable_std_import", isatleastcpp23 and os.isdir(stdmodulesdir))
end
end
-- strip flags that doesn't affect bmi generation
function strip_flags(target, flags)
-- speculative list as there is no resource that list flags that prevent reusability, this list will likely be improve over time
-- @see https://learn.microsoft.com/en-us/cpp/build/reference/compiler-options-listed-alphabetically?view=msvc-170
local strippable_flags = {
"I",
"TP",
"errorReport",
"W",
"w",
"sourceDependencies",
"scanDependencies",
"reference",
"PD",
"nologo",
"MP",
"internalPartition",
"interface",
"ifcOutput",
"help",
"headerUnit",
"headerName",
"Fp",
"Fo",
"Fm",
"Fe",
"Fd",
"FC",
"exportHeader",
"EP",
"E",
"doc",
"diagnostics",
"cgthreads",
"C",
"analyze",
"?",
}
if not target:policy("build.c++.modules.tryreuse.discriminate_on_defines") then
table.join2(strippable_flags, {"D", "U"})
end
local output = {}
for _, flag in ipairs(flags) do
local strip = false
for _, _flag in ipairs(strippable_flags) do
if flag:startswith("cl::-" .. _flag) or flag:startswith("cl::/" .. _flag) or
flag:startswith("-" .. _flag) or flag:startswith("/" .. _flag) then
strip = true
break
end
end
if not strip then
table.insert(output, flag)
end
end
return output
end
-- provide toolchain include dir for stl headerunit when p1689 is not supported
function toolchain_includedirs(target)
for _, toolchain_inst in ipairs(target:toolchains()) do
if toolchain_inst:name() == "msvc" then
local vcvars = toolchain_inst:config("vcvars")
if vcvars.VCInstallDir and vcvars.VCToolsVersion then
return { path.join(vcvars.VCInstallDir, "Tools", "MSVC", vcvars.VCToolsVersion, "include") }
end
break
end
end
raise("msvc toolchain includedirs not found!")
end
-- build c++23 standard modules if needed
function get_stdmodules(target)
if target:policy("build.c++.modules.std") then
if target:data("c++.msvc.enable_std_import") then
local msvc = target:toolchain("msvc")
if msvc then
local vcvars = msvc:config("vcvars")
if vcvars.VCInstallDir and vcvars.VCToolsVersion then
modules = {}
local stdmodulesdir = path.join(vcvars.VCInstallDir, "Tools", "MSVC", vcvars.VCToolsVersion, "modules")
assert(stdmodulesdir, "Can't enable C++23 std modules, directory missing !")
return {path.join(stdmodulesdir, "std.ixx"), path.join(stdmodulesdir, "std.compat.ixx")}
end
end
end
end
wprint("std and std.compat modules not found ! disabling them for the build")
end
function get_bmi_extension()
return ".ifc"
end
function get_ifcoutputflag(target)
local ifcoutputflag = _g.ifcoutputflag
if ifcoutputflag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags({"-ifcOutput", os.tmpfile()}, "cxxflags", {flagskey = "cl_ifc_output"}) then
ifcoutputflag = "-ifcOutput"
end
assert(ifcoutputflag, "compiler(msvc): does not support c++ module flag(/ifcOutput)!")
_g.ifcoutputflag = ifcoutputflag or false
end
return ifcoutputflag or nil
end
function get_ifconlyflag(target)
local ifconlyflag = _g.ifconlyflag
if ifconlyflag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags({"-ifcOnly"}, "cxxflags", {flagskey = "cl_ifc_only"}) then
ifconlyflag = "-ifcOnly"
end
_g.ifconlyflag = ifconlyflag or false
end
return ifconlyflag or nil
end
function get_ifcsearchdirflag(target)
local ifcsearchdirflag = _g.ifcsearchdirflag
if ifcsearchdirflag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags({"-ifcSearchDir", os.tmpdir()}, "cxxflags", {flagskey = "cl_ifc_search_dir"}) then
ifcsearchdirflag = "-ifcSearchDir"
end
assert(ifcsearchdirflag, "compiler(msvc): does not support c++ module flag(/ifcSearchDir)!")
_g.ifcsearchdirflag = ifcsearchdirflag or false
end
return ifcsearchdirflag or nil
end
function get_interfaceflag(target)
local interfaceflag = _g.interfaceflag
if interfaceflag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags("-interface", "cxxflags", {flagskey = "cl_interface"}) then
interfaceflag = "-interface"
end
assert(interfaceflag, "compiler(msvc): does not support c++ module flag(/interface)!")
_g.interfaceflag = interfaceflag or false
end
return interfaceflag
end
function get_referenceflag(target)
local referenceflag = _g.referenceflag
if referenceflag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags({"-reference", "Foo=" .. os.tmpfile()}, "cxxflags", {flagskey = "cl_reference"}) then
referenceflag = "-reference"
end
assert(referenceflag, "compiler(msvc): does not support c++ module flag(/reference)!")
_g.referenceflag = referenceflag or false
end
return referenceflag or nil
end
function get_headernameflag(target)
local headernameflag = _g.headernameflag
if headernameflag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags({"-std:c++latest", "-exportHeader", "-headerName:quote"}, "cxxflags", {flagskey = "cl_header_name_quote"}) and
compinst:has_flags({"-std:c++latest", "-exportHeader", "-headerName:angle"}, "cxxflags", {flagskey = "cl_header_name_angle"}) then
headernameflag = "-headerName"
end
_g.headernameflag = headernameflag or false
end
return headernameflag or nil
end
function get_headerunitflag(target)
local headerunitflag = _g.headerunitflag
if headerunitflag == nil then
local compinst = target:compiler("cxx")
local ifcfile = os.tmpfile()
if compinst:has_flags({"-std:c++latest", "-headerUnit:quote", "foo.h=" .. ifcfile}, "cxxflags", {flagskey = "cl_header_unit_quote"}) and
compinst:has_flags({"-std:c++latest", "-headerUnit:angle", "foo.h=" .. ifcfile}, "cxxflags", {flagskey = "cl_header_unit_angle"}) then
headerunitflag = "-headerUnit"
end
_g.headerunitflag = headerunitflag or false
end
return headerunitflag or nil
end
function get_exportheaderflag(target)
local exportheaderflag = _g.exportheaderflag
if exportheaderflag == nil then
if get_headernameflag(target) then
exportheaderflag = "-exportHeader"
end
_g.exportheaderflag = exportheaderflag or false
end
return exportheaderflag or nil
end
function get_scandependenciesflag(target)
local scandependenciesflag = _g.scandependenciesflag
if scandependenciesflag == nil then
local compinst = target:compiler("cxx")
local scan_dependencies_jsonfile = os.tmpfile() .. ".json"
if compinst:has_flags("-scanDependencies " .. scan_dependencies_jsonfile, "cxflags", {flagskey = "cl_scan_dependencies",
on_check = function (ok, errors)
if os.isfile(scan_dependencies_jsonfile) then
ok = true
end
if ok and not os.isfile(scan_dependencies_jsonfile) then
ok = false
end
return ok, errors
end}) then
scandependenciesflag = "-scanDependencies"
end
_g.scandependenciesflag = scandependenciesflag or false
end
return scandependenciesflag or nil
end
function get_cppversionflag(target)
local cppversionflag = _g.cppversionflag
if cppversionflag == nil then
local compinst = target:compiler("cxx")
local flags = compinst:compflags({target = target})
cppversionflag = table.find_if(flags, function(v) string.startswith(v, "/std:c++") end) or "/std:c++latest"
end
return cppversionflag or nil
end
function get_internalpartitionflag(target)
local internalpartitionflag = _g.internalpartitionflag
if internalpartitionflag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags("-internalPartition", "cxxflags", {flagskey = "cl_internal_partition"}) then
internalpartitionflag = "-internalPartition"
end
_g.internalpartitionflag = internalpartitionflag or false
end
return internalpartitionflag or nil
end
|
0 | repos/xmake/xmake/rules/c++/modules/modules_support | repos/xmake/xmake/rules/c++/modules/modules_support/clang/builder.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki, Arthapz
-- @file clang/builder.lua
--
-- imports
import("core.base.json")
import("core.base.option")
import("core.base.semver")
import("utils.progress")
import("private.action.build.object", {alias = "objectbuilder"})
import("core.tool.compiler")
import("core.project.config")
import("core.project.depend")
import("compiler_support")
import(".builder", {inherit = true})
function _compile_one_step(target, bmifile, sourcefile, objectfile, opt)
-- get flags
local module_outputflag = compiler_support.get_moduleoutputflag(target)
if module_outputflag then
local flags = table.join({"-x", "c++-module", module_outputflag .. bmifile}, opt.std and {"-Wno-include-angled-in-module-purview", "-Wno-reserved-module-identifier"} or {})
if opt and opt.batchcmds then
_batchcmds_compile(opt.batchcmds, target, flags, sourcefile, objectfile)
else
_compile(target, flags, sourcefile, objectfile)
end
else
_compile_bmi_step(target, bmifile, sourcefile, opt)
_compile_objectfile_step(target, bmifile, sourcefile, objectfile, opt)
end
end
function _compile_bmi_step(target, bmifile, sourcefile, opt)
local flags = table.join({"-x", "c++-module", "--precompile"}, opt.std and {"-Wno-include-angled-in-module-purview", "-Wno-reserved-module-identifier"} or {})
if opt and opt.batchcmds then
_batchcmds_compile(opt.batchcmds, target, flags, sourcefile, bmifile)
else
_compile(target, flags, sourcefile, bmifile)
end
end
function _compile_objectfile_step(target, bmifile, sourcefile, objectfile, opt)
_compile(target, {}, sourcefile, objectfile, {bmifile = bmifile})
if opt and opt.batchcmds then
_batchcmds_compile(opt.batchcmds, target, {}, sourcefile, objectfile, {bmifile = bmifile})
else
_compile(target, {}, sourcefile, objectfile, {bmifile = bmifile})
end
end
-- get flags for building a headerunit
function _make_headerunitflags(target, headerunit, bmifile)
local module_headerflag = compiler_support.get_moduleheaderflag(target)
assert(module_headerflag, "compiler(clang): does not support c++ header units!")
local local_directory = (headerunit.type == ":quote") and {"-I" .. path.directory(headerunit.path)} or {}
local headertype = (headerunit.type == ":angle") and "system" or "user"
local flags = table.join(local_directory, {"-xc++-header", "-Wno-everything", module_headerflag .. headertype})
return flags
end
-- do compile
function _compile(target, flags, sourcefile, outputfile, opt)
opt = opt or {}
local dryrun = option.get("dry-run")
local compinst = target:compiler("cxx")
local compflags = compinst:compflags({sourcefile = sourcefile, target = target})
local flags = table.join(compflags or {}, flags)
-- trace
if option.get("verbose") then
print(compinst:compcmd(opt.bmifile or sourcefile, outputfile, {target = target, compflags = flags, rawargs = true}))
end
-- do compile
if not dryrun then
assert(compinst:compile(opt.bmifile or sourcefile, outputfile, {target = target, compflags = flags}))
end
end
-- do compile for batchcmds
-- @note we need to use batchcmds:compilev to translate paths in compflags for generator, e.g. -Ixx
function _batchcmds_compile(batchcmds, target, flags, sourcefile, outputfile, opt)
opt = opt or {}
local compinst = target:compiler("cxx")
local compflags = compinst:compflags({sourcefile = sourcefile, target = target})
flags = table.join("-c", compflags or {}, flags, {"-o", outputfile, opt.bmifile or sourcefile})
batchcmds:compilev(flags, {compiler = compinst, sourcekind = "cxx"})
end
-- get module requires flags
-- e.g
-- -fmodule-file=build/.gens/Foo/rules/modules/cache/foo.pcm
-- -fmodule-file=build/.gens/Foo/rules/modules/cache/iostream.pcm
-- -fmodule-file=build/.gens/Foo/rules/modules/cache/bar.hpp.pcm
-- on LLVM >= 16
-- -fmodule-file=foo=build/.gens/Foo/rules/modules/cache/foo.pcm
-- -fmodule-file=build/.gens/Foo/rules/modules/cache/iostream.pcm
-- -fmodule-file=build/.gens/Foo/rules/modules/cache/bar.hpp.pcm
--
function _get_requiresflags(target, module, opt)
local modulefileflag = compiler_support.get_modulefileflag(target)
local name = module.name
local cachekey = target:name() .. name
local requiresflags = compiler_support.memcache():get2(cachekey, "requiresflags")
or compiler_support.localcache():get2(cachekey, "requiresflags")
if not requiresflags or (opt and opt.regenerate) then
requiresflags = {}
for required, _ in table.orderpairs(module.requires) do
local dep_module = get_from_target_mapper(target, required)
assert(dep_module, "module dependency %s required for %s not found", required, name)
-- aliased headerunit
local bmifile = dep_module.bmi
if dep_module.aliasof then
local aliased = get_from_target_mapper(target, dep_module.aliasof)
bmifile = aliased.bmi
end
local mapflag = (dep_module.opt and dep_module.opt.namedmodule) and format("%s%s=%s", modulefileflag, required, bmifile) or modulefileflag .. bmifile
table.insert(requiresflags, mapflag)
-- append deps
if dep_module.opt and dep_module.opt.deps then
local deps = _get_requiresflags(target, {name = dep_module.name or dep_module.sourcefile, bmi = bmifile, requires = dep_module.opt.deps})
table.join2(requiresflags, deps)
end
end
compiler_support.memcache():set2(cachekey, "requiresflags", table.unique(requiresflags))
compiler_support.localcache():set2(cachekey, "requiresflags", table.unique(requiresflags))
end
return requiresflags
end
function _append_requires_flags(target, module, name, cppfile, bmifile, opt)
local cxxflags = {}
local requiresflags = _get_requiresflags(target, {name = (name or cppfile), bmi = bmifile, requires = module.requires}, {regenerate = opt.build})
for _, flag in ipairs(requiresflags) do
-- we need to wrap flag to support flag with space
if type(flag) == "string" and flag:find(" ", 1, true) then
table.insert(cxxflags, {flag})
else
table.insert(cxxflags, flag)
end
end
target:fileconfig_add(cppfile, {force = {cxxflags = cxxflags}})
end
-- populate module map
function populate_module_map(target, modules)
local clang_version = compiler_support.get_clang_version(target)
local support_namedmodule = semver.compare(clang_version, "16.0") >= 0
for _, module in pairs(modules) do
local name, provide, cppfile = compiler_support.get_provided_module(module)
if provide then
local bmifile = compiler_support.get_bmi_path(provide.bmi)
add_module_to_target_mapper(target, name, cppfile, bmifile, {deps = module.requires, namedmodule = support_namedmodule})
end
end
end
-- get defines for a module
function get_module_required_defines(target, sourcefile)
local compinst = compiler.load("cxx", {target = target})
local compflags = compinst:compflags({sourcefile = sourcefile, target = target})
local defines
for _, flag in ipairs(compflags) do
if flag:startswith("-D") then
defines = defines or {}
table.insert(defines, flag:sub(3))
end
end
return defines
end
-- build module file for batchjobs
function make_module_buildjobs(target, batchjobs, job_name, deps, opt)
local name, provide, _ = compiler_support.get_provided_module(opt.module)
local bmifile = provide and compiler_support.get_bmi_path(provide.bmi)
local dryrun = option.get("dry-run")
return {
name = job_name,
deps = table.join(target:name() .. "_populate_module_map", deps),
sourcefile = opt.cppfile,
job = batchjobs:newjob(name or opt.cppfile, function(index, total, jobopt)
local mapped_bmi
if provide and compiler_support.memcache():get2(target:name() .. name, "reuse") then
mapped_bmi = get_from_target_mapper(target, name).bmi
end
local build, dependinfo
local dependfile = target:dependfile(bmifile or opt.objectfile)
if provide or compiler_support.has_module_extension(opt.cppfile) then
build, dependinfo = should_build(target, opt.cppfile, bmifile, {name = name, objectfile = opt.objectfile, requires = opt.module.requires})
-- needed to detect rebuild of dependencies
if provide and build then
mark_build(target, name)
end
end
-- append requires flags
if opt.module.requires then
_append_requires_flags(target, opt.module, name, opt.cppfile, bmifile, opt)
end
-- for cpp file we need to check after appendings the flags
if build == nil then
build, dependinfo = should_build(target, opt.cppfile, bmifile, {name = name, objectfile = opt.objectfile, requires = opt.module.requires})
end
if build then
-- compile if it's a named module
if provide or compiler_support.has_module_extension(opt.cppfile) then
if not dryrun then
local objectdir = path.directory(opt.objectfile)
if not os.isdir(objectdir) then
os.mkdir(objectdir)
end
end
local fileconfig = target:fileconfig(opt.cppfile)
local public = fileconfig and fileconfig.public
local external = fileconfig and fileconfig.external
local from_moduleonly = external and external.moduleonly
local bmifile = mapped_bmi or bmifile
if external and not from_moduleonly then
if not mapped_bmi then
progress.show(jobopt.progress, "${color.build.target}<%s> ${clear}${color.build.object}compiling.bmi.$(mode) %s", target:name(), name or opt.cppfile)
_compile_bmi_step(target, bmifile, opt.cppfile, {std = (name == "std" or name == "std.compat")})
end
else
progress.show(jobopt.progress, "${color.build.target}<%s> ${clear}${color.build.object}compiling.module.$(mode) %s", target:name(), name or opt.cppfile)
_compile_one_step(target, bmifile, opt.cppfile, opt.objectfile, {std = (name == "std" or name == "std.compat")})
end
else
os.tryrm(opt.objectfile) -- force rebuild for .cpp files
end
depend.save(dependinfo, dependfile)
end
end)}
end
-- build module file for batchcmds
function make_module_buildcmds(target, batchcmds, opt)
local name, provide, _ = compiler_support.get_provided_module(opt.module)
local bmifile = provide and compiler_support.get_bmi_path(provide.bmi)
local mapped_bmi
if provide and compiler_support.memcache():get2(target:name() .. name, "reuse") then
mapped_bmi = get_from_target_mapper(target, name).bmi
end
-- append requires flags
if opt.module.requires then
_append_requires_flags(target, opt.module, name, opt.cppfile, bmifile, opt)
end
-- compile if it's a named module
if provide or compiler_support.has_module_extension(opt.cppfile) then
batchcmds:mkdir(path.directory(opt.objectfile))
local fileconfig = target:fileconfig(opt.cppfile)
local public = fileconfig and fileconfig.public
local external = fileconfig and fileconfig.external
local bmifile = mapped_bmi or bmifile
if external and not from_moduleonly then
if not mapped_bmi then
batchcmds:show_progress(opt.progress, "${color.build.target}<%s> ${clear}${color.build.object}compiling.bmi.$(mode) %s", target:name(), name or opt.cppfile)
_compile_bmi_step(target, bmifile, opt.cppfile, {std = (name == "std" or name == "std.compat"), batchcmds = batchcmds})
end
else
batchcmds:show_progress(opt.progress, "${color.build.target}<%s> ${clear}${color.build.object}compiling.module.$(mode) %s", target:name(), name or opt.cppfile)
_compile_one_step(target, bmifile, opt.cppfile, opt.objectfile, {std = (name == "std" or name == "std.compat"), batchcmds = batchcmds})
end
else
batchcmds:rm(opt.objectfile) -- force rebuild for .cpp files
end
batchcmds:add_depfiles(opt.cppfile)
return os.mtime(opt.objectfile)
end
-- build headerunit file for batchjobs
function make_headerunit_buildjobs(target, job_name, batchjobs, headerunit, bmifile, outputdir, opt)
local already_exists = add_headerunit_to_target_mapper(target, headerunit, bmifile)
if not already_exists then
return {
name = job_name,
sourcefile = headerunit.path,
job = batchjobs:newjob(job_name, function(index, total, jobopt)
if not os.isdir(outputdir) then
os.mkdir(outputdir)
end
local compinst = compiler.load("cxx", {target = target})
local compflags = compinst:compflags({sourcefile = headerunit.path, target = target})
local dependfile = target:dependfile(bmifile)
local dependinfo = depend.load(dependfile) or {}
dependinfo.files = {}
local depvalues = {compinst:program(), compflags}
if opt.build then
progress.show(jobopt.progress, "${color.build.target}<%s> ${clear}${color.build.object}compiling.headerunit.$(mode) %s", target:name(), headerunit.name)
_compile(target, _make_headerunitflags(target, headerunit, bmifile), headerunit.path, bmifile)
end
table.insert(dependinfo.files, headerunit.path)
dependinfo.values = depvalues
depend.save(dependinfo, dependfile)
end)}
end
end
-- build headerunit file for batchcmds
function make_headerunit_buildcmds(target, batchcmds, headerunit, bmifile, outputdir, opt)
batchcmds:mkdir(outputdir)
add_headerunit_to_target_mapper(target, headerunit, bmifile)
if opt.build then
local name = headerunit.unique and headerunit.name or headerunit.path
batchcmds:show_progress(opt.progress, "${color.build.target}<%s> ${clear}${color.build.object}compiling.headerunit.$(mode) %s", target:name(), name)
_batchcmds_compile(batchcmds, target, _make_headerunitflags(target, headerunit, bmifile), bmifile)
end
batchcmds:add_depfiles(headerunit.path)
return os.mtime(bmifile)
end
function get_requires(target, module)
local _requires
local flags = _get_requiresflags(target, module)
for _, flag in ipairs(flags) do
_requires = _requires or {}
table.insert(_requires, flag:split("=")[3])
end
return _requires
end
|
0 | repos/xmake/xmake/rules/c++/modules/modules_support | repos/xmake/xmake/rules/c++/modules/modules_support/clang/dependency_scanner.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki, Arthapz
-- @file clang/dependency_scanner.lua
--
-- imports
import("core.base.json")
import("core.base.semver")
import("core.base.option")
import("core.project.depend")
import("utils.progress")
import("compiler_support")
import(".dependency_scanner", {inherit = true})
function generate_dependency_for(target, sourcefile, opt)
local compinst = target:compiler("cxx")
local changed = false
local dependfile = target:dependfile(sourcefile)
depend.on_changed(function()
if opt.progress then
progress.show(opt.progress, "${color.build.target}<%s> generating.module.deps %s", target:name(), sourcefile)
end
local outputdir = compiler_support.get_outputdir(target, sourcefile)
local jsonfile = path.translate(path.join(outputdir, path.filename(sourcefile) .. ".json"))
local has_clangscandepssupport = compiler_support.has_clangscandepssupport(target)
if has_clangscandepssupport and not target:policy("build.c++.clang.fallbackscanner") then
-- We need absolute path of clang to use clang-scan-deps
-- See https://clang.llvm.org/docs/StandardCPlusPlusModules.html#possible-issues-failed-to-find-system-headers
local clang_path = compinst:program()
if not path.is_absolute(clang_path) then
clang_path = compiler_support.get_clang_path(target) or compinst:program()
end
local clangscandeps = compiler_support.get_clang_scan_deps(target)
local compflags = compinst:compflags({sourcefile = sourcefile, target = target})
local flags = table.join({"--format=p1689", "--",
clang_path, "-x", "c++", "-c", sourcefile, "-o", target:objectfile(sourcefile)}, compflags or {})
if option.get("verbose") then
print(os.args(table.join(clangscandeps, flags)))
end
local outdata, errdata = os.iorunv(clangscandeps, flags)
assert(errdata, errdata)
io.writefile(jsonfile, outdata)
else
if not has_clangscandepssupport then
wprint("No clang-scan-deps found ! using fallback scanner")
end
fallback_generate_dependencies(target, jsonfile, sourcefile, function(file)
local keepsystemincludesflag = compiler_support.get_keepsystemincludesflag(target)
local compflags = compinst:compflags({sourcefile = file, target = target})
-- exclude -fmodule* and -std=c++/gnu++* flags because
-- when they are set clang try to find bmi of imported modules but they don't exists in this point of compilation
table.remove_if(compflags, function(_, flag)
return flag:startswith("-fmodule") or flag:startswith("-std=c++") or flag:startswith("-std=gnu++")
end)
local ifile = path.translate(path.join(outputdir, path.filename(file) .. ".i"))
local flags = table.join(compflags or {}, keepsystemincludesflag or {}, {"-E", "-x", "c++", file, "-o", ifile})
os.vrunv(compinst:program(), flags)
local content = io.readfile(ifile)
os.rm(ifile)
return content
end)
end
changed = true
local rawdependinfo = io.readfile(jsonfile)
return {moduleinfo = rawdependinfo}
end, {dependfile = dependfile, files = {sourcefile}, changed = target:is_rebuilt()})
return changed
end
|
0 | repos/xmake/xmake/rules/c++/modules/modules_support | repos/xmake/xmake/rules/c++/modules/modules_support/clang/compiler_support.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki, Arthapz
-- @file clang/compiler_support.lua
--
-- imports
import("core.base.semver")
import("core.base.option")
import("core.base.json")
import("lib.detect.find_tool")
import("lib.detect.find_file")
import(".compiler_support", {inherit = true})
-- get includedirs for stl headers
--
-- $ echo '#include <vector>' | clang -x c++ -E - | grep '/vector"'
-- # 1 "/usr/include/c++/11/vector" 1 3
-- # 58 "/usr/include/c++/11/vector" 3
-- # 59 "/usr/include/c++/11/vector" 3
--
function _get_toolchain_includedirs_for_stlheaders(target, includedirs, clang)
local tmpfile = os.tmpfile() .. ".cc"
io.writefile(tmpfile, "#include <vector>")
local argv = {"-E", "-x", "c++", tmpfile}
local cpplib = _get_cpplibrary_name(target)
if cpplib then
if cpplib == "c++" then
table.insert(argv, 1, "-stdlib=libc++")
elseif cpplib == "stdc++" then
table.insert(argv, 1, "-stdlib=libstdc++")
end
end
local result = try {function () return os.iorunv(clang, argv, {envs = compinst:runenvs()}) end}
if result then
for _, line in ipairs(result:split("\n", {plain = true})) do
line = line:trim()
if line:startswith("#") and line:find("/vector\"", 1, true) then
local includedir = line:match("\"(.+)/vector\"")
if includedir and os.isdir(includedir) then
table.insert(includedirs, path.normalize(includedir))
break
end
end
end
end
os.tryrm(tmpfile)
end
function _get_cpplibrary_name(target)
-- libc++ come first because on windows, if we use libc++ clang will still use msvc crt so MD / MT / MDd / MTd can be set
if target:has_runtime("c++_shared", "c++_static") then
return "c++"
elseif target:has_runtime("stdc++_shared", "stdc++_static") then
return "stdc++"
elseif target:has_runtime("MD", "MT", "MDd", "MTd") then
return "msstl"
end
if target:is_plat("macosx") then
return "c++"
elseif target:is_plat("linux") then
return "stdc++"
elseif target:is_plat("windows") then
return "msstl"
end
end
function _get_std_module_manifest_path(target)
local print_module_manifest_flag = get_print_library_module_manifest_path_flag(target)
local clang_path = path.directory(get_clang_path(target))
if print_module_manifest_flag then
local compinst = target:compiler("cxx")
local outdata, _ = try { function() return os.iorunv(compinst:program(), {"-std=c++23", "-stdlib=libc++", "--sysroot=" .. path.join(clang_path, ".."), print_module_manifest_flag}, {envs = compinst:runenvs()}) end }
if outdata and not outdata:startswith("<NOT PRESENT>") then
return outdata:trim()
end
end
-- fallback on custom detection
-- manifest can be found in <llvm_path>/lib subdirectory (i.e on debian it should be <llvm_path>/lib/x86_64-unknown-linux-gnu/)
local clang_lib_path = path.join(clang_path, "..", "lib")
local modules_json_path = path.join(clang_lib_path, "libc++.modules.json")
if not os.isfile(modules_json_path) then
modules_json_path = find_file("*/libc++.modules.json", clang_lib_path)
end
return modules_json_path
end
-- load module support for the current target
function load(target)
local clangmodulesflag, modulestsflag, withoutflag = get_modulesflag(target)
-- add module flags
if not withoutflag then
target:add("cxxflags", modulestsflag)
end
-- fix default visibility for functions and variables [-fvisibility] differs in PCH file vs. current file
-- module.pcm cannot be loaded due to a configuration mismatch with the current compilation.
--
-- it will happen in binary target depend on library target with modules, and enable release mode at same time.
--
-- @see https://github.com/xmake-io/xmake/issues/3358#issuecomment-1432586767
local dep_symbols
local has_library_deps = false
for _, dep in ipairs(target:orderdeps()) do
if dep:is_shared() or dep:is_static() or dep:is_object() then
dep_symbols = dep:get("symbols")
has_library_deps = true
break
end
end
if has_library_deps then
target:set("symbols", dep_symbols and dep_symbols or "none")
end
-- on Windows before llvm18 we need to disable delayed-template-parsing because it's incompatible with modules, from llvm >= 18, it's disabled by default
local clang_version = get_clang_version(target)
if semver.compare(clang_version, "18") < 0 then
target:add("cxxflags", "-fno-delayed-template-parsing")
end
end
-- strip flags that doesn't affect bmi generation
function strip_flags(target, flags)
-- speculative list as there is no resource that list flags that prevent reusability, this list will likely be improve over time
-- @see https://clang.llvm.org/docs/StandardCPlusPlusModules.html#consistency-requirement
local strippable_flags = {
"-I",
"-isystem",
"-g",
"-O",
"-W",
"-w",
"-cxx-isystem",
"-Q",
}
if not target:policy("build.c++.modules.tryreuse.discriminate_on_defines") then
table.join2(strippable_flags, {"-D", "-U"})
end
local output = {}
local last_flag_I = false
for _, flag in ipairs(flags) do
local strip = false
for _, _flag in ipairs(strippable_flags) do
if flag:startswith(_flag) or last_flag_I then
last_flag_I = _flag == "-I"
strip = true
break
end
end
if not strip then
table.insert(output, flag)
end
end
return output
end
-- provide toolchain include directories for stl headerunit when p1689 is not supported
function toolchain_includedirs(target)
local includedirs = _g.includedirs
if includedirs == nil then
includedirs = {}
local clang, toolname = target:tool("cxx")
assert(toolname:startswith("clang"))
_get_toolchain_includedirs_for_stlheaders(target, includedirs, clang)
local cpplib = _get_cpplibrary_name(target)
local runtime_flag
if cpplib then
if cpplib == "c++" then
runtime_flag = "-stdlib=libc++"
elseif cpplib == "stdc++" then
runtime_flag = "-stdlib=libstdc++"
end
end
local _, result = try {function () return os.iorunv(clang, table.join({"-E", "-Wp,-v", "-xc", os.nuldev()}, runtime_flag or {})) end}
if result then
for _, line in ipairs(result:split("\n", {plain = true})) do
line = line:trim()
if os.isdir(line) then
table.insert(includedirs, path.normalize(line))
elseif line:startswith("End") then
break
end
end
end
_g.includedirs = includedirs
end
return includedirs
end
-- get clang path
function get_clang_path(target)
local clang_path = _g.clang_path
if not clang_path then
local program, toolname = target:tool("cxx")
if program and toolname:startswith("clang") then
local clang = find_tool(toolname, {program = program,
envs = os.getenvs(), cachekey = "modules_support_clang_" .. toolname})
if clang then
clang_path = clang.program
end
end
clang_path = clang_path or false
_g.clang_path = clang_path
end
return clang_path or nil
end
-- get clang version
function get_clang_version(target)
local clang_version = _g.clang_version
if not clang_version then
local program, toolname = target:tool("cxx")
if program and toolname:startswith("clang") then
local clang = find_tool(toolname, {program = program, version = true,
envs = os.getenvs(), cachekey = "modules_support_clang_" .. toolname})
if clang then
clang_version = clang.version
end
end
clang_version = clang_version or false
_g.clang_version = clang_version
end
return clang_version or nil
end
-- get clang-scan-deps
function get_clang_scan_deps(target)
local clang_scan_deps = _g.clang_scan_deps
if not clang_scan_deps then
local program, toolname = target:tool("cxx")
if program and toolname:startswith("clang") then
local dir = path.directory(program)
local basename = path.basename(program)
local extension = path.extension(program)
program = (basename:rtrim("+"):gsub("clang", "clang-scan-deps")) .. extension
if dir and dir ~= "." and os.isdir(dir) then
program = path.join(dir, program)
end
local result = find_tool("clang-scan-deps", {program = program, version = true})
if result then
clang_scan_deps = result.program
end
end
clang_scan_deps = clang_scan_deps or false
_g.clang_scan_deps = clang_scan_deps
end
return clang_scan_deps or nil
end
function get_stdmodules(target)
if target:policy("build.c++.modules.std") then
local cpplib = _get_cpplibrary_name(target)
if cpplib then
if cpplib == "c++" then
-- libc++ module is found by parsing libc++.modules.json
local modules_json_path = _get_std_module_manifest_path(target)
if modules_json_path then
local modules_json = json.decode(io.readfile(modules_json_path))
if modules_json and modules_json.modules and #modules_json.modules > 0 then
local std_module_directory = path.directory(modules_json.modules[1]["source-path"])
if not path.is_absolute(std_module_directory) then
std_module_directory = path.join(path.directory(modules_json_path), std_module_directory)
end
return {path.join(std_module_directory, "std.cppm"), path.join(std_module_directory, "std.compat.cppm")}
end
end
elseif cpplib == "stdc++" then
-- libstdc++ doesn't have a std module file atm
elseif cpplib == "msstl" then
-- msstl std module file is not compatible with llvm <= 19
-- local toolchain = target:toolchain("clang")
-- local msvc = import("core.tool.toolchain", {anonymous = true}).load("msvc", {plat = toolchain:plat(), arch = toolchain:arch()})
-- if msvc then
-- local vcvars = msvc:config("vcvars")
-- if vcvars.VCInstallDir and vcvars.VCToolsVersion then
-- modules = {}
--
-- local stdmodulesdir = path.join(vcvars.VCInstallDir, "Tools", "MSVC", vcvars.VCToolsVersion, "modules")
-- assert(stdmodulesdir, "Can't enable C++23 std modules, directory missing !")
--
-- return {path.join(stdmodulesdir, "std.ixx"), path.join(stdmodulesdir, "std.compat.ixx")}
-- end
-- end
end
end
end
wprint("std and std.compat modules not found ! disabling them for the build, maybe try to add --sdk=<PATH/TO/LLVM>")
end
function get_bmi_extension()
return ".pcm"
end
function get_modulesflag(target)
local clangmodulesflag = _g.clangmodulesflag
local modulestsflag = _g.modulestsflag
local withoutflag = _g.withoutflag
if clangmodulesflag == nil and modulestsflag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags("-fmodules", "cxxflags", {flagskey = "clang_modules"}) then
clangmodulesflag = "-fmodules"
end
if compinst:has_flags("-fmodules-ts", "cxxflags", {flagskey = "clang_modules_ts"}) then
modulestsflag = "-fmodules-ts"
end
local clang_version = get_clang_version(target)
withoutflag = semver.compare(clang_version, "16.0") >= 0
assert(withoutflag or modulestsflag, "compiler(clang): does not support c++ module!")
_g.clangmodulesflag = clangmodulesflag or false
_g.modulestsflag = modulestsflag or false
_g.withoutflag = withoutflag or false
end
return clangmodulesflag or nil, modulestsflag or nil, withoutflag or nil
end
function get_builtinmodulemapflag(target)
local builtinmodulemapflag = _g.builtinmodulemapflag
if builtinmodulemapflag == nil then
-- this flag seems clang on mingw doesn't distribute it
-- @see https://github.com/xmake-io/xmake/pull/2833
if not target:is_plat("mingw") then
local compinst = target:compiler("cxx")
if compinst:has_flags("-fbuiltin-module-map", "cxxflags", {flagskey = "clang_builtin_module_map"}) then
builtinmodulemapflag = "-fbuiltin-module-map"
end
assert(builtinmodulemapflag, "compiler(clang): does not support c++ module!")
end
_g.builtinmodulemapflag = builtinmodulemapflag or false
end
return builtinmodulemapflag or nil
end
function get_implicitmodulesflag(target)
local implicitmodulesflag = _g.implicitmodulesflag
if implicitmodulesflag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags("-fimplicit-modules", "cxxflags", {flagskey = "clang_implicit_modules"}) then
implicitmodulesflag = "-fimplicit-modules"
end
assert(implicitmodulesflag, "compiler(clang): does not support c++ module!")
_g.implicitmodulesflag = implicitmodulesflag or false
end
return implicitmodulesflag or nil
end
function get_implicitmodulemapsflag(target)
local implicitmodulemapsflag = _g.implicitmodulemapsflag
if implicitmodulemapsflag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags("-fimplicit-module-maps", "cxxflags", {flagskey = "clang_implicit_module_map"}) then
implicitmodulemapsflag = "-fimplicit-module-maps"
end
assert(implicitmodulemapsflag, "compiler(clang): does not support c++ module!")
_g.implicitmodulemapsflag = implicitmodulemapsflag or false
end
return implicitmodulemapsflag or nil
end
function get_noimplicitmodulemapsflag(target)
local noimplicitmodulemapsflag = _g.noimplicitmodulemapsflag
if noimplicitmodulemapsflag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags("-fno-implicit-module-maps", "cxxflags", {flagskey = "clang_no_implicit_module_maps"}) then
noimplicitmodulemapsflag = "-fno-implicit-module-maps"
end
assert(noimplicitmodulemapsflag, "compiler(clang): does not support c++ module!")
_g.noimplicitmodulemapsflag = noimplicitmodulemapsflag or false
end
return noimplicitmodulemapsflag or nil
end
function get_prebuiltmodulepathflag(target)
local prebuiltmodulepathflag = _g.prebuiltmodulepathflag
if prebuiltmodulepathflag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags("-fprebuilt-module-path=" .. os.tmpdir(), "cxxflags", {flagskey = "clang_prebuild_module_path"}) then
prebuiltmodulepathflag = "-fprebuilt-module-path="
end
assert(prebuiltmodulepathflag, "compiler(clang): does not support c++ module!")
_g.prebuiltmodulepathflag = prebuiltmodulepathflag or false
end
return prebuiltmodulepathflag or nil
end
function get_modulecachepathflag(target)
local modulecachepathflag = _g.modulecachepathflag
if modulecachepathflag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags("-fmodules-cache-path=" .. os.tmpdir(), "cxxflags", {flagskey = "clang_modules_cache_path"}) then
modulecachepathflag = "-fmodules-cache-path="
end
assert(modulecachepathflag, "compiler(clang): does not support c++ module!")
_g.modulecachepathflag = modulecachepathflag or false
end
return modulecachepathflag or nil
end
function get_modulefileflag(target)
local modulefileflag = _g.modulefileflag
if modulefileflag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags("-fmodule-file=" .. os.tmpfile() .. get_bmi_extension(), "cxxflags", {flagskey = "clang_module_file"}) then
modulefileflag = "-fmodule-file="
end
assert(modulefileflag, "compiler(clang): does not support c++ module!")
_g.modulefileflag = modulefileflag or false
end
return modulefileflag or nil
end
function get_moduleheaderflag(target)
local moduleheaderflag = _g.moduleheaderflag
if moduleheaderflag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags("-fmodule-header=system", "cxxflags", {flagskey = "clang_module_header"}) then
moduleheaderflag = "-fmodule-header="
end
_g.moduleheaderflag = moduleheaderflag or false
end
return moduleheaderflag or nil
end
function has_clangscandepssupport(target)
local support_clangscandeps = _g.support_clangscandeps
if support_clangscandeps == nil then
local clangscandeps = get_clang_scan_deps(target)
local clang_version = get_clang_version(target)
if clangscandeps and clang_version and semver.compare(clang_version, "16.0") >= 0 then
support_clangscandeps = true
end
_g.support_clangscandeps = support_clangscandeps or false
end
return support_clangscandeps or nil
end
function get_keepsystemincludesflag(target)
local keepsystemincludesflag = _g.keepsystemincludesflag
if keepsystemincludesflag == nil then
local compinst = target:compiler("cxx")
local clang_version = get_clang_version(target)
if compinst:has_flags("-E -fkeep-system-includes", "cxxflags", {flagskey = "clang_keep_system_includes", tryrun = true}) and
semver.compare(clang_version, "18.0") >= 0 then
keepsystemincludesflag = "-fkeep-system-includes"
end
_g.keepsystemincludesflag = keepsystemincludesflag or false
end
return keepsystemincludesflag or nil
end
function get_moduleoutputflag(target)
local moduleoutputflag = _g.moduleoutputflag
if moduleoutputflag == nil then
local compinst = target:compiler("cxx")
local clang_version = get_clang_version(target)
if compinst:has_flags("-fmodule-output=", "cxxflags", {flagskey = "clang_module_output", tryrun = true}) and
semver.compare(clang_version, "16.0") >= 0 then
moduleoutputflag = "-fmodule-output="
end
_g.moduleoutputflag = moduleoutputflag or false
end
return moduleoutputflag or nil
end
function get_print_library_module_manifest_path_flag(target)
local print_library_module_manifest_path_flag = _g.print_library_module_manifest_path_flag
if print_library_module_manifest_path_flag == nil then
local compinst = target:compiler("cxx")
if compinst:has_flags("-print-library-module-manifest-path", "cxxflags", {flagskey = "clang_print_library_module_manifest_path", tryrun = true}) then
print_library_module_manifest_path_flag = "-print-library-module-manifest-path"
end
_g.print_library_module_manifest_path_flag = print_library_module_manifest_path_flag or false
end
return print_library_module_manifest_path_flag or nil
end
|
0 | repos/xmake/xmake/rules/c++ | repos/xmake/xmake/rules/c++/precompiled_header/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
rule("c.build.pcheader")
on_config(function (target, opt)
import("private.action.build.pcheader").config(target, "c", opt)
end)
before_build(function (target, opt)
import("private.action.build.pcheader").build(target, "c", opt)
end)
rule("c++.build.pcheader")
on_config(function (target, opt)
import("private.action.build.pcheader").config(target, "cxx", opt)
end)
before_build(function (target, opt)
import("private.action.build.pcheader").build(target, "cxx", opt)
end)
|
0 | repos/xmake/xmake/rules/c++ | repos/xmake/xmake/rules/c++/unity_build/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
rule("c.unity_build")
on_config(function (target)
import("unity_build")
local sourcebatches = target:sourcebatches()
if sourcebatches then
local sourcebatch = sourcebatches["c.build"]
if sourcebatch then
unity_build(target, sourcebatch)
end
end
end)
before_build(function (target, opt)
import("unity_build")
local sourcebatches = target:sourcebatches()
if sourcebatches then
local sourcebatch = sourcebatches["c.build"]
if sourcebatch then
unity_build.generate_unityfiles(target, sourcebatch, opt)
end
end
end)
rule("c++.unity_build")
on_config(function (target)
import("unity_build")
local sourcebatches = target:sourcebatches()
if sourcebatches then
local sourcebatch = sourcebatches["c++.build"]
if sourcebatch then
unity_build(target, sourcebatch)
end
end
end)
before_build(function (target, opt)
import("unity_build")
local sourcebatches = target:sourcebatches()
if sourcebatches then
local sourcebatch = sourcebatches["c++.build"]
if sourcebatch then
unity_build.generate_unityfiles(target, sourcebatch, opt)
end
end
end)
|
0 | repos/xmake/xmake/rules/c++ | repos/xmake/xmake/rules/c++/unity_build/unity_build.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file unity_build.lua
--
-- imports
import("core.project.depend")
function _merge_unityfile(target, sourcefile_unity, sourcefiles, opt)
local dependfile = target:dependfile(sourcefile_unity)
depend.on_changed(function ()
-- trace
vprint("generating.unityfile %s", sourcefile_unity)
-- do merge
local uniqueid = target:data("unity_build.uniqueid")
local unityfile = io.open(sourcefile_unity, "w")
for _, sourcefile in ipairs(sourcefiles) do
sourcefile = path.absolute(sourcefile)
sourcefile_unity = path.absolute(sourcefile_unity)
sourcefile = path.relative(sourcefile, path.directory(sourcefile_unity))
if uniqueid then
unityfile:print("#define %s %s", uniqueid, "unity_" .. hash.uuid():split("-", {plain = true})[1])
end
unityfile:print("#include \"%s\"", sourcefile)
if uniqueid then
unityfile:print("#undef %s", uniqueid)
end
end
unityfile:close()
end, {dependfile = dependfile, files = sourcefiles, changed = target:is_rebuilt()})
end
function generate_unityfiles(target, sourcebatch, opt)
local unity_batch = target:data("unity_build.unity_batch." .. sourcebatch.rulename)
if unity_batch then
for _, sourcefile_unity in ipairs(sourcebatch.sourcefiles) do
local sourceinfo = unity_batch[sourcefile_unity]
if sourceinfo then
local sourcefiles = sourceinfo.sourcefiles
if sourcefiles then
_merge_unityfile(target, sourcefile_unity, sourcefiles, opt)
end
end
end
end
end
-- use unity build
--
-- e.g.
-- add_rules("c++.unity_build", {batchsize = 2})
-- add_files("src/*.c", "src/*.cpp", {unity_ignored = true})
-- add_files("src/foo/*.c", {unity_group = "foo"})
-- add_files("src/bar/*.c", {unity_group = "bar"})
--
function main(target, sourcebatch)
-- we cannot generate unity build files in project generator
if os.getenv("XMAKE_IN_PROJECT_GENERATOR") then
return
end
-- get unit batch sources
local extraconf = target:extraconf("rules", sourcebatch.sourcekind == "cxx" and "c++.unity_build" or "c.unity_build")
local batchsize = extraconf and extraconf.batchsize
local uniqueid = extraconf and extraconf.uniqueid
local id = 1
local count = 0
local group_id = {}
local group_count = {}
local unity_batch = {}
local sourcefiles = {}
local objectfiles = {}
local dependfiles = {}
local sourcedir = path.join(target:autogendir({root = true}), target:plat(), "unity_build")
for idx, sourcefile in pairs(sourcebatch.sourcefiles) do
local sourcefile_unity
local objectfile = sourcebatch.objectfiles[idx]
local dependfile = sourcebatch.dependfiles[idx]
local fileconfig = target:fileconfig(sourcefile)
if fileconfig and fileconfig.unity_group then
if fileconfig.batchsize then
local curr_group_id = group_id[fileconfig.unity_group] or 1
local curr_group_count = group_count[fileconfig.unity_group] or 0
if curr_group_count >= fileconfig.batchsize then
curr_group_id = curr_group_id + 1
curr_group_count = 0
group_id[fileconfig.unity_group] = curr_group_id
group_count[fileconfig.unity_group] = curr_group_count
end
sourcefile_unity = path.join(sourcedir, "unity_group_" .. fileconfig.unity_group .. "_" .. tostring(curr_group_id) .. path.extension(sourcefile))
group_count[fileconfig.unity_group] = curr_group_count + 1
else
sourcefile_unity = path.join(sourcedir, "unity_group_" .. fileconfig.unity_group .. path.extension(sourcefile))
end
elseif (fileconfig and fileconfig.unity_ignored) or (batchsize and batchsize <= 1) then
-- we do not add these files to unity file
table.insert(sourcefiles, sourcefile)
table.insert(objectfiles, objectfile)
table.insert(dependfiles, dependfile)
else
if batchsize and count >= batchsize then
id = id + 1
count = 0
end
sourcefile_unity = path.join(sourcedir, "unity_" .. tostring(id) .. path.extension(sourcefile))
count = count + 1
end
if sourcefile_unity then
local sourceinfo = unity_batch[sourcefile_unity]
if not sourceinfo then
sourceinfo = {}
sourceinfo.objectfile = target:objectfile(sourcefile_unity)
sourceinfo.dependfile = target:dependfile(sourceinfo.objectfile)
sourceinfo.sourcefile1 = sourcefile
sourceinfo.objectfile1 = objectfile
sourceinfo.dependfile1 = dependfile
unity_batch[sourcefile_unity] = sourceinfo
end
sourceinfo.sourcefiles = sourceinfo.sourcefiles or {}
table.insert(sourceinfo.sourcefiles, sourcefile)
end
end
-- use unit batch
for _, sourcefile_unity in ipairs(table.orderkeys(unity_batch)) do
local sourceinfo = unity_batch[sourcefile_unity]
if #sourceinfo.sourcefiles > 1 then
table.insert(sourcefiles, sourcefile_unity)
table.insert(objectfiles, sourceinfo.objectfile)
table.insert(dependfiles, sourceinfo.dependfile)
else
table.insert(sourcefiles, sourceinfo.sourcefile1)
table.insert(objectfiles, sourceinfo.objectfile1)
table.insert(dependfiles, sourceinfo.dependfile1)
end
end
sourcebatch.sourcefiles = sourcefiles
sourcebatch.objectfiles = objectfiles
sourcebatch.dependfiles = dependfiles
-- save unit batch
target:data_set("unity_build.uniqueid", uniqueid)
target:data_set("unity_build.unity_batch." .. sourcebatch.rulename, unity_batch)
end
|
0 | repos/xmake/xmake/rules/c++ | repos/xmake/xmake/rules/c++/build_sanitizer/config.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file config.lua
--
-- imports
import("core.tool.compiler")
import("core.project.project")
import("lib.detect.find_tool")
import("core.base.semver")
-- add build sanitizer
function _add_build_sanitizer(target, sourcekind, checkmode)
-- add cflags
local _, cc = target:tool(sourcekind)
local flagnames = {
cc = "cflags",
cxx = "cxxflags",
mm = "mflags",
mxx = "mxflags"
}
local flagname = flagnames[sourcekind]
if flagname and target:has_tool(sourcekind, "cl", "clang", "clangxx", "gcc", "gxx") then
target:add(flagname, "-fsanitize=" .. checkmode)
end
-- add ldflags and shflags
if target:has_tool("ld", "link", "clang", "clangxx", "gcc", "gxx") then
target:add("ldflags", "-fsanitize=" .. checkmode)
target:add("shflags", "-fsanitize=" .. checkmode)
end
end
function main(target, sourcekind)
local sanitizer = false
for _, checkmode in ipairs({"address", "thread", "memory", "leak", "undefined"}) do
local enabled = target:policy("build.sanitizer." .. checkmode)
if enabled == nil then
enabled = project.policy("build.sanitizer." .. checkmode)
end
if enabled then
_add_build_sanitizer(target, sourcekind, checkmode)
sanitizer = true
end
end
if sanitizer then
-- enable the debug symbols for sanitizer
if not target:get("symbols") then
target:set("symbols", "debug")
end
-- we need to load runenvs for msvc
-- @see https://github.com/xmake-io/xmake/issues/4176
if target:is_plat("windows") and target:is_binary() then
local msvc = target:toolchain("msvc")
if msvc then
local envs = msvc:runenvs()
local vscmd_ver = envs and envs.VSCMD_VER
if vscmd_ver and semver.match(vscmd_ver):ge("17.7") then
local cl = assert(find_tool("cl", {envs = envs}), "cl not found!")
target:add("runenvs", "PATH", path.directory(cl.program))
end
end
end
end
end
|
0 | repos/xmake/xmake/rules/c++ | repos/xmake/xmake/rules/c++/build_sanitizer/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: c.build.sanitizer
rule("c.build.sanitizer")
on_config(function (target)
import("config")(target, "cc")
end)
-- define rule: c++.build.sanitizer
rule("c++.build.sanitizer")
on_config(function (target)
import("config")(target, "cxx")
end)
-- define rule: objc.build.sanitizer
rule("objc.build.sanitizer")
on_config(function (target)
import("config")(target, "mm")
end)
-- define rule: objc++.build.sanitizer
rule("objc++.build.sanitizer")
on_config(function (target)
import("config")(target, "mxx")
end)
|
0 | repos/xmake/xmake/rules/c++ | repos/xmake/xmake/rules/c++/openmp/load.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file load.lua
--
-- main entry
function main(target, sourcekind)
wprint("we no longer need add_rules(\"%s.openmp\") now, you just need to add add_packages(\"openmp\").", sourcekind == "cxx" and "c++" or "c")
local _, compiler_name = target:tool(sourcekind)
local flag_name = sourcekind == "cxx" and "cxxflags" or "cflags"
if compiler_name == "cl" then
target:add(flag_name, "/openmp")
elseif compiler_name == "clang" or compiler_name == "clangxx" then
if target:is_plat("macosx") then
target:add(flag_name, "-Xpreprocessor -fopenmp")
else
target:add(flag_name, "-fopenmp")
end
elseif compiler_name == "gcc" or compiler_name == "gxx" then
target:add(flag_name, "-fopenmp")
elseif compiler_name == "icc" or compiler_name == "icpc" then
target:add(flag_name, "-qopenmp")
elseif compiler_name == "icl" then
target:add(flag_name, "-Qopenmp")
end
end
|
0 | repos/xmake/xmake/rules/c++ | repos/xmake/xmake/rules/c++/openmp/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: c.openmp
rule("c.openmp")
on_config(function (target)
import("load")(target, "cc")
end)
-- define rule: c++.openmp
rule("c++.openmp")
on_config(function (target)
import("load")(target, "cxx")
end)
|
0 | repos/xmake/xmake/rules/c++ | repos/xmake/xmake/rules/c++/build_optimization/config.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file config.lua
--
-- imports
import("core.tool.compiler")
import("core.project.project")
-- add lto optimization
function _add_lto_optimization(target, sourcekind)
-- add cflags
local _, cc = target:tool(sourcekind)
local cflag = sourcekind == "cxx" and "cxxflags" or "cflags"
if cc == "cl" then
target:add(cflag, "-GL")
elseif cc == "clang" or cc == "clangxx" then
target:add(cflag, "-flto=thin")
elseif cc == "gcc" or cc == "gxx" then
target:add(cflag, "-flto")
end
-- add ldflags and shflags
local program, ld = target:tool("ld")
if ld == "link" then
target:add("ldflags", "-LTCG")
target:add("shflags", "-LTCG")
elseif ld == "clang" or ld == "clangxx" then
target:add("ldflags", "-flto=thin")
target:add("shflags", "-flto=thin")
elseif ld == "gcc" or ld == "gxx" then
target:add("ldflags", "-flto")
target:add("shflags", "-flto")
-- to use the link-time optimizer, -flto and optimization options should be specified at compile time and during the final link.
-- @see https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
local optimize = target:get("optimize")
if optimize then
local optimize_flags = compiler.map_flags(sourcekind == "cc" and "c" or "cxx", "optimize", optimize)
target:add("ldflags", optimize_flags)
target:add("shflags", optimize_flags)
end
end
end
function main(target, sourcekind)
if target:policy("build.optimization.lto") or
project.policy("build.optimization.lto") then
_add_lto_optimization(target, sourcekind)
end
end
|
0 | repos/xmake/xmake/rules/c++ | repos/xmake/xmake/rules/c++/build_optimization/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: c.build.optimization
rule("c.build.optimization")
on_config(function (target)
import("config")(target, "cc")
end)
-- define rule: c++.build.optimization
rule("c++.build.optimization")
on_config(function (target)
import("config")(target, "cxx")
end)
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/objc++/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: objc.build
rule("objc.build")
set_sourcekinds("mm")
add_deps("objc.build.pcheader", "c.build.optimization", "objc.build.sanitizer")
after_load(function (target)
-- deprecated, we only need to use `add_mflags("-fno-objc-arc")` to override it
if target:values("objc.build.arc") == false then
target:add("mflags", "-fno-objc-arc")
end
if target:is_plat("macosx", "iphoneos", "watchos") then
target:add("frameworks", "Foundation", "CoreFoundation")
end
end)
on_build_files("private.action.build.object", {batch = true, distcc = true})
-- define rule: objc++.build
rule("objc++.build")
set_sourcekinds("mxx")
add_deps("objc++.build.pcheader", "c++.build.optimization", "objc++.build.sanitizer")
after_load(function (target)
-- deprecated, we only need to use `add_mxxflags("-fno-objc-arc")` to override it
if target:values("objc++.build.arc") == false then
target:add("mxxflags", "-fno-objc-arc")
end
if target:is_plat("macosx", "iphoneos", "watchos") then
target:add("frameworks", "Foundation", "CoreFoundation")
end
end)
on_build_files("private.action.build.object", {batch = true, distcc = true})
-- define rule: objc
rule("objc++")
-- add build rules
add_deps("objc++.build", "objc.build")
-- inherit links and linkdirs of all dependent targets by default
add_deps("utils.inherit.links")
-- support `add_files("src/*.o")` and `add_files("src/*.a")` to merge object and archive files to target
add_deps("utils.merge.object", "utils.merge.archive")
-- we attempt to extract symbols to the independent file and
-- strip self-target binary if `set_symbols("debug")` and `set_strip("all")` are enabled
add_deps("utils.symbols.extract")
|
0 | repos/xmake/xmake/rules/objc++ | repos/xmake/xmake/rules/objc++/precompiled_header/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
rule("objc.build.pcheader")
on_config(function (target, opt)
import("private.action.build.pcheader").config(target, "m", opt)
end)
before_build(function (target, opt)
import("private.action.build.pcheader").build(target, "m", opt)
end)
rule("objc++.build.pcheader")
on_config(function (target, opt)
import("private.action.build.pcheader").config(target, "mxx", opt)
end)
before_build(function (target, opt)
import("private.action.build.pcheader").build(target, "mxx", opt)
end)
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/zig/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: zig.build
rule("zig.build")
set_sourcekinds("zc")
on_load(function (target)
local cachedir = target:values("zig.cachedir") or path.join(target:objectdir(), "zig-cache")
os.mkdir(cachedir)
target:add("zcflags", "--cache-dir " .. cachedir)
end)
on_build_files("private.action.build.object", {batch = true})
-- define rule: zig
rule("zig")
-- add build rules
add_deps("zig.build")
-- inherit links and linkdirs of all dependent targets by default
add_deps("utils.inherit.links")
-- support `add_files("src/*.o")` and `add_files("src/*.a")` to merge object and archive files to target
add_deps("utils.merge.object", "utils.merge.archive")
-- we attempt to extract symbols to the independent file and
-- strip self-target binary if `set_symbols("debug")` and `set_strip("all")` are enabled
add_deps("utils.symbols.extract")
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/vala/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
rule("vala.build")
set_extensions(".vala")
-- Since vala can directly compile with C files
-- we can add C sourcekinds
-- And in the end we're going to be compiling C code
set_sourcekinds("cc")
on_load(function (target)
-- we disable to build across targets in parallel, because the source files may depend on other target modules
target:set("policy", "build.across_targets_in_parallel", false)
-- get vapi file
local vapifile = target:data("vala.vapifile")
if not vapifile then
local vapiname = target:values("vala.vapi")
if vapiname then
vapifile = path.absolute(path.join(target:targetdir(), vapiname))
else
vapifile = path.absolute(path.join(target:targetdir(), target:name() .. ".vapi"))
end
target:data_set("vala.vapifile", vapifile)
end
-- get header file
local headerfile = target:data("vala.headerfile")
if not headerfile then
local headername = target:values("vala.header")
if headername then
headerfile = path.absolute(path.join(target:targetdir(), headername))
else
headerfile = path.absolute(path.join(target:targetdir(), target:name() .. ".h"))
end
target:data_set("vala.headerfile", headerfile)
end
if headerfile then
target:add("headerfiles", headerfile)
target:add("sysincludedirs", path.directory(headerfile), {public = true})
end
end)
before_buildcmd_files(function (target, batchcmds, sourcebatch, opt)
-- Here we compile vala files into C code
-- We have to compile entire project each time
-- because otherwise valac can't resolve symbols
-- from other files, however, c files can be
-- incrementally built
-- get valac
import("lib.detect.find_tool")
local valac = assert(find_tool("valac"), "valac not found!")
local argv = {"-C", "-d", target:autogendir()}
-- add commands
local packages = target:values("vala.packages")
if packages then
for _, package in ipairs(packages) do
table.insert(argv, "--pkg")
table.insert(argv, path(package))
end
end
if target:is_binary() then
for _, dep in ipairs(target:orderdeps()) do
if dep:is_shared() or dep:is_static() then
local vapifile = dep:data("vala.vapifile")
if vapifile then
table.join2(argv, path(vapifile))
end
end
end
else
local vapifile = target:data("vala.vapifile")
if vapifile then
table.insert(argv, path(vapifile, function (p) return "--vapi=" .. p end))
end
local headerfile = target:data("vala.headerfile")
if headerfile then
table.insert(argv, "-H")
table.insert(argv, path(headerfile))
end
end
local vapidir = target:values("vala.vapidir")
if vapidir then
table.insert(argv, path(vapidir, function (p) return "--vapidir=" .. p end))
end
local valaflags = target:values("vala.flags")
if valaflags then
table.join2(argv, valaflags)
end
-- iterating through source files,
-- otherwise valac would fail when compiling multiple files
local lastmtime = 0
local sourcefiles = {}
for _, sourcefile in ipairs(sourcebatch.sourcefiles) do
-- if it's only a vala file
if path.extension(sourcefile) == ".vala" then
local sourcefile_c = target:autogenfile((sourcefile:gsub(".vala$", ".c")))
batchcmds:show_progress(opt.progress, "${color.build.object}compiling.vala %s", sourcefile)
table.insert(argv, path(sourcefile))
table.insert(sourcefiles, sourcefile)
local sourcefile_c_mtime = os.mtime(sourcefile_c)
if sourcefile_c_mtime > lastmtime then
lastmtime = sourcefile_c_mtime
end
end
end
if #sourcefiles > 0 then
batchcmds:vrunv(valac.program, argv)
batchcmds:add_depfiles(sourcefiles)
batchcmds:set_depmtime(lastmtime)
end
end)
on_buildcmd_file(function (target, batchcmds, sourcefile, opt)
-- Again, only vala files need special treatment
if path.extension(sourcefile) == ".vala" then
local sourcefile_c = target:autogenfile((sourcefile:gsub(".vala$", ".c")))
local basedir = path.directory(sourcefile_c)
batchcmds:mkdir(basedir)
local objectfile = target:objectfile(sourcefile_c)
table.insert(target:objectfiles(), objectfile)
batchcmds:show_progress(opt.progress, "${color.build.object}compiling.c %s", sourcefile_c)
batchcmds:compile(sourcefile_c, objectfile, { configs = { force = { cflags = "-w" } } })
batchcmds:add_depfiles(sourcefile)
batchcmds:set_depmtime(os.mtime(objectfile))
batchcmds:set_depcache(target:dependfile(objectfile))
end
end)
after_install(function (target)
if target:is_shared() or target:is_static() then
local vapifile = target:data("vala.vapifile")
if vapifile then
local installdir = target:installdir()
if installdir then
local sharedir = path.join(installdir, "share")
os.mkdir(sharedir)
os.vcp(vapifile, sharedir)
end
end
end
end)
after_uninstall(function (target)
if target:is_shared() or target:is_static() then
local vapifile = target:data("vala.vapifile")
if vapifile then
local installdir = target:installdir()
if installdir then
os.rm(path.join(installdir, "share", path.filename(vapifile)))
end
end
end
end)
rule("vala")
-- add build rules
add_deps("vala.build")
-- set compiler runtime, e.g. vs runtime
add_deps("utils.compiler.runtime")
-- inherit links and linkdirs of all dependent targets by default
add_deps("utils.inherit.links")
-- support `add_files("src/*.o")` and `add_files("src/*.a")` to merge object and archive files to target
add_deps("utils.merge.object", "utils.merge.archive")
-- we attempt to extract symbols to the independent file and
-- strip self-target binary if `set_symbols("debug")` and `set_strip("all")` are enabled
add_deps("utils.symbols.extract")
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/iverilog/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- @see https://github.com/xmake-io/xmake/issues/3257
rule("iverilog.binary")
set_extensions(".v", ".vhd")
on_load(function (target)
target:set("kind", "binary")
if not target:get("extension") then
target:set("extension", ".vvp")
end
end)
on_buildcmd_files(function(target, batchcmds, sourcebatch, opt)
end)
on_linkcmd(function (target, batchcmds, opt)
local toolchain = assert(target:toolchain("iverilog"), 'we need set_toolchains("iverilog") in target("%s")', target:name())
local iverilog = assert(toolchain:config("iverilog"), "iverilog not found!")
local targetfile = target:targetfile()
local targetdir = path.directory(targetfile)
local argv = {"-o", targetfile}
local sourcebatch = target:sourcebatches()["iverilog.binary"]
local sourcefiles = table.wrap(sourcebatch.sourcefiles)
assert(#sourcefiles > 0, "no source files!")
-- get languages
--
-- Select the Verilog language generation to support in the compiler.
-- This selects between v1364-1995, v1364-2001, v1364-2005, v1800-2005, v1800-2009, v1800-2012.
--
local language_v
local languages = target:get("languages")
if languages then
for _, language in ipairs(languages) do
if language:startswith("v") then
language_v = language
break
end
end
end
if language_v then
local maps = {
["v1364-1995"] = "-g1995",
["v1364-2001"] = "-g2001",
["v1364-2005"] = "-g2005",
["v1800-2005"] = "-g2005-sv",
["v1800-2009"] = "-g2009",
["v1800-2012"] = "-g2012",
}
local flag = maps[language_v]
if flag then
table.insert(argv, flag)
else
assert("unknown language(%s) for iverilog!", language_v)
end
else
local extension = path.extension(sourcefiles[1])
if extension == ".vhd" then
table.insert(argv, "-g2012")
end
end
-- get defines
local defines = target:get("defines")
if defines then
for _, define in ipairs(defines) do
table.insert(argv, "-D" .. define)
end
end
-- get includedirs
local includedirs = target:get("includedirs")
if includedirs then
for _, includedir in ipairs(includedirs) do
table.insert(argv, path(includedir, function (v) return "-I" .. v end))
end
end
-- get flags
local flags = target:values("iverilog.flags")
if flags then
table.join2(argv, flags)
end
-- do build
table.join2(argv, sourcefiles)
batchcmds:show_progress(opt.progress, "${color.build.target}linking.iverilog %s", path.filename(targetfile))
batchcmds:mkdir(targetdir)
batchcmds:vrunv(iverilog, argv)
batchcmds:add_depfiles(sourcefiles)
batchcmds:set_depmtime(os.mtime(targetfile))
batchcmds:set_depcache(target:dependfile(targetfile))
end)
on_run(function (target)
local toolchain = assert(target:toolchain("iverilog"), 'we need set_toolchains("iverilog") in target("%s")', target:name())
local vvp = assert(toolchain:config("vvp"), "vvp not found!")
os.execv(vvp, {"-n", target:targetfile(), "-lxt2"})
end)
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/protobuf/proto.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file proto.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_tool")
import("core.project.depend")
import("private.action.build.object", {alias = "build_objectfiles"})
import("utils.progress")
import("private.utils.batchcmds")
import("private.async.buildjobs")
-- get protoc
function _get_protoc(target, sourcekind)
-- find protoc
-- @see https://github.com/xmake-io/xmake/issues/4659
local envs = os.joinenvs(target:pkgenvs(), os.getenvs())
local protoc = target:data("protobuf.protoc")
if not protoc and sourcekind == "cxx" then
protoc = find_tool("protoc", {envs = envs})
if protoc and protoc.program then
target:data_set("protobuf.protoc", protoc.program)
end
end
-- find protoc-c
local protoc_c = target:data("protobuf.protoc-c")
if not protoc_c and sourcekind == "cc" then
protoc_c = find_tool("protoc-c", {envs = envs}) or protoc
if protoc_c and protoc_c.program then
target:data_set("protobuf.protoc-c", protoc_c.program)
end
end
-- get protoc
return assert(target:data(sourcekind == "cxx" and "protobuf.protoc" or "protobuf.protoc-c"), "protoc not found!")
end
-- get grpc_cpp_plugin
function _get_grpc_cpp_plugin(target, sourcekind)
local envs = os.joinenvs(target:pkgenvs(), os.getenvs())
assert(sourcekind == "cxx", "grpc_cpp_plugin only support c++")
local grpc_cpp_plugin = find_tool("grpc_cpp_plugin", {norun = true, force = true, envs = envs})
return assert(grpc_cpp_plugin and grpc_cpp_plugin.program, "grpc_cpp_plugin not found!")
end
-- we need to add some configs to export includedirs to other targets in on_load
-- @see https://github.com/xmake-io/xmake/issues/2256
function load(target, sourcekind)
-- get the first sourcefile
local sourcefile_proto
local sourcebatch = target:sourcebatches()[sourcekind == "cxx" and "protobuf.cpp" or "protobuf.c"]
if sourcebatch then
sourcefile_proto = sourcebatch.sourcefiles[1]
end
if not sourcefile_proto then
return
end
-- get c/c++ source file for protobuf
local prefixdir
local autogendir
local public
local grpc_cpp_plugin
local fileconfig = target:fileconfig(sourcefile_proto)
if fileconfig then
public = fileconfig.proto_public
prefixdir = fileconfig.proto_rootdir
autogendir = fileconfig.proto_autogendir
grpc_cpp_plugin = fileconfig.proto_grpc_cpp_plugin
end
local rootdir = autogendir and autogendir or path.join(target:autogendir(), "rules", "protobuf")
local filename = path.basename(sourcefile_proto) .. ".pb" .. (sourcekind == "cxx" and ".cc" or "-c.c")
local sourcefile_cx = target:autogenfile(sourcefile_proto, {rootdir = rootdir, filename = filename})
local sourcefile_dir = prefixdir and path.join(rootdir, prefixdir) or path.directory(sourcefile_cx)
-- add includedirs
target:add("includedirs", sourcefile_dir, {public = public})
-- add objectfile, @see https://github.com/xmake-io/xmake/issues/5426
local objectfile_grpc
local objectfile = target:objectfile(sourcefile_cx)
table.insert(target:objectfiles(), objectfile)
if grpc_cpp_plugin then
local filename_grpc = path.basename(sourcefile_proto) .. ".grpc.pb.cc"
local sourcefile_cx_grpc = target:autogenfile(sourcefile_proto, {rootdir = rootdir, filename = filename_grpc})
objectfile_grpc = target:objectfile(sourcefile_cx_grpc)
table.insert(target:objectfiles(), objectfile_grpc)
end
end
function buildcmd_pfiles(target, batchcmds, sourcefile_proto, opt, sourcekind)
-- get protoc
local protoc = _get_protoc(target, sourcekind)
-- get c/c++ source file for protobuf
local prefixdir
local autogendir
local public
local grpc_cpp_plugin
local fileconfig = target:fileconfig(sourcefile_proto)
if fileconfig then
public = fileconfig.proto_public
prefixdir = fileconfig.proto_rootdir
-- custom autogen directory to access the generated header files
-- @see https://github.com/xmake-io/xmake/issues/3678
autogendir = fileconfig.proto_autogendir
grpc_cpp_plugin = fileconfig.proto_grpc_cpp_plugin
end
local rootdir = autogendir and autogendir or path.join(target:autogendir(), "rules", "protobuf")
local filename = path.basename(sourcefile_proto) .. ".pb" .. (sourcekind == "cxx" and ".cc" or "-c.c")
local sourcefile_cx = target:autogenfile(sourcefile_proto, {rootdir = rootdir, filename = filename})
local sourcefile_dir = prefixdir and path.join(rootdir, prefixdir) or path.directory(sourcefile_cx)
local grpc_cpp_plugin_bin
local filename_grpc
local sourcefile_cx_grpc
if grpc_cpp_plugin then
grpc_cpp_plugin_bin = _get_grpc_cpp_plugin(target, sourcekind)
filename_grpc = path.basename(sourcefile_proto) .. ".grpc.pb.cc"
sourcefile_cx_grpc = target:autogenfile(sourcefile_proto, {rootdir = rootdir, filename = filename_grpc})
end
local protoc_args = {
path(sourcefile_proto),
path(prefixdir and prefixdir or path.directory(sourcefile_proto), function (p) return "-I" .. p end),
path(sourcefile_dir, function (p) return (sourcekind == "cxx" and "--cpp_out=" or "--c_out=") .. p end)
}
if grpc_cpp_plugin then
local extension = target:is_plat("windows") and ".exe" or ""
table.insert(protoc_args, "--plugin=protoc-gen-grpc=" .. grpc_cpp_plugin_bin .. extension)
table.insert(protoc_args, path(sourcefile_dir, function (p) return ("--grpc_out=") .. p end))
end
-- add commands
batchcmds:mkdir(sourcefile_dir)
batchcmds:show_progress(
opt.progress,
"${color.build.object}compiling.proto.%s %s",
(sourcekind == "cxx" and "c++" or "c"),
sourcefile_proto
)
batchcmds:vrunv(protoc, protoc_args)
-- add deps
local depmtime = os.mtime(sourcefile_cx)
batchcmds:add_depfiles(sourcefile_proto)
batchcmds:set_depcache(target:dependfile(sourcefile_cx))
if grpc_cpp_plugin then
batchcmds:set_depmtime(math.max(os.mtime(sourcefile_cx_grpc), depmtime))
else
batchcmds:set_depmtime(depmtime)
end
end
function buildcmd_cxfiles(target, batchcmds, sourcefile_proto, opt, sourcekind)
-- get protoc
local protoc = _get_protoc(target, sourcekind)
-- get c/c++ source file for protobuf
local prefixdir
local autogendir
local public
local grpc_cpp_plugin
local fileconfig = target:fileconfig(sourcefile_proto)
if fileconfig then
public = fileconfig.proto_public
prefixdir = fileconfig.proto_rootdir
-- custom autogen directory to access the generated header files
-- @see https://github.com/xmake-io/xmake/issues/3678
autogendir = fileconfig.proto_autogendir
grpc_cpp_plugin = fileconfig.proto_grpc_cpp_plugin
end
local rootdir = autogendir and autogendir or path.join(target:autogendir(), "rules", "protobuf")
local filename = path.basename(sourcefile_proto) .. ".pb" .. (sourcekind == "cxx" and ".cc" or "-c.c")
local sourcefile_cx = target:autogenfile(sourcefile_proto, {rootdir = rootdir, filename = filename})
local sourcefile_dir = prefixdir and path.join(rootdir, prefixdir) or path.directory(sourcefile_cx)
local grpc_cpp_plugin_bin
local filename_grpc
local sourcefile_cx_grpc
if grpc_cpp_plugin then
grpc_cpp_plugin_bin = _get_grpc_cpp_plugin(target, sourcekind)
filename_grpc = path.basename(sourcefile_proto) .. ".grpc.pb.cc"
sourcefile_cx_grpc = target:autogenfile(sourcefile_proto, {rootdir = rootdir, filename = filename_grpc})
end
-- get objectfile
local objectfile = target:objectfile(sourcefile_cx)
local objectfile_grpc
if grpc_cpp_plugin then
objectfile_grpc = target:objectfile(sourcefile_cx_grpc)
end
batchcmds:show_progress(opt.progress, "${color.build.object}compiling.proto.$(mode) %s", sourcefile_cx)
batchcmds:compile(sourcefile_cx, objectfile, {configs = {includedirs = sourcefile_dir}})
if grpc_cpp_plugin then
batchcmds:compile(sourcefile_cx_grpc, objectfile_grpc, {configs = {includedirs = sourcefile_dir}})
end
-- add deps
local depmtime = os.mtime(objectfile)
batchcmds:add_depfiles(sourcefile_proto)
batchcmds:set_depcache(target:dependfile(objectfile))
if grpc_cpp_plugin then
batchcmds:set_depmtime(math.max(os.mtime(objectfile_grpc), depmtime))
else
batchcmds:set_depmtime(depmtime)
end
end
function build_cxfile_objects(target, batchjobs, opt, sourcekind)
local sourcebatch_cx = {
rulename = (sourcekind == "cxx" and "c++" or "c").. ".build",
sourcekind = sourcekind,
sourcefiles = {},
objectfiles = {},
dependfiles = {}
}
for _, sourcefile_proto in ipairs(sourcefiles) do
-- get c/c++ source file for protobuf
local prefixdir
local autogendir
local public
local grpc_cpp_plugin
local fileconfig = target:fileconfig(sourcefile_proto)
if fileconfig then
public = fileconfig.proto_public
prefixdir = fileconfig.proto_rootdir
-- custom autogen directory to access the generated header files
-- @see https://github.com/xmake-io/xmake/issues/3678
autogendir = fileconfig.proto_autogendir
grpc_cpp_plugin = fileconfig.proto_grpc_cpp_plugin
end
local rootdir = autogendir and autogendir or path.join(target:autogendir(), "rules", "protobuf")
local filename = path.basename(sourcefile_proto) .. ".pb" .. (sourcekind == "cxx" and ".cc" or "-c.c")
local sourcefile_cx = target:autogenfile(sourcefile_proto, {rootdir = rootdir, filename = filename})
local sourcefile_dir = prefixdir and path.join(rootdir, prefixdir) or path.directory(sourcefile_cx)
local grpc_cpp_plugin_bin
local filename_grpc
local sourcefile_cx_grpc
if grpc_cpp_plugin then
grpc_cpp_plugin_bin = _get_grpc_cpp_plugin(target, sourcekind)
filename_grpc = path.basename(sourcefile_proto) .. ".grpc.pb.cc"
sourcefile_cx_grpc = target:autogenfile(sourcefile_proto, {rootdir = rootdir, filename = filename_grpc})
end
-- add includedirs
target:add("includedirs", sourcefile_dir, {public = public})
-- add objectfile
local objectfile = target:objectfile(sourcefile_cx)
local dependfile = target:dependfile(sourcefile_proto)
table.insert(sourcebatch_cx.sourcefiles, sourcefile_cx)
table.insert(sourcebatch_cx.objectfiles, objectfile)
table.insert(sourcebatch_cx.dependfiles, dependfile)
local objectfile_grpc
if grpc_cpp_plugin then
objectfile_grpc = target:objectfile(sourcefile_cx_grpc)
table.insert(sourcebatch_cx.sourcefiles, sourcefile_cx_grpc)
table.insert(sourcebatch_cx.objectfiles, objectfile_grpc)
table.insert(sourcebatch_cx.dependfiles, dependfile)
end
end
build_objectfiles(target, batchjobs, sourcebatch_cx, opt)
end
-- build batch jobs
function build_cxfiles(target, batchjobs, sourcebatch, opt, sourcekind)
opt = opt or {}
local nodes = {}
local nodenames = {}
local node_rulename = "rules/" .. sourcebatch.rulename .. "/node"
local sourcefiles = sourcebatch.sourcefiles
for _, sourcefile_proto in ipairs(sourcefiles) do
local nodename = node_rulename .. "/" .. sourcefile_proto
nodes[nodename] = {
name = nodename,
job = batchjobs:addjob(nodename, function(index, total, jobopt)
local batchcmds_ = batchcmds.new({target = target})
buildcmd_pfiles(target, batchcmds_, sourcefile_proto, {progress = jobopt.progress}, sourcekind)
batchcmds_:runcmds({changed = target:is_rebuilt(), dryrun = option.get("dry-run")})
end)
}
table.insert(nodenames, nodename)
end
local rootname = "rules/" .. sourcebatch.rulename .. "/root"
nodes[rootname] = {
name = rootname,
deps = nodenames,
job = batchjobs:addjob(rootname, function(_index, _total)
build_cxfile_objects(target, batchjobs, opt, sourcekind)
end)
}
buildjobs(nodes, batchjobs, opt.rootjob)
end
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/protobuf/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: protobuf.cpp
rule("protobuf.cpp")
add_deps("c++")
set_extensions(".proto")
after_load(function(target)
import("proto").load(target, "cxx")
end)
-- generate build commands
before_buildcmd_file(function(target, batchcmds, sourcefile_proto, opt)
import("proto").buildcmd_pfiles(target, batchcmds, sourcefile_proto, opt, "cxx")
end)
on_buildcmd_file(function(target, batchcmds, sourcefile_proto, opt)
import("proto").buildcmd_cxfiles(target, batchcmds, sourcefile_proto, opt, "cxx")
end)
before_build_files(function (target, batchjobs, sourcebatch, opt)
import("proto").build_cxfiles(target, batchjobs, sourcebatch, opt, "cxx")
end, {batch = true})
-- define rule: protobuf.c
rule("protobuf.c")
add_deps("c++")
set_extensions(".proto")
after_load(function(target)
import("proto").load(target, "cc")
end)
before_buildcmd_file(function(target, batchcmds, sourcefile_proto, opt)
import("proto").buildcmd_pfiles(target, batchcmds, sourcefile_proto, opt, "cc")
end)
on_buildcmd_file(function(target, batchcmds, sourcefile_proto, opt)
import("proto").buildcmd_cxfiles(target, batchcmds, sourcefile_proto, opt, "cc")
end)
before_build_files(function (target, batchjobs, sourcebatch, opt)
import("proto").build_cxfiles(target, batchjobs, sourcebatch, opt, "cc")
end, {batch = true})
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/rust/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- generate bridge.rs.cc/h to call rust library in c++ code
-- @see https://cxx.rs/build/other.html
rule("rust.cxxbridge")
set_extensions(".rsx")
on_load(function (target)
if not target:get("languages") then
target:set("languages", "c++11")
end
end)
before_buildcmd_file("build.cxxbridge")
rule("rust.build")
set_sourcekinds("rc")
on_load(function (target)
-- set cratetype
local cratetype = target:values("rust.cratetype")
if cratetype == "staticlib" then
assert(target:is_static(), "target(%s) must be static kind for cratetype(staticlib)!", target:name())
target:add("arflags", "--crate-type=staticlib")
target:data_set("inherit.links.exportlinks", false)
elseif cratetype == "cdylib" then
assert(target:is_shared(), "target(%s) must be shared kind for cratetype(cdylib)!", target:name())
target:add("shflags", "--crate-type=cdylib", {force = true})
target:add("shflags", "-C prefer-dynamic", {force = true})
elseif target:is_static() then
target:set("extension", ".rlib")
target:add("arflags", "--crate-type=lib", {force = true})
target:data_set("inherit.links.deplink", false)
elseif target:is_shared() then
target:add("shflags", "--crate-type=dylib", {force = true})
-- fix cannot satisfy dependencies so `std` only shows up once
-- https://github.com/rust-lang/rust/issues/19680
--
-- but it will link dynamic @rpath/libstd-xxx.dylib,
-- so we can no longer modify and set other rpath paths
target:add("shflags", "-C prefer-dynamic", {force = true})
elseif target:is_binary() then
target:add("ldflags", "--crate-type=bin", {force = true})
end
-- set edition
local edition = target:values("rust.edition") or "2018"
target:add("rcflags", "--edition", edition, {force = true})
-- set abort panic for no_std
-- https://github.com/xmake-io/xmake/issues/4929
local no_std = false
local sourcebatch = target:sourcebatches()["rust.build"]
if sourcebatch then
for _, sourcefile in ipairs(sourcebatch.sourcefiles) do
local content = io.readfile(sourcefile)
if content and content:find("#![no_std]", 1, true) then
no_std = true
break
end
end
end
if no_std then
target:add("rcflags", "-C panic=abort", {force = true})
end
end)
on_build("build.target")
rule("rust")
add_deps("rust.build")
add_deps("utils.inherit.links")
|
0 | repos/xmake/xmake/rules/rust | repos/xmake/xmake/rules/rust/build/target.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file target.lua
--
-- imports
import("core.base.option")
import("core.base.hashset")
import("core.tool.compiler")
import("core.project.depend")
import("utils.progress")
-- build the source files
function build_sourcefiles(target, sourcebatch, opt)
-- get the target file
local targetfile = target:targetfile()
-- get source files and kind
local sourcefiles = sourcebatch.sourcefiles
local sourcekind = sourcebatch.sourcekind
-- get depend file
local dependfile = target:dependfile(targetfile)
-- load compiler
local compinst = compiler.load(sourcekind, {target = target})
-- get compile flags
local compflags = compinst:compflags({target = target})
-- load dependent info
local dependinfo = option.get("rebuild") and {} or (depend.load(dependfile) or {})
-- need build this object?
local depvalues = {compinst:program(), compflags}
if not depend.is_changed(dependinfo, {lastmtime = os.mtime(targetfile), values = depvalues}) then
return
end
-- trace progress into
progress.show(opt.progress, "${color.build.target}linking.$(mode) %s", path.filename(targetfile))
-- trace verbose info
vprint(compinst:buildcmd(sourcefiles, targetfile, {target = target, compflags = compflags}))
-- flush io buffer to update progress info
io.flush()
-- compile it
dependinfo.files = {}
assert(compinst:build(sourcefiles, targetfile, {target = target, dependinfo = dependinfo, compflags = compflags}))
-- update files and values to the dependent file
dependinfo.values = depvalues
table.join2(dependinfo.files, sourcefiles)
depend.save(dependinfo, dependfile)
end
-- build target
function main(target, opt)
-- @note only support one source kind!
local sourcebatches = target:sourcebatches()
if sourcebatches then
local sourcebatch = sourcebatches["rust.build"]
if sourcebatch then
build_sourcefiles(target, sourcebatch, opt)
end
end
end
|
0 | repos/xmake/xmake/rules/rust | repos/xmake/xmake/rules/rust/build/cxxbridge.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file cxxbridge.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_tool")
function main(target, batchcmds, sourcefile, opt)
local cxxbridge = assert(find_tool("cxxbridge"), "cxxbridge not found, please run `cargo install cxxbridge-cmd` to install it first!")
-- get c/c++ source file for cxxbridge
local headerfile = path.join(target:autogendir(), "rules", "cxxbridge", path.basename(sourcefile) .. ".rs.h")
local sourcefile_cx = path.join(target:autogendir(), "rules", "cxxbridge", path.basename(sourcefile) .. ".rs.cc")
-- add includedirs
target:add("includedirs", path.directory(headerfile))
-- add objectfile
local objectfile = target:objectfile(sourcefile_cx)
table.insert(target:objectfiles(), objectfile)
-- add commands
batchcmds:show_progress(opt.progress, "${color.build.object}compiling.cxxbridge %s", sourcefile)
batchcmds:mkdir(path.directory(sourcefile_cx))
batchcmds:vexecv(cxxbridge.program, {sourcefile}, {stdout = sourcefile_cx})
batchcmds:vexecv(cxxbridge.program, {sourcefile, "--header"}, {stdout = headerfile})
batchcmds:compile(sourcefile_cx, objectfile)
-- add deps
batchcmds:add_depfiles(sourcefile)
batchcmds:set_depmtime(os.mtime(objectfile))
batchcmds:set_depcache(target:dependfile(objectfile))
end
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/qt/config_static.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki, jingkaimori
-- @file config_static.lua
--
-- imports
import("core.base.semver")
function main(target)
-- get qt sdk version
local qt = target:data("qt")
local qt_sdkver = nil
if qt.sdkver then
qt_sdkver = semver.new(qt.sdkver)
else
raise("Qt SDK version not found, please run `xmake f --qt_sdkver=xxx` to set it.")
end
-- @see
-- https://github.com/xmake-io/xmake/issues/1047
-- https://github.com/xmake-io/xmake/issues/2791
local QtPlatformSupport
if qt_sdkver:ge("6.0") then
QtPlatformSupport = nil
elseif qt_sdkver:ge("5.9") then
QtPlatformSupport = "QtPlatformCompositorSupport"
else
QtPlatformSupport = "QtPlatformSupport"
end
-- load some basic plugins and frameworks
local plugins = {}
local frameworks = {}
if target:is_plat("macosx") then
plugins.QCocoaIntegrationPlugin = {linkdirs = "plugins/platforms", links = {"qcocoa", "cups"}}
table.insert(frameworks, "QtWidgets")
if QtPlatformSupport then
table.insert(frameworks, QtPlatformSupport)
end
elseif target:is_plat("windows") then
plugins.QWindowsIntegrationPlugin = {linkdirs = "plugins/platforms", links = {is_mode("debug") and "qwindowsd" or "qwindows"}}
table.join2(frameworks, "QtPrintSupport", "QtWidgets")
if QtPlatformSupport then
table.insert(frameworks, QtPlatformSupport)
end
elseif target:is_plat("wasm") then
plugins.QWasmIntegrationPlugin = {linkdirs = "plugins/platforms", links = {"qwasm"}}
if qt_sdkver:ge("6.0") then
table.join2(frameworks, "QtOpenGL")
else
table.join2(frameworks, "QtEventDispatcherSupport", "QtFontDatabaseSupport", "QtEglSupport")
end
end
return frameworks, plugins, qt_sdkver
end |
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/qt/load.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file load.lua
--
-- imports
import("core.base.semver")
import("core.project.config")
import("core.project.target", {alias = "core_target"})
import("core.base.hashset")
import("lib.detect.find_library")
-- make link for framework
function _link(target, linkdirs, framework, qt_sdkver, infix)
if framework:startswith("Qt") then
local debug_suffix = "_debug"
if target:is_plat("windows") then
debug_suffix = "d"
elseif target:is_plat("mingw") then
if qt_sdkver:ge("5.15.2") then
debug_suffix = ""
else
debug_suffix = "d"
end
elseif target:is_plat("android") or target:is_plat("linux") then
debug_suffix = ""
end
if qt_sdkver:ge("5.0") then
framework = "Qt" .. qt_sdkver:major() .. framework:sub(3) .. infix .. (is_mode("debug") and debug_suffix or "")
else -- for qt4.x, e.g. QtGui4.lib
if target:is_plat("windows", "mingw") then
framework = "Qt" .. framework:sub(3) .. infix .. (is_mode("debug") and debug_suffix or "") .. qt_sdkver:major()
else
framework = "Qt" .. framework:sub(3) .. infix .. (is_mode("debug") and debug_suffix or "")
end
end
if target:is_plat("android") then --> -lQt5Core_armeabi/-lQt5CoreDebug_armeabi for 5.14.x
local libinfo = find_library(framework .. "_" .. config.arch(), linkdirs)
if libinfo and libinfo.link then
framework = libinfo.link
end
end
end
return framework
end
-- find the static links from the given qt link directories, e.g. libqt*.a
function _find_static_links_3rd(target, linkdirs, qt_sdkver, libpattern)
local links = {}
local debug_suffix = "_debug"
if target:is_plat("windows") then
debug_suffix = "d"
elseif target:is_plat("mingw") then
debug_suffix = "d"
elseif target:is_plat("android") or target:is_plat("linux") then
debug_suffix = ""
end
for _, linkdir in ipairs(linkdirs) do
for _, libpath in ipairs(os.files(path.join(linkdir, libpattern))) do
local basename = path.basename(libpath)
-- we need to ignore qt framework libraries, e.g. libQt5xxx.a, Qt5Core.lib ..
-- but bundled library names like libQt5Bundledxxx.a on Qt6.x
-- @see https://github.com/xmake-io/xmake/issues/3572
if basename:startswith("libQt" .. qt_sdkver:major() .. "Bundled") or (
(not basename:startswith("libQt" .. qt_sdkver:major())) and
(not basename:startswith("Qt" .. qt_sdkver:major()))) then
if (is_mode("debug") and basename:endswith(debug_suffix)) or (not is_mode("debug") and not basename:endswith(debug_suffix)) then
table.insert(links, core_target.linkname(path.filename(libpath)))
end
end
end
end
return links
end
-- add plugins
function _add_plugins(target, plugins)
for name, plugin in pairs(plugins) do
target:values_add("qt.plugins", name)
if plugin.links then
target:values_add("qt.links", table.unpack(table.wrap(plugin.links)))
end
if plugin.linkdirs then
target:values_add("qt.linkdirs", table.unpack(table.wrap(plugin.linkdirs)))
end
-- TODO: add prebuilt object files in qt sdk.
-- these file is located at plugins/xxx/objects-Release/xxxPlugin_init/xxxPlugin_init.cpp.o
end
end
-- add includedirs if exists
function _add_includedirs(target, includedirs)
for _, includedir in ipairs(includedirs) do
if os.isdir(includedir) then
target:add("sysincludedirs", includedir)
end
end
end
-- get target c++ version
function _get_target_cppversion(target)
local languages = target:get("languages")
for _, language in ipairs(languages) do
if language:startswith("c++") or language:startswith("cxx") then
local v = language:match("%d+") or language:match("latest")
if v then return v end
end
end
end
-- get frameworks from target
-- @see https://github.com/xmake-io/xmake/issues/4135
function _get_frameworks_from_target(target)
local values = table.wrap(target:get("frameworks"))
for _, value in ipairs((target:get_from("frameworks", "option::*"))) do
table.join2(values, value)
end
for _, value in ipairs((target:get_from("frameworks", "package::*"))) do
table.join2(values, value)
end
for _, value in ipairs((target:get_from("__qt_frameworks", "dep::*", {interface = true}))) do
table.join2(values, value)
end
return table.unique(values)
end
function _add_qmakeprllibs(target, prlfile, qt)
if os.isfile(prlfile) then
local contents = io.readfile(prlfile)
local envs = {}
if contents then
for _, prlenv in ipairs(contents:split('\n', {plain = true})) do
local kv = prlenv:split('=', {plain = true})
if #kv == 2 then
envs[kv[1]:trim()] = kv[2]:trim()
end
end
end
if envs.QMAKE_PRL_LIBS_FOR_CMAKE then
for _, lib in ipairs(envs.QMAKE_PRL_LIBS_FOR_CMAKE:split(';', {plain = true})) do
if lib:startswith("-L") then
local libdir = lib:sub(3)
target:add("linkdirs", libdir)
else
if qt.qmldir then
lib = string.gsub(lib, "%$%$%[QT_INSTALL_QML%]", qt.qmldir)
end
if qt.sdkdir then
lib = string.gsub(lib, "%$%$%[QT_INSTALL_PREFIX%]", qt.sdkdir)
end
if qt.pluginsdir then
lib = string.gsub(lib, "%$%$%[QT_INSTALL_PLUGINS%]", qt.pluginsdir)
end
if qt.libdir then
lib = string.gsub(lib, "%$%$%[QT_INSTALL_LIBS%]", qt.libdir)
end
if lib:startswith("-l") then
lib = lib:sub(3)
end
target:add("syslinks", lib)
end
end
end
end
end
-- the main entry
function main(target, opt)
-- init options
opt = opt or {}
-- get qt sdk
local qt = target:data("qt")
-- get qt sdk version
local qt_sdkver = nil
if qt.sdkver then
qt_sdkver = semver.new(qt.sdkver)
else
raise("Qt SDK version not found, please run `xmake f --qt_sdkver=xxx` to set it.")
end
-- get qt sdk infix
local infix = ""
if qt.mkspecsdir then
if os.isfile(path.join(qt.mkspecsdir, "qconfig.pri")) then
local qconfig = io.readfile(path.join(qt.mkspecsdir, "qconfig.pri"))
if qconfig then
qconfig = qconfig:trim():split("\n")
for _, line in ipairs(qconfig) do
if line:startswith("QT_LIBINFIX") then
local kv = line:split("=", {plain = true, limit = 2})
if #kv == 2 then
infix = kv[2]:trim()
end
end
end
end
end
end
-- add -fPIC
if not target:is_plat("windows", "mingw") then
target:add("cxflags", "-fPIC")
target:add("mxflags", "-fPIC")
target:add("asflags", "-fPIC")
end
if qt_sdkver:ge("6.0") then
-- @see https://github.com/xmake-io/xmake/issues/2071
if target:is_plat("windows") then
target:add("cxxflags", "/Zc:__cplusplus")
target:add("cxxflags", "/permissive-")
end
end
-- need c++11 at least
local languages = target:get("languages")
local cxxlang = false
for _, lang in ipairs(languages) do
-- c++* or gnuc++*
if lang:find("cxx", 1, true) or lang:find("c++", 1, true) then
cxxlang = true
break
end
end
if not cxxlang then
-- Qt6 require at least '/std:c++17'
-- @see https://github.com/xmake-io/xmake/issues/1183
local cppversion = _get_target_cppversion(target)
if qt_sdkver:ge("6.0") then
-- add conditionnaly c++17 to avoid for example "cl : Command line warning D9025 : overriding '/std:c++latest' with '/std:c++17'" warning
if (not cppversion) or (tonumber(cppversion) and tonumber(cppversion) < 17) then
target:add("languages", "c++17")
end
else
-- add conditionnaly c++11 to avoid for example "cl : Command line warning D9025 : overriding '/std:c++latest' with '/std:c++11'" warning
if (not cppversion) or (tonumber(cppversion) and tonumber(cppversion) < 11) then
target:add("languages", "c++11")
end
end
end
-- add definitions for the compile mode
if is_mode("debug") then
target:add("defines", "QT_QML_DEBUG")
elseif is_mode("release") then
target:add("defines", "QT_NO_DEBUG")
elseif is_mode("profile") then
target:add("defines", "QT_QML_DEBUG", "QT_NO_DEBUG")
end
-- The following define makes your compiler emit warnings if you use
-- any feature of Qt which as been marked deprecated (the exact warnings
-- depend on your compiler). Please consult the documentation of the
-- deprecated API in order to know how to port your code away from it.
target:add("defines", "QT_DEPRECATED_WARNINGS")
-- add plugins
if opt.plugins then
_add_plugins(target, opt.plugins)
end
local plugins = target:values("qt.plugins")
if plugins then
local importfile = path.join(config.buildir(), ".qt", "plugin", target:name(), "static_import.cpp")
local file = io.open(importfile, "w")
if file then
file:print("#include <QtPlugin>")
for _, plugin in ipairs(plugins) do
file:print("Q_IMPORT_PLUGIN(%s)", plugin)
end
file:close()
target:add("files", importfile)
end
end
-- backup the user syslinks, we need to add them behind the qt syslinks
local syslinks_user = target:get("syslinks")
target:set("syslinks", nil)
-- add qt links and directories
target:add("syslinks", target:values("qt.links"))
local qtprldirs = {}
for _, qt_linkdir in ipairs(target:values("qt.linkdirs")) do
local linkdir = path.join(qt.sdkdir, qt_linkdir)
if os.isdir(linkdir) then
target:add("linkdirs", linkdir)
table.insert(qtprldirs, linkdir)
end
end
for _, qt_link in ipairs(target:values("qt.links")) do
for _, qt_libdir in ipairs(qtprldirs) do
local prl_file = path.join(qt_libdir, qt_link .. ".prl")
_add_qmakeprllibs(target, prl_file, qt)
end
end
-- backup qt frameworks
local qt_frameworks = target:get("frameworks")
if qt_frameworks then
target:set("__qt_frameworks", qt_frameworks)
end
local qt_frameworks_extra = target:extraconf("frameworks")
if qt_frameworks_extra then
target:extraconf_set("__qt_frameworks", qt_frameworks_extra)
end
-- add frameworks
if opt.frameworks then
target:add("frameworks", opt.frameworks)
end
-- do frameworks for qt
local frameworksset = hashset.new()
local qt_frameworks = _get_frameworks_from_target(target)
for _, framework in ipairs(qt_frameworks) do
-- translate qt frameworks
if framework:startswith("Qt") then
-- add private includedirs
if framework:lower():endswith("private") then
local private_dir = framework:sub(1, -#("private") - 1);
if target:is_plat("macosx") then
local frameworkdir = path.join(qt.libdir, framework .. ".framework")
if os.isdir(frameworkdir) then
_add_includedirs(target, path.join(frameworkdir, "Headers", qt.sdkver))
_add_includedirs(target, path.join(frameworkdir, "Headers", qt.sdkver, private_dir))
else
_add_includedirs(target, path.join(qt.includedir, private_dir, qt.sdkver, private_dir))
_add_includedirs(target, path.join(qt.includedir, private_dir, qt.sdkver))
end
else
_add_includedirs(target, path.join(qt.includedir, private_dir, qt.sdkver, private_dir))
_add_includedirs(target, path.join(qt.includedir, private_dir, qt.sdkver))
end
else
-- add definitions
target:add("defines", "QT_" .. framework:sub(3):upper() .. "_LIB")
-- add includedirs
if target:is_plat("macosx") then
local frameworkdir = path.join(qt.libdir, framework .. ".framework")
if os.isdir(frameworkdir) and os.isdir(path.join(frameworkdir, "Headers")) then
_add_includedirs(target, path.join(frameworkdir, "Headers"))
-- e.g. QtGui.framework/Headers/5.15.0/QtGui/qpa/qplatformopenglcontext.h
-- https://github.com/xmake-io/xmake/issues/1226
_add_includedirs(target, path.join(frameworkdir, "Headers", qt.sdkver))
_add_includedirs(target, path.join(frameworkdir, "Headers", qt.sdkver, framework))
frameworksset:insert(framework)
else
local link = _link(target, qt.libdir, framework, qt_sdkver, infix)
target:add("syslinks", link)
_add_qmakeprllibs(target, path.join(qt.libdir, link .. ".prl"), qt)
_add_includedirs(target, path.join(qt.includedir, framework))
-- e.g. QtGui/5.15.0/QtGui/qpa/qplatformopenglcontext.h
_add_includedirs(target, path.join(qt.includedir, framework, qt.sdkver))
_add_includedirs(target, path.join(qt.includedir, framework, qt.sdkver, framework))
end
else
local link = _link(target, qt.libdir, framework, qt_sdkver, infix)
target:add("syslinks", link)
_add_qmakeprllibs(target, path.join(qt.libdir, link .. ".prl"), qt)
_add_includedirs(target, path.join(qt.includedir, framework))
_add_includedirs(target, path.join(qt.includedir, framework, qt.sdkver))
_add_includedirs(target, path.join(qt.includedir, framework, qt.sdkver, framework))
end
end
elseif target:is_plat("macosx") then
--@see https://github.com/xmake-io/xmake/issues/5336
frameworksset:insert(framework)
end
end
-- remove private frameworks
local local_frameworks = {}
for _, framework in ipairs(target:get("frameworks")) do
if frameworksset:has(framework) then
table.insert(local_frameworks, framework)
end
end
target:set("frameworks", local_frameworks)
-- add some static third-party links if exists
-- and exclude qt framework libraries, e.g. libQt5xxx.a, Qt5xxx.lib
local libpattern
if qt_sdkver:ge("6.0") then
-- e.g. libQt6BundledFreetype.a on Qt6.x
-- @see https://github.com/xmake-io/xmake/issues/3572
libpattern = target:is_plat("windows") and "Qt*.lib" or "libQt*.a"
else
-- e.g. libqtmain.a, libqtfreetype.q, libqtlibpng.a on Qt5.x
libpattern = target:is_plat("windows") and "qt*.lib" or "libqt*.a"
end
target:add("syslinks", _find_static_links_3rd(target, qt.libdir, qt_sdkver, libpattern))
-- add user syslinks
if syslinks_user then
target:add("syslinks", syslinks_user)
end
-- add includedirs, linkdirs
if target:is_plat("macosx") then
target:add("frameworks", "DiskArbitration", "IOKit", "CoreFoundation", "CoreGraphics", "OpenGL")
target:add("frameworks", "Carbon", "Foundation", "AppKit", "Security", "SystemConfiguration")
if not frameworksset:empty() then
target:add("frameworkdirs", qt.libdir)
target:add("rpathdirs", "@executable_path/Frameworks", qt.libdir)
else
target:add("rpathdirs", qt.libdir)
-- remove qt frameworks
local frameworks = table.wrap(target:get("frameworks"))
for i = #frameworks, 1, -1 do
local framework = frameworks[i]
if framework:startswith("Qt") then
table.remove(frameworks, i)
end
end
target:set("frameworks", frameworks)
end
_add_includedirs(target, qt.includedir)
_add_includedirs(target, path.join(qt.mkspecsdir, "macx-clang"))
target:add("linkdirs", qt.libdir)
elseif target:is_plat("linux") then
target:set("frameworks", nil)
_add_includedirs(target, qt.includedir)
_add_includedirs(target, path.join(qt.mkspecsdir, "linux-g++"))
target:add("rpathdirs", qt.libdir)
target:add("linkdirs", qt.libdir)
elseif target:is_plat("windows") then
target:set("frameworks", nil)
_add_includedirs(target, qt.includedir)
_add_includedirs(target, path.join(qt.mkspecsdir, "win32-msvc"))
target:add("linkdirs", qt.libdir)
target:add("syslinks", "ws2_32", "gdi32", "ole32", "advapi32", "shell32", "user32", "opengl32", "imm32", "winmm", "iphlpapi")
-- for debugger, https://github.com/xmake-io/xmake-vscode/issues/225
target:add("runenvs", "PATH", qt.bindir)
elseif target:is_plat("mingw") then
target:set("frameworks", nil)
-- we need to fix it, because gcc maybe does not work on latest mingw when `-isystem D:\a\_temp\msys64\mingw64\include` is passed.
-- and qt.includedir will be this path value when Qt sdk directory just is `D:\a\_temp\msys64\mingw64`
-- @see https://github.com/msys2/MINGW-packages/issues/10761#issuecomment-1044302523
if is_subhost("msys") then
local mingw_prefix = os.getenv("MINGW_PREFIX")
local mingw_includedir = path.normalize(path.join(mingw_prefix or "/", "include"))
if qt.includedir and qt.includedir and path.normalize(qt.includedir) ~= mingw_includedir then
_add_includedirs(target, qt.includedir)
end
else
_add_includedirs(target, qt.includedir)
end
_add_includedirs(target, path.join(qt.mkspecsdir, "win32-g++"))
target:add("linkdirs", qt.libdir)
target:add("syslinks", "mingw32", "ws2_32", "gdi32", "ole32", "advapi32", "shell32", "user32", "iphlpapi")
elseif target:is_plat("android") then
target:set("frameworks", nil)
_add_includedirs(target, qt.includedir)
_add_includedirs(target, path.join(qt.mkspecsdir, "android-clang"))
target:add("rpathdirs", qt.libdir)
target:add("linkdirs", qt.libdir)
elseif target:is_plat("wasm") then
target:set("frameworks", nil)
_add_includedirs(target, qt.includedir)
_add_includedirs(target, path.join(qt.mkspecsdir, "wasm-emscripten"))
target:add("rpathdirs", qt.libdir)
target:add("linkdirs", qt.libdir)
-- add prebuilt object files in qt sdk.
-- these files are located at lib/objects-Release/xxxmodule_resources_x/.rcc/xxxmodule.cpp.o
for _, framework in ipairs(qt_frameworks) do
local prefix = framework
if framework:startswith("Qt") then
prefix = framework:sub(3)
end
for _, filepath in ipairs(os.files(path.join(qt.libdir, "objects-*", prefix .. "_resources_*", ".rcc", "*.o"))) do
table.insert(target:objectfiles(), filepath)
end
end
target:add("ldflags", "-s FETCH=1", "-s ERROR_ON_UNDEFINED_SYMBOLS=1", "-s ALLOW_MEMORY_GROWTH=1", "--bind")
target:add("shflags", "-s FETCH=1", "-s ERROR_ON_UNDEFINED_SYMBOLS=1", "-s ALLOW_MEMORY_GROWTH=1", "--bind")
if qt_sdkver:ge("6.0") then
-- @see https://github.com/xmake-io/xmake/issues/4137
target:add("ldflags", "-s MAX_WEBGL_VERSION=2", "-s WASM_BIGINT=1", "-s DISABLE_EXCEPTION_CATCHING=1")
target:add("ldflags", "-sASYNCIFY_IMPORTS=qt_asyncify_suspend_js,qt_asyncify_resume_js")
target:add("ldflags", "-s EXPORTED_RUNTIME_METHODS=UTF16ToString,stringToUTF16,JSEvents,specialHTMLTargets")
target:add("ldflags", "-s MODULARIZE=1", "-s EXPORT_NAME=createQtAppInstance")
target:add("shflags", "-s MAX_WEBGL_VERSION=2", "-s WASM_BIGINT=1", "-s DISABLE_EXCEPTION_CATCHING=1")
target:add("shflags", "-sASYNCIFY_IMPORTS=qt_asyncify_suspend_js,qt_asyncify_resume_js")
target:add("shflags", "-s EXPORTED_RUNTIME_METHODS=UTF16ToString,stringToUTF16,JSEvents,specialHTMLTargets")
target:add("shflags", "-s MODULARIZE=1", "-s EXPORT_NAME=createQtAppInstance")
target:set("extension", ".js")
else
target:add("ldflags", "-s WASM=1", "-s FULL_ES2=1", "-s FULL_ES3=1", "-s USE_WEBGL2=1")
target:add("ldflags", "-s EXPORTED_RUNTIME_METHODS=[\"UTF16ToString\",\"stringToUTF16\"]")
target:add("shflags", "-s WASM=1", "-s FULL_ES2=1", "-s FULL_ES3=1", "-s USE_WEBGL2=1")
target:add("shflags", "-s EXPORTED_RUNTIME_METHODS=[\"UTF16ToString\",\"stringToUTF16\"]")
end
end
-- is gui application?
if opt.gui then
-- add -subsystem:windows for windows platform
if target:is_plat("windows") then
target:add("defines", "_WINDOWS")
local subsystem = false
for _, ldflag in ipairs(target:get("ldflags")) do
if type(ldflag) == "string" then
ldflag = ldflag:lower()
if ldflag:find("[/%-]subsystem:") then
subsystem = true
break
end
end
end
-- maybe user will set subsystem to console
if not subsystem then
target:add("ldflags", "-subsystem:windows", "-entry:mainCRTStartup", {force = true})
end
elseif target:is_plat("mingw") then
target:add("ldflags", "-mwindows", {force = true})
end
end
-- set default runtime
-- @see https://github.com/xmake-io/xmake/issues/4161
if not target:get("runtimes") then
target:set("runtimes", is_mode("debug") and "MDd" or "MD")
end
end
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/qt/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: qt/wasm application
rule("qt._wasm_app")
add_deps("qt.env")
after_build(function (target)
local qt = target:data("qt")
local pluginsdir = qt and qt.pluginsdir
if pluginsdir then
local targetdir = target:targetdir()
local htmlfile = path.join(targetdir, target:basename() .. ".html")
if os.isfile(path.join(pluginsdir, "platforms/wasm_shell.html")) then
os.vcp(path.join(pluginsdir, "platforms/wasm_shell.html"), htmlfile)
io.gsub(htmlfile, "@APPNAME@", target:name())
os.vcp(path.join(pluginsdir, "platforms/qtloader.js"), targetdir)
os.vcp(path.join(pluginsdir, "platforms/qtlogo.svg"), targetdir)
end
end
end)
-- define rule: qt static library
rule("qt.static")
add_deps("qt.qrc", "qt.ui", "qt.moc", "qt.ts")
-- we must set kind before target.on_load(), may we will use target in on_load()
on_load(function (target)
target:set("kind", "static")
end)
on_config(function (target)
import("load")(target, {frameworks = {"QtCore"}})
end)
-- define rule: qt shared library
rule("qt.shared")
add_deps("qt.qrc", "qt.ui", "qt.moc", "qt.ts")
-- we must set kind before target.on_load(), may we will use target in on_load()
on_load(function (target)
target:set("kind", "shared")
end)
on_config(function (target)
import("load")(target, {frameworks = {"QtCore"}})
end)
-- define rule: qt console
rule("qt.console")
add_deps("qt.qrc", "qt.ui", "qt.moc", "qt.ts")
-- we must set kind before target.on_load(), may we will use target in on_load()
on_load(function (target)
target:set("kind", "binary")
end)
on_config(function (target)
import("load")(target, {frameworks = {"QtCore"}})
end)
after_install("windows", "install.windows")
after_install("mingw", "install.mingw")
-- define rule: qt widgetapp
rule("qt.widgetapp")
add_deps("qt.ui", "qt.moc", "qt._wasm_app", "qt.qrc", "qt.ts")
-- we must set kind before target.on_load(), may we will use target in on_load()
on_load(function (target)
target:set("kind", target:is_plat("android") and "shared" or "binary")
end)
on_config(function (target)
-- get qt sdk version
local qt = target:data("qt")
local qt_sdkver = nil
if qt.sdkver then
import("core.base.semver")
qt_sdkver = semver.new(qt.sdkver)
end
local frameworks = {"QtGui", "QtWidgets", "QtCore"}
if qt_sdkver and qt_sdkver:lt("5.0") then
frameworks = {"QtGui", "QtCore"} -- qt4.x has not QtWidgets, it is in QtGui
end
import("load")(target, {gui = true, frameworks = frameworks})
end)
-- deploy application
after_build("android", "deploy.android")
after_build("macosx", "deploy.macosx")
-- install application for android
on_install("android", "install.android")
after_install("windows", "install.windows")
after_install("mingw", "install.mingw")
-- define rule: qt static widgetapp
rule("qt.widgetapp_static")
add_deps("qt.ui", "qt.moc", "qt._wasm_app", "qt.qrc", "qt.ts")
-- we must set kind before target.on_load(), may we will use target in on_load()
on_load(function (target)
target:set("kind", target:is_plat("android") and "shared" or "binary")
end)
on_config(function (target)
local frameworks, plugins, qt_sdkver = import("config_static")(target)
if qt_sdkver:ge("5.0") then
table.join2(frameworks, {"QtGui", "QtWidgets", "QtCore"})
else
table.join2(frameworks, {"QtGui", "QtCore"})-- qt4.x has not QtWidgets, it is in QtGui
end
import("load")(target, {gui = true, plugins = plugins, frameworks = frameworks})
end)
-- deploy application
after_build("android", "deploy.android")
after_build("macosx", "deploy.macosx")
-- install application for android
on_install("android", "install.android")
after_install("windows", "install.windows")
after_install("mingw", "install.mingw")
-- define rule: qt quickapp
rule("qt.quickapp")
add_deps("qt.qrc", "qt.moc", "qt._wasm_app", "qt.ts")
-- we must set kind before target.on_load(), may we will use target in on_load()
on_load(function (target)
target:set("kind", target:is_plat("android") and "shared" or "binary")
end)
on_config(function (target)
import("load")(target, {gui = true, frameworks = {"QtGui", "QtQuick", "QtQml", "QtCore", "QtNetwork"}})
end)
-- deploy application
after_build("android", "deploy.android")
after_build("macosx", "deploy.macosx")
-- install application for android
on_install("android", "install.android")
after_install("windows", "install.windows")
after_install("mingw", "install.mingw")
-- define rule: qt static quickapp
rule("qt.quickapp_static")
add_deps("qt.qrc", "qt.moc", "qt._wasm_app", "qt.ts")
-- we must set kind before target.on_load(), may we will use target in on_load()
on_load(function (target)
target:set("kind", target:is_plat("android") and "shared" or "binary")
end)
on_config(function (target)
local frameworks, plugins = import("config_static")(target)
table.join2(frameworks, {"QtGui", "QtQuick", "QtQml", "QtQmlModels", "QtCore", "QtNetwork"})
import("load")(target, {gui = true, plugins = plugins, frameworks = frameworks})
end)
-- deploy application
after_build("android", "deploy.android")
after_build("macosx", "deploy.macosx")
-- install application for android
on_install("android", "install.android")
after_install("windows", "install.windows")
after_install("mingw", "install.mingw")
-- define rule: qt qmlplugin
rule("qt.qmlplugin")
add_deps("qt.shared", "qt.qmltyperegistrar", "qt.ts")
on_config(function(target)
import("load")(target, {frameworks = { "QtCore", "QtGui", "QtQuick", "QtQml", "QtNetwork" }})
end)
-- define rule: qt application (deprecated)
rule("qt.application")
add_deps("qt.quickapp", "qt.ui")
|
0 | repos/xmake/xmake/rules/qt | repos/xmake/xmake/rules/qt/moc/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
rule("qt.moc")
add_deps("qt.env")
add_deps("qt.ui", {order = true})
set_extensions(".h", ".hpp")
before_buildcmd_file(function (target, batchcmds, sourcefile, opt)
import("core.tool.compiler")
-- get moc
local qt = assert(target:data("qt"), "Qt not found!")
local moc = path.join(qt.bindir, is_host("windows") and "moc.exe" or "moc")
if not os.isexec(moc) and qt.libexecdir then
moc = path.join(qt.libexecdir, is_host("windows") and "moc.exe" or "moc")
end
if not os.isexec(moc) and qt.libexecdir_host then
moc = path.join(qt.libexecdir_host, is_host("windows") and "moc.exe" or "moc")
end
assert(moc and os.isexec(moc), "moc not found!")
-- get c++ source file for moc
--
-- add_files("mainwindow.h") -> moc_MainWindow.cpp
-- add_files("mainwindow.cpp", {rules = "qt.moc"}) -> mainwindow.moc, @see https://github.com/xmake-io/xmake/issues/750
--
local basename = path.basename(sourcefile)
local filename_moc = "moc_" .. basename .. ".cpp"
if sourcefile:endswith(".cpp") then
filename_moc = basename .. ".moc"
end
-- we need to retain the file directory structure, @see https://github.com/xmake-io/xmake/issues/2343
local sourcefile_moc = target:autogenfile(path.join(path.directory(sourcefile), filename_moc))
-- add objectfile
local objectfile = target:objectfile(sourcefile_moc)
table.insert(target:objectfiles(), objectfile)
-- add commands
batchcmds:show_progress(opt.progress, "${color.build.object}compiling.qt.moc %s", sourcefile)
-- get values from target
-- @see https://github.com/xmake-io/xmake/issues/3930
local function _get_values_from_target(target, name)
local values = {}
for _, value in ipairs((target:get_from(name, "*"))) do
table.join2(values, value)
end
return table.unique(values)
end
-- generate c++ source file for moc
local flags = {}
table.join2(flags, compiler.map_flags("cxx", "define", _get_values_from_target(target, "defines")))
local pathmaps = {
{"includedirs", "includedir"},
{"sysincludedirs", "includedir"}, -- for now, moc process doesn't support MSVC external includes flags and will fail
{"frameworkdirs", "frameworkdir"}
}
for _, pathmap in ipairs(pathmaps) do
for _, item in ipairs(_get_values_from_target(target, pathmap[1])) do
local pathitem = path(item, function (p)
local item = table.unwrap(compiler.map_flags("cxx", pathmap[2], p))
if item then
-- we always need use '/' to fix it for project generator, because it will use path.translate in cl.lua
item = item:gsub("\\", "/")
end
return item
end)
if not pathitem:empty() then
table.insert(flags, pathitem)
end
end
end
local user_flags = target:get("qt.moc.flags") or {}
batchcmds:mkdir(path.directory(sourcefile_moc))
batchcmds:vrunv(moc, table.join(user_flags, flags, path(sourcefile), "-o", path(sourcefile_moc)))
-- we need to compile this moc_xxx.cpp file if exists Q_PRIVATE_SLOT, @see https://github.com/xmake-io/xmake/issues/750
local mocdata = io.readfile(sourcefile)
if mocdata and mocdata:find("Q_PRIVATE_SLOT") or sourcefile_moc:endswith(".moc") then
-- add includedirs of sourcefile_moc
target:add("includedirs", path.directory(sourcefile_moc))
-- remove the object file of sourcefile_moc
local objectfiles = target:objectfiles()
for idx, objectfile in ipairs(objectfiles) do
if objectfile == target:objectfile(sourcefile_moc) then
table.remove(objectfiles, idx)
break
end
end
batchcmds:set_depmtime(os.mtime(sourcefile_moc))
batchcmds:set_depcache(target:dependfile(sourcefile_moc))
else
-- compile c++ source file for moc
batchcmds:compile(sourcefile_moc, objectfile)
batchcmds:set_depmtime(os.mtime(objectfile))
batchcmds:set_depcache(target:dependfile(objectfile))
end
-- add deps
batchcmds:add_depfiles(sourcefile)
end)
|
0 | repos/xmake/xmake/rules/qt | repos/xmake/xmake/rules/qt/env/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
rule("qt.env")
on_config(function (target)
-- imports
import("detect.sdks.find_qt")
-- find qt sdk
local qt = target:data("qt")
if not qt then
qt = assert(find_qt(nil, {verbose = true}), "Qt SDK not found!")
target:data_set("qt", qt)
end
local qmlimportpath = target:values("qt.env.qmlimportpath") or {}
if target:is_plat("windows") or (target:is_plat("mingw") and is_host("windows")) then
target:add("runenvs", "PATH", qt.bindir)
table.insert(qmlimportpath, qt.qmldir)
-- add targetdir in QML2_IMPORT_PATH in case of the user have qml plugins
table.insert(qmlimportpath, target:targetdir())
target:set("runenv", "QML_IMPORT_TRACE", "1")
elseif target:is_plat("msys", "cygwin") then
raise("please run `xmake f -p mingw --mingw=/mingw64` to support Qt/Mingw64 on Msys!")
end
target:set("runenv", "QML2_IMPORT_PATH", qmlimportpath)
end)
|
0 | repos/xmake/xmake/rules/qt | repos/xmake/xmake/rules/qt/ts/xmake.lua | rule("qt.ts")
add_deps("qt.env")
set_extensions(".ts")
on_config(function (target)
-- get source file
local lupdate_argv = {"-no-obsolete"}
local sourcefile_ts
for _, sourcebatch in pairs(target:sourcebatches()) do
if sourcebatch.rulename == "qt.ts" then
sourcefile_ts = sourcebatch.sourcefiles
else
if sourcebatch.sourcefiles then
for _, sourcefile in ipairs(sourcebatch.sourcefiles) do
table.join2(lupdate_argv, path(sourcefile))
end
end
end
end
if sourcefile_ts then
-- get lupdate and lrelease
local qt = assert(target:data("qt"), "qt not found!")
local lupdate = path.join(qt.bindir, is_host("windows") and "lupdate.exe" or "lupdate")
local lrelease = path.join(qt.bindir, is_host("windows") and "lrelease.exe" or "lrelease")
if not os.isexec(lupdate) and qt.libexecdir then
lupdate = path.join(qt.libexecdir, is_host("windows") and "lupdate.exe" or "lupdate")
end
if not os.isexec(lrelease) and qt.libexecdir then
lrelease = path.join(qt.libexecdir, is_host("windows") and "lrelease.exe" or "lrelease")
end
if not os.isexec(lupdate) and qt.libexecdir_host then
lupdate = path.join(qt.libexecdir_host, is_host("windows") and "lupdate.exe" or "lupdate")
end
if not os.isexec(lrelease) and qt.libexecdir_host then
lrelease = path.join(qt.libexecdir_host, is_host("windows") and "lrelease.exe" or "lrelease")
end
assert(os.isexec(lupdate), "lupdate not found!")
assert(os.isexec(lrelease), "lrelease not found!")
for _, tsfile in ipairs(sourcefile_ts) do
local tsargv = {}
table.join2(tsargv, lupdate_argv)
table.join2(tsargv, {"-ts", path(tsfile)})
os.vrunv(lupdate, tsargv)
end
-- save lrelease
target:data_set("qt.ts.lrelease", lrelease)
end
end)
before_buildcmd_file(function (target, batchcmds, sourcefile_ts, opt)
-- get lrelease
local lrelease = target:data("qt.ts.lrelease")
local outputdir = target:targetdir()
local fileconfig = target:fileconfig(sourcefile_ts)
if fileconfig and fileconfig.prefixdir then
if path.is_absolute(fileconfig.prefixdir) then
outputdir = fileconfig.prefixdir
else
outputdir = path.join(target:targetdir(), fileconfig.prefixdir)
end
end
local outfile = path.join(outputdir, path.basename(sourcefile_ts) .. ".qm")
batchcmds:mkdir(outputdir)
batchcmds:show_progress(opt.progress, "${color.build.object}compiling.qt.ts %s", sourcefile_ts)
batchcmds:vrunv(lrelease, {path(sourcefile_ts), "-qm", path(outfile)})
batchcmds:add_depfiles(sourcefile_ts)
end)
|
0 | repos/xmake/xmake/rules/qt | repos/xmake/xmake/rules/qt/deploy/android.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file android.lua
--
-- imports
import("core.theme.theme")
import("core.base.option")
import("core.base.semver")
import("core.project.config")
import("core.project.depend")
import("core.tool.toolchain")
import("lib.detect.find_file")
import("utils.progress")
-- escape path
function _escape_path(p)
return os.args(p, {escape = true})
end
-- deploy application package for android
function main(target, opt)
-- get ndk toolchain
local toolchain_ndk = toolchain.load("ndk", {plat = target:plat(), arch = target:arch()})
-- get target apk path
local target_apk = path.join(target:targetdir(), target:basename() .. ".apk")
-- need re-generate this apk?
local targetfile = target:targetfile()
local dependfile = target:dependfile(target_apk)
local dependinfo = target:is_rebuilt() and {} or (depend.load(dependfile) or {})
if not depend.is_changed(dependinfo, {lastmtime = os.mtime(dependfile)}) then
return
end
-- trace progress info
progress.show(opt.progress, "${color.build.target}generating.qt.app %s.apk", target:basename())
-- get qt sdk
local qt = target:data("qt")
-- get ndk
local ndk = path.translate(assert(toolchain_ndk:config("ndk"), "cannot get NDK!"))
local ndk_sdkver = assert(toolchain_ndk:config("ndk_sdkver"), "cannot get the sdk version of NDK!")
-- get ndk host
local ndk_host = os.host() .. "-" .. os.arch()
if is_host("windows") then
ndk_host = os.arch() == "x64" and "windows-x86_64" or "windows-x86"
elseif is_host("macosx") then
ndk_host = "darwin-x86_64"
elseif is_host("linux") then
ndk_host = "linux-x86_64"
end
-- get androiddeployqt
local androiddeployqt = path.join(qt.bindir, "androiddeployqt" .. (is_host("windows") and ".exe" or ""))
if not os.isexec(androiddeployqt) and qt.bindir_host then
androiddeployqt = path.join(qt.bindir_host, "androiddeployqt" .. (is_host("windows") and ".exe" or ""))
end
assert(os.isexec(androiddeployqt), "androiddeployqt not found!")
-- get working directory
local workdir = path.join(config.buildir(), ".qt", "app", "android", target:name())
-- get android-build directory
local android_buildir = path.join(workdir, "android-build")
-- get android platform
local android_platform = "android-" .. tostring(ndk_sdkver)
-- get java home
local java_home = assert(os.getenv("JAVA_HOME"), "please set $JAVA_HOME environment variable first!")
-- get android sdk directory
local android_sdkdir = path.translate(assert(toolchain_ndk:config("android_sdk"), "please run `xmake f --android_sdk=xxx` to set the android sdk directory!"))
-- get android build-tools version
local android_build_toolver = assert(toolchain_ndk:config("build_toolver"), "please run `xmake f --build_toolver=xxx` to set the android build-tools version!")
-- get qt sdk version
local qt_sdkver = config.get("qt_sdkver")
if qt_sdkver then
qt_sdkver = try { function () return semver.new(qt_sdkver) end}
end
-- get the target architecture
local target_archs =
{
["armv5te"] = "armeabi" -- deprecated
, ["armv7-a"] = "armeabi-v7a" -- deprecated
, ["armeabi"] = "armeabi"
, ["armeabi-v7a"] = "armeabi-v7a"
, ["arm64-v8a"] = "arm64-v8a"
, i386 = "x86"
, x86_64 = "x86_64"
, mips = "mips" -- removed in ndk r71
, mips64 = "mips64" -- removed in ndk r71
}
local target_arch = assert(target_archs[config.arch()], "unsupport target arch(%s)!", config.arch())
-- install target to android-build/libs first
if qt_sdkver and qt_sdkver:ge("5.14") then
-- we need to copy target to android-build/libs/armeabi/libxxx_armeabi.so after Qt 5.14.0
os.cp(target:targetfile(), path.join(android_buildir, "libs", target_arch, "lib" .. target:basename() .. "_" .. target_arch .. ".so"))
else
os.cp(target:targetfile(), path.join(android_buildir, "libs", target_arch, path.filename(target:targetfile())))
end
-- get stdcpp path
local stdcpp_path = path.join(ndk, "sources/cxx-stl/llvm-libc++/libs", target_arch, "libc++_shared.so")
if qt_sdkver and qt_sdkver:ge("5.14") then
local ndk_sysroot = assert(toolchain_ndk:config("ndk_sysroot"), "NDK sysroot directory not found!")
stdcpp_path = path.join(ndk_sysroot, "usr", "lib")
end
-- get toolchain version
local ndk_toolchains_ver = toolchain_ndk:config("ndk_toolchains_ver") or "4.9"
-- generate android-deployment-settings.json file
local android_deployment_settings = path.join(workdir, "android-deployment-settings.json")
local settings_file = io.open(android_deployment_settings, "w")
if settings_file then
settings_file:print('{')
settings_file:print(' "description": "This file is generated by qmake to be read by androiddeployqt and should not be modified by hand.",')
settings_file:print(' "qt": "%s",', _escape_path(qt.sdkdir))
settings_file:print(' "sdk": "%s",', _escape_path(android_sdkdir))
settings_file:print(' "ndk": "%s",', _escape_path(ndk))
settings_file:print(' "sdkBuildToolsRevision": "%s",', android_build_toolver)
settings_file:print(' "toolchain-prefix": "llvm",')
settings_file:print(' "tool-prefix": "llvm",')
settings_file:print(' "toolchain-version": "%s",', ndk_toolchains_ver)
settings_file:print(' "stdcpp-path": "%s",', _escape_path(stdcpp_path))
settings_file:print(' "ndk-host": "%s",', ndk_host)
settings_file:print(' "target-architecture": "%s",', target_arch)
settings_file:print(' "qml-root-path": "%s",', _escape_path(os.projectdir()))
-- for 6.2.x
local qmlimportscanner = path.join(qt.libexecdir, "qmlimportscanner")
if not os.isexec(qmlimportscanner) and qt.libexecdir_host then
qmlimportscanner = path.join(qt.libexecdir_host, "qmlimportscanner")
end
if os.isexec(qmlimportscanner) then
settings_file:print(' "qml-importscanner-binary": "%s",', _escape_path(qmlimportscanner))
end
-- for 6.3.x
local rcc = path.join(qt.bindir, "rcc")
if not os.isexec(rcc) and qt.bindir_host then
rcc = path.join(qt.bindir_host, "rcc")
end
if os.isexec(rcc) then
settings_file:print(' "rcc-binary": "%s",', _escape_path(rcc))
end
local platformplugin = find_file("libplugins_platforms_qtforandroid_" .. target_arch .. "*", path.join(qt.sdkdir, "plugins", "platforms"))
if platformplugin then
settings_file:print(' "deployment-dependencies": {"%s":"%s"},', target_arch, _escape_path(platformplugin))
end
local minsdkversion = target:values("qt.android.minsdkversion")
if minsdkversion then
settings_file:print(' "android-min-sdk-version": "%s",', tostring(minsdkversion))
end
local targetsdkversion = target:values("qt.android.targetsdkversion")
if targetsdkversion then
settings_file:print(' "android-target-sdk-version": "%s",', tostring(targetsdkversion))
end
settings_file:print(' "useLLVM": true,')
if qt_sdkver and qt_sdkver:ge("5.14") then
-- @see https://codereview.qt-project.org/c/qt-creator/qt-creator/+/287145
local triples =
{
["armv5te"] = "arm-linux-androideabi" -- deprecated
, ["armv7-a"] = "arm-linux-androideabi" -- deprecated
, ["armeabi"] = "arm-linux-androideabi" -- removed in ndk r17
, ["armeabi-v7a"] = "arm-linux-androideabi"
, ["arm64-v8a"] = "aarch64-linux-android"
, i386 = "i686-linux-android" -- deprecated
, x86 = "i686-linux-android"
, x86_64 = "x86_64-linux-android"
, mips = "mips-linux-android" -- removed in ndk r17
, mips64 = "mips64-linux-android" -- removed in ndk r17
}
settings_file:print(' "architectures": {"%s":"%s"},', target_arch, triples[target_arch])
settings_file:print(' "application-binary": "%s"', target:basename())
else
settings_file:print(' "application-binary": "%s"', _escape_path(target:targetfile()))
end
settings_file:print('}')
settings_file:close()
end
if option.get("verbose") and option.get("diagnosis") then
io.cat(android_deployment_settings)
end
-- do deploy
local argv = {"--input", android_deployment_settings,
"--output", android_buildir,
"--jdk", java_home,
"--gradle", "--no-gdbserver"}
if option.get("verbose") and option.get("diagnosis") then
table.insert(argv, "--verbose")
end
-- add user flags
local user_flags = target:values("qt.deploy.flags") or {}
if user_flags then
argv = table.join(argv, user_flags)
end
os.vrunv(androiddeployqt, argv)
-- output apk
os.cp(path.join(android_buildir, "build", "outputs", "apk", "debug", "android-build-debug.apk"), target_apk)
-- show apk output path
vprint("the apk output path: %s", target_apk)
-- update files and values to the dependent file
dependinfo.files = {targetfile}
depend.save(dependinfo, dependfile)
end
|
0 | repos/xmake/xmake/rules/qt | repos/xmake/xmake/rules/qt/deploy/macosx.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file macosx.lua
--
-- imports
import("core.theme.theme")
import("core.base.option")
import("core.project.config")
import("core.project.depend")
import("core.tool.toolchain")
import("lib.detect.find_path")
import("detect.sdks.find_qt")
import("utils.progress")
-- save Info.plist
function _save_info_plist(target, info_plist_file)
-- get target minver
local target_minver = nil
local toolchain_xcode = toolchain.load("xcode", {plat = target:plat(), arch = target:arch()})
if toolchain_xcode then
target_minver = toolchain_xcode:config("target_minver")
end
-- generate info.plist
local name = target:basename()
io.writefile(info_plist_file, string.format([[<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>BuildMachineOSBuild</key>
<string>18G95</string>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>%s</string>
<key>CFBundleExecutable</key>
<string>%s</string>
<key>CFBundleIdentifier</key>
<string>org.example.%s</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>%s</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1.0.0</string>
<key>LSMinimumSystemVersion</key>
<string>%s</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
</dict>
</plist>]], name, name, name, name, target_minver or (macos.version():major() .. "." .. macos.version():minor())))
end
-- deploy application package for macosx
function main(target, opt)
-- need re-generate this app?
local target_app = path.join(target:targetdir(), target:basename() .. ".app")
local targetfile = target:targetfile()
local dependfile = target:dependfile(target_app)
local dependinfo = target:is_rebuilt() and {} or (depend.load(dependfile) or {})
if not depend.is_changed(dependinfo, {lastmtime = os.mtime(dependfile)}) then
return
end
-- trace progress info
progress.show(opt.progress, "${color.build.target}generating.qt.app %s.app", target:basename())
-- get qt sdk
local qt = assert(find_qt(), "Qt SDK not found!")
-- get macdeployqt
local macdeployqt = path.join(qt.bindir, "macdeployqt")
assert(os.isexec(macdeployqt), "macdeployqt not found!")
-- generate target app
local target_contents = path.join(target_app, "Contents")
os.tryrm(target_app)
os.cp(target:targetfile(), path.join(target_contents, "MacOS", target:basename()))
os.cp(path.join(os.programdir(), "scripts", "PkgInfo"), target_contents)
-- generate Info.plist
_save_info_plist(target, path.join(target_contents, "Info.plist"))
-- find qml directory
local qmldir = target:values("qt.deploy.qmldir")
if not qmldir then
for _, sourcebatch in pairs(target:sourcebatches()) do
if sourcebatch.rulename == "qt.qrc" then
for _, sourcefile in ipairs(sourcebatch.sourcefiles) do
qmldir = find_path("*.qml", path.directory(sourcefile))
if qmldir then
break
end
end
end
end
else
qmldir = path.join(target:scriptdir(), qmldir)
end
-- do deploy
local argv = {target_app, "-always-overwrite"}
if option.get("diagnosis") then
table.insert(argv, "-verbose=3")
elseif option.get("verbose") then
table.insert(argv, "-verbose=1")
else
table.insert(argv, "-verbose=0")
end
if qmldir then
table.insert(argv, "-qmldir=" .. qmldir)
end
local codesign_identity = target:values("xcode.codesign_identity") or get_config("xcode_codesign_identity")
if codesign_identity then
-- e.g. "Apple Development: [email protected] (T3NA4MRVPU)"
table.insert(argv, "-codesign=" .. codesign_identity)
end
-- add user flags
local user_flags = target:values("qt.deploy.flags") or {}
if user_flags then
argv = table.join(argv, user_flags)
end
os.vrunv(macdeployqt, argv)
-- update files and values to the dependent file
dependinfo.files = {targetfile}
depend.save(dependinfo, dependfile)
end
|
0 | repos/xmake/xmake/rules/qt | repos/xmake/xmake/rules/qt/qrc/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
rule("qt.qrc")
add_deps("qt.env")
set_extensions(".qrc")
on_config(function (target)
-- get rcc
local qt = assert(target:data("qt"), "Qt not found!")
local rcc = path.join(qt.bindir, is_host("windows") and "rcc.exe" or "rcc")
if not os.isexec(rcc) and qt.libexecdir then
rcc = path.join(qt.libexecdir, is_host("windows") and "rcc.exe" or "rcc")
end
if not os.isexec(rcc) and qt.libexecdir_host then
rcc = path.join(qt.libexecdir_host, is_host("windows") and "rcc.exe" or "rcc")
end
assert(os.isexec(rcc), "rcc not found!")
-- save rcc
target:data_set("qt.rcc", rcc)
end)
on_buildcmd_file(function (target, batchcmds, sourcefile_qrc, opt)
-- get rcc
local rcc = target:data("qt.rcc")
-- get c++ source file for qrc
local sourcefile_cpp = path.join(target:autogendir(), "rules", "qt", "qrc", path.basename(sourcefile_qrc).. "_" .. hash.uuid4(sourcefile_qrc):split('%-')[1] .. ".cpp")
local sourcefile_dir = path.directory(sourcefile_cpp)
-- add objectfile
local objectfile = target:objectfile(sourcefile_cpp)
table.insert(target:objectfiles(), objectfile)
-- add commands
batchcmds:show_progress(opt.progress, "${color.build.object}compiling.qt.qrc %s", sourcefile_qrc)
batchcmds:mkdir(sourcefile_dir)
batchcmds:vrunv(rcc, {"-name", path.basename(sourcefile_qrc), path(sourcefile_qrc), "-o", path(sourcefile_cpp)})
batchcmds:compile(sourcefile_cpp, objectfile)
-- get qrc resources files
local outdata = os.iorunv(rcc, {"-name", path.basename(sourcefile_qrc), sourcefile_qrc, "-list"})
-- add resources files to batch
for _, file in ipairs(outdata:split("\n")) do
batchcmds:add_depfiles(file)
end
-- add deps
batchcmds:add_depfiles(sourcefile_qrc)
batchcmds:set_depmtime(os.mtime(objectfile))
batchcmds:set_depcache(target:dependfile(objectfile))
end)
|
0 | repos/xmake/xmake/rules/qt | repos/xmake/xmake/rules/qt/qmltyperegistrar/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author arthapz
-- @file xmake.lua
--
rule("qt.qmltyperegistrar")
add_deps("qt.env")
set_extensions(".h", ".hpp")
on_config(function(target)
-- get qt
local qt = assert(target:data("qt"), "Qt not found!")
-- get qmltyperegistrar
local qmltyperegistrar = path.join(qt.bindir, is_host("windows") and "qmltyperegistrar.exe" or "qmltyperegistrar")
if not os.isexec(qmltyperegistrar) and qt.libexecdir then
qmltyperegistrar = path.join(qt.libexecdir, is_host("windows") and "qmltyperegistrar.exe" or "qmltyperegistrar")
end
if not os.isexec(qmltyperegistrar) and qt.libexecdir_host then
qmltyperegistrar = path.join(qt.libexecdir_host, is_host("windows") and "qmltyperegistrar.exe" or "qmltyperegistrar")
end
assert(qmltyperegistrar and os.isexec(qmltyperegistrar), "qmltyperegistrar not found!")
-- set targetdir
local importname = target:values("qt.qmlplugin.import_name")
assert(importname, "QML plugin import name not set")
local targetdir = target:targetdir()
for _, dir in pairs(importname:split(".", { plain = true })) do
targetdir = path.join(targetdir, dir)
end
os.mkdir(targetdir)
target:set("targetdir", targetdir)
-- add qmldir
local qmldir = target:values("qt.qmlplugin.qmldirfile")
if qmldir then
target:add("installfiles", path.join(target:scriptdir(), qmldir), { prefixdir = path.join("bin", table.unpack(importname:split(".", { plain = true }))) })
end
-- add qmltypes
target:add("installfiles", path.join(target:get("targetdir"), "plugin.qmltypes"), { prefixdir = path.join("bin", table.unpack(importname:split(".", { plain = true }))) })
local sourcefile = path.join(target:autogendir(), "rules", "qt", "qmltyperegistrar", target:name() .. "_qmltyperegistrations.cpp")
local sourcefile_dir = path.directory(sourcefile)
os.mkdir(sourcefile_dir)
target:data_set("qt.qmlplugin.sourcefile", sourcefile)
-- add moc arguments
target:add("qt.moc.flags", "--output-json")
-- save qmltyperegistrar
target:data_set("qt.qmltyperegistrar", qmltyperegistrar)
-- save qmltyperegistrar
target:data_set("qt.qmlplugin.qmltyperegistrar", qmltyperegistrar)
end)
on_buildcmd_files(function(target, batchcmds, sourcebatch, opt)
-- setup qmltyperegistrar arguments
local qmltyperegistrar = target:data("qt.qmltyperegistrar")
local sourcefile = target:data("qt.qmlplugin.sourcefile")
local importname = target:values("qt.qmlplugin.import_name")
local majorversion = target:values("qt.qmlplugin.majorversion") or 1
local minorversion = target:values("qt.qmlplugin.minorversion") or 0
local metatypefiles = {}
for _, mocedfile in ipairs(sourcebatch.sourcefiles) do
target:add("includedirs", path.directory(mocedfile))
local basename = path.basename(mocedfile)
local filename_moc = "moc_" .. basename .. ".cpp"
if mocedfile:endswith(".cpp") then
filename_moc = basename .. ".moc"
end
local sourcefile_moc = target:autogenfile(path.join(path.directory(mocedfile), filename_moc))
table.insert(metatypefiles, path(sourcefile_moc .. ".json"))
end
local args = {
"--generate-qmltypes=" .. target:get("targetdir") .. "/plugin.qmltypes",
"--import-name=" .. importname,
"--major-version=" .. majorversion,
"--minor-version=" .. minorversion,
"-o", sourcefile
}
-- gen sourcefile
batchcmds:show_progress(opt.progress, "${color.build.object}generating.qt.qmltyperegistrar %s", path.filename(sourcefile))
qmltype_source = os.vrunv(qmltyperegistrar, table.join(args, metatypefiles))
-- add objectfile
local objectfile = target:objectfile(sourcefile)
table.insert(target:objectfiles(), objectfile)
-- compile sourcefile
batchcmds:show_progress(opt.progress, "${color.build.object}compiling.qt.qmltyperegistrar %s", path.filename(sourcefile))
batchcmds:compile(sourcefile, objectfile)
batchcmds:add_depfiles(sourcefile)
batchcmds:set_depmtime(os.mtime(objectfile))
batchcmds:set_depcache(target:dependfile(objectfile))
end)
after_build(function(target)
local qmldir = path.join(target:scriptdir(), target:values("qt.qmlplugin.qmldirfile"))
if qmldir then
os.cp(qmldir, target:targetdir())
end
end)
|
0 | repos/xmake/xmake/rules/qt | repos/xmake/xmake/rules/qt/install/windows.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file windows.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("core.tool.toolchain")
import("lib.detect.find_path")
import("detect.sdks.find_qt")
-- get install directory
function _get_installdir(target)
local installdir = assert(target:installdir(), "please use `xmake install -o installdir` or `set_installdir` to set install directory on windows.")
return installdir
end
-- install application package for windows
function main(target, opt)
local targetfile = target:targetfile()
local installdir = _get_installdir(target)
local installfile = path.join(installdir, "bin", path.filename(targetfile))
-- get qt sdk
local qt = assert(find_qt(), "Qt SDK not found!")
-- get windeployqt
local windeployqt = path.join(qt.bindir, "windeployqt.exe")
assert(os.isexec(windeployqt), "windeployqt.exe not found!")
-- find qml directory
local qmldir = target:values("qt.deploy.qmldir")
if not qmldir then
for _, sourcebatch in pairs(target:sourcebatches()) do
if sourcebatch.rulename == "qt.qrc" then
for _, sourcefile in ipairs(sourcebatch.sourcefiles) do
qmldir = find_path("*.qml", path.directory(sourcefile))
if qmldir then
break
end
end
end
end
else
qmldir = path.join(target:scriptdir(), qmldir)
end
-- find msvc to set VCINSTALLDIR env
local envs = nil
local msvc = toolchain.load("msvc", {plat = target:plat(), arch = target:arch()})
if msvc then
local vcvars = msvc:config("vcvars")
if vcvars and vcvars.VCInstallDir then
envs = {VCINSTALLDIR = vcvars.VCInstallDir}
end
end
-- bind qt bin path
-- https://github.com/xmake-io/xmake/issues/4297
if qt.bindir then
envs = envs or {}
envs.PATH = {qt.bindir}
local curpath = os.getenv("PATH")
if curpath then
table.join2(envs.PATH, path.splitenv(curpath))
end
end
local argv = {"--force"}
if option.get("diagnosis") then
table.insert(argv, "--verbose=2")
elseif option.get("verbose") then
table.insert(argv, "--verbose=1")
else
table.insert(argv, "--verbose=0")
end
-- make sure user flags have priority over default
local user_flags = table.wrap(target:values("qt.deploy.flags"))
if table.contains(user_flags, "--debug", "--release") then
if is_mode("debug") then
table.insert(argv, "--debug")
else
table.insert(argv, "--release")
end
end
if qmldir then
table.insert(argv, "--qmldir=" .. qmldir)
end
-- add user flags
if user_flags then
argv = table.join(argv, user_flags)
end
table.insert(argv, installfile)
os.vrunv(windeployqt, argv, {envs = envs})
end
|
0 | repos/xmake/xmake/rules/qt | repos/xmake/xmake/rules/qt/install/mingw.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author jingkaimori
-- @file mingw.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("core.tool.toolchain")
import("lib.detect.find_path")
import("detect.sdks.find_qt")
-- get install directory
function _get_installdir(target)
local installdir = assert(target:installdir(), "please use `xmake install -o installdir` or `set_installdir` to set install directory on windows.")
return installdir
end
-- install application package for windows
function main(target, opt)
local targetfile = target:targetfile()
local installdir = _get_installdir(target)
local installfile = path.join(installdir, "bin", path.filename(targetfile))
-- get qt sdk
local qt = assert(find_qt(), "Qt SDK not found!")
-- get windeployqt
local windeployqt = path.join(qt.bindir, "windeployqt.exe")
assert(os.isexec(windeployqt), "windeployqt.exe not found!")
-- find qml directory
local qmldir = target:values("qt.deploy.qmldir")
if not qmldir then
for _, sourcebatch in pairs(target:sourcebatches()) do
if sourcebatch.rulename == "qt.qrc" then
for _, sourcefile in ipairs(sourcebatch.sourcefiles) do
qmldir = find_path("*.qml", path.directory(sourcefile))
if qmldir then
break
end
end
end
end
else
qmldir = path.join(target:scriptdir(), qmldir)
end
-- add mingw dlls to PATH
local envs = nil
local mingw = toolchain.load("mingw", {plat = target:plat(), arch = target:arch()})
if mingw then
local bindir = mingw:bindir()
if bindir then
envs = {PATH = bindir}
end
end
local argv = {"--force"}
if option.get("diagnosis") then
table.insert(argv, "--verbose=2")
elseif option.get("verbose") then
table.insert(argv, "--verbose=1")
else
table.insert(argv, "--verbose=0")
end
-- make sure user flags have priority over default
local user_flags = table.wrap(target:values("qt.deploy.flags"))
if table.contains(user_flags, "--debug", "--release") then
if is_mode("debug") then
table.insert(argv, "--debug")
else
table.insert(argv, "--release")
end
end
if qmldir then
table.insert(argv, "--qmldir=" .. qmldir)
end
-- add user flags
if user_flags then
argv = table.join(argv, user_flags)
end
table.insert(argv, installfile)
os.vrunv(windeployqt, argv, {envs = envs})
end
|
0 | repos/xmake/xmake/rules/qt | repos/xmake/xmake/rules/qt/install/android.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file android.lua
--
-- install application package for android
function main(target, opt)
-- get target apk path
local target_apk = path.join(path.directory(target:targetfile()), target:basename() .. ".apk")
assert(os.isfile(target_apk), "apk not found, please build %s first!", target:name())
-- show install info
print("installing %s ..", target_apk)
-- get android sdk directory
local android_sdkdir = path.translate(assert(get_config("android_sdk"), "please run `xmake f --android_sdk=xxx` to set the android sdk directory!"))
-- get adb
local adb = path.join(android_sdkdir, "platform-tools", "adb" .. (is_host("windows") and ".exe" or ""))
if not os.isexec(adb) then
adb = "adb"
end
-- install apk to device
os.execv(adb, {"install", "-r", target_apk})
end
|
0 | repos/xmake/xmake/rules/qt | repos/xmake/xmake/rules/qt/ui/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
rule("qt.ui")
add_deps("qt.env")
set_extensions(".ui")
on_config(function (target)
-- get uic
local qt = assert(target:data("qt"), "Qt not found!")
local uic = path.join(qt.bindir, is_host("windows") and "uic.exe" or "uic")
if not os.isexec(uic) and qt.libexecdir then
uic = path.join(qt.libexecdir, is_host("windows") and "uic.exe" or "uic")
end
if not os.isexec(uic) and qt.libexecdir_host then
uic = path.join(qt.libexecdir_host, is_host("windows") and "uic.exe" or "uic")
end
assert(uic and os.isexec(uic), "uic not found!")
-- add includedirs, @note we need to create this directory first to suppress warning (file not found).
-- and we muse add it in load stage to ensure `depend.on_changed` work.
--
-- @see https://github.com/xmake-io/xmake/issues/1180
--
local headerfile_dir = path.join(target:autogendir(), "rules", "qt", "ui")
if not os.isdir(headerfile_dir) then
os.mkdir(headerfile_dir)
end
target:add("includedirs", path.absolute(headerfile_dir, os.projectdir()))
-- save uic
target:data_set("qt.uic", uic)
end)
before_buildcmd_file(function (target, batchcmds, sourcefile_ui, opt)
local uic = target:data("qt.uic")
local headerfile_dir = path.join(target:autogendir(), "rules", "qt", "ui")
local headerfile_ui = path.join(headerfile_dir, "ui_" .. path.basename(sourcefile_ui) .. ".h")
batchcmds:show_progress(opt.progress, "${color.build.object}compiling.qt.ui %s", sourcefile_ui)
batchcmds:mkdir(headerfile_dir)
batchcmds:vrunv(uic, {path(sourcefile_ui), "-o", path(headerfile_ui)})
batchcmds:add_depfiles(sourcefile_ui)
batchcmds:set_depmtime(os.mtime(headerfile_ui))
batchcmds:set_depcache(target:dependfile(headerfile_ui))
end)
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/mode/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define rule: debug mode
rule("mode.debug")
on_config(function (target)
-- is debug mode now? xmake f -m debug
if is_mode("debug") then
-- enable the debug symbols
if not target:get("symbols") then
target:set("symbols", "debug")
end
-- disable optimization
if not target:get("optimize") then
target:set("optimize", "none")
end
end
end)
-- define rule: release mode
rule("mode.release")
on_config(function (target)
-- is release mode now? xmake f -m release
if is_mode("release") then
-- set the symbols visibility: hidden
if not target:get("symbols") and target:kind() ~= "shared" then
target:set("symbols", "hidden")
end
-- enable optimization
if not target:get("optimize") then
if target:is_plat("android", "iphoneos") then
target:set("optimize", "smallest")
else
target:set("optimize", "fastest")
end
end
-- strip all symbols
if not target:get("strip") then
target:set("strip", "all")
end
-- enable NDEBUG macros to disables standard-C assertions
target:add("cxflags", "-DNDEBUG")
end
end)
-- define rule: release with debug symbols mode
rule("mode.releasedbg")
on_config(function (target)
-- is releasedbg mode now? xmake f -m releasedbg
if is_mode("releasedbg") then
-- set the symbols visibility: debug
if not target:get("symbols") then
target:set("symbols", "debug")
end
-- enable optimization
if not target:get("optimize") then
if target:is_plat("android", "iphoneos") then
target:set("optimize", "smallest")
else
target:set("optimize", "fastest")
end
end
-- strip all symbols, but it will generate debug symbol file because debug/symbols is setted
if not target:get("strip") then
target:set("strip", "all")
end
-- enable NDEBUG macros to disables standard-C assertions
target:add("cxflags", "-DNDEBUG")
end
end)
-- define rule: release with minsize mode
rule("mode.minsizerel")
on_config(function (target)
-- is minsizerel mode now? xmake f -m minsizerel
if is_mode("minsizerel") then
-- set the symbols visibility: hidden
if not target:get("symbols") then
target:set("symbols", "hidden")
end
-- enable optimization
if not target:get("optimize") then
target:set("optimize", "smallest")
end
-- strip all symbols
if not target:get("strip") then
target:set("strip", "all")
end
-- enable NDEBUG macros to disables standard-C assertions
target:add("cxflags", "-DNDEBUG")
end
end)
-- define rule: profile mode
rule("mode.profile")
on_config(function (target)
-- is profile mode now? xmake f -m profile
if is_mode("profile") then
-- set the symbols visibility: debug
if not target:get("symbols") then
target:set("symbols", "debug")
end
-- enable optimization
if not target:get("optimize") then
if target:is_plat("android", "iphoneos") then
target:set("optimize", "smallest")
else
target:set("optimize", "fastest")
end
end
-- enable gprof
target:add("cxflags", "-pg")
target:add("mxflags", "-pg")
target:add("ldflags", "-pg")
-- enable NDEBUG macros to disables standard-C assertions
target:add("cxflags", "-DNDEBUG")
end
end)
-- define rule: coverage mode
rule("mode.coverage")
on_config(function (target)
-- is coverage mode now? xmake f -m coverage
if is_mode("coverage") then
-- enable the debug symbols
if not target:get("symbols") then
target:set("symbols", "debug")
end
-- disable optimization
if not target:get("optimize") then
target:set("optimize", "none")
end
-- enable coverage
target:add("cxflags", "--coverage")
target:add("mxflags", "--coverage")
target:add("ldflags", "--coverage")
target:add("shflags", "--coverage")
end
end)
-- define rule: asan mode
rule("mode.asan")
-- we use after_load because c++.build.sanitizer rule/on_config need it
after_load(function (target)
-- is asan mode now? xmake f -m asan
if is_mode("asan") then
-- enable the debug symbols
if not target:get("symbols") then
target:set("symbols", "debug")
end
-- enable optimization
if not target:get("optimize") then
if target:is_plat("android", "iphoneos") then
target:set("optimize", "smallest")
else
target:set("optimize", "fastest")
end
end
-- enable asan checker
target:set("policy", "build.sanitizer.address", true)
-- we should use "build.sanitizer.address" instead of it.
wprint("deprecated: please use set_policy(\"build.sanitizer.address\", true) instead of \"mode.asan\".")
end
end)
-- define rule: tsan mode
rule("mode.tsan")
after_load(function (target)
-- is tsan mode now? xmake f -m tsan
if is_mode("tsan") then
-- enable the debug symbols
if not target:get("symbols") then
target:set("symbols", "debug")
end
-- enable optimization
if not target:get("optimize") then
if target:is_plat("android", "iphoneos") then
target:set("optimize", "smallest")
else
target:set("optimize", "fastest")
end
end
-- enable tsan checker
target:set("policy", "build.sanitizer.thread", true)
-- we should use "build.sanitizer.thread" instead of it.
wprint("deprecated: please use set_policy(\"build.sanitizer.thread\", true) instead of \"mode.tsan\".")
end
end)
-- define rule: msan mode
rule("mode.msan")
after_load(function (target)
-- is msan mode now? xmake f -m msan
if is_mode("msan") then
-- enable the debug symbols
if not target:get("symbols") then
target:set("symbols", "debug")
end
-- enable optimization
if not target:get("optimize") then
if target:is_plat("android", "iphoneos") then
target:set("optimize", "smallest")
else
target:set("optimize", "fastest")
end
end
-- enable msan checker
target:set("policy", "build.sanitizer.memory", true)
-- we should use "build.sanitizer.memory" instead of it.
wprint("deprecated: please use set_policy(\"build.sanitizer.memory\", true) instead of \"mode.msan\".")
end
end)
-- define rule: lsan mode
rule("mode.lsan")
after_load(function (target)
-- is lsan mode now? xmake f -m lsan
if is_mode("lsan") then
-- enable the debug symbols
if not target:get("symbols") then
target:set("symbols", "debug")
end
-- enable optimization
if not target:get("optimize") then
if target:is_plat("android", "iphoneos") then
target:set("optimize", "smallest")
else
target:set("optimize", "fastest")
end
end
-- enable lsan checker
target:set("policy", "build.sanitizer.leak", true)
-- we should use "build.sanitizer.leak" instead of it.
wprint("deprecated: please use set_policy(\"build.sanitizer.leak\", true) instead of \"mode.lsan\".")
end
end)
-- define rule: ubsan mode
rule("mode.ubsan")
after_load(function (target)
-- is ubsan mode now? xmake f -m ubsan
if is_mode("ubsan") then
-- enable the debug symbols
if not target:get("symbols") then
target:set("symbols", "debug")
end
-- enable optimization
if not target:get("optimize") then
if target:is_plat("android", "iphoneos") then
target:set("optimize", "smallest")
else
target:set("optimize", "fastest")
end
end
-- enable ubsan checker
target:set("policy", "build.sanitizer.undefined", true)
-- we should use "build.sanitizer.undefined" instead of it.
wprint("deprecated: please use set_policy(\"build.sanitizer.undefined\", true) instead of \"mode.ubsan\".")
end
end)
-- define rule: valgrind mode
rule("mode.valgrind")
on_config(function (target)
-- is valgrind mode now? xmake f -m valgrind
if is_mode("valgrind") then
-- enable the debug symbols
if not target:get("symbols") then
target:set("symbols", "debug")
end
-- enable optimization
if not target:get("optimize") then
if target:is_plat("android", "iphoneos") then
target:set("optimize", "smallest")
else
target:set("optimize", "fastest")
end
end
end
end)
-- define rule: check mode (deprecated)
rule("mode.check")
on_config(function (target)
-- is check mode now? xmake f -m check
if is_mode("check") then
-- enable the debug symbols
if not target:get("symbols") then
target:set("symbols", "debug")
end
-- disable optimization
if not target:get("optimize") then
target:set("optimize", "none")
end
-- attempt to enable some checkers for pc
if is_mode("check") and is_arch("i386", "x86_64") then
target:add("cxflags", "-fsanitize=address", "-ftrapv")
target:add("mxflags", "-fsanitize=address", "-ftrapv")
target:add("ldflags", "-fsanitize=address")
target:add("shflags", "-fsanitize=address")
end
end
end)
|
0 | repos/xmake/xmake/rules | repos/xmake/xmake/rules/go/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
rule("go.build")
set_sourcekinds("gc")
add_deps("go.env")
on_load(function (target)
-- we disable to build across targets in parallel, because the source files may depend on other target modules
target:set("policy", "build.across_targets_in_parallel", false)
-- xxx.a
if target:is_static() then
target:set("prefixname", "")
end
end)
on_build_files("build.object")
rule("go")
-- add build rules
add_deps("go.build")
-- inherit links and linkdirs of all dependent targets by default
add_deps("utils.inherit.links")
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.